text stringlengths 14 6.51M |
|---|
{ CFUUID.h
Copyright (c) 1999-2005, Apple, Inc. All rights reserved.
}
{ Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, November 2005 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit CFUUID;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,CFBase,CFString;
{$ALIGN POWER}
type
CFUUIDRef = ^SInt32; { an opaque 32-bit type }
CFUUIDRefPtr = ^CFUUIDRef;
type
CFUUIDBytes = record
byte0: SInt8;
byte1: SInt8;
byte2: SInt8;
byte3: SInt8;
byte4: SInt8;
byte5: SInt8;
byte6: SInt8;
byte7: SInt8;
byte8: SInt8;
byte9: SInt8;
byte10: SInt8;
byte11: SInt8;
byte12: SInt8;
byte13: SInt8;
byte14: SInt8;
byte15: SInt8;
end;
CFUUIDBytesPtr = ^CFUUIDBytes;
{ The CFUUIDBytes struct is a 128-bit struct that contains the
raw UUID. A CFUUIDRef can provide such a struct from the
CFUUIDGetUUIDBytes() function. This struct is suitable for
passing to APIs that expect a raw UUID.
}
function CFUUIDGetTypeID: CFTypeID; external name '_CFUUIDGetTypeID';
function CFUUIDCreate( alloc: CFAllocatorRef ): CFUUIDRef; external name '_CFUUIDCreate';
{ Create and return a brand new unique identifier }
function CFUUIDCreateWithBytes( alloc: CFAllocatorRef; byte0: ByteParameter; byte1: ByteParameter; byte2: ByteParameter; byte3: ByteParameter; byte4: ByteParameter; byte5: ByteParameter; byte6: ByteParameter; byte7: ByteParameter; byte8: ByteParameter; byte9: ByteParameter; byte10: ByteParameter; byte11: ByteParameter; byte12: ByteParameter; byte13: ByteParameter; byte14: ByteParameter; byte15: ByteParameter ): CFUUIDRef; external name '_CFUUIDCreateWithBytes';
{ Create and return an identifier with the given contents. This may return an existing instance with its ref count bumped because of uniquing. }
function CFUUIDCreateFromString( alloc: CFAllocatorRef; uuidStr: CFStringRef ): CFUUIDRef; external name '_CFUUIDCreateFromString';
{ Converts from a string representation to the UUID. This may return an existing instance with its ref count bumped because of uniquing. }
function CFUUIDCreateString( alloc: CFAllocatorRef; uuid: CFUUIDRef ): CFStringRef; external name '_CFUUIDCreateString';
{ Converts from a UUID to its string representation. }
function CFUUIDGetConstantUUIDWithBytes( alloc: CFAllocatorRef; byte0: ByteParameter; byte1: ByteParameter; byte2: ByteParameter; byte3: ByteParameter; byte4: ByteParameter; byte5: ByteParameter; byte6: ByteParameter; byte7: ByteParameter; byte8: ByteParameter; byte9: ByteParameter; byte10: ByteParameter; byte11: ByteParameter; byte12: ByteParameter; byte13: ByteParameter; byte14: ByteParameter; byte15: ByteParameter ): CFUUIDRef; external name '_CFUUIDGetConstantUUIDWithBytes';
{ This returns an immortal CFUUIDRef that should not be released. It can be used in headers to declare UUID constants with #define. }
function CFUUIDGetUUIDBytes( uuid: CFUUIDRef ): CFUUIDBytes; external name '_CFUUIDGetUUIDBytes';
function CFUUIDCreateFromUUIDBytes( alloc: CFAllocatorRef; bytes: CFUUIDBytes ): CFUUIDRef; external name '_CFUUIDCreateFromUUIDBytes';
end.
|
PROGRAM Pseudo(INPUT, OUTPUT);
{ Programm writes letters in pseudographics }
CONST
Rows = 5;
Columns = 5;
TYPE
SignsPlace = SET OF 1 .. 25;
PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace);
VAR
PositionInRow: INTEGER;
BEGIN {WritePseudo}
FOR PositionInRow := 1 TO (Rows * Columns)
DO
BEGIN
IF PositionInRow IN PseudoLetter
THEN
WRITE('#')
ELSE
WRITE(' ');
IF (PositionInRow MOD 5) = 0
THEN
WRITELN
END;
WRITELN
END; {WritePseudo}
VAR
PseudoLetter: SignsPlace;
Letters: FILE OF SignsPlace;
BEGIN {Pseudo}
ASSIGN(Letters, 'Letters.alph');
REWRITE(Letters);
PseudoLetter := []; {Blank} {0}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 6, 10, 11, 15, 16, 17, 18, 19, 20, 21, 25]; {1}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25]; {2}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 6, 8, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25]; {3}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 16, 21]; {4}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 9, 12, 13, 14, 16, 17, 18, 19, 20, 21, 25]; {5}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 12, 13, 16, 21, 22, 23, 24, 25]; {6}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 12, 13, 15, 16, 21, 22, 23, 24, 25]; {7}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 3, 5, 7, 8, 9, 13, 17, 18, 19, 21, 23, 25]; {8}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 10, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25]; {9}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 9, 10, 11, 13, 15, 16, 17, 20, 21, 25]; {10}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 3, 5, 6, 9, 10, 11, 13, 15, 16, 17, 20, 21, 25]; {11}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 4, 5, 6, 8, 11, 12, 16, 18, 21, 24, 25]; {12}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 6, 10, 11, 15, 16, 20, 21, 25]; {13}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25]; {14}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 11, 12, 13, 14, 15, 16, 20, 21, 25]; {15}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24, 25]; {16}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 25]; {17}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 21]; {18}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 16, 21, 22, 23, 24, 25]; {19}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 8, 13, 18, 23]; {20}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 7, 9, 13, 17, 21]; {21}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 18, 23]; {22}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 7, 9, 13, 17, 19, 21, 25]; {23}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 4, 6, 9, 11, 14, 16, 17, 18, 19, 20, 25]; {24}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 11, 12, 13, 14, 15, 20, 25]; {25}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 8, 10, 11, 13, 15, 16, 18, 20, 21, 22, 23, 24, 25]; {26}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 8, 10, 11, 13, 15, 16, 17, 18, 19, 20, 25]; {27}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 7, 12, 13, 14, 15, 17, 20, 22, 23, 24, 25]; {28}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 11, 12, 13, 15, 16, 18, 20, 21, 22, 23, 25]; {29}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 7, 12, 13, 14, 15, 17, 20, 22, 23, 24, 25]; {30}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 9, 10, 12, 13, 14, 15, 19, 20, 21, 22, 23, 24]; {31}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 3, 4, 5, 6, 8, 10, 11, 12, 13, 15, 16, 18, 20, 21, 23, 24, 25]; {32}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 5, 7, 10, 12, 13, 14, 15, 17, 20, 21, 25]; {33}
WRITE(Letters, PseudoLetter);
PseudoLetter := [23]; {.}
WRITE(Letters, PseudoLetter);
PseudoLetter := [16, 17, 22]; {,}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 8, 13, 23]; {!}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 10, 13, 14, 15, 23]; {?}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 6]; {'}
WRITE(Letters, PseudoLetter);
PseudoLetter := [11, 12, 13, 14, 15]; {-} {39}
WRITE(Letters, PseudoLetter)
END. {Pseudo}
|
unit TTSDOCSTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSDOCSRecord = record
PImageIndex: Integer;
End;
TTTSDOCSBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSDOCSRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSDOCS = (TTSDOCSPrimaryKey);
TTTSDOCSTable = class( TDBISAMTableAU )
private
FDFImageIndex: TIntegerField;
FDFImages: TBlobField;
procedure SetPImageIndex(const Value: Integer);
function GetPImageIndex:Integer;
procedure SetEnumIndex(Value: TEITTSDOCS);
function GetEnumIndex: TEITTSDOCS;
protected
procedure CreateFields;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSDOCSRecord;
procedure StoreDataBuffer(ABuffer:TTTSDOCSRecord);
property DFImageIndex: TIntegerField read FDFImageIndex;
property DFImages: TBlobField read FDFImages;
property PImageIndex: Integer read GetPImageIndex write SetPImageIndex;
published
property Active write SetActive;
property EnumIndex: TEITTSDOCS read GetEnumIndex write SetEnumIndex;
end; { TTTSDOCSTable }
procedure Register;
implementation
procedure TTTSDOCSTable.CreateFields;
begin
FDFImageIndex := CreateField( 'ImageIndex' ) as TIntegerField;
FDFImages := CreateField( 'Images' ) as TBlobField;
end; { TTTSDOCSTable.CreateFields }
procedure TTTSDOCSTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSDOCSTable.SetActive }
procedure TTTSDOCSTable.SetPImageIndex(const Value: Integer);
begin
DFImageIndex.Value := Value;
end;
function TTTSDOCSTable.GetPImageIndex:Integer;
begin
result := DFImageIndex.Value;
end;
procedure TTTSDOCSTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ImageIndex, Integer, 0, N');
Add('Images, Blob, 0, N');
end;
end;
procedure TTTSDOCSTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, ImageIndex, Y, Y, N, N');
end;
end;
procedure TTTSDOCSTable.SetEnumIndex(Value: TEITTSDOCS);
begin
case Value of
TTSDOCSPrimaryKey : IndexName := '';
end;
end;
function TTTSDOCSTable.GetDataBuffer:TTTSDOCSRecord;
var buf: TTTSDOCSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PImageIndex := DFImageIndex.Value;
result := buf;
end;
procedure TTTSDOCSTable.StoreDataBuffer(ABuffer:TTTSDOCSRecord);
begin
DFImageIndex.Value := ABuffer.PImageIndex;
end;
function TTTSDOCSTable.GetEnumIndex: TEITTSDOCS;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := TTSDOCSPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSDOCSTable, TTTSDOCSBuffer ] );
end; { Register }
function TTTSDOCSBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..1] of string = ('IMAGEINDEX' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 1) and (flist[x] <> s) do inc(x);
if x <= 1 then result := x else result := 0;
end;
function TTTSDOCSBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftInteger;
end;
end;
function TTTSDOCSBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PImageIndex;
end;
end;
end.
|
unit AlgorithmUnit;
interface
type
Point = record
x: integer;
y: integer;
constructor Create(xx, yy : integer);
begin
x := xx;
y := yy;
end;
end;
intArray = array of integer;
Grid = array of array of integer;
Action = procedure;
ActionInt = procedure(data: integer);
Algorithm = class
protected
//Массивы
_grid: Grid;
_gridSize: integer;
//События
_onStep: Action;
_onFinish: Action;
//Точки начала и конца
_start : Point;
_end : Point;
//Вспомогательные функции
function Distance(x1, y1, x2, y2 : integer) : integer;
function IsWalkable(x, y : integer) : boolean;
public
//Конструктор
constructor Create(gridSize: integer; start, finish : Point);
begin
_gridSize := gridSize;
_start := start;
_end := finish;
_grid := new intArray[_gridSize];
for var i := 0 to _gridSize - 1 do
_grid[i] := new integer[_gridSize];
end;
//Поля
property GridData: Grid read _grid write _grid;
//События
property OnStep: Action read _onStep write _onStep;
property OnFinish: Action read _onFinish write _onFinish;
procedure Step(); virtual;
procedure Restart(); virtual;
function GetPathLength() : integer; virtual;
function GetGridLayout() : Grid; virtual;
end;
implementation
procedure Algorithm.Step();
begin
end;
function Algorithm.GetGridLayout() : Grid;
begin
var temp := new intArray[_gridSize];
for var i := 0 to _gridSize - 1 do
temp[i] := new integer[_gridSize];
GetGridLayout := temp;
end;
function Algorithm.IsWalkable(x, y : integer) : boolean;
begin
if(x < 0) or (x > _gridSize-1) or (y < 0) or (y > _gridSize-1) then
IsWalkable := false
else if(_grid[x][y] = 1) then
IsWalkable := false
else
IsWalkable := true;
end;
function Algorithm.Distance(x1, y1, x2, y2 : integer) : integer;
begin
var xDist := abs(x2 - x1);
var yDist := abs(y2 - y1);
var diagonalMove := min(xDist, yDist);
var straightMove := max(xDist, yDist) - diagonalMove;
Distance := straightMove * 10 + diagonalMove * 14;
end;
procedure Algorithm.Restart();
begin
_grid := new intArray[_gridSize];
for var i := 0 to _gridSize - 1 do
_grid[i] := new integer[_gridSize];
end;
function Algorithm.GetPathLength() : integer;
begin
GetPathLength := 0;
end;
end. |
Unit TERRA_AudioMixer;
{$I terra.inc}
Interface
Uses TERRA_Utils, TERRA_String, TERRA_Threads, TERRA_Mutex;
Const
DefaultAudioBufferSize:Integer = 8192;
Type
PAudioSample = ^AudioSample;
AudioSample = Word;
TERRAAudioMixer = Class;
TERRAAudioDriver = Class(TERRAObject)
Protected
_Name:TERRAString;
_Frequency:Cardinal;
_OutputBufferSize:Cardinal;
_Mixer:TERRAAudioMixer;
Public
Function Reset(AFrequency, MaxSamples:Cardinal; Mixer:TERRAAudioMixer):Boolean; Virtual; Abstract;
Procedure Update(); Virtual; Abstract;
End;
TERRAAudioMixer = Class(TERRAObject)
Protected
_Frequency:Cardinal;
_SampleBufferSize:Cardinal;
_Buffer:Array Of Cardinal;
_Thread:TERRAThread;
_Mutex:CriticalSection;
_ThreadTerminated:Boolean;
_Driver:TERRAAudioDriver;
_CurrentOffset:Integer;
Procedure Update();
Procedure Enter();
Procedure Leave();
Procedure Render(DestBuffer:PAudioSample; Offset, Samples:Integer); Virtual;
Public
Constructor Create(Frequency, MaxSamples:Cardinal);
Procedure Release(); Override;
Procedure Start();
Procedure Stop();
Procedure RequestSamples(DestBuffer:PAudioSample; Samples:Integer);
Property Frequency:Cardinal Read _Frequency;
Property SampleBufferSize:Cardinal Read _SampleBufferSize;
End;
AudioMixerThread = Class(TERRAThread)
Protected
_Mixer:TERRAAudioMixer;
Public
Constructor Create(Mixer:TERRAAudioMixer);
Procedure Execute; Override;
End;
Implementation
Uses TERRA_Error, TERRA_OS
{$IFDEF WINDOWS}
, TERRA_WinMMAudioDriver
{$ENDIF}
{$IFDEF OSX}
, TERRA_CoreAudioDriver
{$ENDIF}
;
{ TERRAAudioMixer }
Constructor TERRAAudioMixer.Create(Frequency, MaxSamples:Cardinal);
Var
I:Integer;
Begin
_Frequency := Frequency;
_SampleBufferSize := MaxSamples;
SetLength(_Buffer, MaxSamples * 2); // stereo
{$IFDEF WINDOWS}
_Driver := WindowsAudioDriver.Create();
{$ENDIF}
{$IFDEF OSX}
_Driver := CoreAudioDriver.Create();
{$ENDIF}
_Driver.Reset(Frequency, MaxSamples, Self);
_ThreadTerminated := False;
_Mutex := CriticalSection.Create();
_Thread := AudioMixerThread.Create(Self);
// CREATE_SUSPENDED
// SetThreadPriority(_ThreadHandle, THREAD_PRIORITY_TIME_CRITICAL);
End;
Procedure TERRAAudioMixer.Release();
Begin
Self.Enter();
_ThreadTerminated := True;
Self.Leave();
_Thread.Terminate();
ReleaseObject(_Thread);
ReleaseObject(_Mutex);
ReleaseObject(_Driver);
SetLength(_Buffer, 0);
End;
Procedure TERRAAudioMixer.Enter;
Begin
_Mutex.Lock();
End;
Procedure TERRAAudioMixer.Leave;
Begin
_Mutex.Unlock();
End;
Procedure TERRAAudioMixer.Start;
Begin
_Thread.Resume();
// ResumeThread(_ThreadHandle);
End;
procedure TERRAAudioMixer.Stop;
begin
_Thread.Suspend();
// SuspendThread(_ThreadHandle);
end;
Procedure TERRAAudioMixer.Render(DestBuffer:PAudioSample; Offset, Samples:Integer);
Begin
End;
Procedure TERRAAudioMixer.Update();
Begin
Self.Enter();
Self._Driver.Update();
Self.Leave();
End;
Procedure TERRAAudioMixer.RequestSamples(DestBuffer:PAudioSample; Samples:Integer);
Begin
Self.Render(DestBuffer, _CurrentOffset, Samples);
Inc(_CurrentOffset, Samples);
If (_CurrentOffset >= _SampleBufferSize) Then
Begin
Samples := _CurrentOffset - _CurrentOffset;
_CurrentOffset := 0;
If Samples>0 Then
Self.RequestSamples(DestBuffer, Samples);
End;
End;
{ AudioMixerThread }
Constructor AudioMixerThread.Create(Mixer: TERRAAudioMixer);
Begin
_Mixer := Mixer;
Inherited Create();
End;
Procedure AudioMixerThread.Execute;
Begin
While Not _Mixer._ThreadTerminated DO
Begin
_Mixer.Update();
Application.Sleep(50);
End;
End;
End.
|
{-----------------------------------------------------------------------------
EventDetailForm (historypp project)
Version: 1.4
Created: 31.03.2003
Author: Oxygen
[ Description ]
Form for details about event
[ History ]
1.4
- Added horz scroll bar to memo
1.0 (31.03.2003) - Initial version
[ Modifications ]
* (29.05.2003) Added scroll bar to memo
[ Knows Inssues ]
None
Original file copyright (c) Christian Kastner
Copyright (c) Art Fedorov, 2003
-----------------------------------------------------------------------------}
unit EventDetailForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, TntStdCtrls,
HistoryGrid, HistoryForm,
m_globaldefs, m_api, hpp_messages,
hpp_global, hpp_contacts, hpp_events, hpp_forms;
type
TEventDetailsFrm = class(TForm)
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
EMsgType: TEdit;
EDateTime: TTntEdit;
PrevBtn: TButton;
NextBtn: TButton;
bnReply: TButton;
CloseBtn: TButton;
GroupBox4: TGroupBox;
Panel1: TPanel;
EText: TTntMemo;
Panel7: TPanel;
Panel8: TPanel;
GroupBox2: TGroupBox;
Label3: TLabel;
Label4: TLabel;
EFromNick: TTntEdit;
EFromUIN: TEdit;
EFromMore: TButton;
GroupBox3: TGroupBox;
Label5: TLabel;
Label6: TLabel;
EToNick: TTntEdit;
EToUIN: TEdit;
EToMore: TButton;
procedure PrevBtnClick(Sender: TObject);
procedure NextBtnClick(Sender: TObject);
procedure EFromMoreClick(Sender: TObject);
procedure EToMoreClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CloseBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure bnReplyClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
//FRowIdx: integer;
FParentForm: THistoryFrm;
FItem: Integer;
Prev,Next: Integer;
// procedure SetRowIdx(const Value: integer);
procedure OnCNChar(var Message: TWMChar); message WM_CHAR;
procedure WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo);message wm_GetMinMaxInfo;
procedure LoadPosition;
procedure SavePosition;
procedure SetItem(const Value: Integer);
procedure TranslateForm;
{ Private declarations }
public
TOhContact:THandle;
FROMhContact:THandle;
property ParentForm:THistoryFrm read FParentForm write fParentForm;
// property RowIdx:integer read FRowIdx write SetRowIdx; //line of grid, whoms details should be shown
property Item: Integer read FItem write SetItem;
end;
var
EventDetailsFrm: TEventDetailsFrm;
implementation
uses hpp_database;
{$I m_database.inc}
{$I m_langpack.inc}
{$I m_clist.inc}
{$I m_userinfo.inc}
{$I m_icq.inc}
{$R *.DFM}
{ TForm1 }
procedure TEventDetailsFrm.WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo);
begin
inherited;
with Msg.MinMaxInfo^ do
begin
ptMinTrackSize.x:= 466;
ptMinTrackSize.y:= 340;
end
end;
procedure TEventDetailsFrm.PrevBtnClick(Sender: TObject);
begin
Item := Prev;
end;
procedure TEventDetailsFrm.NextBtnClick(Sender: TObject);
begin
Item := Next;
end;
procedure TEventDetailsFrm.EFromMoreClick(Sender: TObject);
begin
PluginLink.CallService(MS_USERINFO_SHOWDIALOG,FROMhContact,0);
end;
procedure TEventDetailsFrm.EToMoreClick(Sender: TObject);
begin
PluginLink.CallService(MS_USERINFO_SHOWDIALOG,TOhContact,0);
end;
procedure TEventDetailsFrm.FormDestroy(Sender: TObject);
begin
try
FParentForm.EventDetailFrom:=nil;
except end;
end;
procedure TEventDetailsFrm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
Mask: Integer;
begin
with Sender as TWinControl do
begin
if Perform(CM_CHILDKEY, Key, Integer(Sender)) <> 0 then
Exit;
Mask := 0;
case Key of
VK_TAB:
Mask := DLGC_WANTTAB;
VK_RETURN, VK_EXECUTE, VK_ESCAPE, VK_CANCEL:
Mask := DLGC_WANTALLKEYS;
end;
if (Mask <> 0)
and (Perform(CM_WANTSPECIALKEY, Key, 0) = 0)
and (Perform(WM_GETDLGCODE, 0, 0) and Mask = 0)
and (Self.Perform(CM_DIALOGKEY, Key, 0) <> 0)
then Exit;
end;
end;
procedure TEventDetailsFrm.OnCNChar(var Message: TWMChar);
//make tabs work!
begin
if not (csDesigning in ComponentState) then
with Message do
begin
Result := 1;
if (Perform(WM_GETDLGCODE, 0, 0) and DLGC_WANTCHARS = 0) and
(GetParentForm(Self).Perform(CM_DIALOGCHAR,
CharCode, KeyData) <> 0) then Exit;
Result := 0;
end;
end;
procedure TEventDetailsFrm.LoadPosition;
//load last position and filter setting
begin
if DBGetContactSettingDWord(0,'HistoryPlusPlus','EDPosWidth',0)<>0 then begin
Top:=DBGetContactSettingDWord(0,'HistoryPlusPlus','EDPosTop',0);
Left:=DBGetContactSettingDWord(0,'HistoryPlusPlus','EDPosLeft',0);
Height:=DBGetContactSettingDWord(0,'HistoryPlusPlus','EDPosHeight',0);
Width:=DBGetContactSettingDWord(0,'HistoryPlusPlus','EDPosWidth',0);
end;
end;
procedure TEventDetailsFrm.SavePosition;
//load position and filter setting
begin
DBWriteContactSettingDWord(0,'HistoryPlusPlus','EDPosTop',Top);
DBWriteContactSettingDWord(0,'HistoryPlusPlus','EDPosLeft',Left);
DBWriteContactSettingDWord(0,'HistoryPlusPlus','EDPosHeight',Height);
DBWriteContactSettingDWord(0,'HistoryPlusPlus','EDPosWidth',Width);
end;
procedure TEventDetailsFrm.FormShow(Sender: TObject);
begin
LoadPosition;
end;
procedure TEventDetailsFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TEventDetailsFrm.CloseBtnClick(Sender: TObject);
begin
Self.Release;
end;
procedure TEventDetailsFrm.FormCreate(Sender: TObject);
begin
DesktopFont := True;
MakeFontsParent(Self);
TranslateForm;
Prev := -1;
Next := -1;
end;
procedure TEventDetailsFrm.SetItem(const Value: Integer);
var
FromContact,ToContact : boolean;
function GetMsgType(MesType: TMessageTypes; EventInfo: Word): string;
begin
if mtMessage in MesType then
Result := Translate('Message')
else if mtURL in MesType then
Result := Translate('URL')
else if mtFile in MesType then
Result := Translate('File Transfer')
else if mtContacts in MesType then
Result := Translate('Contacts')
//else if mtAdded in MesType then
// Result := Translate('You Were Added Message')
//else if mtAuthRequest in MesType then
// Result := Translate('Authorisation Request')
else if mtSystem in MesType then
Result := Translate('System message')
else if mtSMS in MesType then
Result := Translate('SMS Message')
else if mtWebPager in MesType then
Result := Translate('WebPager')
else if mtEmailExpress in MesType then
Result := Translate('EMail Express')
else if mtOther in MesType then
Result := Translate('Other event')+' '+IntToStr(EventInfo);
end;
begin
Assert(Assigned(FParentForm));
FItem := Value;
EMsgType.Text := GetMsgType(FParentForm.hg.Items[Item].MessageType,FParentForm.hg.Items[Item].EventType);
EDateTime.Text := TimestampToString(FParentForm.hg.Items[Item].Time);
FromContact := false;
ToContact := false;
if mtIncoming in FParentForm.hg.Items[Item].MessageType then begin
FROMhContact := FParentForm.hContact;
if FROMhContact = 0 then FromContact := true;
TOhContact:=0;
end else begin
TOhContact := FParentForm.hContact;
if TOhContact = 0 then ToContact := true;
FromhContact:=0;
end;
EFromMore.Enabled := not FromContact;
EToMore.Enabled := not ToContact;
EFromNick.Text := GetContactDisplayName(FROMhContact,FParentForm.Protocol,FromContact);
EFromUIN.Text := GetContactID(FROMhContact,FParentForm.Protocol,FromContact);
EToNick.Text := GetContactDisplayName(TOhContact,FParentForm.Protocol,ToContact);
EToUIN.Text := GetContactID(TOhContact,FParentForm.Protocol,ToContact);
//EText.Lines.Clear
EText.Lines.Text:=FParentForm.hg.Items[Item].Text;
//EText.Lines.
if FromContact or ToContact then
bnReply.Enabled := False
else
bnReply.Enabled := True;
// check forward and back buttons
Prev := FParentForm.hg.GetPrev(Item);
Next := FParentForm.hg.GetNext(Item);
NextBtn.Enabled := (Next <> -1);
PrevBtn.Enabled := (Prev <> -1);
if FParentForm.hg.selected <> Item then
FParentForm.hg.Selected := Item;
end;
procedure TEventDetailsFrm.FormHide(Sender: TObject);
begin
SavePosition;
end;
procedure TEventDetailsFrm.bnReplyClick(Sender: TObject);
begin
FParentForm.ReplyQuoted(FItem);
end;
procedure TEventDetailsFrm.FormResize(Sender: TObject);
begin
Panel8.Width := ClientWidth div 2;
end;
procedure TEventDetailsFrm.TranslateForm;
begin
Caption := Translate(PChar(Caption));
GroupBox1.Caption:=Translate(PChar(GroupBox1.Caption));
GroupBox2.Caption:=Translate(PChar(GroupBox2.Caption));
GroupBox3.Caption:=Translate(PChar(GroupBox3.Caption));
GroupBox4.Caption:=Translate(PChar(GroupBox4.Caption));
Label1.Caption:=Translate(PChar(Label1.Caption));
Label2.Caption:=Translate(PChar(Label2.Caption));
Label3.Caption:=Translate(PChar(Label3.Caption));
Label4.Caption:=Translate(PChar(Label4.Caption));
Label5.Caption:=Translate(PChar(Label5.Caption));
Label6.Caption:=Translate(PChar(Label6.Caption));
EFromMore.Caption:=Translate(PChar(EFromMore.Caption));
EToMore.Caption:=Translate(PChar(EToMore.Caption));
PrevBtn.Caption:=Translate(PChar(PrevBtn.Caption));
NextBtn.Caption:=Translate(PChar(NextBtn.Caption));
CloseBtn.Caption:=Translate(PChar(CloseBtn.Caption));
bnReply.Caption:=Translate(PChar(bnReply.Caption));
end;
end.
|
unit csClientCommandsManager;
interface
uses
csClient, csCommandsManager, CsDataPipe, csCommandsTypes,
Menus;
type
TcsClientCommandsManager = class(TcsCommandsManager)
private
f_CSClient: TcsClient;
function pm_GetCommandEnabled(Command: TcsCommands): Boolean;
function pm_GetCustomCommands(Index: Integer): TcsCommand;
function pm_GetCustomCommandsCount: Integer;
procedure RequestParams(aCommand: TcsCommand);
public
procedure ExecuteCommand(Sender: TObject);
procedure LoadCommands(aPipe: TcsDataPipe);
procedure UpdateServerMenu(theServerMenu: TMenuItem);
property CommandEnabled[Command: TcsCommands]: Boolean read pm_GetCommandEnabled;
property CSClient: TcsClient read f_CSClient write f_CSClient;
property CustomCommands[Index: Integer]: TcsCommand read pm_GetCustomCommands;
property CustomCommandsCount: Integer read pm_GetCustomCommandsCount;
end;
implementation
uses
ActnList, CsQueryTypes, l3Memory, SysUtils, csCommandsConst, Dialogs,
StrUtils, l3Base, FileCtrl, csImport, csTaskTypes, ddFileIterator;
procedure TcsClientCommandsManager.ExecuteCommand(Sender: TObject);
var
l_Command: TcsCommand;
l_Result: Boolean;
begin
Assert(f_CSClient <> nil);
if CommandExists(TMenuItem(Sender).Tag, l_Command) then
begin
RequestParams(l_Command);
l_Result:= f_CSClient.Exec(qtExecuteCommand, l_Command.ExecuteOnServer);
if l_Command.NeedRespond then
MessageDlg(IfThen(l_Result, 'Команда отправлена на сервер', 'Не удалось передать команду'), mtInformation, [mbOk], 0);
end;
end;
procedure TcsClientCommandsManager.LoadCommands(aPipe: TcsDataPipe);
var
l_Stream: Tl3MemoryStream;
l_Count, i: Integer;
l_Command: TcsCommand;
begin
ClearCommands;
l_Stream:= Tl3MemoryStream.Create;
try
aPipe.ReadStream(l_Stream);
l_Stream.Read(l_Count, SizeOf(l_Count));
for i:= 0 to Pred(l_Count) do
begin
//l_Command:= TcsCommand(l_Stream.ReadComponent(nil));
l_Command:= TcsCommand.Create;
l_Command.Load(l_Stream);
l_Command.OnExecute := ExecuteCommand;
Add(l_Command);
end; // for i
finally
FreeAndNil(l_Stream);
end;
end;
function TcsClientCommandsManager.pm_GetCommandEnabled(Command: TcsCommands): Boolean;
var
l_C: TcsCommand;
begin
Result := CommandExists(Command, l_C);
end;
function TcsClientCommandsManager.pm_GetCustomCommands(Index: Integer): TcsCommand;
var
i, l_Index: Integer;
begin
Result := nil;
l_Index:= -1;
for i:= 0 to Pred(Count) do
if Commands[i].CommandID > c_CommandBaseIndex then
begin
Inc(l_Index);
if l_Index = Index then
Result:= Commands[i];
end;
end;
function TcsClientCommandsManager.pm_GetCustomCommandsCount: Integer;
var
i: Integer;
begin
Result := 0;
for i:= 0 to Pred(Count) do
if Commands[i].CommandID > c_CommandBaseIndex then
Inc(Result);
end;
procedure TcsClientCommandsManager.RequestParams(aCommand: TcsCommand);
var
l_Folder: String;
begin
if aCommand.LinkTask <> nil then
begin
case aCommand.LinkTask.TaskType of
cs_ttAACImport: // Запрашиваем папку с данными, забираем оттуда евдшники
if SelectDirectory(l_Folder, [], 0) then
begin
with TddFileIterator.Make(l_Folder, '*.evd') do
try
TcsAACImport(aCommand.LinkTask).SourceFiles.Assign(FileList);
finally
Free;
end;
end;
end;
end;
end;
procedure TcsClientCommandsManager.UpdateServerMenu(theServerMenu: TMenuItem);
var
i: Integer;
l_MI: TMenuItem;
begin
theServerMenu.Clear;
theServerMenu.Visible:= CustomCommandsCount > 0;
for i:= 0 to CustomCommandsCount-1 do
begin
l_MI:= TmenuItem.Create(theServerMenu);
l_MI.Name:= 'ServerMenu'+ IntToStr(CustomCommands[i].CommandID);
l_MI.Tag:= CustomCommands[i].CommandID;
l_MI.Caption:= CustomCommands[i].Caption;
l_MI.OnClick:= CustomCommands[i].OnExecute;
theServerMenu.Add(l_MI);
end;
end;
end.
|
unit ncsOneFileDeliverer;
// Модуль: "w:\common\components\rtl\Garant\cs\ncsOneFileDeliverer.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TncsOneFileDeliverer" MUID: (546F3804032D)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, l3ProtoObject
, ncsMessageInterfaces
, ncsTaskedFileDesc
, Classes
, ddProgressObj
, ncsTrafficCounter
, ncsFileDesc
, ncsMessage
;
type
TncsOneFileDeliverer = class(Tl3ProtoObject, IncsExecutor, IncsMessageExecutorFactory)
private
f_Transporter: IncsTransporter;
f_LocalPath: AnsiString;
f_TaskID: AnsiString;
f_Stream: TStream;
f_Progressor: TddProgressObject;
f_Counter: IncsTrafficCounter;
f_ReceiveTime: Double;
f_WriteTime: Double;
f_LocalDesc: TncsTaskedFileDesc;
private
function CheckContinue(aRemoteDesc: TncsFileDesc): Boolean;
procedure InitNew(aRemoteDesc: TncsFileDesc);
function LocalControlFileName: AnsiString;
function LocalPartialFileName: AnsiString;
procedure SaveControl;
function LocalFileName: AnsiString;
protected
procedure Execute(const aContext: TncsExecuteContext);
function MakeExecutor(aMessage: TncsMessage): IncsExecutor;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aTransporter: IncsTransporter;
const aTaskID: AnsiString;
const aLocalPath: AnsiString;
aRemoteDesc: TncsFileDesc); reintroduce;
procedure CommitDelivery;
function DoProcess(aProgressor: TddProgressObject): Boolean;
public
property ReceiveTime: Double
read f_ReceiveTime;
property WriteTime: Double
read f_WriteTime;
property LocalDesc: TncsTaskedFileDesc
read f_LocalDesc;
end;//TncsOneFileDeliverer
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, SysUtils
, l3Stream
, l3Types
, l3CRCUtils
, ncsGetFilePartReply
, ncsGetFilePart
, Math
, ncsPushFilePart
, ncsMessageExecutorFactory
, ncsProfile
, l3Base
, l3StopWatch
, l3FileUtils
//#UC START# *546F3804032Dimpl_uses*
//#UC END# *546F3804032Dimpl_uses*
;
const
cControlExt = '.control';
cPartialExt = '.partial';
constructor TncsOneFileDeliverer.Create(const aTransporter: IncsTransporter;
const aTaskID: AnsiString;
const aLocalPath: AnsiString;
aRemoteDesc: TncsFileDesc);
//#UC START# *546F389A0156_546F3804032D_var*
//#UC END# *546F389A0156_546F3804032D_var*
begin
//#UC START# *546F389A0156_546F3804032D_impl*
inherited Create;
f_Transporter := aTransporter;
f_LocalPath := aLocalPath;
f_LocalDesc := TncsTaskedFileDesc.Create;
f_LocalDesc.Name := aRemoteDesc.Name;
f_TaskID := aTaskID;
if not CheckContinue(aRemoteDesc) then
InitNew(aRemoteDesc);
f_ReceiveTime := 0;
f_WriteTime := 0;
Supports(f_Transporter, IncsTrafficCounter, f_Counter);
//#UC END# *546F389A0156_546F3804032D_impl*
end;//TncsOneFileDeliverer.Create
function TncsOneFileDeliverer.CheckContinue(aRemoteDesc: TncsFileDesc): Boolean;
//#UC START# *5473254E0090_546F3804032D_var*
var
l_Stream: TStream;
//#UC END# *5473254E0090_546F3804032D_var*
begin
//#UC START# *5473254E0090_546F3804032D_impl*
Result := False;
if FileExists(LocalControlFileName) then
begin
l_Stream := Tl3FileStream.Create(LocalControlFileName, l3_fmRead);
try
f_LocalDesc.LoadFromEVD(l_Stream);
Assert(f_LocalDesc.Name <> '');
finally
FreeAndNil(l_Stream);
end;
if not FileExists(LocalPartialFileName) then
Exit;
if f_LocalDesc.TaskID <> f_TaskID then
Exit;
if f_LocalDesc.CRC <> aRemoteDesc.CRC then
Exit;
if f_LocalDesc.DateTime <> aRemoteDesc.DateTime then
Exit;
if f_LocalDesc.Size <> aRemoteDesc.Size then
Exit;
Result := True;
end
//#UC END# *5473254E0090_546F3804032D_impl*
end;//TncsOneFileDeliverer.CheckContinue
procedure TncsOneFileDeliverer.InitNew(aRemoteDesc: TncsFileDesc);
//#UC START# *5473255F03A1_546F3804032D_var*
var
l_Stream: TStream;
//#UC END# *5473255F03A1_546F3804032D_var*
begin
//#UC START# *5473255F03A1_546F3804032D_impl*
f_LocalDesc.TaskID := f_TaskID;
f_LocalDesc.CopiedSize := 0;
f_LocalDesc.CRC := aRemoteDesc.CRC;
f_LocalDesc.Size := aRemoteDesc.Size;
f_LocalDesc.DateTime := aRemoteDesc.DateTime;
ForceDirectories(ExtractFilePath(LocalPartialFileName));
l_Stream := Tl3FileStream.Create(LocalPartialFileName, l3_fmCreateReadWrite);
try
l_Stream.Size := f_LocalDesc.Size;
finally
FreeAndNil(l_Stream);
end;
//#UC END# *5473255F03A1_546F3804032D_impl*
end;//TncsOneFileDeliverer.InitNew
function TncsOneFileDeliverer.LocalControlFileName: AnsiString;
//#UC START# *54732616034A_546F3804032D_var*
//#UC END# *54732616034A_546F3804032D_var*
begin
//#UC START# *54732616034A_546F3804032D_impl*
Result := f_LocalPath + f_LocalDesc.Name + cControlExt;
//#UC END# *54732616034A_546F3804032D_impl*
end;//TncsOneFileDeliverer.LocalControlFileName
function TncsOneFileDeliverer.LocalPartialFileName: AnsiString;
//#UC START# *5473263D00AC_546F3804032D_var*
//#UC END# *5473263D00AC_546F3804032D_var*
begin
//#UC START# *5473263D00AC_546F3804032D_impl*
Result := f_LocalPath + f_LocalDesc.Name + cPartialExt;
//#UC END# *5473263D00AC_546F3804032D_impl*
end;//TncsOneFileDeliverer.LocalPartialFileName
procedure TncsOneFileDeliverer.SaveControl;
//#UC START# *5474A3BD0077_546F3804032D_var*
var
l_Stream: TStream;
//#UC END# *5474A3BD0077_546F3804032D_var*
begin
//#UC START# *5474A3BD0077_546F3804032D_impl*
g_SaveControl.Start;
try
l_Stream := Tl3FileStream.Create(LocalControlFileName, l3_fmCreateReadWrite);
try
f_LocalDesc.SaveToEVD(l_Stream, nil);
finally
FreeAndNil(l_Stream);
end;
finally
g_SaveControl.Stop;
end;
//#UC END# *5474A3BD0077_546F3804032D_impl*
end;//TncsOneFileDeliverer.SaveControl
procedure TncsOneFileDeliverer.CommitDelivery;
//#UC START# *5474A3D400D5_546F3804032D_var*
//#UC END# *5474A3D400D5_546F3804032D_var*
begin
//#UC START# *5474A3D400D5_546F3804032D_impl*
RenameFileSafe(LocalPartialFileName, LocalFileName);
if FileExists(LocalControlFileName) then
DeleteFile(LocalControlFileName);
//#UC END# *5474A3D400D5_546F3804032D_impl*
end;//TncsOneFileDeliverer.CommitDelivery
function TncsOneFileDeliverer.LocalFileName: AnsiString;
//#UC START# *5474A7B201FC_546F3804032D_var*
//#UC END# *5474A7B201FC_546F3804032D_var*
begin
//#UC START# *5474A7B201FC_546F3804032D_impl*
Result := f_LocalPath + f_LocalDesc.Name;
//#UC END# *5474A7B201FC_546F3804032D_impl*
end;//TncsOneFileDeliverer.LocalFileName
function TncsOneFileDeliverer.DoProcess(aProgressor: TddProgressObject): Boolean;
//#UC START# *5472E6E201EE_546F3804032D_var*
var
l_Message: TncsGetFilePart;
l_RawReply: TncsMessage;
l_Watch: Tl3StopWatch;
l_StreamWatch: Tl3StopWatch;
const
cPartSize = 31*1024;
//#UC END# *5472E6E201EE_546F3804032D_var*
begin
//#UC START# *5472E6E201EE_546F3804032D_impl*
{$IFNDEF AQTIME_PROFILE}
l_StreamWatch.Reset;
l_Watch.Reset;
l_Watch.Start;
{$ENDIF AQTIME_PROFILE}
try
aProgressor.SetRefTo(f_Progressor);
try
TncsMessageExecutorFactory.Instance.Register(Self);
try
Result := LocalDesc.CopiedSize = LocalDesc.Size;
if Assigned(aProgressor) then
aProgressor.IncProgress(LocalDesc.CopiedSize);
if not Result then
begin
l_RawReply := nil;
if not FileExists(LocalPartialFileName) then
raise EInOutError.Create('File not found');
{$IFNDEF AQTIME_PROFILE}
l_StreamWatch.Start;
{$ENDIF AQTIME_PROFILE}
f_Stream := Tl3FileStream.Create(LocalPartialFileName, l3_fmExclusiveReadWrite);
{$IFNDEF AQTIME_PROFILE}
l_StreamWatch.Stop;
{$ENDIF AQTIME_PROFILE}
try
repeat
if not f_Transporter.Processing then
begin
{$IFNDEF AQTIME_PROFILE}
l3System.Msg2Log('Ошибка доставки - обрыв связи');
{$ENDIF AQTIME_PROFILE}
Exit;
end;
l_Message := TncsGetFilePart.Create;
try
l_Message.TaskID := f_TaskID;
l_Message.FileName := LocalDesc.Name;
l_Message.Offset := LocalDesc.CopiedSize;
l_Message.PartSize := Min(cPartSize, LocalDesc.Size - LocalDesc.CopiedSize);
f_Transporter.Send(l_Message);
FreeAndNil(l_RawReply);
try
{$IFNDEF AQTIME_PROFILE}
g_WaitFile.Start;
{$ENDIF AQTIME_PROFILE}
try
if not f_Transporter.WaitForReply(l_Message, l_RawReply) then
begin
{$IFNDEF AQTIME_PROFILE}
l3System.Msg2Log('Ошибка доставки - не дождались ответа на запрос файла');
{$ENDIF AQTIME_PROFILE}
Exit;
end;
finally
{$IFNDEF AQTIME_PROFILE}
g_WaitFile.Stop;
{$ENDIF AQTIME_PROFILE}
end;
if not (l_RawReply is TncsGetFilePartReply) then
begin
{$IFNDEF AQTIME_PROFILE}
l3System.Msg2Log('Ошибка доставки - нераспознанный ответ на запрос файла');
{$ENDIF AQTIME_PROFILE}
Exit;
end;
if not TncsGetFilePartReply(l_RawReply).IsSuccess then
begin
{$IFNDEF AQTIME_PROFILE}
l3System.Msg2Log('Ошибка доставки - неуспешный ответ на запрос файла');
{$ENDIF AQTIME_PROFILE}
Exit;
end;
finally
FreeAndNil(l_RawReply);
end;
finally
FreeAndNil(l_Message);
end;
if LocalDesc.CopiedSize = LocalDesc.Size then
begin
if (l3CalcCRC32(f_Stream) = LocalDesc.CRC) then
begin
Result := True;
Break;
end
else
begin
LocalDesc.CopiedSize := 0;
if Assigned(aProgressor) then
aProgressor.IncProgress(-LocalDesc.Size);
SaveControl;
end;
end
{$IFNDEF AQTIME_PROFILE}
else
l3System.Msg2Log('Доставка файлов - несовпал размер после сигнала об успехе');
{$ENDIF AQTIME_PROFILE}
until False;
finally
SaveControl;
{$IFNDEF AQTIME_PROFILE}
l_StreamWatch.Start;
{$ENDIF AQTIME_PROFILE}
FreeAndNil(f_Stream);
{$IFNDEF AQTIME_PROFILE}
l_StreamWatch.Stop;
f_WriteTime := f_WriteTime + l_StreamWatch.Time;
{$ENDIF AQTIME_PROFILE}
end;
end;
finally
TncsMessageExecutorFactory.Instance.UnRegister(Self);
end;
finally
FreeAndNil(f_Progressor);
end;
finally
{$IFNDEF AQTIME_PROFILE}
l_Watch.Stop;
f_ReceiveTime := f_ReceiveTime + l_Watch.Time;
{$ENDIF AQTIME_PROFILE}
end;
//#UC END# *5472E6E201EE_546F3804032D_impl*
end;//TncsOneFileDeliverer.DoProcess
procedure TncsOneFileDeliverer.Execute(const aContext: TncsExecuteContext);
//#UC START# *54607DDC0159_546F3804032D_var*
var
l_Message: TncsPushFilePart;
l_Watch: Tl3StopWatch;
//#UC END# *54607DDC0159_546F3804032D_var*
begin
//#UC START# *54607DDC0159_546F3804032D_impl*
{$IFNDEF AQTIME_PROFILE}
l_Watch.Reset;
g_ReceivePartFile.Start;
{$ENDIF AQTIME_PROFILE}
try
l_Message := aContext.rMessage as TncsPushFilePart;
{$IFNDEF AQTIME_PROFILE}
l_Watch.Start;
{$ENDIF AQTIME_PROFILE}
f_Stream.Seek(l_Message.Offset, soBeginning);
{$IFNDEF AQTIME_PROFILE}
g_WriteFile.Start;
{$ENDIF AQTIME_PROFILE}
l_Message.Data.CopyTo(f_Stream, l_Message.PartSize);
{$IFNDEF AQTIME_PROFILE}
g_WriteFile.Stop;
l_Watch.Stop;
f_WriteTime := f_WriteTime + l_Watch.Time;
{$ENDIF AQTIME_PROFILE}
if Assigned(f_Counter) then
f_Counter.DoProgress(l_Message.PartSize);
LocalDesc.CopiedSize := LocalDesc.CopiedSize + l_Message.PartSize;
// SaveControl;
if Assigned(f_Progressor) then
f_Progressor.IncProgress(l_Message.PartSize);
finally
{$IFNDEF AQTIME_PROFILE}
g_ReceivePartFile.Stop;
{$ENDIF AQTIME_PROFILE}
end;
//#UC END# *54607DDC0159_546F3804032D_impl*
end;//TncsOneFileDeliverer.Execute
function TncsOneFileDeliverer.MakeExecutor(aMessage: TncsMessage): IncsExecutor;
//#UC START# *546082B801F3_546F3804032D_var*
//#UC END# *546082B801F3_546F3804032D_var*
begin
//#UC START# *546082B801F3_546F3804032D_impl*
if (aMessage is TncsPushFilePart) and (TncsPushFilePart(aMessage).TaskID = f_TaskID) and (TncsPushFilePart(aMessage).FileName = LocalDesc.Name) then
Result := Self
else
Result := nil;
//#UC END# *546082B801F3_546F3804032D_impl*
end;//TncsOneFileDeliverer.MakeExecutor
procedure TncsOneFileDeliverer.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_546F3804032D_var*
//#UC END# *479731C50290_546F3804032D_var*
begin
//#UC START# *479731C50290_546F3804032D_impl*
f_Transporter := nil;
FreeAndNil(f_LocalDesc);
inherited;
//#UC END# *479731C50290_546F3804032D_impl*
end;//TncsOneFileDeliverer.Cleanup
{$IfEnd} // NOT Defined(Nemesis)
end.
|
program calcperm;
//////
// Intro
// Bit permutation code generator
// (c) 2011..2017 by Jasper L. Neumann
// www.sirrida.de / programming.sirrida.de
// E-Mail: info@sirrida.de
// Granted to the public domain
// First version: 2012-08-31
// Last change: 2013-03-26
// Compile with
// Delphi: dcc32 /cc calcperm.pas
// Free Pascal: fpc -Mtp calcperm.pas
// Gnu Pascal: gpc calcperm.pas
//////
// Head
(*$r-*) // range check off
(*$q-*) // overflow check off
{$i general.pas }
// Choose a working size by including the needed perm_b*.pas here:
{$i perm_b32.pas }
{$i perm_bas.pas }
const
nr_hex_digits = bits shr 2; // each hexdigit encodes 4 bits
type
t_string = string;
//////
// Configuration parameter variables
var
options: record
// Output options
dump_input: t_bool;
dump_inverse: t_bool;
brief: t_bool;
verbose: t_bool;
// Language dependence
comment_prefix: t_string;
comment_postfix: t_string;
hex_prefix: t_string;
hex_postfix: t_string;
op_assign: t_string;
op_and: t_string;
op_or: t_string;
op_xor: t_string;
op_shl: t_string;
op_shr: t_string;
// Function names
op_pstep: t_string;
op_pstep_simple: t_string;
op_rol: t_string;
op_gather: t_string;
op_scatter: t_string;
op_bswap: t_string;
// Input options
in_origin: t_int; // input index origin
in_base: t_int; // input number base
in_indexes_are_target: t_bool; // /in_indexes=source or target
// General costs
cost_rotate_shift: t_int;
cost_bool: t_int;
cost_bswap: t_int;
cost_mul: t_int;
cost_gs: t_int;
cost_mask: t_int;
// Special costs
cost_rotate: t_int;
cost_shift: t_int;
cost_and: t_int;
cost_or: t_int;
cost_xor: t_int;
cost_scatter: t_int;
cost_gather: t_int;
cost_bit_permute_step: t_int;
cost_bit_permute_step_simple: t_int;
// Superscalar boni
bonus_bit_permute_step: t_int;
bonus_bit_permute_step_simple: t_int;
bonus_gs: t_int;
bonus_mask_rol: t_int;
bonus_gs_rol: t_int;
// Calculation options
allow_bswap: t_bool;
allow_bmi: t_bool;
test_bpc: t_bool;
test_bfly: t_bool;
test_ibfly: t_bool;
test_benes: t_bool;
test_bit_groups: t_bool;
test_mul: t_bool;
test_gather_scatter: t_bool;
test_gather_shift: t_bool;
test_gather_shift_sloppy: t_bool;
test_shift_scatter: t_bool;
test_shift_scatter_sloppy: t_bool;
test_sag: t_bool;
opt_gs: t_bool;
opt_rol: t_bool;
opt_rol_ex: t_bool;
opt_bswap: t_bool;
self_test: t_bool;
end;
procedure error_abort;
begin
writeln('ERROR');
HALT(1);
end;
//////
// Auxiliary routines
function min(a,b:t_longint):t_longint;
begin
if a < b then begin
min := a;
end
else begin
min := b;
end;
end;
function max(a,b:t_longint):t_longint;
begin
if a > b then begin
max := a;
end
else begin
max := b;
end;
end;
function cl_mul(x,y:t_bits):t_bits;
var
res: t_bits;
begin
res := 0;
while x <> 0 do begin
if odd(x) then begin
res:=res xor y;
end;
y := y shl 1;
x := x shr 1;
end;
cl_mul := res;
end;
function mul_is_carryless(x,y:t_bits):t_bool;
var
res: t_bool;
q: t_bits;
begin
res := true;
q := 0;
while x <> 0 do begin
if odd(x) then begin
if (q and y) <> 0 then begin
res := false;
BREAK;
end;
q := q or y;
end;
y := y shl 1;
x := x shr 1;
end;
mul_is_carryless := res;
end;
function carries_of_mul(x,y:t_bits):t_bits;
var
res: t_bits;
q: t_bits;
begin
res := 0;
q := 0;
while x <> 0 do begin
if odd(x) then begin
res := res or (q and y);
q := q or y;
end;
y := y shl 1;
x := x shr 1;
end;
carries_of_mul := res;
end;
function mask_hi(x:t_bits):t_bits;
// Mask all but highest 0 bit.
var
res: t_bits;
begin
repeat
res := x;
x := x or (x+1); // turn on rightmost bit
until x = all_bits;
mask_hi := res;
end;
function pdep(x,m:t_bits):t_bits;
// scatter
begin
pdep := expand_right(x,m,ld_bits);
end;
function pext(x,m:t_bits):t_bits;
// gather
begin
pext := compress_right(x,m,ld_bits);
end;
function locase(x:t_char):t_char;
begin
if ('A'<=x) AND
(x<='Z') then begin
x := chr(ord(x)-(ord('a')-ord('A')));
end;
locase := x;
end;
function lostr(const x:t_string):t_string;
var
i: t_int;
res: t_string;
begin
res := '';
for i:=1 to length(x) do begin
res := res+locase(x[i]);
end;
lostr := res;
end;
function upcase(x:t_char):t_char;
begin
if ('a'<=x) AND
(x<='z') then begin
x := chr(ord(x)-(ord('A')-ord('a')));
end;
upcase := x;
end;
function upstr(const x:t_string):t_string;
var
i: t_int;
res: t_string;
begin
res := '';
for i:=1 to length(x) do begin
res := res+upcase(x[i]);
end;
upstr := res;
end;
function num(x:t_int):t_string;
// Convert an integer to a string containing the decimal representation.
var
res: t_string;
neg: t_bool;
begin
// num := inttostr(x);
if x = 0 then begin
res := '0';
end
else begin
neg := x < 0;
if neg then begin
x := -x;
end;
res := '';
while x <> 0 do begin
res := chr((x mod 10)+ord('0'))+res;
x := x div 10;
end;
if neg then begin
res := '-'+res;
end;
end;
num := res;
end;
function hex(x:t_bits):t_string;
// Convert a positive integer to a string
// containing the hexadecimal representation.
const
digits: array [0..15] of char = '0123456789abcdef';
var
res: t_string;
i: t_int;
begin
// hex := hex_prefix+inttohex(x,nr_hex_digits)+hex_postfix;
res := '';
for i := 1 to nr_hex_digits do begin
res := digits[x and 15]+res;
x := x shr 4;
end;
hex := options.hex_prefix+res;
end;
function q2s(x:t_bool):t_string;
begin
if x then begin
q2s:='true';
end
else begin
q2s:='false';
end;
end;
function s2i(const s:t_string):t_longint;
// Convert a string to an integer.
// Simply halts the program in case of an error
// since we use no exception mechanism for simplicity.
var
len: t_int;
i: t_int;
q: t_int;
v: t_longint;
neg: t_bool;
begin
len := length(s);
// Trim trailing spaces
while (len > 0) AND
(s[len] = ' ') do begin
len := len - 1;
end;
q := 1;
// Trim leading spaces
while (q <= len) AND
(s[q] = ' ') do begin
q := q + 1;
end;
neg := false;
// Accept one "-" char
if (q <= len) AND
(s[q] = '-') then begin
neg := true;
q := q + 1;
// Trim more spaces
while (q <= len) AND
(s[q] = ' ') do begin
q := q + 1;
end;
end;
v := 0;
for i := q to len do begin
if s[i] = '_' then begin
// Skip "_" chars
end
else if (s[i] >= '0') AND
(s[i] <= '9') then begin
v := v*10 + (ord(s[i]) - ord('0'));
end
else begin
writeln('ERROR: Number expected in '+s);
error_abort;
end;
end;
if neg then begin
v := -v;
end;
s2i := v;
end;
const
max_pprim = bits;
max_pstep = ld_bits * 2 + 3; // one each extra rol/bswap, one spare
type
tq_prim_kind = (
pk_none,
pk_permute,
pk_permute_simple,
pk_mask,
pk_mask_rol,
pk_mask_shift,
pk_rol,
pk_mul,
pk_gather_scatter,
pk_gather,
pk_gather_shift,
pk_scatter,
pk_shift_scatter,
pk_bswap);
tr_pprim = record
// one permutation substep, these are ORed together
kind: tq_prim_kind;
mask: t_bits; // permute, masked_rol, gather
mask2: t_bits; // scatter, mul
mul: t_bits; // mul
rol: t_int; // rotate/shift count
rol2: t_int; // mul (not yet used)
end;
tr_pstep = record
// one permutation step
description: t_string;
needed_src_bits: t_bits;
resulting_src_bits: t_bits;
nr_pprim: t_int;
a_pprim: array [0..max_pprim-1] of tr_pprim;
end;
tr_imp = record
// complete permutation
perm: ta_index;
description: t_string;
nr_step: t_int;
a_step: array [0..max_pstep-1] of tr_pstep;
needed_src_bits: t_bits;
is_bfly: t_bool; // used in route_benes
end;
tr_gather_scatter = record
// for routing gather/scatter and derivatives
mask_src,mask_tgt: t_bits;
end;
tar_gather_scatter = array [0..bits-1] of tr_gather_scatter;
tr_performance = record
cost: t_int;
cmask: t_int;
end;
var
pre_imp: tr_imp;
post_imp: tr_imp;
procedure imp_dump(const self:tr_imp); forward;
procedure dump_perm(const perm:ta_index); forward;
//////
// Evaluating routines
function pprim_eval(const self:tr_pprim; x:t_bits):t_bits;
var
res: t_bits;
begin
case self.kind of
pk_none: res := x;
pk_permute: res := bit_permute_step(x, self.mask, self.rol);
pk_permute_simple: res := bit_permute_step_simple(x, self.mask, self.rol);
pk_rol: res := rol(x, self.rol);
pk_mask: res := x and self.mask;
pk_mask_rol: res := rol(x and self.mask, self.rol);
pk_mask_shift: begin
if self.rol >= 0 then begin
res := (x and self.mask) shl self.rol;
end
else begin
res := (x and self.mask) shr (-self.rol);
end;
end;
pk_mul: res := rol(t_bits((rol(x, self.rol) and self.mask)*self.mul) and self.mask2, self.rol2);
pk_gather_scatter: res := pdep(pext(x, self.mask), self.mask2);
pk_gather: res := pext(x, self.mask);
pk_gather_shift: res := (pext(x, self.mask) shl self.rol);
pk_scatter: res := pdep(x, self.mask2);
pk_shift_scatter: res := pdep(x shr ((-self.rol) and (bits-1)), self.mask2);
pk_bswap: res := bswap(x);
else begin
res := 0;
writeln('ERROR: pprim_eval: unknown kind '+num(ord(self.kind)));
error_abort;
end;
end;
pprim_eval := res;
end;
function pstep_eval(const self:tr_pstep; x:t_bits):t_bits;
var
i: t_int;
res: t_bits;
begin
if self.nr_pprim = 0 then begin
res := x;
end
else begin
res := pprim_eval(self.a_pprim[0], x);
for i := 1 to self.nr_pprim-1 do begin
res := res or pprim_eval(self.a_pprim[i], x);
end;
end;
pstep_eval := res;
end;
function imp_eval(const self:tr_imp; x:t_bits):t_bits;
var
i: t_int;
res: t_bits;
begin
res := x;
for i := 0 to self.nr_step-1 do begin
res := pstep_eval(self.a_step[i], res);
end;
imp_eval := res;
end;
procedure imp_check(const imp:tr_imp);
var
q: t_int;
mask: t_bits;
x: t_bits;
error: t_bool;
inv_perm: ta_index;
begin
error := false;
mask := 1;
for q := 0 to bits-1 do begin
if imp.perm[q] <> no_index then begin
x := lo_bit shl imp.perm[q];
x := imp_eval(imp, x);
if x <> mask then begin
error := true;
BREAK;
end;
end;
mask := mask shl 1;
end;
if error then begin
writeln('ERROR (mask)');
dump_perm(imp.perm);
imp_dump(imp);
invert_perm(imp.perm,inv_perm);
mask := 1;
for q := 0 to bits-1 do begin
x := imp_eval(imp, mask);
write(hex(mask)+' => '+hex(x));
if (inv_perm[q] <> no_index) AND
(lo_bit shl inv_perm[q] <> x) then begin
writeln(' ERROR, expected: '+hex(lo_bit shl inv_perm[q]));
end
else begin
writeln(' OK');
end;
mask := mask shl 1;
end;
error_abort;
end;
if imp.nr_step <> 0 then begin
if imp_eval(imp, imp.needed_src_bits) <>
imp.a_step[imp.nr_step-1].resulting_src_bits then begin
writeln('ERROR (needed bits defective)');
dump_perm(imp.perm);
imp_dump(imp);
error_abort;
end;
end;
end;
//////
// Init routines
procedure init_gather_scatter(var self:tr_gather_scatter);
begin
self.mask_src := 0;
self.mask_tgt := 0;
end;
procedure init_pprim(var self:tr_pprim);
begin
self.kind := pk_none;
self.mask := 0;
self.mask2 := 0;
self.mul := 0;
self.rol := 0;
self.rol2 := 0;
end;
procedure init_pstep(var self:tr_pstep);
var
i: t_int;
begin
self.description := '';
self.needed_src_bits := 0;
self.resulting_src_bits := 0;
self.nr_pprim := 0;
for i := 0 to max_pprim-1 do begin
init_pprim(self.a_pprim[i]);
end;
end;
procedure init_imp0(var self:tr_imp; const perm:ta_index);
var
needed: t_bits;
i: t_int;
begin
needed := used_source_bits(perm);
self.perm := perm;
self.description := '';
self.nr_step := 0;
for i := 0 to max_pstep-1 do begin
init_pstep(self.a_step[i]);
end;
self.needed_src_bits := needed;
self.is_bfly := false;
self.a_step[0].needed_src_bits := needed;
end;
procedure init_imp(var self:tr_imp; var perm:ta_index);
var
perm1: ta_index;
q: t_int;
x: t_bits;
begin
self := pre_imp;
for q := 0 to bits-1 do begin
perm[q] := no_index;
perm1[q] := no_index;
end;
for q := 0 to bits-1 do begin
if pre_imp.perm[q] <> no_index then begin
x := lo_bit shl pre_imp.perm[q];
x := imp_eval(pre_imp, x);
perm1[q] := nr_trailing_0bits(x);
assert(x = lo_bit shl perm1[q]);
end;
end;
for q := 0 to bits-1 do begin
x := lo_bit shl q;
x := imp_eval(post_imp, x);
perm[q] := perm1[nr_trailing_0bits(x)];
end;
end;
//////
// Count mask routines
function pprim_cmask(const self:tr_pprim):t_int;
var
res: t_int;
begin
case self.kind of
pk_none: res := 0;
pk_permute: res := 1;
pk_permute_simple: res := 1;
pk_rol: res := 0;
pk_mask: res := 1;
pk_mask_rol: res := 1;
pk_mask_shift: res := 1;
pk_mul: res := 3;
pk_gather_scatter: res := 2;
pk_gather: res := 1;
pk_gather_shift: res := 1;
pk_scatter: res := 1;
pk_shift_scatter: res := 1;
pk_bswap: res := 0;
else begin
writeln('ERROR: pprim_cmask: unknown kind');
res := 0;
error_abort;
end;
end;
pprim_cmask := res;
end;
function pstep_cmask(const self:tr_pstep):t_int;
var
i: t_int;
res: t_int;
begin
res := 0;
for i := 0 to self.nr_pprim-1 do begin
res := res + pprim_cmask(self.a_pprim[i]);
end;
pstep_cmask := res;
end;
function imp_cmask(const self:tr_imp):t_int;
var
i: t_int;
res: t_int;
begin
res := 0;
for i := 0 to self.nr_step-1 do begin
res := res + pstep_cmask(self.a_step[i]);
end;
imp_cmask := res;
end;
//////
// Cost routines
function pprim_cost(const self:tr_pprim):t_int;
var
res: t_int;
begin
case self.kind of
pk_none: res := 0;
pk_permute: res := options.cost_bit_permute_step;
pk_permute_simple: res := options.cost_bit_permute_step_simple;
pk_rol: res := options.cost_rotate;
pk_mask: res := options.cost_and;
pk_mask_rol: res := options.cost_and+options.cost_rotate;
pk_mask_shift: res := options.cost_and+options.cost_shift;
pk_mul: begin
res := options.cost_mul + options.cost_and * 2;
if self.rol<>0 then begin
res := res + options.cost_rotate;
end;
if self.rol2<>0 then begin
res := res + options.cost_rotate;
end;
end;
pk_gather_scatter: res := options.cost_scatter+options.cost_gather;
pk_gather: res := options.cost_gather;
pk_gather_shift: res := options.cost_gather+options.cost_shift;
pk_scatter: res := options.cost_scatter;
pk_shift_scatter: res := options.cost_shift+options.cost_scatter;
pk_bswap: res := options.cost_shift+options.cost_bswap;
else begin
writeln('ERROR: pprim_cost: unknown kind');
res := 0;
error_abort;
end;
end;
pprim_cost := res + pprim_cmask(self) * options.cost_mask;
end;
function pstep_cost(const self:tr_pstep):t_int;
const
s_gs = [
pk_gather_scatter,
pk_gather,
pk_gather_shift,
pk_scatter,
pk_shift_scatter];
s_mr = [
pk_rol,
pk_mask,
pk_mask_rol,
pk_mask_shift,
pk_mul];
var
i: t_int;
res: t_int;
begin
if self.nr_pprim = 0 then begin
res := 0;
end
else begin
res := pprim_cost(self.a_pprim[0]);
for i := 1 to self.nr_pprim-1 do begin
res := res + options.cost_or + pprim_cost(self.a_pprim[i]);
if (self.a_pprim[i-1].kind in s_gs) AND
(self.a_pprim[i].kind in s_gs) then begin
res := res - options.bonus_gs;
end
else if (self.a_pprim[i-1].kind in s_mr) AND
(self.a_pprim[i].kind in s_mr) then begin
res := res - options.bonus_mask_rol;
end
else if (self.a_pprim[i-1].kind in s_mr) AND
(self.a_pprim[i].kind in s_gs) then begin
res := res - options.bonus_gs_rol;
end
else if (self.a_pprim[i-1].kind in s_gs) AND
(self.a_pprim[i].kind in s_mr) then begin
res := res - options.bonus_gs_rol;
end;
end;
case self.a_pprim[0].kind of
pk_permute: res := res - options.bonus_bit_permute_step;
pk_permute_simple: res := res - options.bonus_bit_permute_step_simple;
else ;
end;
end;
pstep_cost := res;
end;
function imp_cost(const self:tr_imp):t_int;
var
i: t_int;
res: t_int;
begin
res := 0;
for i := 0 to self.nr_step-1 do begin
res := res + pstep_cost(self.a_step[i]);
end;
imp_cost := res;
end;
//////
// Performance routines
procedure init_performance(var self:tr_performance);
begin
self.cost := maxint;
self.cmask := maxint;
end;
function cmp_performance(const a,b:tr_performance):t_int;
// -1: a<b
// 0: a=b
// 1: a>b
var
res: t_int;
begin
if a.cost < b.cost then begin
res := -1;
end
else if a.cost > b.cost then begin
res := 1;
end
else if a.cmask < b.cmask then begin
res := -1;
end
else if a.cmask > b.cmask then begin
res := 1;
end
else begin
res := 0;
end;
cmp_performance := res;
end;
procedure imp_performance(const imp:tr_imp; var perf:tr_performance);
begin
perf.cost := imp_cost(imp);
perf.cmask := imp_cmask(imp);
end;
//////
// Dumping routines
var
progress_pos: t_int;
procedure progress;
const
chars: array [0..3] of t_char='-\|/';
begin
progress_pos := progress_pos+1;
write(chars[progress_pos and 3]);
write(#$0d);
end;
procedure dump_perm(const perm:ta_index);
var
i: t_int;
begin
for i := 0 to bits-1 do begin
if perm[i] = no_index then begin
write('* ');
end
else begin
write(num(perm[i])+' ');
end;
end;
writeln;
end;
function dump_performance(const perf:tr_performance):t_string;
begin
dump_performance :=
num(perf.cost)+
' cycles, '+
num(perf.cmask)+
' masks';
end;
function pprim_dump(const self:tr_pprim):t_string;
var
res: t_string;
begin
case self.kind of
pk_none: begin
res := '';
end;
pk_permute: begin
res := options.op_pstep+'(x, '+hex(self.mask)+', '+num(self.rol)+')';
end;
pk_permute_simple: begin
res := options.op_pstep_simple+
'(x, '+hex(self.mask)+', '+num(self.rol)+')';
end;
pk_rol: begin
res := options.op_rol+'(x, '+num(self.rol)+')';
end;
pk_mask: begin
res := '(x '+options.op_and+' '+hex(self.mask)+')';
end;
pk_mask_rol: begin
res := options.op_rol+
'(x '+options.op_and+' '+hex(self.mask)+', '+num(self.rol)+')';
end;
pk_mask_shift: begin
if self.rol >= 0 then begin
res := '((x '+options.op_and+' '+hex(self.mask)+') '+
options.op_shl+' '+num(self.rol)+')';
end
else begin
res := '((x '+options.op_and+' '+hex(self.mask)+') '+
options.op_shr+' '+num(-self.rol)+')';
end;
end;
pk_mul: begin
if self.rol=0 then begin
if self.rol2=0 then begin
res := '(((x '+options.op_and+' '+hex(self.mask)+') * '+
hex(self.mul)+') '+options.op_and+' '+hex(self.mask2)+')';
end
else begin
res := options.op_rol+
'(((x '+options.op_and+' '+hex(self.mask)+') * '+
hex(self.mul)+') '+options.op_and+' '+hex(self.mask2)+', '+
num(self.rol2 and (bits-1))+')';
end;
end
else begin
if self.rol2=0 then begin
res := '((('+options.op_rol+'(x, '+num(self.rol)+') '+
options.op_and+' '+hex(self.mask)+') * '+hex(self.mul)+') '+
options.op_and+' '+hex(self.mask2)+')';
end
else begin
res := options.op_rol+
'((('+options.op_rol+'(x, '+num(self.rol)+') '+
options.op_and+' '+hex(self.mask)+') * '+hex(self.mul)+') '+
options.op_and+' '+hex(self.mask2)+', '+
num(self.rol2 and (bits-1))+')';
end;
end;
end;
pk_gather_scatter: begin
res := options.op_scatter+
'('+options.op_gather+'(x, '+hex(self.mask)+'), '+hex(self.mask2)+')';
end;
pk_gather: begin
res := options.op_gather+'(x, '+hex(self.mask)+')';
end;
pk_gather_shift: begin
res := '('+options.op_gather+
'(x, '+hex(self.mask)+') '+options.op_shl+' '+num(self.rol)+')';
end;
pk_scatter: begin
res := options.op_scatter+'(x, '+hex(self.mask2)+')';
end;
pk_shift_scatter: begin
res := options.op_scatter+'(x '+options.op_shr+' '+
num((-self.rol) and (bits-1))+', '+hex(self.mask2)+')';
end;
pk_bswap: begin
res := options.op_bswap+'(x)';
end;
else begin
res := '';
writeln('ERROR: pprim_dump: unknown kind');
error_abort;
end;
end;
pprim_dump := res;
end;
procedure pstep_dump(const self:tr_pstep);
var
i: t_int;
begin
if self.nr_pprim <> 0 then begin
write('x '+options.op_assign+' '+pprim_dump(self.a_pprim[0]));
for i := 1 to self.nr_pprim-1 do begin
writeln;
write(' '+options.op_or+' '+pprim_dump(self.a_pprim[i]));
end;
write(';');
end;
end;
procedure imp_dump_simple(const self:tr_imp);
var
perf: tr_performance;
begin
imp_performance(self, perf);
writeln(
self.description+
': '+
dump_performance(perf));
end;
procedure imp_dump(const self:tr_imp);
var
i: t_int;
begin
imp_dump_simple(self);
for i := 0 to self.nr_step-1 do begin
pstep_dump(self.a_step[i]);
if self.a_step[i].description <> '' then begin
write(' '+options.comment_prefix+self.a_step[i].description+options.comment_postfix);
end;
writeln;
end;
end;
//////
// Code construction routines
procedure concat_description(var tgt:t_string; const src:t_string);
begin
if tgt = '' then begin
tgt := src;
end
else if src <> '' then begin
tgt := tgt + ' + ' + src;
end;
end;
procedure finish_step(var imp:tr_imp);
var
needed,resulting: t_bits;
begin
if imp.nr_step = 0 then begin
needed := imp.needed_src_bits;
end
else begin
needed := imp.a_step[imp.nr_step-1].resulting_src_bits;
end;
resulting := pstep_eval(imp.a_step[imp.nr_step], needed);
imp.a_step[imp.nr_step].resulting_src_bits := resulting;
imp.nr_step := imp.nr_step+1;
imp.a_step[imp.nr_step].needed_src_bits := resulting;
end;
procedure finish_perm(var imp:tr_imp);
var
i: t_int;
begin
for i := 0 to post_imp.nr_step-1 do begin
imp.a_step[imp.nr_step] := post_imp.a_step[i];
finish_step(imp);
end;
concat_description(imp.description, post_imp.description);
end;
procedure add_permute(var imp:tr_imp; mask:t_bits; rol:t_int);
// Add a permute step
var
n: t_bits;
begin
if mask <> 0 then begin
rol := rol and (bits-1);
imp.a_step[imp.nr_step].a_pprim[0].rol := rol;
imp.a_step[imp.nr_step].a_pprim[0].mask := mask;
n := imp.a_step[imp.nr_step].needed_src_bits;
if nr_1bits(bit_permute_step_simple(n,mask,rol)) = nr_1bits(n) then begin
// bit_permute_step_simple does not kill needed bits
imp.a_step[imp.nr_step].a_pprim[0].kind := pk_permute_simple;
end
else begin
// we need a full permute step
imp.a_step[imp.nr_step].a_pprim[0].kind := pk_permute;
end;
imp.a_step[imp.nr_step].nr_pprim := 1;
finish_step(imp);
end;
end;
procedure make_rol_step(var pstep:tr_pstep; mask:t_bits; rol:t_int);
// Add a mask/rol step
begin
rol := rol and (bits-1);
pstep.a_pprim[pstep.nr_pprim].rol := rol;
pstep.a_pprim[pstep.nr_pprim].mask := mask;
if mask = all_bits then begin
// nothing to mask
pstep.a_pprim[pstep.nr_pprim].kind := pk_rol;
end
else if rol = 0 then begin
// nothing to rotate
pstep.a_pprim[pstep.nr_pprim].kind := pk_mask;
end
else if (t_bits(mask shl rol) shr rol) = mask then begin
// shift left is sufficient
pstep.a_pprim[pstep.nr_pprim].kind := pk_mask_shift;
end
else if (t_bits(mask shr (bits-rol)) shl (bits-rol)) = mask then begin
// shift right is sufficient
pstep.a_pprim[pstep.nr_pprim].kind := pk_mask_shift;
pstep.a_pprim[pstep.nr_pprim].rol := rol-bits; // < 0
end
else begin
// we need a rotate; a shift is not enough
pstep.a_pprim[pstep.nr_pprim].kind := pk_mask_rol;
end;
end;
procedure add_rol_step(var pstep:tr_pstep; mask:t_bits; rol:t_int);
begin
rol := rol and (bits-1);
if (mask <> 0) AND
( (mask <> all_bits) OR
(rol <> 0) ) then begin
make_rol_step(pstep, mask, rol);
pstep.nr_pprim := pstep.nr_pprim+1;
end;
end;
procedure add_rol(var imp:tr_imp; mask:t_bits; rol:t_int);
begin
add_rol_step(imp.a_step[imp.nr_step], mask, rol);
end;
procedure add_bswap_step(var pstep:tr_pstep);
begin
pstep.a_pprim[pstep.nr_pprim].kind := pk_bswap;
pstep.nr_pprim := pstep.nr_pprim+1;
end;
procedure add_bswap(var imp:tr_imp);
begin
add_bswap_step(imp.a_step[imp.nr_step]);
end;
procedure add_gs_step(var pstep:tr_pstep; mask,mask2:t_bits);
// Add a gather/scatter step
var
t1,t2: t_int;
begin
if mask <> 0 then begin
pstep.a_pprim[pstep.nr_pprim].rol := 0;
pstep.a_pprim[pstep.nr_pprim].mask := mask;
pstep.a_pprim[pstep.nr_pprim].mask2 := mask2;
t1 := nr_trailing_0bits(mask);
t2 := nr_trailing_0bits(mask2);
if mask = mask2 then begin
// we scatter what we gather, only masking needed
pstep.a_pprim[pstep.nr_pprim].kind := pk_mask;
end
else if (mask shr t1) = (mask2 shr t2) then begin
// the masks differ by a shift, so mask and rotate
make_rol_step(pstep, mask, t2-t1);
end
else if is_contiguous_1bits(mask2) then begin
// the target bits are contiguous
if t2 = 0 then begin
// single gather, no shift necessary
pstep.a_pprim[pstep.nr_pprim].kind := pk_gather;
end
else begin
// gather and shift
pstep.a_pprim[pstep.nr_pprim].kind := pk_gather_shift;
pstep.a_pprim[pstep.nr_pprim].rol := t2;
end;
end
else if is_contiguous_1bits(mask) then begin
// the source bits are contiguous
if t1 = 0 then begin
// single scatter, no shift necessary
pstep.a_pprim[pstep.nr_pprim].kind := pk_scatter;
end
else begin
// shift to 0 position and scatter
pstep.a_pprim[pstep.nr_pprim].kind := pk_shift_scatter;
pstep.a_pprim[pstep.nr_pprim].rol := (-t1) and (bits-1);
end;
end
else begin
// last resort: gather and scatter
pstep.a_pprim[pstep.nr_pprim].kind := pk_gather_scatter;
end;
pstep.nr_pprim := pstep.nr_pprim+1;
end;
end;
procedure add_gs(var imp:tr_imp; mask,mask2:t_bits);
begin
add_gs_step(imp.a_step[imp.nr_step], mask, mask2);
end;
procedure add_sag_step(var pstep:tr_pstep; mask:t_bits; rol:t_int);
// Add a sheep and goats step
var
lo_mask: t_bits;
begin
rol := rol and (bits-1);
lo_mask := (lo_bit shl rol)-1;
add_gs_step(pstep, mask, lo_mask shl rol);
add_gs_step(pstep, (not mask) and (lo_mask+(lo_mask shl rol)), lo_mask);
end;
procedure add_sag(var imp:tr_imp; mask:t_bits; rol:t_int);
begin
add_sag_step(imp.a_step[imp.nr_step], mask, rol);
finish_step(imp);
end;
procedure add_mul_step(var pstep:tr_pstep; mask,mul,mask2:t_bits; rol,rol2:t_int);
// Add a mul step
begin
if mask <> 0 then begin
pstep.a_pprim[pstep.nr_pprim].kind := pk_mul;
pstep.a_pprim[pstep.nr_pprim].rol := rol and (bits-1);
pstep.a_pprim[pstep.nr_pprim].rol2 := rol2 and (bits-1);
pstep.a_pprim[pstep.nr_pprim].mask := mask;
pstep.a_pprim[pstep.nr_pprim].mask2 := mask2;
pstep.a_pprim[pstep.nr_pprim].mul := mul;
pstep.nr_pprim := pstep.nr_pprim+1;
end;
end;
//////
// Routing routines
function is_identity:t_bool;
var
imp: tr_imp;
perm: ta_index;
i: t_int;
res: t_bool;
begin
res := true;
init_imp(imp,perm);
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
if i<>perm[i] then begin
res := false;
end;
end;
end;
is_identity := res;
end;
procedure route_benes(var imp:tr_imp; const a_stage:ta_subword);
var
perm: ta_index;
benes: tr_benes;
stage_idx,stage: t_int;
begin
init_imp(imp,perm);
gen_benes_ex(benes,perm,a_stage);
concat_description(imp.description, 'Benes ');
imp.is_bfly := true;
for stage_idx := 0 to ld_bits-1 do begin
stage := a_stage[stage_idx];
imp.description := imp.description+num(stage);
if benes.b1.cfg[stage] <> 0 then begin
imp.is_bfly := false;
add_permute(imp, benes.b1.cfg[stage], 1 shl stage);
end;
end;
for stage_idx := ld_bits-1 downto 0 do begin
stage := a_stage[stage_idx];
if benes.b2.cfg[stage] <> 0 then begin
add_permute(imp, benes.b2.cfg[stage], 1 shl stage);
end;
end;
finish_perm(imp);
end;
procedure route_bit_groups(var imp:tr_imp);
var
perm: ta_index;
i,j,k,count,min_pos: t_int;
s: t_bits; // set of differences
masks: array [0..bits-1] of t_bits;
begin
init_imp(imp,perm);
concat_description(imp.description, 'Bit group moving');
s := 0;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
s := s or (lo_bit shl ((i-perm[i]) and (bits-1)));
end;
end;
count := 0;
min_pos := 0;
for i := bits-1 downto 0 do begin
if ((lo_bit shl i) and s) <> 0 then begin
count := count+1;
min_pos := i;
end;
end;
case count of
0: begin
finish_perm(imp);
EXIT;
end;
1: begin
if min_pos = 0 then begin
finish_perm(imp);
EXIT;
end;
add_rol(imp, all_bits, min_pos);
finish_step(imp);
finish_perm(imp);
EXIT;
end;
else ;
end;
for i := 0 to bits-1 do begin
masks[i] := 0;
end;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
j := (i-perm[i]) and (bits-1);
k := (i-j) and (bits-1);
masks[j] := masks[j] or (lo_bit shl k);
end;
end;
for i := 0 to bits-1 do begin
add_rol(imp, masks[i], i);
end;
finish_step(imp);
finish_perm(imp);
end;
procedure route_mul1(var imp:tr_imp);
// 2013-03-19 J. Neumann
var
perm: ta_index;
i: t_int;
idx: t_int;
best_idx: t_int;
diff: t_int;
rotate: t_int;
u,use,m,mul,tgt: t_bits;
empty: t_bool;
pop, best_pop: t_int;
save_perm: ta_index;
nr_pprim: t_int;
redo: t_bool;
my_cost_mul, my_cost_rol: t_int;
begin
init_imp(imp,perm);
concat_description(imp.description, 'Shift by mul (1)');
nr_pprim := imp.a_step[imp.nr_step].nr_pprim;
save_perm := perm;
repeat
redo := false;
rotate := 0;
while true do begin
empty := true;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
empty := false;
BREAK;
end;
end;
if empty then begin
BREAK;
end;
best_idx := 0;
best_pop := 0;
for idx := 0 to bits-1 do begin
// Pseudo-calc
mul := 0;
use := 0;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
diff := i-((perm[i]-idx) and (bits-1));
if diff < 0 then begin
CONTINUE; // Can not be reached by mul
end;
u := lo_bit shl ((perm[i]-idx) and (bits-1));
m := lo_bit shl diff;
if (t_bits(mul*use) and t_bits(mul*u)) <> 0 then begin
CONTINUE; // Conflict
end;
if (m and mul) <> 0 then begin
// already handled
end
else begin
// new entry
if (t_bits(mul*(use or u)) and t_bits(m*(use or u))) <> 0 then begin
CONTINUE; // Conflict
end;
mul := mul or m;
end;
use := use or u;
end;
end;
pop := nr_1bits(mul) * 10 + nr_1bits(use);
if ((idx+rotate) and (bits-1)) = 0 then begin
pop := pop + 5; // prefer not to rotate
end;
if pop > best_pop then begin
best_idx := idx;
best_pop := pop;
end;
end;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
perm[i] := (perm[i]-best_idx) and (bits-1);
end;
end;
rotate := rotate + best_idx;
mul := 0;
use := 0;
tgt := 0;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
diff := i-perm[i];
if diff < 0 then begin
CONTINUE; // Can not be reached by mul
end;
u := lo_bit shl perm[i];
m := lo_bit shl diff;
if (t_bits(mul*use) and t_bits(mul*u)) <> 0 then begin
CONTINUE; // Conflict
end;
if (m and mul) <> 0 then begin
// already handled
end
else begin
// new entry
if (t_bits(mul*(use or u)) and t_bits(m*(use or u))) <> 0 then begin
CONTINUE; // Conflict
end;
mul := mul or m;
end;
use := use or u;
tgt := tgt or (lo_bit shl i);
perm[i] := no_index;
end;
end;
my_cost_mul :=
// +options.cost_rotate*ord(rotate<>0)
+options.cost_rotate
+options.cost_mul
+options.cost_and*2
+options.cost_mask*2
+options.cost_or
-options.bonus_mask_rol;
my_cost_rol :=
// -ord((mul and 1)<>0)*options.cost_rotate
+nr_1bits(mul)*(
+options.cost_and
+options.cost_rotate
+options.cost_or
+options.cost_mask
-options.bonus_mask_rol);
if my_cost_mul <= my_cost_rol then begin
add_mul_step(imp.a_step[imp.nr_step], use,mul,tgt,-rotate,0);
end
else begin
diff := (rotate-nr_trailing_0bits(mul)) and (bits-1);
use := 0;
for i := 0 to bits-1 do begin
if save_perm[i] <> no_index then begin
if ((save_perm[i]-i) and (bits-1)) = diff then begin
use := use or (lo_bit shl ((i+diff) and (bits-1)));
save_perm[i] := no_index;
end;
end;
end;
imp.a_step[imp.nr_step].nr_pprim := nr_pprim;
add_rol(imp, use, -diff);
nr_pprim := imp.a_step[imp.nr_step].nr_pprim;
perm := save_perm;
redo := true;
BREAK;
end;
end;
until NOT redo;
finish_step(imp);
finish_perm(imp);
end;
procedure route_mul2(var imp:tr_imp);
// 2013-03-22 J. Neumann
var
perm: ta_index;
i,j,best_count: t_int;
rotate: t_int;
mask,u,use,m,mul,used,tgt,use0,u1: t_bits;
found: t_bool;
my_cost_mul, my_cost_rol: t_int;
masks: array [0..bits-1] of t_bits;
counts: array [0..bits-1] of t_int; // nr_1bits(masks[i])
begin
init_imp(imp,perm);
concat_description(imp.description, 'Shift by mul (2)');
mask := 0;
for i := 0 to bits-1 do begin
masks[i] := 0;
counts[i] := 0;
end;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
j := (i-perm[i]) and (bits-1);
u := lo_bit shl ((i-j) and (bits-1));
mask := mask or u;
masks[j] := masks[j] or u;
counts[j] := counts[j] + 1;
end;
end;
while mask<>0 do begin
best_count := 0;
i := 0;
for j := 0 to bits-1 do begin
if masks[j]<>0 then begin
if counts[j]>best_count then begin
best_count := counts[j];
i := j;
end;
end;
end;
use := rol(masks[i],i); // used bits
rotate := i;
used := lo_bit shl i; // set of indexes which masks are used
mul := 1;
tgt := use;
use0 := use;
my_cost_rol := 1;
repeat
found := false;
for i := 0 to bits-1 do begin
if (masks[i] <> 0) AND
((used and (lo_bit shl i)) = 0) then begin
u := rol(masks[i],rotate);
j := ((i-rotate) and (bits-1));
m := lo_bit shl j;
if nr_1bits(m*u) = nr_1bits(u) then begin
// if carries_of_mul(mul or m, use or u) = 0 then begin
if (carries_of_mul(mul or m, use or u) and
mask_hi(tgt or (u shl j))) = 0 then begin
my_cost_rol := my_cost_rol + 1;
use := use or u;
mul := mul or m;
used := used or (lo_bit shl i);
tgt := tgt or (u shl j);
found := true;
end;
end;
end;
end;
until NOT found;
my_cost_mul :=
+options.cost_rotate*ord(rotate<>0)
+options.cost_mul
+options.cost_and*2
+options.cost_mask*2
+options.cost_or
-options.bonus_mask_rol;
my_cost_rol :=
my_cost_rol*(
+options.cost_and
+options.cost_rotate
+options.cost_or
+options.cost_mask
-options.bonus_mask_rol);
if my_cost_mul >= my_cost_rol then begin
mask := mask and not masks[rotate];
masks[rotate] := 0;
add_rol(imp, rol(use0,-rotate), rotate);
end
else begin
for i := 0 to bits-1 do begin
if (used and (lo_bit shl i)) <> 0 then begin
mask := mask and not masks[i];
masks[i] := 0;
counts[i] := 0;
end;
end;
repeat
found := false;
for i := bits-1 downto 0 do begin
if masks[i] <> 0 then begin
u := rol(masks[i],rotate);
j := ((i-rotate) and (bits-1));
m := lo_bit shl j;
while u<>0 do begin
u1 := u and (-u);
if nr_1bits(m*u1) = nr_1bits(u1) then begin
if (carries_of_mul(mul or m, use or u1) and
mask_hi(tgt or (u1 shl j))) = 0 then begin
// my_cost_rol := my_cost_rol + 1;
use := use or u1;
mul := mul or m;
// used := used or (lo_bit shl i);
tgt := tgt or (u1 shl j);
mask := mask and not rol(u1,-rotate);
masks[i] := masks[i] and not rol(u1,-rotate);
counts[i] := counts[i] - 1;
found := true;
end;
end;
u := u and not u1;
end;
end;
end;
until NOT found;
add_mul_step(imp.a_step[imp.nr_step], use,mul,tgt,rotate,0);
end;
end;
finish_step(imp);
finish_perm(imp);
end;
procedure route_mul3(var imp:tr_imp);
// 2013-03-19 J. Neumann
var
perm: ta_index;
i,j: t_int;
idx: t_int;
best_idx: t_int;
diff: t_int;
rotate: t_int;
u,use,m,mul,tgt: t_bits;
empty: t_bool;
pop, best_pop: t_int;
save_perm: ta_index;
nr_pprim: t_int;
redo: t_bool;
hibit: t_int;
himask: t_bits;
my_cost_mul, my_cost_rol: t_int;
begin
init_imp(imp,perm);
concat_description(imp.description, 'Shift by mul (3)');
nr_pprim := imp.a_step[imp.nr_step].nr_pprim;
save_perm := perm;
repeat
redo := false;
rotate := 0;
while true do begin
empty := true;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
empty := false;
BREAK;
end;
end;
if empty then begin
BREAK;
end;
best_idx := 0;
best_pop := 0;
for idx := 0 to bits-1 do begin
// Pseudo-calc
mul := 0;
use := 0;
hibit := 0;
for i := bits-1 downto 0 do begin
if perm[i] <> no_index then begin
j := ((perm[i]-idx) and (bits-1));
diff := i-j;
if diff < 0 then begin
CONTINUE; // Can not be reached by mul
end;
u := lo_bit shl j;
m := lo_bit shl diff;
if i > hibit then begin
j := i;
end
else begin
j := hibit;
end;
himask := (lo_bit shl j)*2-1;
if (t_bits(mul*use) and t_bits(mul*u) and himask) <> 0 then begin
CONTINUE; // Conflict
end;
if (m and mul) <> 0 then begin
// already handled
end
else begin
// new entry
if (t_bits(mul*(use or u)) and t_bits(m*(use or u)) and himask) <> 0 then begin
CONTINUE; // Conflict
end;
mul := mul or m;
end;
use := use or u;
if i > hibit then begin
hibit := i;
end;
end;
end;
pop := nr_1bits(mul) + nr_1bits(use) * 10;
if ((idx+rotate) and (bits-1)) = 0 then begin
pop := pop + 1; // prefer not to rotate
end;
if pop > best_pop then begin
best_idx := idx;
best_pop := pop;
end;
end;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
perm[i] := (perm[i]-best_idx) and (bits-1);
end;
end;
rotate := rotate + best_idx;
mul := 0;
use := 0;
tgt := 0;
hibit := 0;
for i := bits-1 downto 0 do begin
if perm[i] <> no_index then begin
diff := i-perm[i];
if diff < 0 then begin
CONTINUE; // Can not be reached by mul
end;
u := lo_bit shl perm[i];
m := lo_bit shl diff;
if i > hibit then begin
j := i;
end
else begin
j := hibit;
end;
himask := (lo_bit shl j)*2-1;
if (t_bits(mul*use) and t_bits(mul*u) and himask) <> 0 then begin
CONTINUE; // Conflict
end;
if (m and mul) <> 0 then begin
// already handled
end
else begin
// new entry
if (t_bits(mul*(use or u)) and t_bits(m*(use or u)) and himask) <> 0 then begin
CONTINUE; // Conflict
end;
mul := mul or m;
end;
use := use or u;
tgt := tgt or (lo_bit shl i);
if i > hibit then begin
hibit := i;
end;
perm[i] := no_index;
end;
end;
my_cost_mul :=
+options.cost_rotate*ord(rotate<>0)
+options.cost_mul
+options.cost_and*2
+options.cost_mask*2
+options.cost_or
-options.bonus_mask_rol;
my_cost_rol :=
+nr_1bits(mul)*(
+options.cost_and
+options.cost_rotate
+options.cost_or
+options.cost_mask
-options.bonus_mask_rol);
if my_cost_mul<=my_cost_rol then begin
add_mul_step(imp.a_step[imp.nr_step], use,mul,tgt,-rotate,0);
end
else begin
best_idx := 0;
best_pop := 0;
for idx := 0 to bits-1 do begin
if ((lo_bit shl idx) and mul) <> 0 then begin
diff := (rotate-idx) and (bits-1);
// Pseudo-calc
pop := 0;
for i := 0 to bits-1 do begin
if save_perm[i] <> no_index then begin
if ((save_perm[i]-i) and (bits-1)) = diff then begin
pop := pop + 1;
end;
end;
end;
if pop > best_pop then begin
best_idx := idx;
best_pop := pop;
end;
end;
end;
diff := (rotate-best_idx) and (bits-1);
use := 0;
for i := 0 to bits-1 do begin
if save_perm[i] <> no_index then begin
if ((save_perm[i]-i) and (bits-1)) = diff then begin
use := use or (lo_bit shl ((i+diff) and (bits-1)));
save_perm[i] := no_index;
end;
end;
end;
imp.a_step[imp.nr_step].nr_pprim := nr_pprim;
add_rol(imp, use, -diff);
nr_pprim := imp.a_step[imp.nr_step].nr_pprim;
perm := save_perm;
redo := true;
BREAK;
end;
end;
until NOT redo;
finish_step(imp);
finish_perm(imp);
end;
procedure route_sag(var imp:tr_imp);
// 2012-09-14 (Knuth)
var
perm: ta_index;
a: array [0..ld_bits-1] of record
mask: t_bits;
needed: t_bits;
end;
i,j: t_int;
mask_src: t_bits;
max_src,max_tgt: t_int;
my_ld_bits: t_int;
my_bits: t_int;
needed_src: t_bits;
inv_perm: ta_index;
perm1: ta_index;
perm2: ta_index;
begin
init_imp(imp,perm);
concat_description(imp.description, 'Sheep-and-goats method');
for i := 0 to ld_bits-1 do begin
a[i].mask := 0;
a[i].needed := 0;
end;
invert_perm(perm,inv_perm);
needed_src := 0; // set of needed source bits
mask_src := 1;
max_src := -1;
max_tgt := -1;
for i := 0 to bits-1 do begin
if perm[i] > max_tgt then begin
max_tgt := perm[i];
end;
if inv_perm[i] <> no_index then begin
needed_src := needed_src or mask_src;
if inv_perm[i] > max_src then begin
max_src := inv_perm[i];
end;
end;
mask_src := mask_src shl 1;
end;
// fill don't care entries ascending with hole indexes
j := 0;
for i := 0 to bits-1 do begin
if perm[i] <> no_index then begin
perm1[i] := perm[i];
end
else begin
while ((lo_bit shl j) and needed_src) <> 0 do begin
j := j+1;
end;
perm1[i] := j;
j := j+1;
end;
end;
if max_tgt < 0 then begin
finish_perm(imp);
EXIT; // nothing to do
end;
if max_src > max_tgt then begin
max_tgt := max_src;
end;
my_ld_bits := 0;
while max_tgt <> 0 do begin
my_ld_bits := my_ld_bits+1;
max_tgt := max_tgt shr 1;
end;
my_bits := 1 shl my_ld_bits;
invert_perm(perm1,perm2);
for i := 0 to my_ld_bits-1 do begin
for j := 0 to my_bits-1 do begin
a[i].mask := a[i].mask or (t_bits(((perm2[j] shr i) and 1)) shl j);
end;
a[i].needed := needed_src;
end;
for i := 0 to my_ld_bits-1 do begin
for j := i+1 to my_ld_bits-1 do begin
a[j].mask :=
compress_right(a[j].mask,not a[i].mask,my_ld_bits) or
(compress_right(a[j].mask,a[i].mask,my_ld_bits) shl (my_bits shr 1));
a[j].needed :=
compress_right(a[j].needed,not a[i].mask,my_ld_bits) or
(compress_right(a[j].needed,a[i].mask,my_ld_bits) shl (my_bits shr 1));
end;
add_sag(imp, a[i].mask, my_bits shr 1);
end;
finish_perm(imp);
end;
type
tf_aux_route_gs = function (
var a: tar_gather_scatter;
const perm: ta_index;
needed_src: t_bits;
needed_tgt: t_bits): t_int;
function aux_route_gather_scatter(
var a: tar_gather_scatter;
const perm: ta_index;
needed_src: t_bits;
needed_tgt: t_bits): t_int;
// FAR;
// 2012-09-27 J. Neumann
var
a_count: t_int;
s,t: t_int;
mask_src: t_bits;
mask_tgt: t_bits;
begin
a_count := 0;
while needed_src <> 0 do begin
s := 0;
t := -1;
while true do begin
t := t+1;
while (t < bits) AND
(((lo_bit shl t) and needed_tgt) = 0) do begin
t := t+1;
end;
if t >= bits then begin
BREAK;
end;
if perm[t] < s then begin
CONTINUE;
end;
s := perm[t];
// assert(s <> no_index);
mask_src := lo_bit shl s;
mask_tgt := lo_bit shl t;
a[a_count].mask_src := a[a_count].mask_src or mask_src;
a[a_count].mask_tgt := a[a_count].mask_tgt or mask_tgt;
needed_src := needed_src and not mask_src;
needed_tgt := needed_tgt and not mask_tgt;
end;
a_count := a_count+1;
end;
aux_route_gather_scatter := a_count;
end;
function aux_route_gather_shift_sloppy(
var a: tar_gather_scatter;
const perm: ta_index;
needed_src: t_bits;
needed_tgt: t_bits): t_int;
// FAR;
// 2012-09-25 J. Neumann
var
a_count: t_int;
s,t: t_int;
mask_src: t_bits;
mask_tgt: t_bits;
begin
a_count := 0;
while needed_src <> 0 do begin
s := 0; // -bits;
t := -1;
while true do begin
t := t+1;
while (t < bits) AND
(((lo_bit shl t) and needed_tgt) = 0) do begin
t := t+1;
// s := s+1;
end;
if t >= bits then begin
BREAK;
end;
if perm[t] < s then begin
BREAK;
end;
s := perm[t];
// assert(s <> no_index);
mask_src := lo_bit shl s;
mask_tgt := lo_bit shl t;
a[a_count].mask_src := a[a_count].mask_src or mask_src;
a[a_count].mask_tgt := a[a_count].mask_tgt or mask_tgt;
needed_src := needed_src and not mask_src;
needed_tgt := needed_tgt and not mask_tgt;
end;
a_count := a_count+1;
end;
aux_route_gather_shift_sloppy := a_count;
end;
function aux_route_gather_shift(
var a: tar_gather_scatter;
const perm: ta_index;
needed_src: t_bits;
needed_tgt: t_bits): t_int;
// FAR;
// 2012-09-26 J. Neumann
var
a_count: t_int;
s,t: t_int;
mask_src: t_bits;
mask_tgt: t_bits;
begin
a_count := 0;
while needed_src <> 0 do begin
s := 0; // -bits;
t := 0;
while (t < bits) AND
(((lo_bit shl t) and needed_tgt) = 0) do begin
t := t+1;
end;
t := t-1;
while true do begin
t := t+1;
if t >= bits then begin
BREAK;
end;
if perm[t] = no_index then begin
BREAK;
end;
if perm[t] < s then begin
BREAK;
end;
s := perm[t];
mask_src := lo_bit shl s;
mask_tgt := lo_bit shl t;
a[a_count].mask_src := a[a_count].mask_src or mask_src;
a[a_count].mask_tgt := a[a_count].mask_tgt or mask_tgt;
needed_src := needed_src and not mask_src;
needed_tgt := needed_tgt and not mask_tgt;
end;
a_count := a_count+1;
end;
aux_route_gather_shift := a_count;
end;
function aux_route_shift_scatter_sloppy(
var a: tar_gather_scatter;
const perm: ta_index;
needed_src: t_bits;
needed_tgt: t_bits): t_int;
// FAR;
// 2012-09-25 J. Neumann
var
a_count: t_int;
s,t: t_int;
mask_src: t_bits;
mask_tgt: t_bits;
inv_perm: ta_index;
begin
invert_perm(perm,inv_perm);
a_count := 0;
while needed_tgt <> 0 do begin
t := 0; // -bits;
s := -1;
while true do begin
s := s+1;
while (s < bits) AND
(((lo_bit shl s) and needed_src) = 0) do begin
s := s+1;
// t := t+1;
end;
if s >= bits then begin
BREAK;
end;
if inv_perm[s] < t then begin
BREAK;
end;
t := inv_perm[s];
// assert(t <> no_index);
mask_tgt := lo_bit shl t;
mask_src := lo_bit shl s;
a[a_count].mask_tgt := a[a_count].mask_tgt or mask_tgt;
a[a_count].mask_src := a[a_count].mask_src or mask_src;
needed_tgt := needed_tgt and not mask_tgt;
needed_src := needed_src and not mask_src;
end;
a_count := a_count+1;
end;
aux_route_shift_scatter_sloppy := a_count;
end;
function aux_route_shift_scatter(
var a: tar_gather_scatter;
const perm: ta_index;
needed_src: t_bits;
needed_tgt: t_bits): t_int;
// FAR;
// 2012-09-26 J. Neumann
var
a_count: t_int;
s,t: t_int;
mask_src: t_bits;
mask_tgt: t_bits;
inv_perm: ta_index;
begin
invert_perm(perm,inv_perm);
a_count := 0;
while needed_tgt <> 0 do begin
t := 0; // -bits;
s := 0;
while (s < bits) AND
(((lo_bit shl s) and needed_src) = 0) do begin
s := s+1;
end;
s := s-1;
while true do begin
s := s+1;
if s >= bits then begin
BREAK;
end;
if inv_perm[s] = no_index then begin
BREAK;
end;
if inv_perm[s] < t then begin
BREAK;
end;
t := inv_perm[s];
mask_tgt := lo_bit shl t;
mask_src := lo_bit shl s;
a[a_count].mask_tgt := a[a_count].mask_tgt or mask_tgt;
a[a_count].mask_src := a[a_count].mask_src or mask_src;
needed_tgt := needed_tgt and not mask_tgt;
needed_src := needed_src and not mask_src;
end;
a_count := a_count+1;
end;
aux_route_shift_scatter := a_count;
end;
procedure decorate_route_gs(var imp:tr_imp; opt:t_bool);
begin
if opt then begin
imp.description := imp.description+' opt';
end
else begin
imp.description := imp.description+' pure';
end;
end;
procedure frame_route_gs(var imp:tr_imp; opt:t_bool; fn:tf_aux_route_gs; const des:t_string);
// 2012-09-27 J. Neumann
var
perm: ta_index;
a: tar_gather_scatter;
a_count: t_int;
i,j,s,t: t_int;
mask_src: t_bits;
mask_tgt: t_bits;
skip: t_int;
diff: t_int;
ok: t_bool;
begin
init_imp(imp,perm);
concat_description(imp.description, des);
decorate_route_gs(imp,opt);
skip := 0;
repeat
ok := true;
imp.a_step[imp.nr_step].nr_pprim := skip;
for i := 0 to bits-1 do begin
init_gather_scatter(a[i]);
end;
a_count := fn(a,perm,used_source_bits(perm),used_target_bits(perm));
for i := 0 to a_count-1 do begin
mask_src := a[i].mask_src;
mask_tgt := a[i].mask_tgt;
if opt then begin
s := nr_trailing_0bits(mask_src);
t := nr_trailing_0bits(mask_tgt);
if mask_src shr s = mask_tgt shr t then begin
imp.a_step[imp.nr_step].nr_pprim := skip;
skip := skip+1;
diff := (t-s) and (bits-1);
mask_src := 0;
for j := 0 to bits-1 do begin
if (perm[j] <> no_index) AND
(((j-perm[j]) and (bits-1)) = diff) then begin
mask_src := mask_src or (lo_bit shl j);
perm[j] := no_index;
end;
end;
add_rol(imp, rol(mask_src,-diff), diff);
ok := false;
BREAK;
end;
end;
add_gs(imp,mask_src,mask_tgt);
end;
until ok;
finish_step(imp);
finish_perm(imp);
end;
procedure route_gather_scatter(var imp:tr_imp; opt:t_bool);
begin
frame_route_gs(imp,opt,aux_route_gather_scatter, 'Gather/scatter');
end;
procedure route_gather_shift_sloppy(var imp:tr_imp; opt:t_bool);
begin
frame_route_gs(imp,opt,aux_route_gather_shift_sloppy, 'Gather/shift sloppy');
end;
procedure route_gather_shift(var imp:tr_imp; opt:t_bool);
begin
frame_route_gs(imp,opt,aux_route_gather_shift, 'Gather/shift');
end;
procedure route_shift_scatter_sloppy(var imp:tr_imp; opt:t_bool);
begin
frame_route_gs(imp,opt,aux_route_shift_scatter_sloppy, 'Shift/scatter sloppy');
end;
procedure route_shift_scatter(var imp:tr_imp; opt:t_bool);
begin
frame_route_gs(imp,opt,aux_route_shift_scatter, 'Shift/scatter');
end;
//////
// Best performance
var
best_performance: tr_performance;
best_imp: tr_imp;
procedure use_best_imp(const imp:tr_imp);
var
performance: tr_performance;
begin
imp_performance(imp, performance);
if cmp_performance(performance, best_performance) < 0 then begin
best_performance := performance;
best_imp := imp;
end;
end;
procedure check_best(const imp:tr_imp);
begin
if options.verbose then begin
imp_dump_simple(imp);
end;
imp_check(imp);
use_best_imp(imp);
end;
//////
// Test routing variations (BPC / Benes)
type
tf_test_route = procedure (const idx:ta_subword);
procedure permute_sub(x:t_int; var idx:ta_subword; fn:tf_test_route);
var
i: t_int;
q: t_int;
begin
if x = ld_bits-1 then begin
fn(idx);
end
else begin
for i := x+1 to ld_bits-1 do begin
permute_sub(x+1,idx,fn);
q := idx[x];
idx[x] := idx[i];
idx[i] := q;
end;
permute_sub(x+1,idx,fn);
for i := ld_bits-1 downto x+1 do begin
q := idx[x];
idx[x] := idx[i];
idx[i] := q;
end;
end;
end;
procedure permute(fn:tf_test_route);
var
idx: ta_subword;
i: t_int;
begin
for i := 0 to ld_bits-1 do begin
idx[i] := i;
end;
permute_sub(0, idx, fn);
end;
var
is_bpc_perm: t_bool;
bpc_performance: tr_performance;
benes_performance: tr_performance;
procedure route_bpc(var imp:tr_imp; const tgt:ta_subword; k:t_bit_index);
// 2012-08-31
var
perm: ta_index;
src,inv_src: ta_subword;
n,m: t_int;
i,j,ii,kk: t_subword;
begin
init_imp(imp,perm);
concat_description(imp.description, 'BPC permutation ');
for i := 0 to ld_bits-1 do begin
imp.description := imp.description+num(tgt[i]);
src[i] := i;
inv_src[i] := i;
end;
imp.description := imp.description+'/'+hex(k);
kk := 0; // k for generated
for i := 0 to ld_bits-1 do begin // any order
n := 1 shl i;
ii := src[i];
if tgt[i] = ii then begin
if ((k xor kk) and n) <> 0 then begin
// x := bit_index_complement(x,i);
imp.a_step[imp.nr_step].needed_src_bits := all_bits;
add_permute(imp, a_bfly_mask[i], n); // 1 shl i;
end;
end
else begin
j := inv_src[tgt[i]];
m := 1 shl j;
if ((k and n) <> 0) XOR // boolean xor
((kk and m) <> 0) then begin
// x := bit_index_swap_complement(x,i,j);
imp.a_step[imp.nr_step].needed_src_bits := all_bits;
add_permute(imp, a_bfly_mask[j] and a_bfly_mask[i], m+n);
if (kk and n) = 0 then begin
kk := kk or m;
end
else begin
kk := kk and not m;
end;
end
else begin
// x := bit_index_swap(x,i,j);
imp.a_step[imp.nr_step].needed_src_bits := all_bits;
add_permute(imp, a_bfly_mask[j] and not a_bfly_mask[i], m-n);
if (kk and n) <> 0 then begin
kk := kk or m;
end
else begin
kk := kk and not m;
end;
end;
inv_src[ii] := j;
src[j] := ii;
end;
end;
finish_perm(imp);
end;
procedure test_route_bpc(const idx:ta_subword);
// FAR;
var
perm: ta_index;
inv: t_bit_index; // 0..bits-1, i.e. set of [0..ld_bits-1]
i,j: t_int;
found: t_bool;
v: t_bit_index; // 0..bits-1, i.e. set of [0..ld_bits-1]
imp: tr_imp;
performance: tr_performance;
begin
init_imp(imp,perm);
for inv := 0 to bits-1 do begin
found := true;
for j := 0 to bits-1 do begin
if perm[j] <> no_index then begin
v := 0;
for i := 0 to ld_bits-1 do begin
if ((j xor inv) and (1 shl i)) <> 0 then begin
v := v or (1 shl idx[i]);
end;
end;
if perm[j] <> v then begin
found := false;
BREAK;
end;
end;
end;
if found then begin
is_bpc_perm := true;
route_bpc(imp,idx,inv);
imp_check(imp);
// imp_dump_simple(imp);
use_best_imp(imp);
imp_performance(imp, performance);
if cmp_performance(performance, bpc_performance) < 0 then begin
bpc_performance := performance;
end;
end;
end;
end;
procedure test_route_benes(const idx:ta_subword);
// FAR;
var
imp: tr_imp;
performance: tr_performance;
begin
route_benes(imp,idx);
imp_check(imp);
// imp_dump_simple(imp);
use_best_imp(imp);
imp_performance(imp, performance);
if cmp_performance(performance, benes_performance) < 0 then begin
benes_performance := performance;
end;
end;
//////
// Permutation decorators
procedure test_all(ex:t_bool);
// needs pre_imp and post_imp correctly initialized
var
imp: tr_imp;
perm: ta_index;
save_is_bpc_perm: t_bool;
begin
save_is_bpc_perm:=is_bpc_perm;
if options.verbose then begin
writeln;
end;
if is_identity then begin
init_imp(imp,perm);
// concat_description(imp.description, 'Identity');
finish_perm(imp);
check_best(imp);
end
else begin
init_performance(bpc_performance);
init_performance(benes_performance);
if options.test_bpc AND ex then begin
permute(test_route_bpc);
if options.verbose then begin
if is_bpc_perm then begin
writeln(
'Altered best BPC permutation: '+dump_performance(bpc_performance));
end
else begin
writeln('Altered BPC: Not possible');
end;
end;
end;
if options.test_benes AND ex then begin
permute(test_route_benes);
if options.verbose then begin
writeln('Altered best Benes: '+dump_performance(benes_performance));
end;
end;
if options.test_bit_groups then begin
route_bit_groups(imp);
check_best(imp);
end;
if options.test_mul then begin
route_mul1(imp);
check_best(imp);
route_mul2(imp);
check_best(imp);
route_mul3(imp);
check_best(imp);
end;
if options.allow_bmi then begin
if options.test_gather_scatter then begin
route_gather_scatter(imp,options.opt_gs);
check_best(imp);
end;
if options.test_gather_shift then begin
route_gather_shift(imp,options.opt_gs);
check_best(imp);
end;
if options.test_gather_shift_sloppy then begin
route_gather_shift_sloppy(imp,options.opt_gs);
check_best(imp);
end;
if options.test_shift_scatter then begin
route_shift_scatter(imp,options.opt_gs);
check_best(imp);
end;
if options.test_shift_scatter_sloppy then begin
route_shift_scatter_sloppy(imp,options.opt_gs);
check_best(imp);
end;
if options.test_sag then begin
route_sag(imp);
check_best(imp);
end;
end;
end;
is_bpc_perm:=save_is_bpc_perm;
end;
procedure try_pre_rol(const perm:ta_index; opt_bswap:t_bool);
var
i,j,xswap: t_int;
begin
if opt_bswap then begin
xswap := 7;
end
else begin
xswap := 0;
end;
for i:=bits-1 downto 1 do begin // all rotates but 0
// progress;
write(num(i)+' '#$0d);
for j:=0 to xswap do begin
init_imp0(pre_imp,perm);
if (j and 1)<>0 then begin
concat_description(pre_imp.description, 'Bswap');
add_bswap(pre_imp);
finish_step(pre_imp);
end;
concat_description(pre_imp.description, 'Rol '+num(i));
add_rol(pre_imp,all_bits,i);
finish_step(pre_imp);
if (j and 2)<>0 then begin
concat_description(pre_imp.description, 'Bswap');
add_bswap(pre_imp);
finish_step(pre_imp);
end;
init_imp0(post_imp,perm);
if (j and 4)<>0 then begin
concat_description(post_imp.description, 'Bswap');
add_bswap(post_imp);
finish_step(post_imp);
end;
test_all(options.opt_rol_ex);
end;
end;
end;
procedure try_post_rol(const perm:ta_index; opt_bswap:t_bool);
var
i,j,xswap: t_int;
begin
if opt_bswap then begin
xswap := 7;
end
else begin
xswap := 0;
end;
for i:=bits-1 downto 1 do begin // all rotates but 0
// progress;
write(num(i)+' '#$0d);
for j:=0 to xswap do begin
init_imp0(pre_imp,perm);
if (j and 1)<>0 then begin
concat_description(pre_imp.description, 'Bswap');
add_bswap(pre_imp);
finish_step(pre_imp);
end;
init_imp0(post_imp,perm);
if (j and 2)<>0 then begin
concat_description(post_imp.description, 'Bswap');
add_bswap(post_imp);
finish_step(post_imp);
end;
concat_description(post_imp.description, 'Rol '+num(i));
add_rol(post_imp,all_bits,i);
finish_step(post_imp);
if (j and 4)<>0 then begin
concat_description(post_imp.description, 'Bswap');
add_bswap(post_imp);
finish_step(post_imp);
end;
test_all(options.opt_rol_ex);
end;
end;
end;
procedure try_bswap(const perm:ta_index);
var
j: t_int;
begin
for j:=1 to 3 do begin
init_imp0(pre_imp,perm);
if (j and 1)<>0 then begin
concat_description(pre_imp.description, 'Bswap');
add_bswap(pre_imp);
finish_step(pre_imp);
end;
init_imp0(post_imp,perm);
if (j and 2)<>0 then begin
concat_description(post_imp.description, 'Bswap');
add_bswap(post_imp);
finish_step(post_imp);
end;
test_all(true);
end;
end;
procedure my_random_perm(var perm:ta_index);
var
i: t_int;
hi: t_int;
begin
random_perm(perm);
case random_int(4) of
0: begin
for i := 1 to random_int(bits) do begin
perm[random_int(bits)] := no_index;
end;
end;
else ;
end;
case random_int(4) of
0: begin
hi := random_int(bits);
for i := 0 to bits-1 do begin
if perm[i] >= hi then begin
perm[i] := no_index;
end;
end;
end;
else ;
end;
case random_int(4) of
0: begin
hi := random_int(bits);
for i := hi to bits-1 do begin
perm[i] := no_index;
end;
end;
else ;
end;
end;
procedure self_test;
var
perm: ta_index;
imp: tr_imp;
loop: t_longint;
begin
for loop := 1030 downto 1 do begin
if (loop and $3f) = 0 then begin
write(loop,' '#$0d);
// flush;
end;
my_random_perm(perm);
init_imp0(pre_imp,perm);
init_imp0(post_imp,perm);
route_mul1(imp);
imp_check(imp);
route_mul2(imp);
imp_check(imp);
route_mul3(imp);
imp_check(imp);
route_bit_groups(imp);
imp_check(imp);
route_benes(imp,a_stage_bwd);
imp_check(imp);
route_benes(imp,a_stage_fwd);
imp_check(imp);
route_gather_scatter(imp,true);
imp_check(imp);
route_gather_shift_sloppy(imp,true);
imp_check(imp);
route_gather_shift(imp,true);
imp_check(imp);
route_shift_scatter_sloppy(imp,true);
imp_check(imp);
route_shift_scatter(imp,true);
imp_check(imp);
route_sag(imp);
imp_check(imp);
end;
write(' '#$0d);
for loop := 260 downto 1 do begin
if (loop and $0f) = 0 then begin
write(loop,' '#$0d);
// flush;
end;
my_random_perm(perm);
init_imp0(pre_imp,perm);
init_imp0(post_imp,perm);
permute(test_route_bpc);
permute(test_route_benes);
end;
write(' '#$0d);
end;
var
perm: ta_index;
//////
// Startup/parameter routines
procedure split_opt(const opt:t_string; var name,value:t_string);
var
i,len: t_int;
begin
name := '';
value := '';
len := length(opt);
// search for line comment sign (#)
i := 1;
while (i <= len) AND
(opt[i] <> '#') do begin
i := i + 1;
end;
if i <= len then begin // we found the #, now trim
len := i - 1;
end;
// trim right
while (len > 0) AND
(opt[len] <= ' ') do begin
len := len - 1;
end;
if len = 0 then begin
EXIT; // nothing to do
end;
// trim left
i := 1;
while (i <= len) AND
(opt[i] <= ' ') do begin
i := i + 1;
end;
// skip lead in character if present
if (i <= len) AND
( (opt[i] = '/') OR
(opt[i] = '-') ) then begin
i := i + 1;
end;
// extract name
while (i <= len) AND
(opt[i] <> '=') AND
(opt[i] <> ':') do begin
name := name + locase(opt[i]);
i := i + 1;
end;
// skip delimiter
i := i + 1;
// extract value
while i <= len do begin
value := value + opt[i];
i := i + 1;
end;
end;
procedure setup_default_pascal;
begin
options.comment_prefix:='// ';
options.comment_postfix:='';
options.hex_prefix := '$';
options.hex_postfix := '';
options.op_assign := ':=';
options.op_and := 'and';
options.op_or := 'or';
options.op_xor := 'xor';
options.op_shl := 'shl';
options.op_shr := 'shr';
end;
procedure setup_default_c;
begin
options.comment_prefix:='// ';
options.comment_postfix:='';
options.hex_prefix := '0x';
options.hex_postfix := '';
options.op_assign := '=';
options.op_and := '&';
options.op_or := '|';
options.op_xor := '^';
options.op_shl := '<<';
options.op_shr := '>>';
end;
procedure recalc_cost_permute;
begin
options.cost_bit_permute_step :=
options.cost_shift*2+options.cost_xor*3+options.cost_and;
options.cost_bit_permute_step_simple :=
options.cost_shift*2+options.cost_and*2+options.cost_or;
end;
procedure recalc_cost_opt;
begin
options.cost_rotate := options.cost_rotate_shift;
options.cost_shift := options.cost_rotate_shift;
options.cost_and := options.cost_bool;
options.cost_or := options.cost_bool;
options.cost_xor := options.cost_bool;
options.cost_scatter := options.cost_gs;
options.cost_gather := options.cost_gs;
recalc_cost_permute;
end;
procedure setup_defaults;
begin
options.dump_input := true;
options.dump_inverse := true;
options.verbose := true;
options.brief := true;
setup_default_pascal;
// setup_default_c;
options.op_pstep := 'bit_permute_step';
options.op_pstep_simple := 'bit_permute_step_simple';
options.op_rol := 'rol';
options.op_gather := 'pext';
options.op_scatter := 'pdep';
options.op_bswap := 'bswap';
options.in_origin := 0; // input index origin
options.in_base := 10; // input number base
options.in_indexes_are_target := false; // /in_indexes=source or target
options.cost_rotate_shift := 1;
options.cost_bool := 1;
options.cost_bswap := 1;
options.cost_mul := 4;
options.cost_gs := 3;
options.cost_mask := 0;
recalc_cost_opt;
options.bonus_bit_permute_step := 1; // implicitely parallel
options.bonus_bit_permute_step_simple := 1; // implicitely parallel
options.bonus_gs := 3; // 2 parallel gs
options.bonus_mask_rol := 2; // 2 parallel mask_rol/mask_shift ops
options.bonus_gs_rol := 1; // parallel mask_rol/mask_shift and gs ops
options.allow_bswap := true;
options.allow_bmi := false;
options.test_bpc := true;
options.test_bfly := true;
options.test_ibfly := true;
options.test_benes := true;
options.test_bit_groups := true;
options.test_mul := true;
options.test_gather_scatter := true;
options.test_gather_shift := true;
options.test_gather_shift_sloppy := true;
options.test_shift_scatter := true;
options.test_shift_scatter_sloppy := true;
options.test_sag := true;
options.opt_gs := true;
options.opt_rol := true;
options.opt_rol_ex := false;
options.opt_bswap := true;
options.self_test := false;
end;
procedure setup(const opt:t_string); forward;
procedure setup_file(const n:t_string);
var
f: text;
s: t_string;
i: t_int;
n1: t_string;
begin
n1 := '';
for i:=1 to length(n) do begin
if n[i]<>'"' then begin
n1 := n1 + n[i];
end;
end;
assign(f, n1);
reset(f);
while NOT eof(f) do begin
readln(f, s);
setup(s);
end;
close(f);
end;
procedure setup(const opt:t_string);
var
n,v: t_string;
begin
if opt = '' then begin
// ignore
end
else if opt[1] = '@' then begin
setup_file(copy(opt,2,length(opt)-1));
end
else begin
split_opt(opt,n,v);
if n = '' then begin
// ignore
end
else if n = 'dump_input' then begin
options.dump_input := s2i(v)<>0;
end
else if n = 'dump_inverse' then begin
options.dump_inverse := s2i(v)<>0;
end
else if n = 'verbose' then begin
options.verbose := s2i(v)<>0;
end
else if n = 'brief' then begin
options.brief := s2i(v)<>0;
end
else if n = 'output_pas' then begin
setup_default_pascal;
end
else if n = 'output_c' then begin
setup_default_c;
end
else if n = 'comment_prefix' then begin
if v = '' then begin
options.comment_prefix := '';
end
else begin
options.comment_prefix := v+' ';
end;
end
else if n = 'comment_postfix' then begin
if v = '' then begin
options.comment_postfix := '';
end
else begin
options.comment_postfix := ' '+v;
end;
end
else if n = 'hex_prefix' then begin
options.hex_prefix := v;
end
else if n = 'hex_postfix' then begin
options.hex_postfix := v;
end
else if n = 'op_assign' then begin
options.op_assign := v;
end
else if n = 'op_and' then begin
options.op_and := v;
end
else if n = 'op_or' then begin
options.op_or := v;
end
else if n = 'op_xor' then begin
options.op_xor := v;
end
else if n = 'op_shl' then begin
options.op_shl := v;
end
else if n = 'op_shr' then begin
options.op_shr := v;
end
else if n = 'in_origin' then begin
options.in_origin := s2i(v);
end
else if n = 'in_base' then begin
options.in_base := s2i(v);
end
else if n = 'in_indexes' then begin
v := lostr(v);
if v = 'source' then begin
options.in_indexes_are_target := false;
end
else if v = 'target' then begin
options.in_indexes_are_target := true;
end
else begin
writeln('ERROR: Unknown option to /in_indexes '+v);
error_abort;
end;
end
else if n = 'op_pstep' then begin
options.op_pstep := v;
end
else if n = 'op_pstep_simple' then begin
options.op_pstep_simple := v;
end
else if n = 'op_rol' then begin
options.op_rol := v;
end
else if n = 'op_gather' then begin
options.op_gather := v;
end
else if n = 'op_scatter' then begin
options.op_scatter := v;
end
else if n = 'op_bswap' then begin
options.op_bswap := v;
end
else if n = 'cost_rotate_shift' then begin
options.cost_rotate_shift := s2i(v);
recalc_cost_opt;
end
else if n = 'cost_bool' then begin
options.cost_bool := s2i(v);
recalc_cost_opt;
end
else if n = 'cost_bswap' then begin
options.cost_bswap := s2i(v);
recalc_cost_opt;
end
else if n = 'cost_mul' then begin
options.cost_mul := s2i(v);
recalc_cost_opt;
end
else if n = 'cost_gs' then begin
options.cost_gs := s2i(v);
recalc_cost_opt;
end
else if n = 'cost_mask' then begin
options.cost_mask := s2i(v);
end
else if n = 'cost_rotate' then begin
options.cost_rotate := s2i(v);
recalc_cost_permute;
end
else if n = 'cost_shift' then begin
options.cost_shift := s2i(v);
recalc_cost_permute;
end
else if n = 'cost_and' then begin
options.cost_and := s2i(v);
recalc_cost_permute;
end
else if n = 'cost_or' then begin
options.cost_or := s2i(v);
recalc_cost_permute;
end
else if n = 'cost_xor' then begin
options.cost_xor := s2i(v);
recalc_cost_permute;
end
else if n = 'cost_scatter' then begin
options.cost_scatter := s2i(v);
end
else if n = 'cost_gather' then begin
options.cost_gather := s2i(v);
end
else if n = 'cost_bit_permute_step' then begin
options.cost_bit_permute_step := s2i(v);
end
else if n = 'cost_bit_permute_step_simple' then begin
options.cost_bit_permute_step_simple := s2i(v);
end
else if n = 'bonus_bit_permute_step' then begin
options.bonus_bit_permute_step := s2i(v);
end
else if n = 'bonus_bit_permute_step_simple' then begin
options.bonus_bit_permute_step_simple := s2i(v);
end
else if n = 'bonus_gs' then begin
options.bonus_gs := s2i(v);
end
else if n = 'bonus_mask_rol' then begin
options.bonus_mask_rol := s2i(v);
end
else if n = 'bonus_gs_rol' then begin
options.bonus_gs_rol := s2i(v);
end
else if n = 'allow_bswap' then begin
options.allow_bswap := s2i(v)<>0;
end
else if n = 'allow_bmi' then begin
options.allow_bmi := s2i(v)<>0;
end
else if n = 'test_bpc' then begin
options.test_bpc := s2i(v)<>0;
end
else if n = 'test_bfly' then begin
options.test_bfly := s2i(v)<>0;
end
else if n = 'test_ibfly' then begin
options.test_ibfly := s2i(v)<>0;
end
else if n = 'test_benes' then begin
options.test_benes := s2i(v)<>0;
end
else if n = 'test_bit_groups' then begin
options.test_bit_groups := s2i(v)<>0;
end
else if n = 'test_mul' then begin
options.test_mul := s2i(v)<>0;
end
else if n = 'test_gather_scatter' then begin
options.test_gather_scatter := s2i(v)<>0;
end
else if n = 'test_gather_shift' then begin
options.test_gather_shift := s2i(v)<>0;
end
else if n = 'test_gather_shift_sloppy' then begin
options.test_gather_shift_sloppy := s2i(v)<>0;
end
else if n = 'test_shift_scatter' then begin
options.test_shift_scatter := s2i(v)<>0;
end
else if n = 'test_shift_scatter_sloppy' then begin
options.test_shift_scatter_sloppy := s2i(v)<>0;
end
else if n = 'test_sag' then begin
options.test_sag := s2i(v)<>0;
end
else if n = 'opt_gs' then begin
options.opt_gs := s2i(v)<>0;
end
else if n = 'opt_rol' then begin
options.opt_rol := s2i(v)<>0;
end
else if n = 'opt_rol_ex' then begin
options.opt_rol_ex := s2i(v)<>0;
end
else if n = 'opt_bswap' then begin
options.opt_bswap := s2i(v)<>0;
end
else if n = 'self_test' then begin
options.self_test := s2i(v)<>0;
end
else begin
writeln('ERROR: Unknown option '+n);
error_abort;
end;
end;
end;
procedure get_perm(const opt:t_string; var perm:ta_index);
var
i: t_int;
idx: t_int;
ok: t_bits;
c: char;
my_base: t_int;
val: t_int;
letter_ofs: t_int;
digit: t_int;
s: t_string;
begin
for i := 0 to bits-1 do begin
perm[i] := no_index;
end;
my_base := options.in_base;
ok := 0;
idx := -1;
i := 1;
while i <= length(opt) do begin
c := opt[i];
val := -2;
case c of
#$00..' ', ',': begin
i := i+1;
CONTINUE;
end;
'*': begin
val := -1;
end;
'$': begin
my_base := 16;
i := i+1;
CONTINUE;
end;
'/', '-': begin
s := '';
while (i <= length(opt)) AND
(opt[i] <> ' ') do begin
s := s+opt[i];
i := i+1;
end;
setup(s);
my_base := options.in_base; // in_base might have changed
CONTINUE;
end;
'#': begin
BREAK; // comment until end of line
end;
'@': begin
i := i+1; // skip @
s := '';
while (i <= length(opt)) AND
(opt[i] <> ' ') do begin
if opt[i] <> '"' then begin
s := s+opt[i];
i := i+1;
end
else begin
while (i <= length(opt)) AND
(opt[i] <> '"') do begin
s := s+opt[i];
i := i+1;
end;
i := i+1;
end;
end;
setup_file(s);
my_base := options.in_base; // in_base might have changed
CONTINUE;
end;
'0'..'9', 'a'..'z', 'A'..'Z': begin
if my_base = 26 then begin
letter_ofs := 0;
end
else begin
letter_ofs := 10;
end;
val := 0;
digit := 0; // Delphi, shut up!
while i <= length(opt) do begin
c := opt[i];
case c of
'0'..'9': digit := ord(c)-ord('0');
'a'..'z': digit := ord(c)-ord('a')+letter_ofs;
'A'..'Z': digit := ord(c)-ord('A')+letter_ofs;
else BREAK;
end;
if (my_base <> 26) AND
(digit >= my_base) then begin
writeln('ERROR: Invalid digit');
error_abort;
end;
val := val*my_base + digit;
i := i+1;
end;
i := i-1;
end;
else ;
end;
if val = -2 then begin
writeln('ERROR: Illegal character');
i := i+1;
CONTINUE;
end;
idx := idx+1;
if val = -1 then begin
// ignore
end
else if (val < options.in_origin) OR
(val-options.in_origin > bits-1) then begin
writeln('ERROR: Out of range');
error_abort;
end
else begin
val := val - options.in_origin;
if ((lo_bit shl val) and ok) <> 0 then begin
writeln('ERROR: Dupe: '+num(val));
error_abort;
end;
ok := ok or (lo_bit shl val);
end;
perm[idx] := val;
my_base := options.in_base;
i := i+1;
end;
if idx < 0 then begin
// random_perm(perm);
// for i := 1 to random_int(bits) do begin
// perm[random_int(bits)] := no_index;
// end;
my_random_perm(perm);
end;
end;
procedure startup;
var
opt: t_string;
i: t_int;
inv_perm: ta_index;
begin
setup_defaults;
setup_file('calcperm.ini');
opt := '';
for i := 1 to paramcount do begin
opt := opt+' '+paramstr(i);
end;
get_perm(opt, perm);
if options.in_indexes_are_target then begin
invert_perm(perm,inv_perm);
perm := inv_perm;
end;
init_imp0(pre_imp,perm);
init_imp0(post_imp,perm);
end;
var
inv_perm: ta_index;
imp: tr_imp;
is_bfly_perm: t_bool;
is_ibfly_perm: t_bool;
//////
// Main program
begin
if NOT init_general then begin
HALT(1);
end;
writeln('Permutation code generator (in Pascal, bits=',bits,')...');
if sizeof(t_bits)*8 <> bits then begin
writeln('Sizes wrong! sizeof(t_bits)=', sizeof(t_bits));
HALT(1);
end;
my_randseed := random_int(32767);
startup;
if options.self_test then begin
self_test;
writeln('OK');
end
else begin
if options.dump_input then begin
write('Permutation vector: ');
dump_perm(perm);
end;
if options.dump_inverse then begin
write('Inverse vector: ');
invert_perm(perm,inv_perm);
dump_perm(inv_perm);
end;
init_performance(best_performance);
init_performance(bpc_performance);
init_performance(benes_performance);
is_bpc_perm := false;
is_bfly_perm := false;
is_ibfly_perm := false;
if options.verbose then begin
writeln;
end;
if is_identity then begin
is_bpc_perm := true;
is_bfly_perm := true;
is_ibfly_perm := true;
init_imp(imp,perm);
concat_description(imp.description, 'Identity');
finish_perm(imp);
check_best(imp);
end
else begin
if options.test_bpc then begin
permute(test_route_bpc);
if options.verbose then begin
if is_bpc_perm then begin
writeln('Best BPC permutation: '+dump_performance(bpc_performance));
end;
end;
end;
if options.test_bfly then begin
route_benes(imp,a_stage_bwd);
if imp.is_bfly then begin
check_best(imp);
is_bfly_perm := true;
end;
end;
if options.test_ibfly then begin
route_benes(imp,a_stage_fwd);
if imp.is_bfly then begin
check_best(imp);
is_ibfly_perm := true;
end;
end;
if options.test_benes then begin
permute(test_route_benes);
if options.verbose then begin
writeln('Best Benes: '+dump_performance(benes_performance));
end;
end;
if options.test_bit_groups then begin
route_bit_groups(imp);
check_best(imp);
end;
if options.test_mul then begin
route_mul1(imp);
check_best(imp);
route_mul2(imp);
check_best(imp);
route_mul3(imp);
check_best(imp);
end;
if options.allow_bmi then begin
if options.test_gather_scatter then begin
route_gather_scatter(imp,options.opt_gs);
check_best(imp);
end;
if options.test_gather_shift then begin
route_gather_shift(imp,options.opt_gs);
check_best(imp);
end;
if options.test_gather_shift_sloppy then begin
route_gather_shift_sloppy(imp,options.opt_gs);
check_best(imp);
end;
if options.test_shift_scatter then begin
route_shift_scatter(imp,options.opt_gs);
check_best(imp);
end;
if options.test_shift_scatter_sloppy then begin
route_shift_scatter_sloppy(imp,options.opt_gs);
check_best(imp);
end;
if options.test_sag then begin
route_sag(imp);
check_best(imp);
end;
end;
if options.opt_rol then begin
try_pre_rol(perm, options.opt_bswap AND options.allow_bswap);
try_post_rol(perm, options.opt_bswap AND options.allow_bswap);
write(' '#$0d); // get rid of progress display
end;
if options.opt_bswap AND options.allow_bswap then begin
try_bswap(perm);
end;
end;
if options.brief OR options.verbose then begin
writeln;
if options.test_bpc then begin
writeln('BPC permutation: '+q2s(is_bpc_perm));
end;
if options.test_bfly then begin
writeln('Butterfly: '+q2s(is_bfly_perm));
end;
if options.test_ibfly then begin
writeln('Inverse Butterfly: '+q2s(is_ibfly_perm));
end;
writeln;
writeln('=== Best method ===');
end;
if best_performance.cost = maxint then begin
writeln('NOT ROUTABLE WITH ALLOWED METHODS');
end
else begin
imp_dump(best_imp);
end;
end;
end.
// eof.
|
{$include lem_directives.inc}
unit GamePreviewScreen;
interface
uses
Windows, Classes, Controls, Graphics, SysUtils,
GR32, GR32_Image, GR32_Layers,
UMisc, Dialogs, PngImage,
LemCore, LemStrings, LemDosStructures, LemRendering, LemLevelSystem,
GameControl, GameBaseScreen, GameWindow;
type
TGamePreviewScreen = class(TGameBaseScreen)
private
procedure SaveLevelImage;
procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
function GetScreenText: string;
protected
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure BuildScreen; override;
procedure BuildScreenInvis;
procedure PrepareGameParams(Params: TDosGameParams); override;
end;
implementation
uses LemGraphicSet, LemDosGraphicSet, LemLevel, FBaseDosForm;
{ TGamePreviewScreen }
procedure TGamePreviewScreen.BuildScreen;
var
Inf: TRenderInfoRec;
Mainpal: TArrayOfColor32;
Temp, W: TBitmap32;
DstRect: TRect;
epf: String;
begin
Assert(GameParams <> nil);
ScreenImg.BeginUpdate;
try
MainPal := GetDosMainMenuPaletteColors32;
InitializeImageSizeAndPosition(640, 350);
ExtractBackGround;
ExtractPurpleFont;
// prepare the renderer, this is a little bit shaky (wrong place)
with GameParams do
begin
with GraphicSet do
begin
ClearMetaData;
ClearData;
GraphicSetId := Level.Info.GraphicSet;
GraphicSetIdExt := Level.Info.GraphicSetEx;
{$ifdef cust}{$ifndef flexi}
epf := GameParams.ExternalPrefix;
if epf <> '' then epf := epf + '_';
{$else}epf := '';{$endif}
{$else}epf := '';{$endif}
{$ifdef extra}if Info.dSection <= 3 then GraphicSetId := GraphicSetId + 10;{$endif}
MetaInfoFile := GameParams.Directory + epf + 'ground' + i2s(GraphicSetId) + 'o.dat';
GraphicFile := GameParams.Directory + epf + 'vgagr' + i2s(GraphicSetId) + '.dat';
if not FileExists(MetaInfoFile) then MetaInfoFile := GameParams.Directory + 'ground' + i2s(GraphicSetId) + 'o.dat';
if not FileExists(GraphicFile) then GraphicFile := GameParams.Directory + 'vgagr' + i2s(GraphicSetId) + '.dat';
{$ifdef testmode}
if GameParams.fTestMode then
begin
MetaInfoFile := GameParams.fTestGroundFile;
GraphicFile := GameParams.fTestVgagrFile;
end;
{$endif}
MetaInfoFN := MetaInfoFile;
GraphicFN := GraphicFile;
if GraphicSetIdExt = 0 then
begin
GraphicExtFile := '';
GraphicExtFN := '';
end
else
begin
GraphicExtFile := GameParams.Directory + epf + 'vgaspec' + i2s(GraphicSetIdExt - 1) + '.dat';
if not FileExists(GraphicExtFile) then GraphicExtFile := GameParams.Directory + 'vgaspec' + i2s(GraphicSetIdExt - 1) + '.dat';
{$ifdef testmode}
if GameParams.fTestMode then GraphicExtFile := GameParams.fTestVgaspecFile;
{$endif}
GraphicExtFN := GraphicExtFile;
end;
ReadMetaData;
ReadData;
end;
Inf.Level:=Level;
Inf.GraphicSet := Graphicset;
Renderer.PrepareGameRendering(Inf);
end;
Temp := TBitmap32.Create;
W := TBitmap32.Create;
try
Temp.SetSize(640, 350);
Temp.Clear(0);
// draw level preview
W.SetSize(GAME_BMPWIDTH, 160);
W.Clear(0);
// W.ResamplerClassName := 'TLinearResampler';//DraftResampler';
// W.ResamplerClassName := 'TDraftResampler';
GameParams.Renderer.RenderWorld(W, True);
DstRect := Rect(0, 0, 400, 40); // div 4
RectMove(DstRect, 120, 20); // set location
W.DrawTo(Temp, DstRect, W.BoundsRect);
// draw background
TileBackgroundBitmap(0, 78, Temp);
// draw text
DrawPurpleText(Temp, GetScreenText, 0, 80);
ScreenImg.Bitmap.Assign(Temp);
finally
W.Free;
Temp.Free;
end;
finally
ScreenImg.EndUpdate;
end;
end;
procedure TGamePreviewScreen.SaveLevelImage;
var
Dlg : TSaveDialog;
SaveName: String;
TempBitmap: TBitmap32;
OutImage: TPngObject;
X, Y: Integer;
C: TColor32;
R, G, B: Byte;
begin
if GameParams.DumpMode then
SaveName := LeadZeroStr(GameParams.Info.dSection + 1, 2) + LeadZeroStr(GameParams.Info.dLevel + 1, 2) + '.png'
else begin
Dlg := TSaveDialog.Create(self);
dlg.Filter := 'PNG Image (*.png)|*.png';
dlg.FilterIndex := 1;
//dlg.InitialDir := '"' + GameParams. + '/"';
dlg.DefaultExt := '.png';
if dlg.Execute then
SaveName := dlg.FileName
else
SaveName := '';
Dlg.Free;
end;
if SaveName = '' then Exit;
TempBitmap := TBitmap32.Create;
TempBitmap.SetSize(GAME_BMPWIDTH, 160);
GameParams.Renderer.RenderWorld(TempBitmap, True);
OutImage := TPngObject.CreateBlank(COLOR_RGB, 8, TempBitmap.Width, TempBitmap.Height);
for Y := 0 to TempBitmap.Height - 1 do
for X := 0 to TempBitmap.Width - 1 do
begin
C := TempBitmap.Pixel[X, Y];
R := C shr 16;
G := C shr 8;
B := C;
C := ($FF shl 24) + (B shl 16) + (G shl 8) + (R);
OutImage.Pixels[X, Y] := C;
end;
OutImage.CompressionLevel := 9;
OutImage.SaveToFile(SaveName);
OutImage.Free;
TempBitmap.Free;
end;
procedure TGamePreviewScreen.BuildScreenInvis;
var
Inf: TRenderInfoRec;
Mainpal: TArrayOfColor32;
Temp, W: TBitmap32;
DstRect: TRect;
epf: String;
begin
Assert(GameParams <> nil);
//ScreenImg.BeginUpdate;
try
MainPal := GetDosMainMenuPaletteColors32;
//InitializeImageSizeAndPosition(640, 350);
ExtractBackGround;
ExtractPurpleFont;
// prepare the renderer, this is a little bit shaky (wrong place)
with GameParams do
begin
with GraphicSet do
begin
ClearMetaData;
ClearData;
GraphicSetId := Level.Info.GraphicSet;
GraphicSetIdExt := Level.Info.GraphicSetEx;
{$ifdef cust}{$ifndef flexi}
epf := GameParams.ExternalPrefix;
if epf <> '' then epf := epf + '_';
{$else}epf := '';{$endif}
{$else}epf := '';{$endif}
MetaInfoFile := GameParams.Directory + epf + 'ground' + i2s(GraphicSetId) + 'o.dat';
GraphicFile := GameParams.Directory + epf + 'vgagr' + i2s(GraphicSetId) + '.dat';
if not FileExists(MetaInfoFile) then MetaInfoFile := GameParams.Directory + 'ground' + i2s(GraphicSetId) + 'o.dat';
if not FileExists(GraphicFile) then GraphicFile := GameParams.Directory + 'vgagr' + i2s(GraphicSetId) + '.dat';
{$ifdef testmode}
if GameParams.fTestMode then
begin
MetaInfoFile := GameParams.fTestGroundFile;
GraphicFile := GameParams.fTestVgagrFile;
end;
{$endif}
MetaInfoFN := MetaInfoFile;
GraphicFN := GraphicFile;
if GraphicSetIdExt = 0 then
begin
GraphicExtFile := '';
GraphicExtFN := '';
end
else
begin
GraphicExtFile := GameParams.Directory + epf + 'vgaspec' + i2s(GraphicSetIdExt - 1) + '.dat';
if not FileExists(GraphicExtFile) then GraphicExtFile := GameParams.Directory + 'vgaspec' + i2s(GraphicSetIdExt - 1) + '.dat';
{$ifdef testmode}
if GameParams.fTestMode then GraphicExtFile := GameParams.fTestVgaspecFile;
{$endif}
GraphicExtFN := GraphicExtFile;
end;
ReadMetaData;
ReadData;
end;
Inf.Level:=Level;
Inf.GraphicSet := Graphicset;
Renderer.PrepareGameRendering(Inf);
end;
{Temp := TBitmap32.Create;
W := TBitmap32.Create;
try
Temp.SetSize(640, 350);
Temp.Clear(0);
// draw level preview
W.SetSize(GAME_BMPWIDTH, 160);
W.Clear(0);
// W.ResamplerClassName := 'TLinearResampler';//DraftResampler';
// W.ResamplerClassName := 'TDraftResampler';
GameParams.Renderer.RenderWorld(W, True);
DstRect := Rect(0, 0, 400, 40); // div 4
RectMove(DstRect, 120, 20); // set location
W.DrawTo(Temp, DstRect, W.BoundsRect);
// draw background
TileBackgroundBitmap(0, 78, Temp);
// draw text
DrawPurpleText(Temp, GetScreenText, 0, 80);
ScreenImg.Bitmap.Assign(Temp);
finally
W.Free;
Temp.Free;
end;}
if GameParams.DumpMode then SaveLevelImage;
finally
//ScreenImg.EndUpdate;
end;
end;
constructor TGamePreviewScreen.Create(aOwner: TComponent);
begin
inherited;
OnKeyDown := Form_KeyDown;
OnMouseDown := Form_MouseDown;
ScreenImg.OnMouseDown := Img_MouseDown;
end;
destructor TGamePreviewScreen.Destroy;
begin
inherited;
end;
procedure TGamePreviewScreen.Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_ESCAPE: begin
{$ifdef testmode}if GameParams.fTestMode then
CloseScreen(gstExit)
else{$endif}
CloseScreen(gstMenu);
end;
VK_RETURN: CloseScreen(gstPlay);
$49: SaveLevelImage;
end;
end;
procedure TGamePreviewScreen.Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
CloseScreen(gstPlay);
end;
procedure TGamePreviewScreen.Img_MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer;
Layer: TCustomLayer);
begin
if Button = mbLeft then
CloseScreen(gstPlay);
end;
function TGamePreviewScreen.GetScreenText: string;
var
Perc: string;
begin
Assert(GameParams <> nil);
// with GameParams.Level.Info do
begin
Perc := PadR(i2s(Percentage(GameParams.Level.Info.LemmingsCount,
GameParams.Level.Info.RescueCount)) + '%', 4);
{$ifdef extra}
if (GameParams.Info.dSection = 4) and (GameParams.Info.dLevel = 2) then
Perc := '66% ';
{$endif}
{$ifdef testmode}
if GameParams.fTestMode then GameParams.Info.dSectionName := 'TEST MODE';
{$endif}
Result := Format(SPreviewString,
[GameParams.Info.dLevel + 1, // humans read 1-based
Trim(GameParams.Level.Info.Title),
GameParams.Level.Info.LemmingsCount,
Perc,
GameParams.Level.Info.ReleaseRate,
GameParams.Level.Info.TimeLimit,
GameParams.Info.dSectionName
]);
end;
end;
procedure TGamePreviewScreen.PrepareGameParams(Params: TDosGameParams);
//var
//Inf: TDosGamePlayInfoRec;
begin
inherited;
with Params, Info do
begin
case WhichLevel of
wlFirst: Style.LevelSystem.FindFirstLevel(Info);
wlFirstSection: Style.LevelSystem.FindFirstLevel(Info);
wlLevelCode: Style.LevelSystem.FindLevel(Info);
wlNext: Style.LevelSystem.FindNextLevel(Info);
wlSame: Style.LevelSystem.FindLevel(Info);
end;
(*
if not GameResult.gValid then
begin
if not Info.dValid then
Style.LevelSystem.FindFirstLevel(Info)
else
Style.LevelSystem.FindLevel(Info) // used to fill sectionname
end
else if GameResult.gSuccess then
begin
Style.LevelSystem.FindNextLevel(Info);
end;
ClearGameResult;
*)
Style.LevelSystem.LoadSingleLevel(dPack, dSection, dLevel, Level);
WhichLevel := wlSame;
// Style.LevelSystem.LoadSingleLevel(0, 3, 1, Level);
end;
end;
end.
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// author this port to delphi - Marat Shaymardanov, Tomsk (2007, 2013)
//
// You can freely use this code in any project
// if sending any postcards with postage stamp to my address:
// Frunze 131/1, 56, Russia, Tomsk, 634021
unit Example1;
interface
uses Classes, SysUtils, Contnrs, pbPublic, pbInput, pbOutput;
(*
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
*)
type
TPhoneType = (ptMOBILE, ptHOME, ptWORK);
TPhoneNumber = class
private
FTyp: TPhoneType;
FNumber: AnsiString;
const
ft_Number = 1;
ft_Typ = 2;
public
constructor Create;
property Number: AnsiString read FNumber write FNumber;
property Typ: TPhoneType read FTyp write FTyp;
end;
TPerson = class
private
FName: AnsiString;
FEmail: AnsiString;
FId: integer;
FPhones: TObjectList;
function GetPhones(Index: integer): TPhoneNumber;
function GetPhonesCount: integer;
const
ft_Name = 1;
ft_Id = 2;
ft_Email = 3;
ft_Phone = 4;
public
constructor Create;
destructor Destroy; override;
procedure AddPhone(const Number: AnsiString; Typ: TPhoneType = ptHOME);
procedure DeletePhone(Index: integer);
property Name: AnsiString read FName write FName;
property Id: integer read FId write FId;
property Email: AnsiString read FEmail write FEmail;
property PhonesCount: integer read GetPhonesCount;
property Phones[Index: integer]: TPhoneNumber read GetPhones;
end;
TPersonBuilder = class
private
FBuffer: TProtoBufOutput;
public
constructor Create;
destructor Destroy; override;
function GetBuf: TProtoBufOutput;
procedure Write(Person: TPerson);
end;
TPersonReader = class
private
FBuffer: TProtoBufInput;
procedure LoadPhone(Phone: TPhoneNumber);
public
constructor Create;
destructor Destroy; override;
function GetBuf: TProtoBufInput;
procedure Load(person: TPerson);
end;
implementation
{ TPhoneNumber }
constructor TPhoneNumber.Create;
begin
inherited Create;
FTyp := ptHOME;
end;
{ TPerson }
constructor TPerson.Create;
begin
inherited Create;
FPhones := TObjectList.Create(True);
end;
destructor TPerson.Destroy;
begin
FPhones.Free;
inherited;
end;
function TPerson.GetPhonesCount: integer;
begin
Result := FPhones.Count;
end;
function TPerson.GetPhones(Index: Integer): TPhoneNumber;
begin
Result := FPhones.Items[Index] as TPhoneNumber;
end;
procedure TPerson.AddPhone(const Number: AnsiString; Typ: TPhoneType = ptHOME);
var
Phone: TPhoneNumber;
begin
Phone := TPhoneNumber.Create;
Phone.Number := Number;
Phone.Typ := Typ;
FPhones.Add(Phone);
end;
procedure TPerson.DeletePhone(Index: integer);
begin
FPhones.Delete(Index);
end;
{ TPersonBuilder }
constructor TPersonBuilder.Create;
begin
inherited Create;
FBuffer := TProtoBufOutput.Create;
end;
destructor TPersonBuilder.Destroy;
begin
FBuffer.Free;
inherited;
end;
function TPersonBuilder.GetBuf: TProtoBufOutput;
begin
Result := FBuffer;
end;
procedure TPersonBuilder.Write(Person: TPerson);
var
Phone: TPhoneNumber;
PhonesBuffer: TProtoBufOutput;
i: Integer;
begin
FBuffer.writeString(TPerson.ft_Name, Person.Name);
FBuffer.writeInt32(TPerson.ft_Id, Person.FId);
// Not save empty e-mail
if Person.Email <> '' then
FBuffer.writeString(TPerson.ft_Email, Person.Email);
// Save Phones as Message
if Person.GetPhonesCount > 0 then
begin
PhonesBuffer := TProtoBufOutput.Create;
try
// Write person's phones
for i := 0 to Person.GetPhonesCount - 1 do
begin
PhonesBuffer.Clear;
Phone := Person.Phones[i];
PhonesBuffer.writeString(TPhoneNumber.ft_Number, Phone.Number);
// Not save phone type with Default value = ptHOME
if Phone.FTyp <> ptHOME then
PhonesBuffer.writeInt32(TPhoneNumber.ft_Typ, Ord(Phone.FTyp));
// Write phones as message
FBuffer.writeMessage(TPerson.ft_Phone, PhonesBuffer);
end;
finally
PhonesBuffer.Free;
end;
end;
end;
{ TPersonReader }
constructor TPersonReader.Create;
begin
inherited;
FBuffer := TProtoBufInput.Create;
end;
destructor TPersonReader.Destroy;
begin
FBuffer.Free;
inherited;
end;
function TPersonReader.GetBuf: TProtoBufInput;
begin
Result := FBuffer;
end;
procedure TPersonReader.Load(person: TPerson);
var
tag, fieldNumber, wireType: integer;
Phone: TPhoneNumber;
begin
tag := FBuffer.readTag;
while tag <> 0 do begin
wireType := getTagWireType(tag);
fieldNumber := getTagFieldNumber(tag);
case fieldNumber of
TPerson.ft_Name:
begin
Assert(wireType = WIRETYPE_LENGTH_DELIMITED);
person.Name := FBuffer.readString;
end;
TPerson.ft_Id:
begin
Assert(wireType = WIRETYPE_VARINT);
person.Id := FBuffer.readInt32;
end;
TPerson.ft_Email:
begin
Assert(wireType = WIRETYPE_LENGTH_DELIMITED);
person.Email := FBuffer.readString;
end;
TPerson.ft_Phone:
begin
Assert(wireType = WIRETYPE_LENGTH_DELIMITED);
Phone := TPhoneNumber.Create;
Person.FPhones.Add(Phone);
LoadPhone(Phone);
end;
else
FBuffer.skipField(tag);
end;
tag := FBuffer.readTag;
end;
end;
procedure TPersonReader.LoadPhone(Phone: TPhoneNumber);
var
tag, fieldNumber, wireType: integer;
size: Integer;
endPosition: Integer;
begin
size := FBuffer.readInt32;
endPosition := FBuffer.getPos + size;
repeat
tag := FBuffer.readTag;
if tag = 0 then exit;
wireType := getTagWireType(tag);
fieldNumber := getTagFieldNumber(tag);
case fieldNumber of
TPhoneNumber.ft_Number:
begin
Assert(wireType = WIRETYPE_LENGTH_DELIMITED);
Phone.Number := FBuffer.readString;
end;
TPhoneNumber.ft_Typ:
begin
Assert(wireType = WIRETYPE_VARINT);
Phone.Typ := TPhoneType(FBuffer.readInt32);
end;
else
FBuffer.skipField(tag);
end;
until FBuffer.getPos >= endPosition;
end;
end.
|
{
Copyright (c) 2017 - 2018 Sphere 10 Software
Common GUI unit usable across all tiers.
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
Acknowledgements:
Herman Schoenfeld
}
unit UCommon.UI;
{$mode delphi}
interface
uses
Classes, SysUtils, Forms, Controls,ExtCtrls,
FGL, Graphics, Generics.Collections, Generics.Defaults, syncobjs,
UMemory;
type
TApplicationForm = class(TForm)
private
FActivatedCount : UInt32;
FActivateFirstTime : TNotifyEvent;
FDestroyed : TNotifyEvent;
FCloseAction : TCloseAction;
FDisposables : TDisposables;
procedure NotifyActivateFirstTime;
procedure NotifyDestroyed;
protected
FUILock : TCriticalSection;
procedure DoCreate; override;
procedure Activate; override;
procedure ActivateFirstTime; virtual;
procedure DoClose(var CloseAction: TCloseAction); override;
procedure DoDestroy; override;
procedure DoDestroyed; virtual;
published
property CloseAction : TCloseAction read FCloseAction write FCloseAction;
property OnActivateFirstTime : TNotifyEvent read FActivateFirstTime write FActivateFirstTime;
property OnDestroyed : TNotifyEvent read FDestroyed write FDestroyed;
public
property ActivationCount : UInt32 read FActivatedCount;
function AutoDispose(AObject : TObject) : TObject;
end;
{ TWinControlHelper }
TWinControlHelper = class helper for TWinControl
procedure RemoveAllControls(destroy : boolean);
procedure AddControlDockCenter(AControl: TWinControl);
end;
{ TFormHelper }
TFormHelper = class helper for TForm
end;
{ TImageHelper }
TImageHelper = class helper for TImage
procedure SetImageListPicture(AImageList: TImageList; AIndex : SizeInt);
end;
implementation
{%region TApplicationForm}
procedure TApplicationForm.DoCreate;
begin
inherited;
FUILock := TCriticalSection.Create;
FActivatedCount := 0;
FCloseAction:=caHide;
end;
procedure TApplicationForm.Activate;
begin
inherited;
inc(FActivatedCount);
if (FActivatedCount = 1) then
NotifyActivateFirstTime;
end;
procedure TApplicationForm.ActivateFirstTime;
begin;
end;
procedure TApplicationForm.DoClose(var CloseAction: TCloseAction);
begin
CloseAction := FCloseAction;
end;
procedure TApplicationForm.DoDestroy;
begin
inherited;
FActivatedCount:=0;
FUILock.Destroy;
FUILock := nil;
NotifyDestroyed;
end;
procedure TApplicationForm.DoDestroyed;
begin;
end;
function TApplicationform.AutoDispose(AObject : TObject) : TObject;
begin
Result := FDisposables.AddObject(AObject);
end;
procedure TApplicationForm.NotifyActivateFirstTime;
begin
ActivateFirstTime;
if Assigned(FActivateFirstTime) then
FActivateFirstTime(Self);
end;
procedure TApplicationForm.NotifyDestroyed;
begin
DoDestroyed;
if Assigned(FDestroyed) then
FDestroyed(Self);
end;
{%endregion}
{%region TWinControlHelper}
procedure TWinControlHelper.RemoveAllControls(destroy : boolean);
var
control : TControl;
begin
while self.ControlCount > 0 do begin
control := self.Controls[0];
self.RemoveControl(control);
if destroy then control.Destroy;
end;
end;
procedure TWinControlHelper.AddControlDockCenter(AControl: TWinControl);
begin
if AControl.ClassType.InheritsFrom(TCustomForm) then begin
with TCustomForm(AControl) do begin
// Needed to avoid infinite WMSize loop
Constraints.MinHeight := 0;
Constraints.MaxHeight := 0;
Constraints.MinWidth := 0;
Constraints.MaxWidth := 0;
Anchors := [akTop, akLeft, akRight, akBottom];
end;
end;
with AControl do begin
Align := alClient;
Parent := Self;
Show;
if AControl.ClassType.InheritsFrom(TApplicationForm) then
TApplicationForm(AControl).Activate;
end;
end;
{%endregion}
{%region TFormHelper}
{%endregion}
{%region TImageHelper}
procedure TImageHelper.SetImageListPicture(AImageList: TImageList; AIndex : SizeInt);
begin
AImageList.GetBitmap(AIndex, Self.Picture.Bitmap);
end;
{%endregion}
end.
|
unit np.promise;
interface
uses sysUtils, np.common, np.value, generics.collections;
type
EPromise = class(exception);
TPromiseFunction = reference to procedure(ok,ko:TProc<IValue>);
TPromiseResult = reference to function(value: IValue) : IValue;
IPromise = interface(IValue)
['{A6F2C65C-709B-43BC-8CE1-447E922CF6E7}']
function then_( onFulfilled, onRejected: TPromiseResult ) : IPromise; overload;
function then_( onFulfilled : TPromiseResult) : IPromise; overload;
procedure then_(onFulfilled, onRejected: TProc<IValue>); overload;
procedure then_(onFulfilled: TProc<IValue>); overload;
function done( onComplete: TProc<IValue>) : IPromise; overload;
function done( onComplete: TProc) : IPromise; overload;
function catch( onRejected: TPromiseResult ) : IPromise;
end;
Promise = record
class function resolve(const value : IValue) : IPromise; static;
class function reject(const value : IValue) : IPromise; static;
class function all(const promises: array of const ) : IPromise; static;
class function race( const promises: array of const ) : IPromise; static;
class function new( const fn:TPromiseFunction ) : IPromise; static;
end;
function p2f(p: TProc<IValue>) : TPromiseResult;
var
_unhandledRejectionFn : TProc<IValue>;
implementation
uses np.core;
type
IHandler = interface
['{24BCEC98-66BC-4AAD-AE96-05EACEBB566C}']
end;
Tpromise = class(TSelfValue, IPromise, IValue)
private
_state : integer;
_handled : Boolean;
_value : IValue;
_deferreds : TList<IHandler>;
public
constructor Create(const fn:TPromiseFunction);
constructor CreateResolved(const AValue: IValue);
constructor CreateRejected(const AValue: IValue);
function then_( onFulfilled, onRejected: TPromiseResult ) : IPromise;overload;
function then_( onFulfilled: TPromiseResult ) : IPromise;overload;
procedure then_( onFulfilled, onRejected: TProc<IValue>);overload;
procedure then_( onFulfilled: TProc<IValue>);overload;
function done( onComplete: TProc<IValue>) : IPromise; overload;
function done( onComplete: TProc) : IPromise; overload;
function catch( onRejected: TPromiseResult ) : IPromise;
destructor Destroy; override;
end;
THandler = class(TInterfacedObject, IHandler)
private
onFulfilled : TPromiseResult;
onRejected : TPromiseResult;
promise : IPromise;
constructor Create( AonFulfilled : TPromiseResult;
AonRejected : TPromiseResult;
Apromise : IPromise);
end;
procedure doResolve(const fn : TPromiseFunction; promise:TPromise); forward;
procedure resolve(promise:TPromise; newValue:IValue); forward;
procedure reject(promise:TPromise; newValue :IValue); forward;
procedure finale(promise: TPromise); forward;
function Tpromise.catch(onRejected: TPromiseResult): IPromise;
begin
Result := then_(nil,onRejected);
end;
constructor Tpromise.Create(const fn: TPromiseFunction);
begin
assert(assigned(fn));
inherited Create;
//application.addTask;
_addRef;
_state := 0;
_value := nil;
_deferreds := TList<IHandler>.Create;
doResolve(fn,self);
end;
procedure handle(promise:TPromise; Adeferred : THandler);
begin
// while promise._value is TPromise do
// promise := TPromise(promise._value);
while promise._state = 3 do
promise := TPromise(promise._value);
// if assigned(Promise_onHandle) then
// promise_onHandle(promise);
if promise._state = 0 then
begin
promise._deferreds.Add( Adeferred );
exit;
end;
promise._handled := true;
promise._AddRef;
Adeferred._AddRef;
SetImmediate(
procedure
var
cb : TPromiseResult;
ret : IValue;
begin
try
if promise._state = 1 then
cb := Adeferred.onFulfilled
else
cb := Adeferred.onRejected;
if not assigned(cb) then
begin
if promise._state = 1 then
resolve(Adeferred.promise as TPromise, promise._value)
else
reject(Adeferred.promise as TPromise, promise._value);
exit;
end;
try
ret := cb(promise._value);
except
reject(Adeferred.promise as TPromise, TExceptionValue.Create);
exit;
end;
resolve(Adeferred.promise as TPromise, ret);
finally
promise._Release;
ADeferred._Release;
end;
end
);
end;
procedure resolve(promise:TPromise; newValue:IValue);
begin
if promise = nil then
exit;
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
try
if newValue is TPromise then
begin
if Tpromise(newValue) = promise then
raise EPromise.Create('A promise cannot be resolved with itself.');
promise._state := 3;
promise._value := newValue;
finale(promise);
exit;
end;
promise._state := 1;
promise._value := newValue;
finale(promise);
except
reject(promise,TExceptionValue.Create);
end;
end;
procedure reject(promise:TPromise; newValue :IValue);
begin
if promise = nil then
exit;
promise._state := 2;
promise._value := newValue;
finale(promise);
end;
procedure finale(promise: TPromise);
var
i : integer;
begin
if (promise._state = 2) and (promise._deferreds.Count = 0) then
begin
SetImmediate(
procedure
begin
try
if (not promise._handled) and assigned(_unhandledRejectionFn) then
_unhandledRejectionFn(promise._value);
finally
promise._Release;
end;
end);
exit;
end;
try
for i := 0 to promise._deferreds.count-1 do
begin
handle(promise, promise._deferreds[i] as THandler);
end;
promise._deferreds.Clear;
finally
promise._Release;
end;
end;
constructor THandler.Create( AonFulfilled : TPromiseResult;
AonRejected : TPromiseResult;
Apromise : IPromise);
begin
onFulfilled := AonFulFilled;
onRejected := AOnRejected;
promise := APromise;
end;
(**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*)
procedure doResolve(const fn : TPromiseFunction; promise:TPromise);
var done: Boolean;
begin
done := false;
try
fn(procedure(value:IValue)
begin
if done then
exit;
done := true;
resolve(promise,value);
end,
procedure(value:IValue)
begin
if done then
exit;
done := true;
reject(promise,value);
end);
except
on E:Exception do
begin
if done then
exit;
done := true;
reject(promise, TValue<string>.Create(E.Message,'reject'));
end;
end;
end;
constructor Tpromise.CreateResolved(const AValue: IValue);
begin
inherited Create;
_state := 1;
_value := AValue;
end;
constructor Tpromise.CreateRejected(const AValue: IValue);
begin
inherited Create;
_state := 2;
_value := AValue;
end;
function TPromise.then_( onFulfilled, onRejected: TPromiseResult ) : IPromise;
begin
result := TPromise.Create(procedure(ok,ko:TProc<IValue>) begin end);
handle(self, THandler.Create( onFulfilled, onRejected, result) );
end;
destructor Tpromise.Destroy;
begin
freeAndNil(_deferreds);
//application.log_debug(Format('Destroy Promise: %u',[NativeUint(self)]));
inherited;
end;
function Tpromise.done(onComplete: TProc): IPromise;
var
doneLast : TProc<IValue>;
begin
result := self;
if not assigned(onComplete) then
exit;
doneLast := procedure(ignoredVal: IValue)
begin
SetImmediate( onComplete );
end;
then_(doneLast,doneLast);
end;
procedure Tpromise.then_(onFulfilled: TProc<IValue>);
begin
then_(onFulfilled,nil);
end;
function Tpromise.done(onComplete: TProc<IValue>): IPromise;
var
doneLast : TProc<IValue>;
begin
result := self;
if not assigned(OnComplete) then
exit;
doneLast := procedure (val:IValue)
begin
SetImmediate(
procedure
begin
onComplete(val);
end);
end;
then_(doneLast,doneLast);
end;
procedure Tpromise.then_(onFulfilled, onRejected: TProc<IValue>);
begin
handle(self, THandler.Create(p2f( onFulfilled ), p2f( onRejected ), nil) );
end;
function Tpromise.then_(onFulfilled: TPromiseResult): IPromise;
begin
result := then_(onFulfilled,nil);
end;
{ Promise }
class function Promise.all(const promises: array of const): IPromise;
var
all : IValue;
begin
all := TAnyArray.Create( promises );
result := Promise.new(
procedure (Resolve,Reject:TProc<IValue>)
var
lCount : integer;
all_cast: TAnyArray;
begin
try
lCount := 0;
all_cast := all as TAnyArray;
all_cast.forEach(
procedure (value: IValue; Index: int64)
begin
if value is Tpromise then
begin
inc(lCount);
TPromise(value).then_(
procedure(value: IValue)
begin
all_cast[index] := value;
dec(lCount);
if lCount = 0 then
resolve( all );
end,
procedure(value:IValue)
begin
reject(value);
end);
end;
end);
if lCount = 0 then
resolve( all );
except
reject(TExceptionValue.Create);
end;
end);
end;
class function Promise.new(const fn: TPromiseFunction): IPromise;
begin
result := Tpromise.Create(fn);
end;
class function Promise.race(const promises: array of const): IPromise;
var
all : IValue;
begin
all := TAnyArray.Create( promises );
result := Promise.new(
procedure(resolve,reject: TProc<IValue>)
var
cast : TAnyArray;
begin
cast := all as TAnyArray;
cast.forEach(
procedure (value: IValue)
begin
if value is TPromise then
begin
TPromise(value).then_(resolve,reject);
end
else
resolve( value );
end);
end);
end;
class function Promise.reject(const value: IValue): IPromise;
begin
result := TPromise.CreateRejected(value);
end;
class function Promise.resolve(const value: IValue): IPromise;
begin
result := TPromise.CreateResolved(value);
end;
function p2f(p: TProc<IValue>) : TPromiseResult;
begin
result := function (value:IValue) : IValue
begin
if assigned(p) then
begin
p(value);
end;
result := void_0;
end
end;
initialization
_unhandledRejectionFn := procedure(Aerror:IValue)
begin
// if assigned(application) then
// application.log_warn(Format(
// 'Possible Unhandled Promise Rejection: %s',
// [(AError as TObject).ToString] ));
end;
end.
|
PROGRAM TreeSort(INPUT, OUTPUT);
{ Программа сортирует данные с помощью BinTree }
TYPE
Tree = ^Node;
Node = RECORD
Key: CHAR;
Left, Right: Tree;
END;
VAR
Root: Tree;
Ch: CHAR;
PROCEDURE Insert(VAR Ptr: Tree; Data: CHAR);
{ Процедура вставляет новые элементы в дерево }
BEGIN {Insert}
IF Ptr = NIL
THEN
BEGIN
NEW(Ptr);
Ptr^.Key := Data;
Ptr^.Left := NIL;
Ptr^.Right := NIL
END
ELSE
IF Ptr^.Key > Data
THEN
Insert(Ptr^.Left, Data)
ELSE
Insert(Ptr^.Right, Data)
END; {Insert}
PROCEDURE PrintTree(Ptr: Tree);
BEGIN {PrintTree}
IF Ptr <> NIL
THEN
BEGIN
PrintTree(Ptr^.Left);
WRITE(Ptr^.Key);
PrintTree(Ptr^.Right)
END
END; {PrintTree}
BEGIN { TreeSort }
Root := NIL;
WHILE NOT EOLN
DO
BEGIN
READ(Ch);
Insert(Root, Ch)
END;
PrintTree(Root);
WRITELN
END. { TreeSort }
|
unit UEditItems;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons,
// selfmade units
uConfig, uItems, uUtils;
type
TfrmEditItem = class(TForm)
BtnOK: TBitBtn;
BtnCancel: TBitBtn;
procedure BtnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
CurItemId: Integer;
ItemControls: array[NItemParam] of THackControl;
public
function Add(): TModalResult;
function Edit(Index: Integer): TModalResult;
end;
var
frmEditItem: TfrmEditItem;
implementation
{$R *.dfm}
function TfrmEditItem.Add(): TModalResult;
begin
Result := Edit(ItemConfig.Add);
end;
procedure TfrmEditItem.BtnOKClick(Sender: TObject);
var
i: NItemParam;
begin
for i := Low(NItemParam) to High(NItemParam) do
ItemConfig.Items[CurItemId, i] := ItemControls[i].Text;
end;
function TfrmEditItem.Edit(Index: Integer): TModalResult;
var
I: NItemParam;
begin
CurItemId := Index;
for i := Low(NItemParam) to High(NItemParam) do
begin
if (Trim(ItemConfig.Items[Index, i]) <> '') then
ItemControls[i].text := ItemConfig.Items[Index, i];
end;
Result := ShowModal;
end;
procedure TfrmEditItem.FormCreate(Sender: TObject);
const
middle = NItemParam(Ord(High(NItemParam)) div 2);
var
I: NItemParam;
T, L: Integer;
begin
T := 0; L := 0;
ClientWidth := (Ord(High(NItemParam)) div Ord(Middle)) * 300;
ClientHeight := Ord(Middle) * 30 + 90;
for i := Low(NItemParam) to High(NItemParam) do
begin
with TLabel.Create(Self) do
begin
Top := Ord(T) * 30 + 4;
Left := L;
Parent := Self;
Caption := ItemParamNames[i];
end;
TControl(ItemControls[i]) := ControlTypes[ItemParamType[i]].Create(Self);
with ItemControls[i] do
begin
case ItemParamType[I] of
npString: Width := 192;
end;
Top := Ord(T) * 30;
Left := L + 100;
Tag := Ord(i);
Parent := Self;
if i in [ipID] then Enabled := False;
end;
if (T = Ord(Middle)) then
begin
T := 0;
Inc(L, 300);
end else Inc(T);
end;
end;
end.
|
{ Subroutine SST_W_C_EXP_IMPLICIT (EXP,SYM_P)
*
* Create an implicit variable for the value of expression EXP, if EXP is
* not a "simple" expression. If an implicit variable is created, then SYM_P
* will point to its symbol descriptor. If not, then SYM_P will be returned
* NIL.
}
module sst_w_c_EXP_IMPLICIT;
define sst_w_c_exp_implicit;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_exp_implicit ( {create implicit var for exp value, if needed}
in exp: sst_exp_t; {descriptor for expression}
out sym_p: sst_symbol_p_t); {will pnt to implicit var, or NIL for unused}
begin
if sst_exp_simple (exp) then begin {no need for an implicit variable ?}
sym_p := nil; {indicate no implicit variable created}
return;
end;
sst_w_c_exp_explicit (exp, exp.dtype_p^, sym_p);
end;
|
{
Copyright (C) 2013-2021 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit SnippetSource.Forms.Console;
{$MODE DELPHI}
interface
uses
Classes, SysUtils, process, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls,
PythonEngine, uCmdBox;
type
{ TfrmConsole }
TfrmConsole = class(TForm)
cmdMain : TCmdBox;
prcMain : TProcess;
PythonEngine : TPythonEngine;
PythonInputOutput : TPythonInputOutput;
tmrMain : TTimer;
{$REGION 'event handlers'}
procedure cmdMainInput(ACmdBox: TCmdBox; Input: string);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure PythonInputOutputReceiveData(
Sender : TObject;
var Data : AnsiString
);
procedure PythonInputOutputSendData(
Sender : TObject;
const Data : AnsiString
);
procedure tmrMainTimer(Sender: TObject);
{$ENDREGION}
private
procedure ProcessString(const AString: string);
public
procedure AfterConstruction; override;
destructor Destroy; override;
procedure Execute(const AFileName: string);
procedure ExecutePy(const AStrings: TStrings);
end;
implementation
uses
ts.Core.Logger;
{$R *.lfm}
{$REGION 'construction and destruction'}
procedure TfrmConsole.AfterConstruction;
begin
inherited AfterConstruction;
prcMain.Active := True;
tmrMain.Enabled := True;
//PythonEngine.LoadDll;
//cmdMain.StartRead(clSilver, clBlack, '', clWhite, clBlack);
end;
destructor TfrmConsole.Destroy;
begin
Logger.Enter(Self, 'Destroy');
prcMain.Active := False;
tmrMain.Enabled := True;
inherited Destroy;
Logger.Leave(Self, 'Destroy');
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TfrmConsole.tmrMainTimer(Sender: TObject);
var
LBuf : array[0..2048] of Char;
S : string;
begin
LBuf := '';
if prcMain.Output.NumBytesAvailable > 0 then
begin
while prcMain.Output.NumBytesAvailable > 0 do
begin
Logger.Watch('prcMain.Output.NumBytesAvailable', prcMain.Output.NumBytesAvailable);
FillChar(LBuf, SizeOf(LBuf), #0);
prcMain.Output.Read(LBuf, SizeOf(LBuf) - 1);
S := LBuf;
ProcessString(S);
end;
end;
if prcMain.Stderr.NumBytesAvailable > 0 then
begin
while prcMain.Stderr.NumBytesAvailable > 0 do
begin
Logger.Watch('prcMain.StdErr.NumBytesAvailable', prcMain.StdErr.NumBytesAvailable);
FillChar(LBuf, SizeOf(LBuf), #0);
prcMain.Stderr.Read(LBuf, SizeOf(LBuf) - 1);
S := LBuf;
cmdMain.TextColor(clRed);
cmdMain.Write(S);
end;
end;
end;
procedure TfrmConsole.cmdMainInput(ACmdBox: TCmdBox; Input: string);
var
S : string;
begin
Logger.Enter(Self, 'cmdMainInput');
S := Input + LineEnding;
Logger.SendText(S);
prcMain.Input.Write(S[1], Length(S));
//ProcessString(S);
//PythonEngine.ExecString(S);
Logger.Leave(Self, 'cmdMainInput');
end;
procedure TfrmConsole.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
cmdMain.Clear;
end;
procedure TfrmConsole.PythonInputOutputReceiveData(Sender: TObject;
var Data: AnsiString);
begin
//ProcessString(Data);
//PythonEngine.ExecString(Data);
end;
procedure TfrmConsole.PythonInputOutputSendData(Sender: TObject;
const Data: AnsiString);
begin
// ProcessString(Data);
// cmdMain.Writeln(Data);
end;
{$ENDREGION}
{$REGION 'protected methods'}
procedure TfrmConsole.ProcessString(const AString: string);
var
SL : TStringList;
I : Integer;
S : string;
begin
SL := TStringList.Create;
try
SL.Text := AString;
if SL.Count > 0 then
begin
for I := 0 to SL.Count - 1 do
begin
S := SL[I];
if (I = (SL.Count - 1)) and (S[Length(S)] = '>') then
begin
cmdMain.StartRead(clSilver, clBlack, S, clWhite, clBlack);
Logger.Info(S);
end
else if I < (SL.Count - 1) then
begin
cmdMain.TextColor(clSilver);
cmdMain.Writeln(S);
end
else
begin
cmdMain.TextColor(clSilver);
cmdMain.Write(S);
end;
end;
end
else
cmdMain.StartRead(clSilver, clBlack, AString, clWhite, clBlack);
finally
SL.Free;
end;
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TfrmConsole.Execute(const AFileName: string);
begin
Logger.Enter(Self, 'Execute');
prcMain.Executable := 'cmd';
prcMain.Parameters.Add('/K call ' + AFileName);
prcMain.Execute;
cmdMain.SetFocus;
Logger.Leave(Self, 'Execute');
end;
procedure TfrmConsole.ExecutePy(const AStrings: TStrings);
begin
PythonEngine.ExecStrings(AStrings);
end;
{$ENDREGION}
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpAsn1Null;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpAsn1Object,
ClpIAsn1Null;
type
/// <summary>
/// A Null object.
/// </summary>
TAsn1Null = class abstract(TAsn1Object, IAsn1Null)
public
function ToString(): String; override;
end;
implementation
{ TAsn1Null }
function TAsn1Null.ToString: String;
begin
result := 'NULL';
end;
end.
|
procedure TEqualizerForm.TrackBar_Ch00Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh00, TrackBar_Ch00, Label_GainCh00);
end;
procedure TEqualizerForm.TrackBar_Ch01Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh01, TrackBar_Ch01, Label_GainCh01);
end;
procedure TEqualizerForm.TrackBar_Ch02Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh02, TrackBar_Ch02, Label_GainCh02);
end;
procedure TEqualizerForm.TrackBar_Ch03Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh03, TrackBar_Ch03, Label_GainCh03);
end;
procedure TEqualizerForm.TrackBar_Ch04Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh04, TrackBar_Ch04, Label_GainCh04);
end;
procedure TEqualizerForm.TrackBar_Ch05Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh05, TrackBar_Ch05, Label_GainCh05);
end;
procedure TEqualizerForm.TrackBar_Ch06Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh06, TrackBar_Ch06, Label_GainCh06);
end;
procedure TEqualizerForm.TrackBar_Ch07Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh07, TrackBar_Ch07, Label_GainCh07);
end;
procedure TEqualizerForm.TrackBar_Ch08Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh08, TrackBar_Ch08, Label_GainCh08);
end;
procedure TEqualizerForm.TrackBar_Ch09Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh09, TrackBar_Ch09, Label_GainCh09);
end;
procedure TEqualizerForm.TrackBar_Ch10Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh10, TrackBar_Ch10, Label_GainCh10);
end;
procedure TEqualizerForm.TrackBar_Ch11Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh11, TrackBar_Ch11, Label_GainCh11);
end;
procedure TEqualizerForm.TrackBar_Ch12Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh12, TrackBar_Ch12, Label_GainCh12);
end;
procedure TEqualizerForm.TrackBar_Ch13Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh13, TrackBar_Ch13, Label_GainCh13);
end;
procedure TEqualizerForm.TrackBar_Ch14Change(Sender: TObject);
begin
UpdateFromTrackbar_4_12(Link_EQGainCh14, TrackBar_Ch14, Label_GainCh14);
end;
procedure TEqualizerForm.AudioProcessorFormShow(Sender: TObject);
begin
TrackBar_Ch00 .Value := 10;
TrackBar_Ch01 .Value := 10;
TrackBar_Ch02 .Value := 10;
TrackBar_Ch03 .Value := 10;
TrackBar_Ch04 .Value := 10;
TrackBar_Ch05 .Value := 10;
TrackBar_Ch06 .Value := 10;
TrackBar_Ch07 .Value := 10;
TrackBar_Ch08 .Value := 10;
TrackBar_Ch09 .Value := 10;
TrackBar_Ch10 .Value := 10;
TrackBar_Ch11 .Value := 10;
TrackBar_Ch12 .Value := 10;
TrackBar_Ch13 .Value := 10;
TrackBar_Ch14 .Value := 10;
Check_EQEnable.Checked := True;
Check_EQDeltaOnly.Checked := False;
end;
procedure TEqualizerForm.Check_EQEnableClick(Sender: TObject);
begin
Check_EQDeltaOnly.Enabled := Check_EQEnable.Checked;
end;
|
unit impl;
interface
uses
System.TypInfo, Macapi.ObjectiveC, Macapi.CocoaTypes, Macapi.Foundation, Macapi.AppKit;
type
TOCLocalEx<T, I: NSObject> = class abstract(TOCLocal)
protected
function Super: I; inline;
function GetObjectiveCClass: PTypeInfo; override;
public
constructor Create;
end;
CircleView = interface(NSView)
['{DD9EF84E-A302-4009-AF48-1F72290E7D32}']
// Standard view create/free methods
function initWithFrame(frame: NSRect): Pointer; cdecl;
/// procedure dealloc; cdecl;
// Drawing
procedure drawRect(rect: NSRect); cdecl;
function isOpaque: Boolean; cdecl;
// Event handling
procedure mouseDown(event: NSEvent); cdecl;
procedure mouseDragged(event: NSEvent); cdecl;
// Custom methods for actions this view implements
procedure takeColorFrom(sender: NSColorWell); cdecl;
procedure takeRadiusFrom(sender: NSControl); cdecl;
procedure takeStartingAngleFrom(sender: NSControl); cdecl;
procedure takeAngularVelocityFrom(sender: NSControl); cdecl;
procedure takeStringFrom(sender: NSControl); cdecl;
procedure startAnimation(sender: NSControl); cdecl;
procedure stopAnimation(sender: NSControl); cdecl;
procedure toggleAnimation(sender: NSControl); cdecl;
// Method invoked by timer
procedure performAnimation(sender: NSTimer); cdecl;
end;
TCircleView = class(TOCLocalEx<CircleView, NSView>)
private
center: NSPoint;
radius: CGFloat;
startingAngle: CGFloat;
angularVelocity: CGFloat;
textStorage: NSTextStorage;
layoutManager: NSLayoutManager;
textContainer: NSTextContainer;
timer: NSTimer;
lastTime: NSTimeInterval;
private
// Methods to set parameters
procedure setColor(color: NSColor);
procedure setRadius(distance: CGFloat);
procedure setStartingAngle(angle: CGFloat);
procedure setAngularVelocity(velocity: CGFloat);
procedure setString(&string: NSString);
public { ObjectiveC }
// Standard view create/free methods
function initWithFrame(frame: NSRect): Pointer; cdecl;
destructor Destroy; /// procedure dealloc; cdecl;
// Drawing
procedure drawRect(rect: NSRect); cdecl;
function isOpaque: Boolean; cdecl;
// Event handling
procedure mouseDown(event: NSEvent); cdecl;
procedure mouseDragged(event: NSEvent); cdecl;
// Custom methods for actions this view implements
procedure takeColorFrom(sender: NSColorWell); cdecl;
procedure takeRadiusFrom(sender: NSControl); cdecl;
procedure takeStartingAngleFrom(sender: NSControl); cdecl;
procedure takeAngularVelocityFrom(sender: NSControl); cdecl;
procedure takeStringFrom(sender: NSControl); cdecl;
procedure startAnimation(sender: NSControl); cdecl;
procedure stopAnimation(sender: NSControl); cdecl;
procedure toggleAnimation(sender: NSControl); cdecl;
// Method invoked by timer
procedure performAnimation(sender: NSTimer); cdecl;
end;
implementation
uses Macapi.ObjCRuntime;
const
AppKitLib = '/System/Library/Frameworks/AppKit.framework/AppKit';
M_PI_2 = PI / 2;
YES = True;
NO = False;
procedure NSRectFill(aRect: NSRect); cdecl; external AppKitLib name '_NSRectFill';
function NSMaxRange(const range: NSRange): NSUInteger; inline;
begin
Result := range.location + range.length;
end;
function NSMakeRange(location: NSUInteger; length: NSUInteger): NSRange; inline;
begin
Result.location := location;
Result.length := length;
end;
function NSMakePoint(x: Single; y: Single): NSPoint; inline;
begin
Result.x := x;
Result.y := y;
end;
{ TOCLocalEx<T> }
constructor TOCLocalEx<T, I>.Create;
begin
inherited Create;
end;
function TOCLocalEx<T, I>.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(T);
end;
function TOCLocalEx<T, I>.Super: I;
begin
Result := I(inherited Super);
end;
{ TCircleView }
// Many of the methods here are similar to those in the simpler DotView example.
// See that example for detailed explanations; here we will discuss those
// features that are unique to CircleView.
// CircleView draws text around a circle, using Cocoa's text system for
// glyph generation and layout, then calculating the positions of glyphs
// based on that layout, and using NSLayoutManager for drawing.
function TCircleView.initWithFrame(frame: NSRect): Pointer;
begin
if Self = nil then
begin
Result := TCircleView.Create.initWithFrame(frame);
end else
begin
Super.initWithFrame(frame);
Result := GetObjectID;
// First, we set default values for the various parameters.
center.x := frame.size.width / 2;
center.y := frame.size.height / 2;
radius := 115.0;
startingAngle := M_PI_2;
angularVelocity := M_PI_2;
// Next, we create and initialize instances of the three
// basic non-view components of the text system:
// an NSTextStorage, an NSLayoutManager, and an NSTextContainer.
textStorage := TNSTextStorage.Wrap(TNSTextStorage.Alloc.initWithString(NSSTR('Here''s to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes, the ones who see things differently.')));
layoutManager := TNSLayoutManager.Create;
textContainer := TNSTextContainer.Create;
layoutManager.addTextContainer(textContainer);
textContainer.release; // The layoutManager will retain the textContainer
textStorage.addLayoutManager(layoutManager);
layoutManager.release; // The textStorage will retain the layoutManager
// Screen fonts are not suitable for scaled or rotated drawing.
// Views that use NSLayoutManager directly for text drawing should
// set this parameter appropriately.
layoutManager.setUsesScreenFonts(NO);
end;
end;
destructor TCircleView.Destroy; /// procedure TCircleView.dealloc;
begin
timer.invalidate;
timer.release;
textStorage.release;
inherited Destroy;
end;
var
set_SEL: Pointer;
procedure TCircleView.drawRect(rect: NSRect);
var
glyphIndex: NSUInteger;
glyphRange: NSRange;
usedRect: NSRect;
context: NSGraphicsContext;
lineFragmentRect: NSRect;
viewLocation: NSPoint;
layoutLocation: NSPoint;
angle: CGFloat;
distance: CGFloat;
transform: NSAffineTransform;
begin
if set_SEL = nil then
begin
set_SEL := sel_registerName('set');
end;
objc_msgSend(TNSColor.OCClass.whiteColor, set_SEL);
NSRectFill(Super.bounds);
// Note that usedRectForTextContainer: does not force layout, so it must
// be called after glyphRangeForTextContainer:, which does force layout.
glyphRange := layoutManager.glyphRangeForTextContainer(textContainer);
usedRect := layoutManager.usedRectForTextContainer(textContainer);
for glyphIndex := glyphRange.location to NSMaxRange(glyphRange) - 1 do
begin
context := TNSGraphicsContext.Wrap(TNSGraphicsContext.OCClass.currentContext);
lineFragmentRect := layoutManager.lineFragmentRectForGlyphAtIndex(glyphIndex, nil);
viewLocation := layoutManager.locationForGlyphAtIndex(glyphIndex);
layoutLocation := viewLocation;
transform := TNSAffineTransform.Wrap(TNSAffineTransform.OCClass.transform);
// Here layoutLocation is the location (in container coordinates) where the glyph was laid out.
layoutLocation.x := layoutLocation.x + lineFragmentRect.origin.x;
layoutLocation.y := layoutLocation.y + lineFragmentRect.origin.y;
// We then use the layoutLocation to calculate an appropriate position for the glyph
// around the circle (by angle and distance, or viewLocation in rectangular coordinates).
distance := radius + usedRect.size.height - layoutLocation.y;
angle := startingAngle + layoutLocation.x / distance;
viewLocation.x := center.x + distance * sin(angle);
viewLocation.y := center.y + distance * cos(angle);
// We use a different affine transform for each glyph, to position and rotate it
// based on its calculated position around the circle.
transform.translateXBy(viewLocation.x, viewLocation.y);
transform.rotateByRadians(-angle);
// We save and restore the graphics state so that the transform applies only to this glyph.
context.saveGraphicsState();
transform.concat();
// drawGlyphsForGlyphRange: draws the glyph at its laid-out location in container coordinates.
// Since we are using the transform to place the glyph, we subtract the laid-out location here.
layoutManager.drawGlyphsForGlyphRange(NSMakeRange(glyphIndex, 1), NSMakePoint(-layoutLocation.x, -layoutLocation.y));
context.restoreGraphicsState();
end;
end;
function TCircleView.isOpaque: Boolean;
begin
Result := YES;
end;
// DotView changes location on mouse up, but here we choose to do so
// on mouse down and mouse drags, so the text will follow the mouse.
procedure TCircleView.mouseDown(event: NSEvent);
var
eventLocation: NSPoint;
begin
eventLocation := event.locationInWindow;
center := Super.convertPoint(eventLocation, nil);
Super.setNeedsDisplay(YES);
end;
procedure TCircleView.mouseDragged(event: NSEvent);
var
eventLocation: NSPoint;
begin
eventLocation := event.locationInWindow;
center := Super.convertPoint(eventLocation, nil);
Super.setNeedsDisplay(YES);
end;
// DotView uses action methods to set its parameters. Here we have
// factored each of those into a method to set each parameter directly
// and a separate action method.
procedure TCircleView.setColor(color: NSColor);
begin
// Text drawing uses the attributes set on the text storage rather
// than drawing context attributes like the current color.
textStorage.addAttribute(NSForegroundColorAttributeName, (color as ILocalObject).GetObjectID, NSMakeRange(0, textStorage.length));
Super.setNeedsDisplay(YES);
end;
procedure TCircleView.setRadius(distance: CGFloat);
begin
radius := distance;
Super.setNeedsDisplay(YES);
end;
procedure TCircleView.setStartingAngle(angle: CGFloat);
begin
startingAngle := angle;
Super.setNeedsDisplay(YES);
end;
procedure TCircleView.setAngularVelocity(velocity: CGFloat);
begin
angularVelocity := velocity;
Super.setNeedsDisplay(YES);
end;
procedure TCircleView.setString(&string: NSString);
begin
textStorage.replaceCharactersInRange(NSMakeRange(0, textStorage.length), &string);
Super.setNeedsDisplay(YES);
end;
procedure TCircleView.takeColorFrom(sender: NSColorWell);
begin
setColor(sender.color);
end;
procedure TCircleView.takeRadiusFrom(sender: NSControl);
begin
setRadius(sender.doubleValue);
end;
procedure TCircleView.takeStartingAngleFrom(sender: NSControl);
begin
setStartingAngle(sender.doubleValue);
end;
procedure TCircleView.takeAngularVelocityFrom(sender: NSControl);
begin
setAngularVelocity(sender.doubleValue);
end;
procedure TCircleView.takeStringFrom(sender: NSControl);
begin
setString(sender.stringValue);
end;
var
performAnimation_SEL: Pointer;
procedure TCircleView.startAnimation(sender: NSControl);
begin
stopAnimation(sender);
// We schedule a timer for a desired 30fps animation rate.
// In performAnimation: we determine exactly
// how much time has elapsed and animate accordingly.
if performAnimation_SEL = nil then
begin
performAnimation_SEL := sel_registerName('performAnimation:');
end;
timer := TNSTimer.Wrap(TNSTimer.OCClass.scheduledTimerWithTimeInterval(1.0/30.0, GetObjectID, performAnimation_SEL, nil, Yes));
timer.retain;
// The next two lines make sure that animation will continue to occur
// while modal panels are displayed and while event tracking is taking
// place (for example, while a slider is being dragged).
TNSRunLoop.Wrap(TNSRunLoop.OCClass.currentRunLoop).addTimer(timer, NSModalPanelRunLoopMode);
TNSRunLoop.Wrap(TNSRunLoop.OCClass.currentRunLoop).addTimer(timer, NSEventTrackingRunLoopMode);
lastTime := TNSDate.OCClass.timeIntervalSinceReferenceDate;
end;
procedure TCircleView.stopAnimation(sender: NSControl);
begin
if timer <> nil then
begin
timer.invalidate;
timer.release;
timer := nil;
end;
end;
procedure TCircleView.toggleAnimation(sender: NSControl);
begin
if timer <> nil then
begin
stopAnimation(sender);
end else
begin
startAnimation(sender);
end;
end;
procedure TCircleView.performAnimation(sender: NSTimer);
var
thisTime: NSTimeInterval;
begin
// We determine how much time has elapsed since the last animation,
// and we advance the angle accordingly.
thisTime := TNSDate.OCClass.timeIntervalSinceReferenceDate;
setStartingAngle(startingAngle + angularVelocity * (thisTime - lastTime));
lastTime := thisTime;
end;
end.
|
unit UStudent;
interface
uses
System.SysUtils,Vcl.Dialogs;
type
TStudent = class
private
FFirstName: string;
FSecondName: string;
FAge: Integer;
FLike: TArray<string>;
procedure SetAge(const Value: Integer);
procedure SetFirstName(const Value: string);
procedure SetSecondName(const Value: string);
procedure SetLike(const Value: TArray<string>);
public
property FirstName: string read FFirstName write SetFirstName;
property SecondName: string read FSecondName write SetSecondName;
property Age: Integer read FAge write SetAge;
property Like: TArray<string> read FLike write SetLike;
constructor Create(FFirstName: string; FSecondName: string; FAge: Integer); overload;
end;
implementation
{ TStudent }
constructor TStudent.Create(FFirstName, FSecondName: string; FAge: Integer);
begin
Self.FFirstName := FFirstName;
Self.FSecondName := FSecondName;
Self.FAge := FAge;
end;
procedure TStudent.SetAge(const Value: Integer);
begin
FAge := Value;
end;
procedure TStudent.SetFirstName(const Value: string);
begin
FFirstName := Value;
end;
procedure TStudent.SetLike(const Value: TArray<string>);
var
Num: Integer;
begin
// 动态数组,必须先设定长度才能赋值,否则出错
SetLength(FLike, 10);
for Num := Low(Value) to High(Value) do
begin
// 最多能有10个爱好
if Num > 9 then
begin
ShowMessage('爱好不能超过10个');
Break;
end;
FLike[Num] := Value[Num];
end;
end;
procedure TStudent.SetSecondName(const Value: string);
begin
FSecondName := Value;
end;
end.
|
unit QRNewXLSXFiltProcs;
interface
uses windows, classes, sysutils;
type
TAppParams = record
creator : string;
sheetname : string;
company : string;
LastCell : string;
numstrings : string;
end;
var
appParams : TAppParams;
fontlist : TStringlist;
fillslist : TStringlist;
styleslist : TStringlist;
colwidths : TStringlist;
procedure Load_app_file( alist : TStringlist);
procedure Load_core_file( alist : TStringlist);
procedure Load_ContentTypes_file( alist : TStringlist);
procedure Load_dotrels_file( alist : TStringlist);
procedure Load_workbookdotrels_file( alist : TStringlist);
procedure Load_workbook_file( alist : TStringlist; sheetname : string);
procedure Load_sheet1prolog( alist : TStringlist);
function num2XLCol( n : integer ) : string;
procedure MakeStyles( alist : TStringlist);
implementation
function num2XLCol( n : integer ) : string;
var
major, minor : integer;
begin
// row 0 is A. row 26 is AA
if n<=25 then
result := ''+chr(ord('A') + n)
else
begin
major := n div 26;
minor := n mod 26;
result := ''+chr(ord('A') + major-1) + chr(ord('A') + minor)
end;
end;
procedure MakeStyles( alist : TStringlist);
var
n : integer;
begin
alist.add('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
alist.add('<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">');
alist.add('<fonts count="'+inttostr(fontlist.Count)+'" >');
for n := 0 to fontlist.Count-1 do
begin
alist.Add(fontlist[n]);
end;
alist.Add('</fonts>');
{$ifdef XXXX}
// add one fill
alist.Add('<fills count="1"><fill><patternFill patternType="none"/></fill></fills>');
{$else}
alist.add('<fills count="'+inttostr(fillslist.Count)+'" >');
for n := 0 to fillslist.Count-1 do
begin
alist.Add(fillslist[n]);
end;
alist.Add('</fills>');
{$endif}
// add one border
alist.Add('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
alist.Add('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
// <cellXfs count="3"> one for each font
{$ifdef XXXX}
alist.add('<cellXfs count="'+inttostr(fontlist.Count)+'" >');
for n := 0 to fontlist.Count-1 do
begin
alist.Add(' <xf numFmtId="0" fontId="'+inttostr(n)+'" fillId="0" borderId="0" xfId="0" applyFont="1"/>');
end;
{$else}
alist.add('<cellXfs count="'+inttostr(styleslist.Count)+'" >');
for n := 0 to styleslist.Count-1 do
begin
alist.Add(styleslist[n]);
end;
{$endif}
alist.add('</cellXfs>');
alist.add('</styleSheet>');
end;
procedure Load_sheet1prolog( alist : TStringlist);
var
n : integer;
begin
alist.add('<?xml version="1.0" encoding="utf-8"?>');
alist.add('<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
if colwidths.Count > 0 then
begin
alist.add('<x:cols>');
for n := 0 to colwidths.Count-1 do
alist.add(colwidths[n]);
alist.add('</x:cols>');
end;
alist.add(' <x:sheetData>');
end;
procedure Load_workbook_file( alist : TStringlist; sheetname : string);
begin
alist.add('<?xml version="1.0" encoding="utf-8"?>');
alist.add('<x:workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
alist.add(' <x:sheets>');
alist.add(' <x:sheet name="'+sheetname+'" sheetId="1" r:id="rId1"/>');
alist.add(' </x:sheets>');
alist.add('</x:workbook>');
end;
procedure Load_app_file( alist : TStringlist);
begin
alist.add('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
alist.add('<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">');
alist.add(' <Application>Microsoft Excel</Application>');
alist.add(' <DocSecurity>0</DocSecurity>');
alist.add(' <ScaleCrop>false</ScaleCrop>');
alist.add(' <HeadingPairs>');
alist.add(' <vt:vector size="2" baseType="variant">');
alist.add(' <vt:variant>');
alist.add(' <vt:lpstr>Worksheets</vt:lpstr>');
alist.add(' </vt:variant>');
alist.add(' <vt:variant>');
alist.add(' <vt:i4>1</vt:i4>');
alist.add(' </vt:variant>');
alist.add(' </vt:vector>');
alist.add(' </HeadingPairs>');
alist.add(' <TitlesOfParts>');
alist.add(' <vt:vector size="1" baseType="lpstr">');
alist.add(' <vt:lpstr>'+appParams.sheetname+'</vt:lpstr>');
alist.add(' </vt:vector>');
alist.add(' </TitlesOfParts>');
alist.add(' <Company>'+appParams.company+'</Company>');
alist.add(' <LinksUpToDate>false</LinksUpToDate>');
alist.add(' <SharedDoc>false</SharedDoc>');
alist.add(' <HyperlinksChanged>false</HyperlinksChanged>');
alist.add(' <AppVersion>14.0300</AppVersion>');
alist.add('</Properties>');
end;
procedure Load_core_file( alist : TStringlist);
var
tstr : string;
begin
alist.add('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
tstr := 'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
alist.add('<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ' + tstr);
alist.add(' <dc:creator>'+appParams.creator+'</dc:creator>');
alist.add(' <cp:lastModifiedBy>'+appParams.creator+'</cp:lastModifiedBy>');
alist.add(' <dcterms:created xsi:type="dcterms:W3CDTF">2014-07-22T09:23:12Z</dcterms:created>');
alist.add(' <dcterms:modified xsi:type="dcterms:W3CDTF">2014-07-22T09:23:12Z</dcterms:modified>');
alist.add('</cp:coreProperties>');
end;
procedure Load_ContentTypes_file( alist : TStringlist);
begin
alist.add('<?xml version="1.0" encoding="utf-8"?>');
alist.add('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">');
alist.add(' <Default Extension="xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>');
alist.add(' <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>');
alist.add(' <Override PartName="/xl/worksheets/sheet.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>');
alist.add(' <Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>');
alist.add('</Types>');
end;
procedure Load_dotrels_file( alist : TStringlist);
begin
alist.add('<?xml version="1.0" encoding="utf-8"?>');
alist.add('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
alist.add(' <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="/xl/workbook.xml" Id="R9e4add5772f8421c"/>');
alist.add('</Relationships>');
end;
procedure Load_workbookdotrels_file( alist : TStringlist);
begin
alist.add('<?xml version="1.0" encoding="utf-8"?>');
alist.add('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
alist.add(' <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="/xl/worksheets/sheet.xml" Id="rId1"/>');
alist.add(' <Relationship Target="/xl/styles.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Id="rId2"/>');
alist.add('</Relationships>');
end;
end.
|
PROGRAM Pseudo(INPUT, OUTPUT);
CONST
Rows = 5;
Columns = 5;
TYPE
SignsPlace = SET OF 1 .. 25;
PROCEDURE WritePseudo(VAR PseudoLetter: SignsPlace);
VAR
Row, PositionInRow: INTEGER;
PROCEDURE WriteLine(VAR PseudoLetter: SignsPlace; VAR Row, Column: INTEGER);
BEGIN {WriteLine}
FOR Column := Column TO (Row * Rows)
DO
IF Column IN PseudoLetter
THEN
BEGIN
WRITE('#');
PseudoLetter := PseudoLetter - [Column]
END
ELSE
WRITE(' ');
Column := Column + 1;
WRITELN
END; {WriteLine}
BEGIN {WritePseudo}
PositionInRow := 1;
Row := 1;
WHILE Row <> Rows
DO
BEGIN
CASE Row OF
1 : WriteLine(PseudoLetter, Row, PositionInRow);
2 : WriteLine(PseudoLetter, Row, PositionInRow);
3 : WriteLine(PseudoLetter, Row, PositionInRow);
4 : WriteLine(PseudoLetter, Row, PositionInRow);
5 : WriteLine(PseudoLetter, Row, PositionInRow)
END;
Row := Row + 1;
END
END; {WritePseudo}
VAR
PseudoLetter: SignsPlace;
BEGIN {Pseudo}
PseudoLetter := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25];
WritePseudo(PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 25];
WritePseudo(PseudoLetter)
END. {Pseudo}
|
unit fmuPrintBarcodePrinter;
interface
uses
// VCL
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ComCtrls,
// This
untPages, untUtil, untDriver, Spin;
type
{ TfmPrintBarcode }
TfmPrintBarcodePrinter = class(TPage)
lblData: TLabel;
edtBarcode: TEdit;
lblBarWidth: TLabel;
lblBarcodeType: TLabel;
seBarWidth: TSpinEdit;
seLineNumber: TSpinEdit;
lblLineNumber: TLabel;
btnPrintBarcodeUsingPrinter: TButton;
seFontType: TSpinEdit;
lblFontType: TLabel;
seHRIPosition: TSpinEdit;
lblHRIPosition: TLabel;
chbCutPaper: TCheckBox;
cbBarcodeType: TComboBox;
chbPrintMaxWidth: TCheckBox;
procedure btnPrintBarcodeUsingPrinterClick(Sender: TObject);
private
procedure CutPaper;
procedure PrintMaxWidthLine;
procedure Check(ResultCode: Integer);
public
procedure Initialize; override;
end;
implementation
type
TBarcode = record
BarcodeType: Integer;
Description: string;
end;
const
Barcodes: array[0..9] of TBarcode = (
(BarcodeType: 0;
Description: 'UPC-A'),
(BarcodeType: 1;
Description: 'UPC-E'),
(BarcodeType: 2;
Description: 'EAN13 (JAN)'),
(BarcodeType: 3;
Description: 'EAN8 (JAN)'),
(BarcodeType: 4;
Description: 'CODE39'),
(BarcodeType: 5;
Description: 'ITF'),
(BarcodeType: 6;
Description: 'CODABAR'),
(BarcodeType: 7;
Description: 'CODE93'),
(BarcodeType: 8;
Description: 'CODE128'),
(BarcodeType: 20;
Description: 'CODE32'));
{$R *.DFM}
{ TfmPrintBarcode }
procedure TfmPrintBarcodePrinter.Initialize;
var
i : Integer;
begin
for i := 0 to 9 do
cbBarcodeType.AddItem(Barcodes[i].Description, TObject(Barcodes[i].BarcodeType));
cbBarcodeType.ItemIndex := 0;
end;
procedure TfmPrintBarcodePrinter.CutPaper;
begin
if chbCutPaper.Checked then
begin
// Промотка
Driver.UseJournalRibbon := False;
Driver.UseReceiptRibbon := True;
Driver.UseSlipDocument := False;
Driver.StringQuantity := 10;
Check(Driver.FeedDocument);
// Отрезка
Driver.CutType := True;
Check(Driver.CutCheck);
Sleep(100);
end;
end;
procedure TfmPrintBarcodePrinter.PrintMaxWidthLine;
var
Count: Integer; // количество байт
begin
if not chbPrintMaxWidth.Checked then Exit;
// Узнаем ширину печати
Driver.FontType := 1;
Check(Driver.GetFontMetrics);
Count := Driver.PrintWidth div 8;
// Печатаем
Driver.LineNumber := 10;
Driver.LineData := StringOfChar(#$FF, Count);
Check(Driver.PrintLine);
end;
procedure TfmPrintBarcodePrinter.Check(ResultCode: Integer);
begin
if ResultCode <> 0 then Abort;
end;
procedure TfmPrintBarcodePrinter.btnPrintBarcodeUsingPrinterClick(
Sender: TObject);
begin
EnableButtons(False);
try
Driver.LineNumber := seLineNumber.Value;
Driver.BarWidth := seBarWidth.Value;
Driver.HRIPosition := seHRIPosition.Value;
Driver.FontType := seFontType.Value;
Driver.BarcodeType := Integer(cbBarcodeType.Items.Objects[cbBarcodeType.ItemIndex]);
Driver.BarCode := edtBarcode.Text;
Check(Driver.PrintBarcodeUsingPrinter);
CutPaper;
PrintMaxWidthLine;
finally
EnableButtons(True);
end;
end;
end.
|
{
A Companhia de Taxi LocalCerto armazena os dados de seus motoristas (codigo,nome, número do taxi e Kper).
Elabore um programa capaz de ler os dados de n (máximo de 20) motoristas (utilizar um vetor de registros para
armazenar esses dados). Em seguida, o programa deve imprimir um relatório conforme o modelo abaixo.
Nome Motorista Número do Taxi Valor a Receber
XXX XXX XX
XXX XXX XX
XXX XXX XX
O valor a receber é calculado multiplicando-se a quantidade Kper (Kilometro percorrido) por R$ 1,20.
Ao final o programa deve também exibir todos os dados do motorista com maior valor a receber.
}
Program Exc4;
uses Crt;
Type
reg_motorista = record
codigo: integer;
nome: string;
numero: integer;
kper: real;
end;
vet_motoristas = array[1..20] of reg_motorista;
Function calculo(kper:real):real;
begin
calculo := kper * 1.20;
end;
Procedure ler(var vet:vet_motoristas; n:integer);
var
i: integer;
begin
for i := 1 to n do
begin
write('Código do motorista ', i, ': ');
readln(vet[i].codigo);
write('Nome do motorista ', i, ': ');
readln(vet[i].nome);
write('Número do taxi ', i, ': ');
readln(vet[i].numero);
write('Kilometros percorridos ', i, ': ');
readln(vet[i].kper);
ClrScr;
end;
end;
Procedure imprimir(vet: vet_motoristas; n:integer);
var
i: integer;
columns: array[1..3] of integer;
begin
ClrScr;
columns[1] := 10;
columns[2] := 40;
columns[3] := 60;
writeln('-------------------------------RELATÓRIO---------------------------------');
gotoXY(columns[1], 0);
write('Nome Motorista');
gotoXY(columns[2], 0);
write('Número do taxi');
gotoXY(columns[3], 0);
write('Valor a Receber');
for i := 1 to n do
begin
gotoXY(columns[1]+5, 3*i);
write(vet[i].nome);
gotoXY(columns[2]+5, 3*i);
write(vet[i].numero);
gotoXY(columns[3]+5, 3*i);
writeln(calculo(vet[i].kper):6:2);
end;
writeln('-------------------------------------------------------------------------');
end;
Var
n: integer;
vet: vet_motoristas;
Begin
repeat
write('Quantos motoristas você deseja cadastrar? (máximo 20): ');
readln(n);
ClrScr;
until(n <= 20);
ler(vet, n);
imprimir(vet, n);
End.
|
unit CompanyServicesSheetForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit,
GradientBox, FramedButton, SheetHandlers, ExtCtrls, FingerTabs,
InternationalizerComponent;
const
tidSecurityId = 'SecurityId';
tidTrouble = 'Trouble';
tidServiceCount = 'ServiceCount';
tidCurrBlock = 'CurrBlock';
tidCost = 'Cost';
tidROI = 'ROI';
tidInput = 'cInput';
tidCompInputCnt = 'cInputCount';
tidInputSup = 'cInputSup';
tidInputDem = 'cInputDem';
tidInputRatio = 'cInputRatio';
tidInputMax = 'cInputMax';
tidEditable = 'cEditable';
tidUnits = 'cUnits';
const
facStoppedByTycoon = $04;
type
TCompanyInputsSheetHandler = class;
TCompanyInputsSheetViewer = class(TVisualControl)
Notebook: TNotebook;
trgPanel: TPanel;
Panel2: TPanel;
Shape1: TShape;
Label3: TLabel;
lbSupply: TLabel;
lbDemand: TLabel;
Label5: TLabel;
Label1: TLabel;
lbRatio: TLabel;
peDemand: TPercentEdit;
ftServices: TFingerTabs;
Panel1: TPanel;
InternationalizerComponent1: TInternationalizerComponent;
procedure ftServicesOnFingerChange(Sender: TObject);
procedure peDemandMoveBar(Sender: TObject);
procedure peDemandChange(Sender: TObject);
private
procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND;
procedure SelectService(index : integer);
private
fHandler : TCompanyInputsSheetHandler;
fUnits : string;
fMax : integer;
end;
TCompanyInputsSheetHandler =
class(TLockableSheetHandler, IPropertySheetHandler)
private
fControl : TCompanyInputsSheetViewer;
fOwnsFacility : boolean;
fCurrBlock : integer;
private
procedure SetContainer(aContainer : IPropertySheetContainerHandler); override;
function CreateControl(Owner : TControl) : TControl; override;
function GetControl : TControl; override;
procedure RenderProperties(Properties : TStringList); override;
procedure SetFocus; override;
procedure Clear; override;
private
procedure RenderInputsToVCL(List : TStringList);
procedure RenderInputsToList(Proxy : OleVariant; Update, count : integer; List : TStringList);
procedure threadedGetProperties(const parms : array of const);
procedure threadedRenderProperties(const parms : array of const);
procedure threadChangeDemand(const parms : array of const);
end;
var
CompanyInputsSheetViewer: TCompanyInputsSheetViewer;
function CompanyInputsSheetHandlerCreator : IPropertySheetHandler; stdcall;
implementation
uses
SheetHandlerRegistry, FiveViewUtils, ObjectInspectorHandleViewer, Protocol,
GateInfo, MathUtils, Threads, CacheCommon, SheetUtils, ClientMLS;
{$R *.DFM}
// TCompanyInputsSheetHandler
procedure TCompanyInputsSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler);
begin
inherited;
end;
function TCompanyInputsSheetHandler.CreateControl(Owner : TControl) : TControl;
begin
fControl := TCompanyInputsSheetViewer.Create(Owner);
fControl.fHandler := self;
//fContainer.ChangeHeight(130);
result := fControl;
end;
function TCompanyInputsSheetHandler.GetControl : TControl;
begin
result := fControl;
end;
procedure TCompanyInputsSheetHandler.RenderProperties(Properties : TStringList);
var
trouble : string;
begin
LockWindowUpdate( fControl.Handle );
try
trouble := Properties.Values[tidTrouble];
fOwnsFacility := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId] );
if fOwnsFacility and (Properties.Values[tidCurrBlock] <> '')
then fCurrBlock := StrToInt(Properties.Values[tidCurrBlock])
else fCurrBlock := 0;
RenderInputsToVCL(Properties);
if fControl.ftServices.TabNames.Count > 0
then
begin
fControl.ftServices.CurrentFinger := 0;
fControl.Notebook.PageIndex := 1;
end
else fControl.Notebook.PageIndex := 0;
finally
LockWindowUpdate(0);
end;
end;
procedure TCompanyInputsSheetHandler.SetFocus;
var
Names : TStringList;
begin
if not fLoaded
then
begin
inherited;
fCurrBlock := 0;
Names := TStringList.Create;
Threads.Fork(threadedGetProperties, priNormal, [Names, fLastUpdate]);
end;
end;
procedure TCompanyInputsSheetHandler.Clear;
begin
inherited;
fControl.lbDemand.Caption := NA;
fControl.lbSupply.Caption := NA;
fControl.lbRatio.Caption := NA;
fControl.peDemand.Enabled := false;
Lock;
try
fControl.ftServices.ClearFingers;
finally
Unlock;
end;
fControl.Notebook.PageIndex := 0;
end;
procedure TCompanyInputsSheetHandler.RenderInputsToVCL(List : TStringList);
var
i : integer;
Info : TGateInfo;
ppName : string;
fgName : string;
count : integer;
iStr : string;
begin
try
count := StrToInt(List.Values[tidCompInputCnt]);
except
count := 0;
end;
fControl.ftServices.BeginUpdate;
fControl.ftServices.ClearFingers;
for i := 0 to pred(count) do
begin
Info := TGateInfo.Create;
iStr := IntToStr(i);
ppName := tidInput + iStr + '.' + WideString(ActiveLanguage);
fgName := List.Values[ppName];
Info.AddProp(tidInput, fgName);
ppName := tidInputSup + iStr;
Info.AddProp(tidInputSup, List.Values[ppName]);
ppName := tidInputDem + iStr;
Info.AddProp(tidInputDem, List.Values[ppName]);
ppName := tidInputRatio + iStr;
Info.AddProp(tidInputRatio, List.Values[ppName]);
ppName := tidInputMax + iStr;
Info.AddProp(tidInputMax, List.Values[ppName]);
ppName := tidInputMax + iStr;
Info.AddProp(tidInputMax, List.Values[ppName]);
ppName := tidEditable + iStr;
Info.AddProp(tidEditable, List.Values[ppName]);
ppName := tidUnits + iStr + '.' + ActiveLanguage;
Info.AddProp(tidUnits, List.Values[ppName]);
fControl.ftServices.AddFinger(UpperCase(fgName), Info);
end;
fControl.ftServices.EndUpdate;
end;
procedure TCompanyInputsSheetHandler.RenderInputsToList(Proxy : OleVariant; Update, count : integer; List : TStringList);
var
i : integer;
iStr : string;
Names : TStringList;
begin
Names := TStringList.Create;
try
i := 0;
while (Update = fLastUpDate) and (i < count) do
begin
iStr := IntToStr(i);
Names.Add(tidInput + iStr + '.' + WideString(ActiveLanguage));
Names.Add(tidInputSup + iStr);
Names.Add(tidInputDem + iStr);
Names.Add(tidInputRatio + iStr);
Names.Add(tidInputMax + iStr);
Names.Add(tidEditable + iStr);
Names.Add(tidUnits + iStr + '.' + ActiveLanguage);
inc(i);
end;
GetContainer.GetPropertyList(Proxy, Names, List);
finally
Names.Free;
end;
end;
procedure TCompanyInputsSheetHandler.threadedGetProperties( const parms : array of const );
var
Names : TStringList absolute parms[0].vPointer;
Prop : TStringList;
Update : integer;
impCnt : string;
Proxy : OleVariant;
begin
Update := parms[1].vInteger;
Names.Add(tidSecurityId);
//Names.Add(tidTrouble);
Names.Add(tidCurrBlock);
Names.Add(tidCompInputCnt);
Lock;
try
try
Proxy := GetContainer.GetCacheObjectProxy;
if (Update = fLastUpdate) and not VarIsEmpty(Proxy)
then
begin
Prop := TStringList.Create;
fContainer.GetPropertyList(Proxy, Names, prop);
end
else Prop := nil;
finally
Names.Free;
end;
if (Update = fLastUpdate) and (Prop <> nil)
then impCnt := Prop.Values[tidCompInputCnt]
else impCnt := '';
if (impCnt <> '') and (Update = fLastUpdate) and not VarIsEmpty(Proxy)
then RenderInputsToList(Proxy, fLastUpdate, StrToInt(impCnt), Prop);
finally
Unlock;
end;
if Update = fLastUpdate
then Threads.Join(threadedRenderProperties, [Prop, Update])
else Prop.Free;
end;
procedure TCompanyInputsSheetHandler.threadedRenderProperties( const parms : array of const );
var
Prop : TStringList absolute parms[0].vPointer;
begin
try
try
if fLastUpdate = parms[1].vInteger
then RenderProperties(Prop);
finally
Prop.Free;
end;
except
end;
end;
procedure TCompanyInputsSheetHandler.threadChangeDemand(const parms : array of const);
var
Proxy : OleVariant;
begin
try
if (fLastUpdate = parms[0].vInteger) and (fControl.ftServices.CurrentFinger = parms[1].vInteger)
then
begin
Proxy := fContainer.GetMSProxy;
if not VarIsEmpty(Proxy)
then
try
Proxy.BindTo(fCurrBlock);
Proxy.RDOSetCompanyInputDemand(parms[1].vInteger, parms[2].vInteger);
except
end;
end;
except
end;
end;
// TServiceGeneralSheetViewer
procedure TCompanyInputsSheetViewer.WMEraseBkgnd(var Message: TMessage);
begin
Message.Result := 1;
end;
procedure TCompanyInputsSheetViewer.SelectService(index : integer);
var
Info : TGateInfo;
edt : boolean;
begin
LockWindowUpdate(Handle);
try
Info := TGateInfo(ftServices.Objects[index]);
if Info <> nil
then
begin
fUnits := Info.StrValue[tidUnits];
fMax := Info.IntValue[tidInputMax];
if fMax > 0
then peDemand.Value := min(100, round(100*Info.FloatValue[tidInputDem]/fMax))
else peDemand.Value := 0;
edt := Info.StrValue[tidEditable] <> '';
peDemand.Visible := edt;
peDemand.Enabled := edt and fHandler.fOwnsFacility;
lbDemand.Caption := Info.StrValue[tidInputDem] + ' ' + fUnits;
lbSupply.Caption := Info.StrValue[tidInputSup] + ' ' + fUnits;
lbRatio.Caption := Info.StrValue[tidInputRatio] + '%';
end;
finally
LockWindowUpdate(0);
end;
end;
procedure TCompanyInputsSheetViewer.ftServicesOnFingerChange(Sender: TObject);
begin
SelectService(ftServices.CurrentFinger);
end;
procedure TCompanyInputsSheetViewer.peDemandMoveBar(Sender: TObject);
begin
lbDemand.Caption := Format('%.0n', [(peDemand.Value/100)*fMax]) + ' ' + fUnits;
end;
procedure TCompanyInputsSheetViewer.peDemandChange(Sender: TObject);
begin
if fHandler.fOwnsFacility
then Threads.Fork(fHandler.threadChangeDemand, priNormal, [fHandler.fLastUpdate, ftServices.CurrentFinger, peDemand.Value]);
end;
// Registration function
function CompanyInputsSheetHandlerCreator : IPropertySheetHandler;
begin
result := TCompanyInputsSheetHandler.Create;
end;
initialization
SheetHandlerRegistry.RegisterSheetHandler('compInputs', CompanyInputsSheetHandlerCreator);
end.
|
unit m3DBProxyWriteStream;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "m3"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/m3/m3DBProxyWriteStream.pas"
// Начат: 17.03.2009 18:44
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::m3::m3DB::Tm3DBProxyWriteStream
//
// Поток, пишущий в базу
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\m3\m3Define.inc}
interface
uses
l3Interfaces,
m3DBProxyStream
;
type
Tm3DBProxyWriteStream = class(Tm3DBProxyStream, Il3Rollback)
{* Поток, пишущий в базу }
private
// private fields
f_NeedCommit : Boolean;
{* Сохранять ли изменения}
protected
// property methods
function pm_GetIsNewVersion: Boolean; virtual;
protected
// realized methods
procedure Rollback;
{* Откатить данные }
protected
// overridden protected methods
procedure InitFields; override;
procedure BeforeRelease; override;
public
// public properties
property IsNewVersion: Boolean
read pm_GetIsNewVersion;
{* Новая версия документа }
end;//Tm3DBProxyWriteStream
implementation
uses
SysUtils,
l3Base
;
// start class Tm3DBProxyWriteStream
function Tm3DBProxyWriteStream.pm_GetIsNewVersion: Boolean;
//#UC START# *49BFE6600304_49BFC520008Aget_var*
//#UC END# *49BFE6600304_49BFC520008Aget_var*
begin
//#UC START# *49BFE6600304_49BFC520008Aget_impl*
Result := false;
//#UC END# *49BFE6600304_49BFC520008Aget_impl*
end;//Tm3DBProxyWriteStream.pm_GetIsNewVersion
procedure Tm3DBProxyWriteStream.Rollback;
//#UC START# *49C1040A0256_49BFC520008A_var*
//#UC END# *49C1040A0256_49BFC520008A_var*
begin
//#UC START# *49C1040A0256_49BFC520008A_impl*
f_NeedCommit := false;
//#UC END# *49C1040A0256_49BFC520008A_impl*
end;//Tm3DBProxyWriteStream.Rollback
procedure Tm3DBProxyWriteStream.InitFields;
//#UC START# *47A042E100E2_49BFC520008A_var*
//#UC END# *47A042E100E2_49BFC520008A_var*
begin
//#UC START# *47A042E100E2_49BFC520008A_impl*
inherited;
f_NeedCommit := true;
//#UC END# *47A042E100E2_49BFC520008A_impl*
end;//Tm3DBProxyWriteStream.InitFields
procedure Tm3DBProxyWriteStream.BeforeRelease;
//#UC START# *49BFC98902FF_49BFC520008A_var*
//#UC END# *49BFC98902FF_49BFC520008A_var*
begin
//#UC START# *49BFC98902FF_49BFC520008A_impl*
if f_NeedCommit then
try
DB.Commit(Self);
except
on E: Exception do
begin
f_NeedCommit := false;
l3System.Exception2Log(E);
end;//on E: Exception
end//try..except
else
DB.Revert(Self);
inherited;
//#UC END# *49BFC98902FF_49BFC520008A_impl*
end;//Tm3DBProxyWriteStream.BeforeRelease
end. |
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
// Yawara static site generator
// settings unit
// read and write settings
// @author : Zendrael <zendrael@gmail.com>
// @date : 2013/10/20
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
unit untSettings;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles;
type
{ TSettings }
TSettings = class
protected
confFile: TINIFile;
strThemes: string;
strPosts: string;
strPages: string;
strPreview: string;
strFinal: string;
strPostsPerPage: string;
strPageNext : string;
strPagePrev : string;
strThemeName: string;
booGenerateMenus : boolean;
strBlogPage : string;
strSiteAuthor: string;
strSiteName: string;
strSiteDescription: string;
strSiteKeywords: string;
strDateTime: string;
strSiteURL: string;
public
procedure getConfig;
procedure setThemes(themePath: string);
function getThemes: string;
procedure setPosts(postsPath: string);
function getPosts: string;
procedure setPages(pagesPath: string);
function getPages: string;
procedure setPreview(previewPath: string);
function getPreview: string;
procedure setFinal(finalPath: string);
function getFinal: string;
procedure setPostsPerPage(postsPerPage: string);
function getPostsPerPage: string;
procedure setPageNext(pageNext: string);
function getPageNext: string;
procedure setPagePrev(pagePrev: string);
function getPagePrev: string;
procedure setThemeName(themeName: string);
function getThemeName: string;
procedure setGenerateMenus(menus: string);
function getGenerateMenus: Boolean;
procedure setBlogPage(pageName: string);
function getBlogPage: string;
procedure setSiteAuthor(SiteAuthor: string);
function getSiteAuthor: string;
procedure setSiteName(SiteName: string);
function getSiteName: string;
procedure setSiteDescription(SiteDescription: string);
function getSiteDescription: string;
procedure setSiteKeywords(SiteKeywords: string);
function getSiteKeywords: string;
procedure setDateTime(SiteDateTime: string);
function getDateTime: string;
procedure setSiteURL(strURL: string);
function getSiteURL: string;
constructor Create;
destructor Destroy; override;
end;
implementation
procedure TSettings.getConfig;
begin
try
confFile:= TIniFile.Create('yawara.conf');
//setup directories
setPosts( confFile.ReadString('Global','Posts','') );
setPages( confFile.ReadString('Global','Pages','') );
setPreview( confFile.ReadString('Global','Preview','') );
setFinal( confFile.ReadString('Global','Output','') );
setThemes( confFile.ReadString('Global','Themes','') );
//setup pages
setSiteAuthor( confFile.ReadString('Site','Author','') );
setSiteName( confFile.ReadString('Site','Name','') );
setSiteDescription( confFile.ReadString('Site','Description','') );
setSiteKeywords( confFile.ReadString('Site','Keywords','') );
setThemeName( confFile.ReadString('Site','Theme','') );
setGenerateMenus( confFile.ReadString('Site','GenerateMenus','') );
setBlogPage( confFile.ReadString('Site','BlogPage','') );
setPostsPerPage( confFile.ReadString('Site','PostsPerPage','') );
setPageNext( confFile.ReadString('Site','PageNext','') );
setPagePrev( confFile.ReadString('Site','PagePrev','') );
setDateTime( confFile.ReadString('Site','DateTime','') );
setSiteURL( confFile.ReadString('Site','SiteURL','') );
finally
confFile.Free;
end;
end;
procedure TSettings.setThemes(themePath: string);
begin
self.strThemes:= themePath;
end;
function TSettings.getThemes: string;
begin
Result:= self.strThemes;
end;
procedure TSettings.setPosts(postsPath: string);
begin
self.strPosts:= postsPath;
end;
function TSettings.getPosts: string;
begin
Result:= self.strPosts;
end;
procedure TSettings.setPages(pagesPath: string);
begin
self.strPages:= pagesPath;
end;
function TSettings.getPages: string;
begin
Result:= self.strPages;
end;
procedure TSettings.setPreview(previewPath: string);
begin
self.strPreview:= previewPath;
end;
function TSettings.getPreview: string;
begin
Result:= self.strPreview;
end;
procedure TSettings.setFinal(finalPath: string);
begin
self.strFinal:= finalPath;
end;
function TSettings.getFinal: string;
begin
Result:= self.strFinal;
end;
procedure TSettings.setPostsPerPage(postsPerPage: string);
begin
self.strPostsPerPage:= postsPerPage;
end;
function TSettings.getPostsPerPage: string;
begin
Result:= self.strPostsPerPage;
end;
procedure TSettings.setPageNext(pageNext: string);
begin
self.strPageNext:= pageNext;
end;
function TSettings.getPageNext: string;
begin
Result:= self.strPageNext;
end;
procedure TSettings.setPagePrev(pagePrev: string);
begin
self.strPagePrev:= pagePrev;
end;
function TSettings.getPagePrev: string;
begin
Result:= self.strPagePrev;
end;
procedure TSettings.setThemeName(themeName: string);
begin
self.strThemeName:= themeName;
end;
function TSettings.getThemeName: string;
begin
Result:= self.strThemeName;
end;
procedure TSettings.setGenerateMenus(menus: string);
begin
if( menus = 'yes') then
self.booGenerateMenus:= true;
end;
function TSettings.getGenerateMenus: Boolean;
begin
Result := self.booGenerateMenus;
end;
procedure TSettings.setBlogPage(pageName: string);
begin
self.strBlogPage:= pageName;
end;
function TSettings.getBlogPage: string;
begin
Result := self.strBlogPage;
end;
procedure TSettings.setSiteAuthor(SiteAuthor: string);
begin
self.strSiteAuthor:= SiteAuthor;
end;
function TSettings.getSiteAuthor: string;
begin
Result:= self.strSiteAuthor;
end;
procedure TSettings.setSiteName(SiteName: string);
begin
self.strSiteName:= SiteName;
end;
function TSettings.getSiteName: string;
begin
Result:= self.strSiteName;
end;
procedure TSettings.setSiteDescription(SiteDescription: string);
begin
self.strSiteDescription:= SiteDescription;
end;
function TSettings.getSiteDescription: string;
begin
Result:= self.strSiteDescription;
end;
procedure TSettings.setSiteKeywords(SiteKeywords: string);
begin
self.strSiteKeywords:= SiteKeywords;
end;
function TSettings.getSiteKeywords: string;
begin
Result:= self.strSiteKeywords;
end;
procedure TSettings.setDateTime(SiteDateTime: string);
begin
self.strDateTime:= SiteDateTime;
end;
function TSettings.getDateTime: string;
begin
Result:= self.strDateTime;
end;
procedure TSettings.setSiteURL(strURL: string);
begin
self.strSiteURL:= strURL;
end;
function TSettings.getSiteURL: string;
begin
Result:= self.strSiteURL;
end;
constructor TSettings.Create;
begin
//
end;
destructor TSettings.Destroy;
begin
inherited Destroy;
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
{
Amarildo Lacerda
03/10/2016
PluginManager é utilizado no Application que consumir um plugin a ser
utilizado;
}
unit plugin.Manager;
{$I plugin.inc}
interface
uses
Windows, System.Classes, System.SysUtils, plugin.Interf,
{$IFDEF FMX} FMX.Menus, {$ELSE} WinAPI.GDIPObj, VCL.Menus, {$ENDIF}
System.Generics.Collections,
System.IOUtils;
type
TPluginInfo = class
public
Handle: THandle;
plugin: IPluginItems;
Filename: string;
constructor Create;
destructor Destroy; override;
end;
IPluginManager = interface
['{F5A6F163-06BC-4021-9AF9-905797FC6F4F}']
function Count: Integer;
function GetApplication: IPluginApplication;
procedure SetApplication(Const AApplication: IPluginApplication);
procedure SetFileName(AFilename: string);
function GetItem(idx: Integer): IPluginItems;
function Add(AHandle: THandle; AFilename: string;
APlugins: IPluginItems): Integer;
function LoadPlugin(APlugin: string): Integer;
function LoadPlugins(APlugin: string; AApplication: IPluginApplication)
: Integer; overload;
function Open(AApplication: IPluginApplication): Integer; overload;
function InstallPlugin(APlugin: string): Integer;
procedure UnInstallPlugin(APlugin: string);
procedure Connection(const AConnectionString: string);
procedure User(const AFilial: Integer; const AAppUser: string);
end;
TPluginManagerIntf = class(TInterfacedObject, IPluginManager)
private
FFilename: string;
FConnectionString: string;
FAppUser: string;
FFilial: Integer;
protected
FList: TList<TPluginInfo>;
public
constructor Create;
destructor Destroy; override;
function GetApplication: IPluginApplication;
procedure SetApplication(Const AApplication: IPluginApplication);
procedure SetFileName(AFilename: string);
function Count: Integer;
function GetItem(idx: Integer): IPluginItems;
function Find(APlugin: string): TPluginInfo;
function IndexOf(APlugin: string): Integer;
function Add(AHandle: THandle; AFilename: String;
APlugins: IPluginItems): Integer;
procedure LoadPluginPath(APath: string);
function LoadPlugin(APlugin: string): Integer;
function LoadPlugins(AFilename: string; AApplication: IPluginApplication)
: Integer; overload;
procedure Connection(const AConnectionString: string);
procedure User(const AFilial: Integer; const AAppUser: string);
function Open(AApplication: IPluginApplication): Integer; overload;
procedure Sync(const AJson: string);
property Filename: string read FFilename write SetFileName;
function InstallPlugin(APlugin: string): Integer;
procedure UnInstallPlugin(APlugin: string);
end;
TPluginAttributeControl = class
public
TypeID: Int64;
SubTypeID: Int64;
PluginExecute: IPluginExecute;
end;
TPluginApplicationMenuItemEvent = procedure(const AParentMenuItemName,
ACaption: string; ADoExecute: IPluginMenuItem) of object;
TPluginApplicationToolbarItemEvent = procedure(const AParentItemName,
ACaption: string; ADoExecute: IPluginToolbarItem) of object;
TPluginApplicationControlEvent = procedure(const AType, ASubType: Int64;
ADoExecute: IPluginControl) of object;
TPluginBeforeExecuteEvent = procedure(const AExecute: IPluginExecuteBase;
var AContinue: boolean) of object;
TPluginApplication = class(TInterfacedObject, IPluginApplication)
procedure RegisterMenuItem(const AParentMenuItemName, ACaption: string;
ADoExecute: IPluginMenuItem);
procedure RegisterToolbarItem(const AParentItemName, ACaption: string;
ADoExecute: IPluginToolbarItem);
procedure RegisterAttributeControl(const AType, ASubType: Int64;
ADoExecute: IPluginControl);
end;
TPluginManager = class(TComponent { , IPluginApplication } )
private
FonRegisterMenuItem: TPluginApplicationMenuItemEvent;
FonRegisterToolbarItem: TPluginApplicationToolbarItemEvent;
FonRegisterControl: TPluginApplicationControlEvent;
FPlugins: TPluginManagerIntf;
FAttributeControls: TObjectList<TPluginAttributeControl>;
FActive: boolean;
FOnActive: TNotifyEvent;
FMenuItem: TMenuItem;
FMainMenu: TMainMenu;
FonBeforeExecute: TPluginBeforeExecuteEvent;
FLocalPluginPath: string;
procedure SetActive(const Value: boolean);
procedure SetOnActive(const Value: TNotifyEvent);
function GetFileName: string;
procedure SetFileName(const Value: string);
procedure SetonRegisterMenuItem(const Value
: TPluginApplicationMenuItemEvent);
procedure SetonRegisterToolbarItem(const Value
: TPluginApplicationToolbarItemEvent);
procedure SetonRegisterControl(const Value: TPluginApplicationControlEvent);
procedure SetMainMenu(const Value: TMainMenu);
procedure SetMenuItem(const Value: TMenuItem);
procedure SetonBeforeExecute(const Value: TPluginBeforeExecuteEvent);
procedure SetLocalPluginPath(const Value: string);
protected
// IPluginApplication
procedure &RegisterMenuItem(const AParentMenuItemName, ACaption: string;
ADoExecute: IPluginMenuItem);
procedure &RegisterToolbarItem(const AParentItemName, ACaption: string;
ADoExecute: IPluginToolbarItem);
procedure &RegisterAttributeControl(const AType, ASubType: Int64;
ADoExecute: IPluginControl);
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(ow: TComponent); override;
destructor Destroy; override;
procedure Perform(ATypeID: Int64; AMsg: Cardinal; WParam: NativeUInt;
LParam: NativeUInt);
procedure SendCommand(ACommand: string; ABody: string);
function CreateCommand(ACommand: string; ABody: string): string;
// default create item
procedure NewMenuItem(AMainMenu: TMainMenu; ADefaultMenu: TMenuItem;
const APath, ACaption: string; ADoExecute: IPluginMenuItem;
AProc: TProc<TObject>); overload;
procedure NewAttributeControl(const ATypeID, ASubTypeID: Int64;
ADoExecute: IPluginExecute); overload;
procedure EmbedControl(AParentHandle: THandle; AControlID: Int64;
AControlType: Int64 = 0); overload; virtual;
procedure EmbedControl(AControlID: Int64; AControlType: Int64;
AProc: TProc<IPluginExecute>); overload; virtual;
// jobs
procedure LoadPluginPath(APath: string); virtual;
function LoadPlugins(APlugin: string): Integer; virtual;
function InstallPlugin(APlugin: string): Integer; virtual;
procedure UnInstallPlugin(APlugin: string); virtual;
procedure OpenDialog(AIniFile: string);
// list os plugins
property Plugins: TPluginManagerIntf read FPlugins;
// list of plugins controls
property AttributeControls: TObjectList<TPluginAttributeControl>
read FAttributeControls;
// operations
procedure Open(AApp: IPluginApplication);
procedure Connection(const AConnectionString: String);
procedure User(const AFilial: Integer; const AAppUser: string);
procedure Sync(const AJson: string);
published
// events fire when plugin start
property onRegisterMenuItem: TPluginApplicationMenuItemEvent
read FonRegisterMenuItem write SetonRegisterMenuItem;
property onRegisterToolbarItem: TPluginApplicationToolbarItemEvent
read FonRegisterToolbarItem write SetonRegisterToolbarItem;
property onRegisterControl: TPluginApplicationControlEvent
read FonRegisterControl write SetonRegisterControl;
property onBeforeExecute: TPluginBeforeExecuteEvent read FonBeforeExecute
write SetonBeforeExecute;
// aditional
property Filename: string read GetFileName write SetFileName;
property LocalPluginPath: string read FLocalPluginPath
write SetLocalPluginPath;
property MainMenu: TMainMenu read FMainMenu write SetMainMenu;
property MenuItem: TMenuItem read FMenuItem write SetMenuItem;
property OnActive: TNotifyEvent read FOnActive write SetOnActive;
property Active: boolean read FActive write SetActive;
end;
// extens TMenuItem to implements anonimous and Interfaced menu item;
TRecInterfaced = record
Controller: IPluginMenuItem;
end;
TPluginMenuItemInterf = class(TMenuItem)
protected
FProc: TProc<TObject>;
procedure DoClick(Sender: TObject);
public
[unsafe]
PluginMenuItem: TRecInterfaced;
constructor Create(AOwner: TComponent; AProc: TProc<TObject>); overload;
end;
function GetPluginManager: TPluginManager;
procedure Register;
implementation
uses
plugin.Common,
{$IFNDEF DLL} plugin.Service, {$ENDIF}
{$IFNDEF BPL}plugin.FormManager, {$ENDIF}
IniFiles {$IFDEF USE_INIFILEEx}, IniFilesEx{$ENDIF};
var
LPluginManager: TPluginManager;
procedure Register;
begin
RegisterComponents('Store', [TPluginManager]);
end;
procedure TPluginManager.NewAttributeControl(const ATypeID, ASubTypeID: Int64;
ADoExecute: IPluginExecute);
var
it: TPluginAttributeControl;
begin
it := TPluginAttributeControl.Create;
it.TypeID := ATypeID;
it.SubTypeID := ASubTypeID;
it.PluginExecute := ADoExecute;
FAttributeControls.Add(it);
end;
{$IFDEF FMX}
{$ELSE}
type
TMenuItemHelper = class helper for TMenuItem
public
function FindItem(const aName: string): TMenuItem;
end;
function TMenuItemHelper.FindItem(const aName: string): TMenuItem;
var
i: Integer;
begin
result := nil;
if sametext(Name, aName) then
begin
result := self;
exit;
end
else
for i := 0 to Count - 1 do
begin
result := items[i].FindItem(aName);
if assigned(result) then
exit;
end;
end;
type
TMainMenuHelper = class helper for TMainMenu
public
function FindItem(const aName: string): TMenuItem;
end;
function TMainMenuHelper.FindItem(const aName: string): TMenuItem;
var
i: Integer;
begin
result := nil;
for i := 0 to items.Count - 1 do
begin
result := items[i].FindItem(aName);
if assigned(result) then
exit;
end;
end;
{$ENDIF}
var
itCount: Integer = 0;
procedure TPluginManager.NewMenuItem(AMainMenu: TMainMenu;
ADefaultMenu: TMenuItem; const APath, ACaption: string;
ADoExecute: IPluginMenuItem; AProc: TProc<TObject>);
var
it: TPluginMenuItemInterf;
itClient: TMenuItem;
begin
inc(itCount);
itClient := nil;
{$IFDEF FMX}
{$ELSE}
// procura o menu para mostrar
itClient := AMainMenu.FindItem(APath);
{$ENDIF}
//ADefaultMenu.
if itClient = nil then
begin
itClient := ADefaultMenu; // se nao encontrou pega um padrao
if itClient.caption='-' then
itClient := ADefaultMenu.Parent;
end;
if not assigned(AProc) then
AProc := (
procedure(Sender: TObject)
var
AContinue: boolean;
begin
with TPluginMenuItemInterf(Sender) do
begin
AContinue := true;
if assigned(FonBeforeExecute) then
FonBeforeExecute(PluginMenuItem.Controller, AContinue);
if AContinue then
PluginMenuItem.Controller.DoClick(0);
end;
end);
// cria o menu
it := TPluginMenuItemInterf.Create(AMainMenu, AProc);
it.Name := 'mnPlugin_' + formatDatetime
('hhmmsszzz_' + intToStr(itCount), now);
it.PluginMenuItem.Controller := ADoExecute;
{$IFDEF FMX}
it.text := (it.PluginMenuItem as IPluginMenuItem).GetCaption;
{$ELSE}
it.Caption := (it.PluginMenuItem.Controller as IPluginMenuItem).GetCaption;
itClient.Add(it);
{$ENDIF}
// adiciona o menu na lista
end;
procedure TPluginManager.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = TOperation.opRemove) then
begin
if (AComponent = FMainMenu) then
FMainMenu := nil;
if AComponent = FMenuItem then
FMenuItem := nil;
end;
end;
var
LPluginMangerLocal: boolean = false;
function GetPluginManager: TPluginManager;
begin
if not assigned(LPluginManager) then
begin
LPluginManager := TPluginManager.Create(nil);
LPluginMangerLocal := true;
end;
result := LPluginManager;
end;
{ TPluginManager }
function TPluginManagerIntf.Add(AHandle: THandle; AFilename: String;
APlugins: IPluginItems): Integer;
var
p: TPluginInfo;
i: Integer;
begin
result := -1;
p := TPluginInfo.Create;
p.Handle := AHandle;
p.plugin := APlugins;
p.Filename := AFilename;
for i := 0 to APlugins.Count - 1 do
begin
APlugins.GetItem(i).GetInterface.Connection(FConnectionString);
APlugins.GetItem(i).GetInterface.User(FFilial, FAppUser);
end;
FList.Add(p);
result := FList.Count - 1;
end;
procedure TPluginManagerIntf.Connection(const AConnectionString: string);
var
i, n: Integer;
begin
FConnectionString := AConnectionString;
for i := 0 to FList.Count - 1 do
for n := 0 to FList.items[i].plugin.Count - 1 do
FList.items[i].plugin.GetItem(n).GetInterface.Connection
(FConnectionString);
end;
function TPluginManagerIntf.Count: Integer;
begin
result := FList.Count;
end;
constructor TPluginManagerIntf.Create;
begin
inherited;
FList := TList<TPluginInfo>.Create;
FFilename := 'Plugin.ini';
end;
destructor TPluginManagerIntf.Destroy;
var
p: TPluginInfo;
begin
while FList.Count > 0 do
begin
try
p := FList.items[FList.Count - 1];
p.Free;
except
end;
FList.Delete(FList.Count - 1);
end;
FList.Free;
inherited;
end;
function TPluginManagerIntf.Find(APlugin: string): TPluginInfo;
var
i: Integer;
begin
result := nil;
i := IndexOf(APlugin);
if i >= 0 then
result := FList.items[i];
end;
function TPluginManagerIntf.GetApplication: IPluginApplication;
begin
result := PluginApplication;
end;
function TPluginManagerIntf.GetItem(idx: Integer): IPluginItems;
begin
result := FList.items[idx].plugin;
end;
function TPluginManagerIntf.LoadPlugin(APlugin: string): Integer;
var
F: function(APApplication: IPluginApplication): IPluginItems;
H: THandle;
i: Integer;
itens: IPluginItems;
begin
result := -1;
H := LoadLibrary(PWideChar(ExpandConstant(APlugin)));
if H > 0 then
begin
try
@F := GetProcAddress(H, 'LoadPlugin');
if assigned(F) then
begin
itens := F(PluginApplication);
result := LPluginManager.FPlugins.Add(H, APlugin, itens);
end
else
raise Exception.Create('Não carregou o plugin');
except
FreeLibrary(H);
raise;
end;
end;
end;
procedure TPluginManagerIntf.LoadPluginPath(APath: string);
var
LFileMask: string;
LSearchRec: TSearchRec;
begin
APath := ExpandConstant(APath);
LFileMask := TPath.Combine(APath, '*.dll');
ForceDirectories(ExtractFileDir(LFileMask));
if FindFirst(LFileMask, faAnyFile, LSearchRec) = 0 then
try
repeat
LoadPlugin(TPath.Combine(APath, LSearchRec.Name));
until FindNext(LSearchRec) <> 0;
finally
findClose(LSearchRec);
end;
end;
function TPluginManagerIntf.Open(AApplication: IPluginApplication): Integer;
{$IFNDEF DLL}
var
n, i: Integer;
it: IPluginItems;
begin
it := GetPluginItems;
if assigned(it) then
with GetPluginItems do
for i := 0 to Count - 1 do
begin
GetItem(i).DoStart;
end;
{$ELSE}
begin
{$ENDIF}
result := LoadPlugins(ExtractFileName(ParamStr(0)), AApplication);
end;
function TPluginManagerIntf.LoadPlugins(AFilename: string;
AApplication: IPluginApplication): Integer;
var
i, n: Integer;
F: string;
achei: boolean;
begin
if assigned(AApplication) then
SetApplication(AApplication);
if AFilename = '' then
AFilename := FFilename;
if FFilename = '' then
FFilename := AFilename;
result := 0;
with TIniFile.Create(FFilename) do
try
n := 0;
while readString(AFilename, 'Plugin' + intToStr(n), '*fim*') <> '*fim*' do
begin
try
F := readString(AFilename, 'Plugin' + intToStr(n), '');
if fileExists(F) then
begin
achei := false;
for i := 0 to FList.Count - 1 do
if sametext(F, FList.items[i].Filename) then
begin // check if repeat the same DLL
achei := true;
break;
end;
if not achei then
begin
LoadPlugin(F);
inc(result);
end;
end;
except
on e: Exception do
raise Exception.Create('Erro LoadPlugins <' + F + '>: ' +
e.message);
end;
inc(n);
end;
finally
Free;
end;
end;
function TPluginManagerIntf.IndexOf(APlugin: string): Integer;
var
i: Integer;
begin
result := -1;
for i := 0 to FList.Count - 1 do
if sametext(APlugin, FList.items[i].Filename) then
begin
result := i;
exit;
end;
end;
function TPluginManagerIntf.InstallPlugin(APlugin: string): Integer;
var
i: Integer;
app: string;
info: TPluginInfo;
begin
result := -1;
i := IndexOf(APlugin);
if i >= 0 then
exit;
result := LoadPlugin(APlugin);
if result >= 0 then
begin
i := 0;
app := ExtractFileName(ParamStr(0));
with TIniFile.Create(FFilename) do
try
while readString(app, 'Plugin' + intToStr(i), '') <> '' do
inc(i);
WriteString(app, 'Plugin' + intToStr(i), APlugin);
finally
Free;
end;
info := Find(APlugin);
if assigned(info) then
begin
info.plugin.Connection(FConnectionString);
info.plugin.Install;
end;
end;
end;
procedure TPluginManagerIntf.SetApplication(const AApplication
: IPluginApplication);
begin
if AApplication <> PluginApplication then
PluginApplication := AApplication;
end;
procedure TPluginManagerIntf.SetFileName(AFilename: string);
begin
FFilename := AFilename;
end;
procedure TPluginManagerIntf.Sync(const AJson: string);
procedure process(AExecute: IPluginExecuteBase; ACommand: string);
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Queue(nil,
procedure
begin
try
AExecute.Sync(ACommand);
except
end;
end);
end).start;
end;
var
i, n: Integer;
begin
for i := 0 to FList.Count - 1 do
for n := 0 to FList.items[i].plugin.Count - 1 do
process(FList.items[i].plugin.GetItem(n).GetInterface, AJson);
end;
procedure TPluginManagerIntf.UnInstallPlugin(APlugin: string);
var
info: TPluginInfo;
begin
info := Find(APlugin);
if assigned(info) then
info.plugin.UnInstall;
end;
procedure TPluginManagerIntf.User(const AFilial: Integer;
const AAppUser: string);
var
i, n: Integer;
begin
FFilial := AFilial;
FAppUser := AAppUser;
for i := 0 to FList.Count - 1 do
for n := 0 to FList.items[i].plugin.Count - 1 do
FList.items[i].plugin.GetItem(n).GetInterface.User(FFilial, FAppUser);
end;
{ TPluginInfo }
constructor TPluginInfo.Create;
begin
inherited;
Handle := 0;
end;
destructor TPluginInfo.Destroy;
var
p: procedure;
begin
if Handle > 0 then
try
@p := GetProcAddress(Handle, 'UnloadPlugin');
if assigned(p) then
p;
plugin := nil;
sleep(100);
FreeLibrary(Handle);
except
end;
inherited;
end;
{ TPluginMananer }
procedure TPluginManager.Connection(const AConnectionString: string);
begin
if assigned(FPlugins) then
FPlugins.Connection(AConnectionString);
end;
constructor TPluginManager.Create(ow: TComponent);
begin
inherited;
FLocalPluginPath := '{app}\Plugins';
if not assigned(LPluginManager) then
LPluginManager := self;
FPlugins := TPluginManagerIntf.Create;
FAttributeControls := TObjectList<TPluginAttributeControl>.Create;
end;
function TPluginManager.CreateCommand(ACommand: string; ABody: string): string;
begin
if ABody = '' then
ABody := '""';
result := '{ "command":"' + ACommand + '", "body":' + ABody + '}';
end;
destructor TPluginManager.Destroy;
var
i: Integer;
begin
FAttributeControls.Free;
FPlugins.Free;
inherited;
end;
procedure TPluginManager.EmbedControl(AControlID, AControlType: Int64;
AProc: TProc<IPluginExecute>);
var
i: Integer;
intf: IPluginExecute;
AContinue: boolean;
begin
if assigned(FAttributeControls) then
for i := 0 to FAttributeControls.Count - 1 do
with FAttributeControls.items[i] do
if (TypeID = AControlID) and
((SubTypeID = AControlType) or (AControlType = -1)) then
begin
AContinue := true;
if assigned(FonBeforeExecute) then
FonBeforeExecute(FAttributeControls.items[i].PluginExecute,
AContinue);
if AContinue then
begin
PluginExecute.Connection(FPlugins.FConnectionString);
PluginExecute.User(FPlugins.FFilial, FPlugins.FAppUser);
intf := PluginExecute;
AProc(intf);
intf.Sync(CreateCommand('start', ''));
end;
end;
end;
function TPluginManager.GetFileName: string;
begin
if assigned(FPlugins) then
result := FPlugins.Filename;
end;
procedure TPluginManager.EmbedControl(AParentHandle: THandle;
AControlID, AControlType: Int64);
var
i: Integer;
AContinue: boolean;
begin
if assigned(FAttributeControls) then
for i := 0 to FAttributeControls.Count - 1 do
with FAttributeControls.items[i] do
if (TypeID = AControlID) and (SubTypeID = AControlType) then
begin
AContinue := true;
if assigned(FonBeforeExecute) then
FonBeforeExecute(FAttributeControls.items[i].PluginExecute,
AContinue);
if AContinue then
with FAttributeControls.items[i] do
begin
PluginExecute.Connection(FPlugins.FConnectionString);
PluginExecute.User(FPlugins.FFilial, FPlugins.FAppUser);
PluginExecute.Embedded(AParentHandle);
PluginExecute.Sync(CreateCommand('start', ''));
end;
end;
end;
procedure TPluginManager.LoadPluginPath(APath: string);
begin
if assigned(FPlugins) then
FPlugins.LoadPluginPath(APath);
end;
function TPluginManager.LoadPlugins(APlugin: string): Integer;
begin
if assigned(FPlugins) then
result := FPlugins.LoadPlugin(APlugin);
end;
procedure TPluginManager.Open(AApp: IPluginApplication);
begin
if assigned(FPlugins) then
Plugins.Open(AApp);
end;
procedure TPluginManager.OpenDialog(AIniFile: string);
begin
{$IFNDEF BPL}
if AIniFile = '' then
AIniFile := Filename;
// install news plugins
with PluginFormManagerDlg do
try
Filename := AIniFile;
ShowModal;
finally
end;
{$ENDIF}
end;
procedure TPluginManager.Perform(ATypeID: Int64; AMsg: Cardinal;
WParam, LParam: NativeUInt);
var
i, n: Integer;
intf: IPluginInfo;
begin
if assigned(FPlugins) then
for i := 0 to Plugins.Count - 1 do
for n := 0 to Plugins.GetItem(i).Count - 1 do
begin
intf := Plugins.GetItem(i).GetItem(n);
if (ATypeID = 0) or (ATypeID = intf.GetTypeID) then
intf.GetInterface.Perform(AMsg, WParam, LParam);
end;
end;
function TPluginManager.InstallPlugin(APlugin: string): Integer;
begin
result := FPlugins.InstallPlugin(APlugin);
end;
procedure TPluginManager.SendCommand(ACommand, ABody: string);
begin
Sync(CreateCommand(ACommand, ABody));
end;
procedure TPluginManager.SetActive(const Value: boolean);
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Queue(nil,
procedure
begin
if not(csDesigning in ComponentState) then
begin
if not assigned(PluginApplication) then
raise Exception.Create
('Não inicializou o objeto PluginApplication');
if Value then
begin
FPlugins.Open(PluginApplication);
if FLocalPluginPath <> '' then
FPlugins.LoadPluginPath(FLocalPluginPath);
if assigned(FOnActive) then
FOnActive(self);
end;
end;
end);
end).start;
FActive := Value;
end;
procedure TPluginManager.SetFileName(const Value: string);
begin
if assigned(FPlugins) then
FPlugins.Filename := Value;
end;
procedure TPluginManager.SetLocalPluginPath(const Value: string);
begin
FLocalPluginPath := Value;
end;
procedure TPluginManager.SetMainMenu(const Value: TMainMenu);
begin
FMainMenu := Value;
end;
procedure TPluginManager.SetMenuItem(const Value: TMenuItem);
begin
FMenuItem := Value;
end;
procedure TPluginManager.SetOnActive(const Value: TNotifyEvent);
begin
FOnActive := Value;
end;
procedure TPluginManager.UnInstallPlugin(APlugin: string);
begin
if assigned(FPlugins) then
FPlugins.UnInstallPlugin(APlugin);
end;
procedure TPluginManager.User(const AFilial: Integer; const AAppUser: string);
begin
if assigned(FPlugins) then
Plugins.User(AFilial, AAppUser);
end;
{ TMenuItemInterf }
constructor TPluginMenuItemInterf.Create(AOwner: TComponent;
AProc: TProc<TObject>);
begin
inherited Create(AOwner);
FProc := AProc;
inherited OnClick := DoClick;
end;
procedure TPluginMenuItemInterf.DoClick(Sender: TObject);
begin
FProc(self);
end;
{ TPluginApplication }
procedure TPluginManager.RegisterAttributeControl(const AType, ASubType: Int64;
ADoExecute: IPluginControl);
begin
if assigned(FonRegisterControl) then
FonRegisterControl(AType, ASubType, ADoExecute)
else
NewAttributeControl(AType, ASubType, ADoExecute);
end;
procedure TPluginManager.RegisterMenuItem(const AParentMenuItemName,
ACaption: string; ADoExecute: IPluginMenuItem);
begin
if assigned(FonRegisterMenuItem) then
FonRegisterMenuItem(AParentMenuItemName, ACaption, ADoExecute)
else if assigned(FMainMenu) and assigned(FMenuItem) then
NewMenuItem(FMainMenu, FMenuItem, AParentMenuItemName, ACaption,
ADoExecute, nil);
end;
procedure TPluginManager.RegisterToolbarItem(const AParentItemName,
ACaption: string; ADoExecute: IPluginToolbarItem);
begin
if assigned(FonRegisterToolbarItem) then
FonRegisterToolbarItem(AParentItemName, ACaption, ADoExecute);
end;
procedure TPluginManager.SetonBeforeExecute(const Value
: TPluginBeforeExecuteEvent);
begin
FonBeforeExecute := Value;
end;
procedure TPluginManager.SetonRegisterControl(const Value
: TPluginApplicationControlEvent);
begin
FonRegisterControl := Value;
end;
procedure TPluginManager.SetonRegisterMenuItem(const Value
: TPluginApplicationMenuItemEvent);
begin
FonRegisterMenuItem := Value;
end;
procedure TPluginManager.SetonRegisterToolbarItem
(const Value: TPluginApplicationToolbarItemEvent);
begin
FonRegisterToolbarItem := Value;
end;
procedure TPluginManager.Sync(const AJson: string);
begin
if assigned(FPlugins) then
FPlugins.Sync(AJson);
end;
{ TPluginApplication }
procedure TPluginApplication.RegisterAttributeControl(const AType,
ASubType: Int64; ADoExecute: IPluginControl);
begin
GetPluginManager.RegisterAttributeControl(AType, ASubType, ADoExecute);
end;
procedure TPluginApplication.RegisterMenuItem(const AParentMenuItemName,
ACaption: string; ADoExecute: IPluginMenuItem);
begin
GetPluginManager.RegisterMenuItem(AParentMenuItemName, ACaption, ADoExecute);
end;
procedure TPluginApplication.RegisterToolbarItem(const AParentItemName,
ACaption: string; ADoExecute: IPluginToolbarItem);
begin
GetPluginManager.RegisterToolbarItem(AParentItemName, ACaption, ADoExecute);
end;
initialization
PluginApplication := TPluginApplication.Create() as IPluginApplication;
Finalization
if LPluginMangerLocal then
FreeAndNil(LPluginManager);
PluginApplication := nil;
end.
|
unit StreetHousesViewForma;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DBGridEhGrouping,
ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, CnErrorProvider, Vcl.Menus,
System.Actions, Vcl.ActnList, Data.DB, Vcl.StdCtrls, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ToolWin, EhLibVCL, GridsEh,
DBAxisGridsEh, DBGridEh, MemTableDataEh, MemTableEh, DataDriverEh,
pFIBDataDriverEh, DBGridEhImpExp, PrnDbgeh;
type
TStreetHouseViewForm = class(TForm)
dbgView: TDBGridEh;
srcView: TDataSource;
drvFIBView: TpFIBDataDriverEh;
mtView: TMemTableEh;
pmPopUp: TPopupMenu;
mniFilterFLD: TMenuItem;
mniN1: TMenuItem;
pmgCopy: TMenuItem;
pmgSelectAll: TMenuItem;
pmgSep2: TMenuItem;
pmgSaveSelection: TMenuItem;
prntdbgrdh: TPrintDBGridEh;
miN1: TMenuItem;
miN2: TMenuItem;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure mniFilterFLDClick(Sender: TObject);
procedure pmgCopyClick(Sender: TObject);
procedure pmgSelectAllClick(Sender: TObject);
procedure pmgSaveSelectionClick(Sender: TObject);
procedure miN2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
StreetHouseViewForm: TStreetHouseViewForm;
implementation
uses DM, MAIN, AtrStrUtils, PrjConst;
{$R *.dfm}
procedure TStreetHouseViewForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
i: Integer;
begin
if (dbgView.DataGrouping.ActiveGroupLevelsCount = 0) then
begin
for i := 0 to ComponentCount - 1 do
if Components[i] is TDBGridEh then
(Components[i] as TDBGridEh).SaveColumnsLayoutIni(A4MainForm.GetIniFileName,
Self.Name + '.' + Components[i].Name, True);
end;
Action := caFree;
mtView.Active := False;
StreetHouseViewForm := nil;
end;
procedure TStreetHouseViewForm.FormShow(Sender: TObject);
var
i: Integer;
Font_size: Integer;
Font_name: string;
Row_height: Integer;
begin
Font_size := 0;
if TryStrToInt(dmMain.GetIniValue('FONT_SIZE'), i) then
begin
Font_size := i;
Font_name := dmMain.GetIniValue('FONT_NAME');
end;
if not TryStrToInt(dmMain.GetIniValue('ROW_HEIGHT'), i) then
i := 0;
Row_height := i;
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TDBGridEh then
begin
(Components[i] as TDBGridEh).RestoreColumnsLayoutIni(A4MainForm.GetIniFileName,
Self.Name + '.' + Components[i].Name, [crpColIndexEh, crpColWidthsEh, crpColVisibleEh, crpSortMarkerEh]);
if (Components[i] as TDBGridEh).DataSource.DataSet.Active then
(Components[i] as TDBGridEh).DefaultApplySorting;
if Font_size <> 0 then
begin
(Components[i] as TDBGridEh).Font.Name := Font_name;
(Components[i] as TDBGridEh).Font.Size := Font_size;
(Components[i] as TDBGridEh).ColumnDefValues.Layout := tlCenter;
(Components[i] as TDBGridEh).RowHeight := Row_height;
end;
end;
end;
mtView.Active := True;
end;
procedure TStreetHouseViewForm.miN2Click(Sender: TObject);
begin
prntdbgrdh.Preview;
end;
procedure TStreetHouseViewForm.mniFilterFLDClick(Sender: TObject);
begin
try
dbgView.SearchPanel.Visible := True;
dbgView.SearchPanel.SearchingText := dbgView.SelectedField.AsString;
dbgView.SearchPanel.ApplySearchFilter;
dbgView.SearchPanel.Active := True;
except
dbgView.SearchPanel.CancelSearchFilter;
dbgView.SearchPanel.Visible := False;
end;
end;
procedure TStreetHouseViewForm.pmgCopyClick(Sender: TObject);
var
dbg: TDBGridEh;
begin
if (ActiveControl is TDBGridEh) then
begin
dbg := (ActiveControl as TDBGridEh);
if (geaCopyEh in dbg.EditActions) then
if dbg.CheckCopyAction then
begin
// Экспорт информации
if (dmMain.AllowedAction(rght_Export)) then
DBGridEh_DoCopyAction(dbg, False);
end
else
StrToClipbrd(dbg.SelectedField.AsString);
end;
end;
procedure TStreetHouseViewForm.pmgSaveSelectionClick(Sender: TObject);
var
ExpClass: TDBGridEhExportClass;
Ext: String;
begin
// Экспорт информации
if (not dmMain.AllowedAction(rght_Export)) then
Exit;
A4MainForm.SaveDialog.FileName := rsTable;
if (ActiveControl is TDBGridEh) then
if A4MainForm.SaveDialog.Execute then
begin
case A4MainForm.SaveDialog.FilterIndex of
1:
begin
ExpClass := TDBGridEhExportAsUnicodeText;
Ext := 'txt';
end;
2:
begin
ExpClass := TDBGridEhExportAsCSV;
Ext := 'csv';
end;
3:
begin
ExpClass := TDBGridEhExportAsHTML;
Ext := 'htm';
end;
4:
begin
ExpClass := TDBGridEhExportAsRTF;
Ext := 'rtf';
end;
5:
begin
ExpClass := TDBGridEhExportAsOLEXLS;
Ext := 'xls';
end;
else
ExpClass := nil;
Ext := '';
end;
if ExpClass <> nil then
begin
if AnsiUpperCase(Copy(A4MainForm.SaveDialog.FileName, Length(A4MainForm.SaveDialog.FileName) - 2, 3)) <>
AnsiUpperCase(Ext) then
A4MainForm.SaveDialog.FileName := A4MainForm.SaveDialog.FileName + '.' + Ext;
SaveDBGridEhToExportFile(ExpClass, TDBGridEh(ActiveControl), A4MainForm.SaveDialog.FileName, False);
end;
end;
end;
procedure TStreetHouseViewForm.pmgSelectAllClick(Sender: TObject);
begin
if (ActiveControl is TDBGridEh) then
with TDBGridEh(ActiveControl) do
if CheckSelectAllAction and (geaSelectAllEh in EditActions) then
Selection.SelectAll;
end;
end.
|
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{*
Find the maximum value in a matrix, returning that position.
*}
function ArgMax(Mat:T2DByteArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
{*
Find the maximum value in a matrix, returning that position.
*}
function ArgMax(Mat:T2DIntArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DExtArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DDoubleArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DFloatArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
{*
Find the minimum value in a matrix, returning that position.
*}
function ArgMin(Mat:T2DByteArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DIntArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DExtArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DDoubleArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DFloatArray): TPoint; overload;
var
X,Y,W,H:Integer;
begin
Result := Point(0,0);
H := High(Mat);
W := High(Mat[0]);
for Y:=0 to H do
for X:=0 to W do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
{***********************************************************]
Extended version
[***********************************************************}
//procedure WrapAroundBox(var B: TBox; W,H: Integer); Inline; || defined in Indices
{*
Find the maximum value in a matrix, returning that position.
*}
function ArgMax(Mat:T2DByteArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DIntArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DExtArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DDoubleArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMax(Mat:T2DFloatArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] > Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
{*
Find the minimum value in a matrix, returning that position.
*}
function ArgMin(Mat:T2DByteArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DIntArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DExtArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DDoubleArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
function ArgMin(Mat:T2DFloatArray; B:TBox): TPoint; overload;
var
X,Y,W,H:Integer;
begin
H := High(Mat);
W := High(Mat[0]);
WrapAroundBox(B, W+1,H+1);
Result := Point(B.x1,B.y1);
for Y:=B.y1 to B.y2 do
for X:=B.x1 to B.x2 do
if Mat[Y][X] < Mat[Result.y][Result.x] then
begin
Result.x := x;
Result.y := y;
end;
end;
|
unit UpdateInfo;
interface
uses
Classes, Types, StrUtils, SysUtils;
type
TUpdateInfo = class
private
FComponents: TStringlist;
FVersions: TStringList;
FSources: TStringlist;
function GetPatcherVersion: string;
public
constructor Create();
destructor Destroy(); override;
procedure LoadFromFile(AFile: string);
property Components: TStringlist read FComponents;
property Versions: TStringList read FVersions;
property Sources: TStringlist read FSources;
property PatcherVersion: string read GetPatcherVersion;
end;
implementation
uses
IniFiles, PatcherVersion;
{ TUpdateInfo }
constructor TUpdateInfo.Create;
begin
FComponents := TStringList.Create();
FVersions := TStringList.Create();
FSources := TStringList.Create();
end;
destructor TUpdateInfo.Destroy;
begin
FComponents.Free;
FVersions.Free;
FSources.Free;
inherited;
end;
function TUpdateInfo.GetPatcherVersion: string;
var
LIndex: Integer;
begin
Result := '0';
LIndex := FComponents.IndexOf(CPatcherName);
if LIndex > -1 then
begin
Result := FVersions[LIndex];
end;
end;
procedure TUpdateInfo.LoadFromFile(AFile: string);
var
LIni: TIniFile;
LSection: string;
begin
if not FileExists(AFile) then
begin
raise Exception.Create('Update file ' + QuotedStr(AFile) + ' does not exists!');
end;
LIni := TIniFile.Create(AFile);
try
LIni.ReadSections(FComponents);
for LSection in FComponents do
begin
FVersions.Add(LIni.ReadString(LSection, 'Version', '0'));
FSources.Add(LIni.ReadString(LSection, 'Source', ''));
end;
finally
LIni.Free;
end;
end;
end.
|
program pl0(input,output,fin) ; { version 1.0 oct.1989 }
{ PL/0 compiler with code generation }
const norw = 13; { no. of reserved words }
txmax = 100; { length of identifier table }
nmax = 14; { max. no. of digits in numbers }
al = 10; { length of identifiers }
amax = 2047; { maximum address }
levmax = 3; { maximum depth of block nesting }
cxmax = 200; { size of code array }
type symbol =
( nul,ident,number,plus,minus,times,slash,oddsym,eql,neq,lss,
leq,gtr,geq,lparen,rparen,comma,semicolon,period,becomes,
beginsym,endsym,ifsym,thensym,whilesym,dosym,callsym,constsym,
varsym,procsym,readsym,writesym );
alfa = packed array[1..al] of char;
objecttyp = (constant,variable,prosedure);
symset = set of symbol;
fct = ( lit,opr,lod,sto,cal,int,jmp,jpc,red,wrt ); { functions }
instruction = packed record
f : fct; { function code }
l : 0..levmax; { level }
a : 0..amax; { displacement address }
end;
{ lit 0, a : load constant a
opr 0, a : execute operation a
lod l, a : load variable l,a
sto l, a : store variable l,a
cal l, a : call procedure a at level l
int 0, a : increment t-register by a
jmp 0, a : jump to a
jpc 0, a : jump conditional to a
red l, a : read variable l,a
wrt 0, 0 : write stack-top
}
var ch : char; { last character read }
sym: symbol; { last symbol read }
id : alfa; { last identifier read }
num: integer; { last number read }
cc : integer; { character count }
ll : integer; { line length }
kk,err: integer;
cx : integer; { code allocation index }
line: array[1..81] of char;
a : alfa;
code : array[0..cxmax] of instruction;
word : array[1..norw] of alfa;
wsym : array[1..norw] of symbol;
ssym : array[char] of symbol;
mnemonic : array[fct] of
packed array[1..5] of char;
declbegsys, statbegsys, facbegsys : symset;
table : array[0..txmax] of
record
name : alfa;
case kind: objecttyp of
constant : (val:integer );
variable,prosedure: (level,adr: integer )
end;
fin : text; { source program file }
sfile: string; { source program file name }
procedure error( n : integer );
begin
writeln( '****', ' ':cc-1, '^', n:2 );
err := err+1
end; { error }
procedure getsym;
var i,j,k : integer;
procedure getch;
begin
if cc = ll { get character to end of line }
then begin { read next line }
if eof(fin)
then begin
writeln('program incomplete');
close(fin);
exit;
end;
ll := 0;
cc := 0;
write(cx:4,' '); { print code address }
while not eoln(fin) do
begin
ll := ll+1;
read(fin,ch);
write(ch);
line[ll] := ch
end;
writeln;
readln(fin);
ll := ll+1;
line[ll] := ' ' { process end-line }
end;
cc := cc+1;
ch := line[cc]
end; { getch }
begin { procedure getsym; }
while ch = ' ' do
getch;
if ch in ['a'..'z']
then begin { identifier of reserved word }
k := 0;
repeat
if k < al
then begin
k := k+1;
a[k] := ch
end;
getch
until not( ch in ['a'..'z','0'..'9']);
if k >= kk { kk : last identifier length }
then kk := k
else repeat
a[kk] := ' ';
kk := kk-1
until kk = k;
id := a;
i := 1;
j := norw; { binary search reserved word table }
repeat
k := (i+j) div 2;
if id <= word[k]
then j := k-1;
if id >= word[k]
then i := k+1
until i > j;
if i-1 > j
then sym := wsym[k]
else sym := ident
end
else if ch in ['0'..'9']
then begin { number }
k := 0;
num := 0;
sym := number;
repeat
num := 10*num+(ord(ch)-ord('0'));
k := k+1;
getch
until not( ch in ['0'..'9']);
if k > nmax
then error(30)
end
else if ch = ':'
then begin
getch;
if ch = '='
then begin
sym := becomes;
getch
end
else sym := nul
end
else if ch = '<'
then begin
getch;
if ch = '='
then begin
sym := leq;
getch
end
else if ch = '>'
then begin
sym := neq;
getch
end
else sym := lss
end
else if ch = '>'
then begin
getch;
if ch = '='
then begin
sym := geq;
getch
end
else sym := gtr
end
else begin
sym := ssym[ch];
getch
end
end; { getsym }
procedure gen( x: fct; y,z : integer );
begin
if cx > cxmax
then begin
writeln('program too long');
close(fin);
exit
end;
with code[cx] do
begin
f := x;
l := y;
a := z
end;
cx := cx+1
end; { gen }
procedure test( s1,s2 :symset; n: integer );
begin
if not ( sym in s1 )
then begin
error(n);
s1 := s1+s2;
while not( sym in s1) do
getsym
end
end; { test }
procedure block( lev,tx : integer; fsys : symset );
var dx : integer; { data allocation index }
tx0: integer; { initial table index }
cx0: integer; { initial code index }
procedure enter( k : objecttyp );
begin { enter object into table }
tx := tx+1;
with table[tx] do
begin
name := id;
kind := k;
case k of
constant : begin
if num > amax
then begin
error(30);
num := 0
end;
val := num
end;
variable : begin
level := lev;
adr := dx;
dx := dx+1
end;
prosedure: level := lev;
end
end
end; { enter }
function position ( id : alfa ): integer;
var i : integer;
begin
table[0].name := id;
i := tx;
while table[i].name <> id do
i := i-1;
position := i
end; { position }
procedure constdeclaration;
begin
if sym = ident
then begin
getsym;
if sym in [eql,becomes]
then begin
if sym = becomes
then error(1);
getsym;
if sym = number
then begin
enter(constant);
getsym
end
else error(2)
end
else error(3)
end
else error(4)
end; { constdeclaration }
procedure vardeclaration;
begin
if sym = ident
then begin
enter(variable);
getsym
end
else error(4)
end; { vardeclaration }
procedure listcode;
var i : integer;
begin
for i := cx0 to cx-1 do
with code[i] do
writeln( i:4, mnemonic[f]:7,l:3, a:5)
end; { listcode }
procedure statement( fsys : symset );
var i,cx1,cx2: integer;
procedure expression( fsys: symset);
var addop : symbol;
procedure term( fsys : symset);
var mulop: symbol ;
procedure factor( fsys : symset );
var i : integer;
begin
test( facbegsys, fsys, 24 );
while sym in facbegsys do
begin
if sym = ident
then begin
i := position(id);
if i= 0
then error(11)
else
with table[i] do
case kind of
constant : gen(lit,0,val);
variable : gen(lod,lev-level,adr);
prosedure: error(21)
end;
getsym
end
else if sym = number
then begin
if num > amax
then begin
error(30);
num := 0
end;
gen(lit,0,num);
getsym
end
else if sym = lparen
then begin
getsym;
expression([rparen]+fsys);
if sym = rparen
then getsym
else error(22)
end;
test(fsys,[lparen],23)
end
end; { factor }
begin { procedure term( fsys : symset);
var mulop: symbol ; }
factor( fsys+[times,slash]);
while sym in [times,slash] do
begin
mulop := sym;
getsym;
factor( fsys+[times,slash] );
if mulop = times
then gen( opr,0,4 )
else gen( opr,0,5)
end
end; { term }
begin { procedure expression( fsys: symset);
var addop : symbol; }
if sym in [plus, minus]
then begin
addop := sym;
getsym;
term( fsys+[plus,minus]);
if addop = minus
then gen(opr,0,1)
end
else term( fsys+[plus,minus]);
while sym in [plus,minus] do
begin
addop := sym;
getsym;
term( fsys+[plus,minus] );
if addop = plus
then gen( opr,0,2)
else gen( opr,0,3)
end
end; { expression }
procedure condition( fsys : symset );
var relop : symbol;
begin
if sym = oddsym
then begin
getsym;
expression(fsys);
gen(opr,0,6)
end
else begin
expression( [eql,neq,lss,gtr,leq,geq]+fsys);
if not( sym in [eql,neq,lss,leq,gtr,geq])
then error(20)
else begin
relop := sym;
getsym;
expression(fsys);
case relop of
eql : gen(opr,0,8);
neq : gen(opr,0,9);
lss : gen(opr,0,10);
geq : gen(opr,0,11);
gtr : gen(opr,0,12);
leq : gen(opr,0,13);
end
end
end
end; { condition }
begin { procedure statement( fsys : symset );
var i,cx1,cx2: integer; }
if sym = ident
then begin
i := position(id);
if i= 0
then error(11)
else if table[i].kind <> variable
then begin { giving value to non-variation }
error(12);
i := 0
end;
getsym;
if sym = becomes
then getsym
else error(13);
expression(fsys);
if i <> 0
then
with table[i] do
gen(sto,lev-level,adr)
end
else if sym = callsym
then begin
getsym;
if sym <> ident
then error(14)
else begin
i := position(id);
if i = 0
then error(11)
else
with table[i] do
if kind = prosedure
then gen(cal,lev-level,adr)
else error(15);
getsym
end
end
else if sym = ifsym
then begin
getsym;
condition([thensym,dosym]+fsys);
if sym = thensym
then getsym
else error(16);
cx1 := cx;
gen(jpc,0,0);
statement(fsys);
code[cx1].a := cx
end
else if sym = beginsym
then begin
getsym;
statement([semicolon,endsym]+fsys);
while sym in ([semicolon]+statbegsys) do
begin
if sym = semicolon
then getsym
else error(10);
statement([semicolon,endsym]+fsys)
end;
if sym = endsym
then getsym
else error(17)
end
else if sym = whilesym
then begin
cx1 := cx;
getsym;
condition([dosym]+fsys);
cx2 := cx;
gen(jpc,0,0);
if sym = dosym
then getsym
else error(18);
statement(fsys);
gen(jmp,0,cx1);
code[cx2].a := cx
end
else if sym = readsym
then begin
getsym;
if sym = lparen
then
repeat
getsym;
if sym = ident
then begin
i := position(id);
if i = 0
then error(11)
else if table[i].kind <> variable
then begin
error(12);
i := 0
end
else with table[i] do
gen(red,lev-level,adr)
end
else error(4);
getsym;
until sym <> comma
else error(40);
if sym <> rparen
then error(22);
getsym
end
else if sym = writesym
then begin
getsym;
if sym = lparen
then begin
repeat
getsym;
expression([rparen,comma]+fsys);
gen(wrt,0,0);
until sym <> comma;
if sym <> rparen
then error(22);
getsym
end
else error(40)
end;
test(fsys,[],19)
end; { statement }
begin { procedure block( lev,tx : integer; fsys : symset );
var dx : integer; /* data allocation index */
tx0: integer; /*initial table index */
cx0: integer; /* initial code index */ }
dx := 3;
tx0 := tx;
table[tx].adr := cx;
gen(jmp,0,0); { jump from declaration part to statement part }
if lev > levmax
then error(32);
repeat
if sym = constsym
then begin
getsym;
repeat
constdeclaration;
while sym = comma do
begin
getsym;
constdeclaration
end;
if sym = semicolon
then getsym
else error(5)
until sym <> ident
end;
if sym = varsym
then begin
getsym;
repeat
vardeclaration;
while sym = comma do
begin
getsym;
vardeclaration
end;
if sym = semicolon
then getsym
else error(5)
until sym <> ident;
end;
while sym = procsym do
begin
getsym;
if sym = ident
then begin
enter(prosedure);
getsym
end
else error(4);
if sym = semicolon
then getsym
else error(5);
block(lev+1,tx,[semicolon]+fsys);
if sym = semicolon
then begin
getsym;
test( statbegsys+[ident,procsym],fsys,6)
end
else error(5)
end;
test( statbegsys+[ident],declbegsys,7)
until not ( sym in declbegsys );
code[table[tx0].adr].a := cx; { back enter statement code's start adr. }
with table[tx0] do
begin
adr := cx; { code's start address }
end;
cx0 := cx;
gen(int,0,dx); { topstack point to operation area }
statement( [semicolon,endsym]+fsys);
gen(opr,0,0); { return }
test( fsys, [],8 );
listcode;
end { block };
procedure interpret;
const stacksize = 500;
var p,b,t: integer; { program-,base-,topstack-register }
i : instruction;{ instruction register }
s : array[1..stacksize] of integer; { data store }
function base( l : integer ): integer;
var b1 : integer;
begin { find base l levels down }
b1 := b;
while l > 0 do
begin
b1 := s[b1];
l := l-1
end;
base := b1
end; { base }
begin
writeln( 'START PL/0' );
t := 0;
b := 1;
p := 0;
s[1] := 0;
s[2] := 0;
s[3] := 0;
repeat
i := code[p];
p := p+1;
with i do
case f of
lit : begin
t := t+1;
s[t]:= a;
end;
opr : case a of { operator }
0 : begin { return }
t := b-1;
p := s[t+3];
b := s[t+2];
end;
1 : s[t] := -s[t];
2 : begin
t := t-1;
s[t] := s[t]+s[t+1]
end;
3 : begin
t := t-1;
s[t] := s[t]-s[t+1]
end;
4 : begin
t := t-1;
s[t] := s[t]*s[t+1]
end;
5 : begin
t := t-1;
s[t] := s[t]div s[t+1]
end;
6 : s[t] := ord(odd(s[t]));
8 : begin
t := t-1;
s[t] := ord(s[t]=s[t+1])
end;
9 : begin
t := t-1;
s[t] := ord(s[t]<>s[t+1])
end;
10: begin
t := t-1;
s[t] := ord(s[t]< s[t+1])
end;
11: begin
t := t-1;
s[t] := ord(s[t] >= s[t+1])
end;
12: begin
t := t-1;
s[t] := ord(s[t] > s[t+1])
end;
13: begin
t := t-1;
s[t] := ord(s[t] <= s[t+1])
end;
end;
lod : begin
t := t+1;
s[t] := s[base(l)+a]
end;
sto : begin
s[base(l)+a] := s[t]; { writeln(s[t]); }
t := t-1
end;
cal : begin { generate new block mark }
s[t+1] := base(l);
s[t+2] := b;
s[t+3] := p;
b := t+1;
p := a;
end;
int : t := t+a;
jmp : p := a;
jpc : begin
if s[t] = 0
then p := a;
t := t-1;
end;
red : begin
writeln('??:');
readln(s[base(l)+a]);
end;
wrt : begin
writeln(s[t]);
t := t+1
end
end { with,case }
until p = 0;
writeln('END PL/0');
end; { interpret }
begin { main }
writeln('please input source program file name : ');
readln(sfile);
assign(fin,sfile);
reset(fin);
for ch := 'A' to ';' do
ssym[ch] := nul;
word[1] := 'begin '; word[2] := 'call ';
word[3] := 'const '; word[4] := 'do ';
word[5] := 'end '; word[6] := 'if ';
word[7] := 'odd '; word[8] := 'procedure ';
word[9] := 'read '; word[10]:= 'then ';
word[11]:= 'var '; word[12]:= 'while ';
word[13]:= 'write ';
wsym[1] := beginsym; wsym[2] := callsym;
wsym[3] := constsym; wsym[4] := dosym;
wsym[5] := endsym; wsym[6] := ifsym;
wsym[7] := oddsym; wsym[8] := procsym;
wsym[9] := readsym; wsym[10]:= thensym;
wsym[11]:= varsym; wsym[12]:= whilesym;
wsym[13]:= writesym;
ssym['+'] := plus; ssym['-'] := minus;
ssym['*'] := times; ssym['/'] := slash;
ssym['('] := lparen; ssym[')'] := rparen;
ssym['='] := eql; ssym[','] := comma;
ssym['.'] := period;
ssym['<'] := lss; ssym['>'] := gtr;
ssym[';'] := semicolon;
mnemonic[lit] := 'LIT '; mnemonic[opr] := 'OPR ';
mnemonic[lod] := 'LOD '; mnemonic[sto] := 'STO ';
mnemonic[cal] := 'CAL '; mnemonic[int] := 'INT ';
mnemonic[jmp] := 'JMP '; mnemonic[jpc] := 'JPC ';
mnemonic[red] := 'RED '; mnemonic[wrt] := 'WRT ';
declbegsys := [ constsym, varsym, procsym ];
statbegsys := [ beginsym, callsym, ifsym, whilesym];
facbegsys := [ ident, number, lparen ];
err := 0;
cc := 0;
cx := 0;
ll := 0;
ch := ' ';
kk := al;
getsym;
block( 0,0,[period]+declbegsys+statbegsys );
if sym <> period
then error(9);
if err = 0
then interpret
else write('ERRORS IN PL/0 PROGRAM');
writeln;
close(fin)
end.
|
unit DW.NotificationReceiver;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
// Unit associated with workaround for: https://quality.embarcadero.com/browse/RSP-20565
// You should probably not use this unit for anything else
interface
uses
// Android
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes,
// DW
DW.MultiReceiver.Android;
type
TNotificationReceiver = class(TMultiReceiver)
protected
procedure Receive(context: JContext; intent: JIntent); override;
procedure ConfigureActions; override;
public
class function ACTION_NOTIFICATION: JString;
class function EXTRA_NOTIFICATION: JString;
class function EXTRA_NOTIFICATION_ID: JString;
end;
implementation
uses
// RTL
System.SysUtils,
// Android
Androidapi.Helpers, Androidapi.JNIBridge, Androidapi.JNI.App;
function NotificationManager: JNotificationManager;
var
LObject: JObject;
begin
LObject := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.NOTIFICATION_SERVICE);
Result := TJNotificationManager.Wrap((LObject as ILocalObject).GetObjectID);
end;
{ TNotificationReceiver }
class function TNotificationReceiver.ACTION_NOTIFICATION: JString;
begin
Result := StringToJString('ACTION_NOTIFICATION_EX');
end;
class function TNotificationReceiver.EXTRA_NOTIFICATION: JString;
begin
Result := StringToJString('EXTRA_NOTIFICATION');
end;
class function TNotificationReceiver.EXTRA_NOTIFICATION_ID: JString;
begin
Result := StringToJString('EXTRA_NOTIFICATION_ID');
end;
procedure TNotificationReceiver.ConfigureActions;
begin
IntentFilter.addAction(ACTION_NOTIFICATION);
end;
procedure TNotificationReceiver.Receive(context: JContext; intent: JIntent);
var
LNotification: JNotification;
begin
LNotification := TJNotification.Wrap(intent.getParcelableExtra(EXTRA_NOTIFICATION));
NotificationManager.notify(intent.getIntExtra(EXTRA_NOTIFICATION_ID, 0), LNotification);
end;
end.
|
unit HeaderFooterTemplate;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.MobilePreview, Androidapi.JNI.GraphicsContentViewText, FMX.Helpers.Android,
Androidapi.JNI.JavaTypes, FMX.Platform.Android, AndroidApi.JniBridge, AndroidApi.Jni.App,
AndroidAPI.jni.OS;
type
THeaderFooterForm = class(TForm)
Header: TToolBar;
Footer: TToolBar;
HeaderLabel: TLabel;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
HeaderFooterForm: THeaderFooterForm;
implementation
{$R *.fmx}
procedure THeaderFooterForm.Button1Click(Sender: TObject);
{$IFDEF ANDROID}
var
ShortcutIntent: JIntent;
addIntent: JIntent;
wIconIdentifier : integer;
wIconResource : JIntent_ShortcutIconResource;
{$ENDIF}
begin
{$IFDEF ANDROID}
ShortcutIntent := TJIntent.JavaClass.init(SharedActivityContext, SharedActivityContext.getClass);
ShortcutIntent.setAction(TJIntent.JavaClass.ACTION_MAIN);
addIntent := TJIntent.Create;
addIntent.putExtra(TJIntent.JavaClass.EXTRA_SHORTCUT_INTENT, TJParcelable.Wrap((shortcutIntent as ILocalObject).GetObjectID));// here we need to cast the intent as it's not done in delphi by default, not like java
addIntent.putExtra(TJIntent.JavaClass.EXTRA_SHORTCUT_NAME, StringToJString(Application.Title));
addIntent.setAction(StringToJString('com.android.launcher.action.INSTALL_SHORTCUT'));
// get icon resource identifier
wIconIdentifier := SharedActivity.getResources.getIdentifier(StringToJString('ic_launcher'), StringToJString('drawable'), StringToJString('com.embarcadero.HeaderFooterApplication')); // if the app name change, you must change the package name
wIconResource := TJIntent_ShortcutIconResource.JavaClass.fromContext(SharedActivityContext, wIconIdentifier);
// set icon for shortcut
addIntent.putExtra(TJIntent.JavaClass.EXTRA_SHORTCUT_ICON_RESOURCE, TJParcelable.Wrap((wIconResource as ILocalObject).GetObjectID));
SharedActivityContext.sendBroadcast(addIntent);
{$ENDIF}
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals 5.00 }
{ File name: flcTCPUtils.pas }
{ File version: 5.01 }
{ Description: TCP utilities. }
{ }
{ Copyright: Copyright (c) 2007-2021, David J Butler }
{ All rights reserved. }
{ This file is licensed under the BSD License. }
{ See http://www.opensource.org/licenses/bsd-license.php }
{ 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. }
{ 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. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2020/05/20 0.01 Initial version from unit flcTCPConnection. }
{ TCP timers helpers. TCP CompareMem helper. }
{ }
{******************************************************************************}
{$INCLUDE ..\flcInclude.inc}
{$INCLUDE flcTCP.inc}
unit flcTCPUtils;
interface
uses
SysUtils,
SyncObjs,
Classes,
{ Fundamentals }
flcStdTypes;
{ }
{ TCP timer helpers }
{ }
function TCPGetTick: Word64;
function TCPTickDelta(const D1, D2: Word64): Int64;
function TCPTickDeltaU(const D1, D2: Word64): Word64;
{ }
{ TCP CompareMem helper }
{ }
function TCPCompareMem(const Buf1; const Buf2; const Count: Integer): Boolean;
{ TCP Log Type }
type
TTCPLogType = (
tlDebug,
tlParameter,
tlInfo,
tlWarning,
tlError
);
{ TCP Thread }
type
TTCPThread = class(TThread)
public
constructor Create;
destructor Destroy; override;
procedure Finalise; virtual;
property Terminated;
function SleepUnterminated(const ATimeMs: Int32): Boolean;
end;
procedure TCPThreadTerminate(const AThread: TTCPThread);
procedure TCPThreadFinalise(const AThread: TTCPThread);
type
ETAbortableMultiWaitEventError = class(Exception);
TAbortableMultiWaitEvent = class
FLock : TCriticalSection;
FEvent : TSimpleEvent;
FWaitCount : Int32;
FTerminated : Boolean;
procedure Lock;
procedure Unlock;
public
constructor Create;
destructor Destroy; override;
procedure SetEvent;
procedure ResetEvent;
function WaitEvent(const ATimeout: UInt32): TWaitResult;
procedure SetTerminated;
procedure WaitTerminated(const ATimeout: UInt32);
end;
implementation
uses
{ Fundamentals }
flcTimers;
{ }
{ TCP timer helpers }
{ }
function TCPGetTick: Word64;
begin
Result := GetMilliTick;
end;
function TCPTickDelta(const D1, D2: Word64): Int64;
begin
Result := MilliTickDelta(D1, D2);
end;
function TCPTickDeltaU(const D1, D2: Word64): Word64;
begin
Result := MilliTickDeltaU(D1, D2);
end;
{ }
{ TCP CompareMem helper }
{ }
{$IFDEF ASM386_DELPHI}
function TCPCompareMem(const Buf1; const Buf2; const Count: Integer): Boolean;
asm
// EAX = Buf1, EDX = Buf2, ECX = Count
OR ECX, ECX
JLE @Fin1
CMP EAX, EDX
JE @Fin1
PUSH ESI
PUSH EDI
MOV ESI, EAX
MOV EDI, EDX
MOV EDX, ECX
SHR ECX, 2
XOR EAX, EAX
REPE CMPSD
JNE @Fin0
MOV ECX, EDX
AND ECX, 3
REPE CMPSB
JNE @Fin0
INC EAX
@Fin0:
POP EDI
POP ESI
RET
@Fin1:
MOV AL, 1
end;
{$ELSE}
function TCPCompareMem(const Buf1; const Buf2; const Count: Integer): Boolean;
var P, Q : Pointer;
D, I : Integer;
begin
P := @Buf1;
Q := @Buf2;
if (Count <= 0) or (P = Q) then
begin
Result := True;
exit;
end;
D := Word32(Count) div 4;
for I := 1 to D do
if PWord32(P)^ = PWord32(Q)^ then
begin
Inc(PWord32(P));
Inc(PWord32(Q));
end
else
begin
Result := False;
exit;
end;
D := Word32(Count) and 3;
for I := 1 to D do
if PByte(P)^ = PByte(Q)^ then
begin
Inc(PByte(P));
Inc(PByte(Q));
end
else
begin
Result := False;
exit;
end;
Result := True;
end;
{$ENDIF}
{ TTCPThread }
constructor TTCPThread.Create;
begin
FreeOnTerminate := False;
inherited Create(False);
end;
destructor TTCPThread.Destroy;
begin
if not Terminated then
Terminate;
inherited Destroy;
end;
procedure TTCPThread.Finalise;
begin
if not Terminated then
Terminate;
try
{$IFNDEF DELPHI7}
if not Finished then
{$ENDIF}
WaitFor;
except
end;
end;
function TTCPThread.SleepUnterminated(const ATimeMs: Int32): Boolean;
var
LTime : Int32;
begin
if Terminated then
begin
Result := False;
exit;
end;
if ATimeMs < 0 then
begin
Result := True;
exit;
end;
if ATimeMs = 0 then
Sleep(0)
else
begin
LTime := ATimeMs;
while LTime >= 100 do
begin
Sleep(100);
if Terminated then
begin
Result := False;
exit;
end;
Dec(LTime, 100);
end;
if LTime > 0 then
Sleep(LTime);
end;
Result := not Terminated;
end;
procedure TCPThreadTerminate(const AThread: TTCPThread);
begin
if Assigned(AThread) then
if not AThread.Terminated then
AThread.Terminate;
end;
procedure TCPThreadFinalise(const AThread: TTCPThread);
begin
if Assigned(AThread) then
AThread.Finalise;
end;
{ TAbortableMultiWaitEvent }
constructor TAbortableMultiWaitEvent.Create;
begin
inherited Create;
FLock := TCriticalSection.Create;
FEvent := TSimpleEvent.Create;
FTerminated := False;
end;
destructor TAbortableMultiWaitEvent.Destroy;
begin
if Assigned(FEvent) and Assigned(FLock) and not FTerminated then
try
WaitTerminated(20);
except
end;
FreeAndNil(FEvent);
FreeAndNil(FLock);
inherited Destroy;
end;
procedure TAbortableMultiWaitEvent.Lock;
begin
FLock.Acquire;
end;
procedure TAbortableMultiWaitEvent.Unlock;
begin
FLock.Release;
end;
function TAbortableMultiWaitEvent.WaitEvent(const ATimeout: UInt32): TWaitResult;
procedure CheckTerminated;
begin
if FTerminated then
raise ETAbortableMultiWaitEventError.Create('Terminated');
end;
var
LEvent : TSimpleEvent;
begin
LEvent := FEvent;
Lock;
try
CheckTerminated;
Inc(FWaitCount);
finally
Unlock;
end;
try
Result := LEvent.WaitFor(ATimeout);
case Result of
wrAbandoned : raise ETAbortableMultiWaitEventError.Create('Abandoned');
wrError : raise ETAbortableMultiWaitEventError.Create('Wait error');
end;
CheckTerminated;
finally
Lock;
try
CheckTerminated;
Dec(FWaitCount);
finally
Unlock;
end;
end;
end;
procedure TAbortableMultiWaitEvent.SetEvent;
begin
FEvent.SetEvent;
end;
procedure TAbortableMultiWaitEvent.ResetEvent;
begin
if not FTerminated then
FEvent.ResetEvent;
end;
procedure TAbortableMultiWaitEvent.SetTerminated;
begin
Lock;
try
if FTerminated then
exit;
FTerminated := True;
FEvent.SetEvent;
finally
Unlock;
end;
end;
{$IFDEF DELPHI7}
const
INFINITE = -1;
{$ENDIF}
procedure TAbortableMultiWaitEvent.WaitTerminated(const ATimeout: UInt32);
var
L : UInt32;
begin
SetTerminated;
L := ATimeout;
while L <> 0 do
begin
Lock;
try
if FWaitCount <= 0 then
exit;
finally
Unlock;
end;
Sleep(1);
if L <> INFINITE then
if L >= 1 then
Dec(L, 1)
else
L := 0;
end;
if ATimeout > 0 then
raise ETAbortableMultiWaitEventError.Create('Timeout waiting for termination');
end;
end.
|
unit SaveInJpeg;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
StdCtrls, ExtCtrls,Figure,Transformation,FrameTimer,math;
type
{ TForm3 }
TForm3 = class(TForm)
Button1: TButton;
ComboBox1: TComboBox;
EditWidth: TEdit;
EditHeigth: TEdit;
Panel1: TPanel;
Panel2: TPanel;
procedure EditWidthChange (Sender: TObject);
procedure EditWidthKeyPress (Sender: TObject; var Key: char);
private
{ private declarations }
public
{ public declarations }
end;
procedure SaveJpeg (Name: string);
var
Form3: TForm3;
PictureWidth,PictureHight: integer;
FileName: String;
implementation
{$R *.lfm}
{ TForm3 }
procedure SaveJpeg (Name: string);
var p: TPoint;
i,h,w: integer;
s: Double;
f: File;
BitMap : TBitmap;
Picture : TJPEGImage;
begin
BitMap:=TBitmap.Create;
h:=StrToInt(Form3.EditHeigth.Text);
w:=StrToInt(Form3.EditWidth.Text);
p:=Offset;
s:=scale;
scale:=min((w-5)/(maxx-minx),(h-5)/(maxy-miny));
Offset.X:=round(minx*scale);
Offset.y:=round(miny*scale);
Bitmap.SetSize (w, h);
Bitmap.Canvas.Brush.Color := clWhite;
Bitmap.Canvas.Brush.Style := bsSolid;
Bitmap.Canvas.Pen.Color := clWhite;
Bitmap.Canvas.Pen.Width := 1;
Bitmap.Canvas.Rectangle (0, 0, w, h);
for i:=0 to High(Figures) do begin
Figures[i].Selected:=False;
Figures[i].Draw (Bitmap.Canvas);
end;
scale:=s;
Offset:=p;
Picture:=TJPEGImage.Create;
Picture.Assign(BitMap);
Picture.SaveToFile(Name);
end;
procedure TForm3.EditWidthKeyPress (Sender: TObject; var Key: char);
begin
if not (key in ['0'..'9', #8]) then
Key := #0;
end;
procedure TForm3.EditWidthChange (Sender: TObject);
begin
if ((Sender as TEdit).Text = '') or ((Sender as TEdit).Text[1] = '0') then
(Sender as TEdit).Text := '1';
end;
end.
|
{**************************************************************************}
{ THTMLPopup component }
{ for Delphi & C++Builder }
{ }
{ Copyright © 2001-2013 }
{ TMS Software }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{ }
{ The source code is given as is. The author is not responsible }
{ for any possible damage done due to the use of this code. }
{ The component can be freely used in any application. The complete }
{ source code remains property of the author and may not be distributed, }
{ published, given or sold in any form as such. No parts of the source }
{ code can be included in any other component or application without }
{ written authorization of the author. }
{**************************************************************************}
unit HTMLPopup;
interface
{$I TMSDEFS.INC}
{$DEFINE REMOVESTRIP}
{$DEFINE REMOVEDRAW}
uses
Classes, Windows, Graphics, Messages, Controls, Forms, SysUtils,
PictureContainer, ImgList, ExtCtrls, Types
{$IFDEF DELPHIXE3_LVL}
, System.UITypes
{$ENDIF}
;
const
MAJ_VER = 1; // Major version nr.
MIN_VER = 4; // Minor version nr.
REL_VER = 0; // Release nr.
BLD_VER = 0; // Build nr.
// version history
// 1.2.0.0 : New property AutoSizeType added
// 1.3.0.0 : New : Event OnClick event added
// : New : Property HideType & TimeOut added
// : Improved : DFM property storage
// 1.3.1.0 : New : support for customizing bullets in HTML UL lists
// 1.4.0.0 : New : Support for PNG images via images in associated PictureContainer
type
TAnchorClickEvent = procedure(Sender: TObject; Anchor: string) of object;
TShadeDirection = (sdHorizontal, sdVertical);
TAutoSizeType = (asdHeight, asdWidth, asdBoth);
THideType = (htMouseLeave, htTimeOut);
{ THTMLPopup }
THTMLPopupWindow = class(THintWindow)
private
FImageCache: THTMLPictureCache;
FContainer: TPictureContainer;
FHoverLink: Integer;
FHover: Boolean;
FHoverRect: TRect;
FOnAnchorClick: TAnchorClickEvent;
FOnClick: TNotifyEvent;
FShadeEnable: Boolean;
FShadeSteps: Integer;
FShadeStartColor: TColor;
FShadeEndColor: TColor;
FColor: TColor;
FShadeDirection: TShadeDirection;
FBorderSize: Integer;
FImages: TImageList;
FAutoHide: Boolean;
FAutoSize: Boolean;
FAutoSizeType: TAutoSizeType;
FAlwaysOnTop: Boolean;
FMarginY: Integer;
FMarginX: Integer;
procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS;
procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure SetHover(const Value: Boolean);
procedure SetAutoSizeEx(const Value: Boolean);
procedure SetAlwaysOnTop(const Value: Boolean);
protected
procedure PaintShading(FromColor,ToColor: TColor; Steps: Integer; Direction: Boolean);
procedure Paint; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property AlwaysOnTop: Boolean read FAlwaysOnTop write SetAlwaysOnTop default false;
property AutoHide: Boolean read FAutoHide write FAutoHide default false;
property AutoSize: Boolean read FAutoSize write SetAutoSizeEx default false;
property AutoSizeType: TAutoSizeType read FAutoSizeType write FAutoSizeType default asdHeight;
property BorderSize: Integer read FBorderSize write FBorderSize default 0;
property Color: TColor read FColor write FColor default clInfoBk;
property Images: TImageList read FImages write FImages;
property MarginX: Integer read FMarginX write FMarginX default 4;
property MarginY: Integer read FMarginY write FMarginY default 4;
property ShadeEnable: Boolean read FShadeEnable write FShadeEnable default false;
property ShadeStartColor: TColor read FShadeStartColor write FShadeStartColor default clSilver;
property ShadeEndColor: TColor read FShadeEndColor write FShadeEndColor default clGray;
property ShadeSteps: Integer read FShadeSteps write FShadeSteps default 40;
property ShadeDirection: TShadeDirection read FShadeDirection write FShadeDirection default sdHorizontal;
property Hover: Boolean read FHover write SetHover default false;
property PictureContainer: TPictureContainer read FContainer write FContainer;
property OnAnchorClick: TAnchorClickEvent read FOnAnchorClick write FOnAnchorClick;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
end;
{$IFDEF DELPHIXE2_LVL}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
THTMLPopup = class(TComponent)
private
FOwner: TWinControl;
FHTMLPopupWindow: THTMLPopupWindow;
FHeight: Integer;
FWidth: Integer;
FContainer: TPictureContainer;
FText: TStringList;
FLeft: Integer;
FTop: Integer;
FHover: Boolean;
FOnAnchorClick: TAnchorClickEvent;
FOnClick: TNotifyEvent;
FShadeEnable: Boolean;
FShadeSteps: Integer;
FShadeStartColor: TColor;
FShadeEndColor: TColor;
FColor: TColor;
FFont: TFont;
FShadeDirection: TShadeDirection;
FBorderSize: Integer;
FImages: TImageList;
FAutoHide: Boolean;
FAutoSize: Boolean;
FAutoSizeType: TAutoSizeType;
FAlwaysOnTop: Boolean;
FMarginY: Integer;
FMarginX: Integer;
FRollUpSpace: Integer;
FTimer: TTimer;
FTimeOut: integer;
FHideType: THideType;
procedure SetText(const Value: TStringList);
procedure SetImages(const Value: TImageList);
procedure SetFont(const Value: TFont);
function GetVersion: string;
procedure SetVersion(const Value: string);
function GetVersionNr: Integer;
protected
procedure WindowAnchorClick(Sender: TObject; Anchor:string);
procedure WindowClick(Sender: TObject);
procedure WindowTimer(Sender: TObject);
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure CreatePopup;
procedure TextChanged(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Show;
procedure RollUp;
procedure RollDown;
procedure Hide;
property PopupWindow: THTMLPopupWindow read FHTMLPopupWindow;
published
property AlwaysOnTop: Boolean read FAlwaysOnTop write FAlwaysOnTop default false;
property AutoHide: Boolean read FAutoHide write FAutoHide default false;
property AutoSize: Boolean read FAutoSize write FAutoSize default false;
property AutoSizeType: TAutoSizeType read FAutoSizeType write FAutoSizeType default asdHeight;
property BorderSize: Integer read FBorderSize write FBorderSize default 0;
property Color: TColor read FColor write FColor default clInfoBk;
property Font: TFont read FFont write SetFont;
property Hover: Boolean read FHover write FHover default false;
property HideType: THideType read FHideType write FHideType default htMouseLeave;
property Images: TImageList read FImages write SetImages;
property MarginX: Integer read FMarginX write FMarginX default 4;
property MarginY: Integer read FMarginY write FMarginY default 4;
property PopupLeft: Integer read FLeft write FLeft default 0;
property PopupTop: Integer read FTop write FTop default 0;
property RollUpSpace: Integer read FRollUpSpace write FRollUpSpace default 0;
property ShadeEnable: Boolean read FShadeEnable write FShadeEnable default false;
property ShadeStartColor: TColor read FShadeStartColor write FShadeStartColor default clSilver;
property ShadeEndColor: TColor read FShadeEndColor write FShadeEndColor default clGray;
property ShadeSteps: Integer read FShadeSteps write FShadeSteps default 40;
property ShadeDirection: TShadeDirection read FShadeDirection write FShadeDirection default sdHorizontal;
property Text: TStringList read FText write SetText;
property TimeOut: integer read FTimeOut write FTimeOut default 2000;
property PictureContainer: TPictureContainer read FContainer write FContainer;
property PopupWidth: Integer read FWidth write FWidth default 200;
property PopupHeight: Integer read FHeight write FHeight default 200;
property OnAnchorClick: TAnchorClickEvent read FOnAnchorClick write FOnAnchorClick;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property Version: string read GetVersion write SetVersion;
end;
implementation
uses
Commctrl, ShellApi;
{$I HTMLENGO.PAS}
{ THTMLPopupWindow }
constructor THTMLPopupWindow.Create(AOwner: TComponent);
begin
inherited;
FImageCache := THTMLPictureCache.Create;
FHoverLink := -1;
FHover := True;
FImages := nil;
FAutoSizeType := asdBoth;
end;
destructor THTMLPopupWindow.Destroy;
begin
FImageCache.Free;
inherited;
end;
procedure THTMLPopupWindow.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if Assigned(OnClick) then
OnClick(Self);
end;
procedure THTMLPopupWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style - WS_BORDER;
if FAlwaysOnTop then
Params.ExStyle := Params.ExStyle or WS_EX_TOPMOST;
end;
procedure THTMLPopupWindow.PaintShading(FromColor,ToColor: TColor; Steps: Integer; Direction: Boolean);
var
diffr,startr,endr:longint;
diffg,startg,endg:longint;
diffb,startb,endb:longint;
rstepr:real;
rstepg:real;
rstepb:real;
rstepw:real;
i,stepw:word;
begin
if Steps = 0 then
Steps := 1;
startr := (FromColor and $0000ff);
startg := (FromColor and $00ff00) shr 8;
startb := (FromColor and $ff0000) shr 16;
endr := (ToColor and $0000ff);
endg := (ToColor and $00ff00) shr 8;
endb := (ToColor and $ff0000) shr 16;
diffr := endr-startr;
diffg := endg-startg;
diffb := endb-startb;
rstepr := diffr/steps;
rstepg := diffg/steps;
rstepb := diffb/steps;
if Direction then
rstepw := width/Steps
else
rstepw := height/Steps;
with Canvas do
begin
for i := 0 to steps-1 do
begin
endr := startr+round(rstepr*i);
endg := startg+round(rstepg*i);
endb := startb+round(rstepb*i);
stepw := round(i*rstepw);
pen.Color := endr + (endg shl 8) + (endb shl 16);
brush.Color := pen.Color;
if Direction then
Rectangle(stepw,0,stepw+round(rstepw)+1,height)
else
Rectangle(0,stepw,width,stepw+round(rstepw)+1);
end;
end;
end;
procedure THTMLPopupWindow.SetAutoSizeEx(const Value: Boolean);
var
R, rd, hr : TRect;
Anchor,Stripped,FocusAnchor:string;
XSize,YSize,HyperLinks,MouseLink:integer;
begin
FAutoSize := Value;
if not FAutoSize then
Exit;
R := ClientRect;
RD := ClientRect;
InflateRect(R,-FBorderSize,-FBorderSize);
RD.Left := R.Left + 6;
RD.Top := R.Top + 2;
// RD.Bottom := R.bottom - 8;
// RD.Right := R.Right - 4;
//RD.Right := RD.Left + 4096;
//RD.Bottom := RD.Top + 4096;
if FAutoSizeType in [asdWidth, asdBoth] then
RD.Right := RD.Left + 4096
else
RD.Right := RD.Left;
if FAutoSizeType in [asdHeight, asdBoth] then
RD.Bottom := RD.Top + 4096
else
RD.Bottom := RD.Top;
Canvas.Font.Assign(Self.Font);
HTMLDrawEx(Canvas,Caption,rd,FImages,0,0,-1,FHoverLink,1,False,False,False,False,True,FHover,True,
1.0,clBlue,clNone,clNone,clGray,Anchor,Stripped,FocusAnchor,XSize,YSize,
HyperLinks,MouseLink,hr,FImageCache,FContainer,0);
Width := XSize + 16 + BorderSize *2;
Height := YSize + 16 + BorderSize * 2;
end;
procedure THTMLPopupWindow.Paint;
var
DC: HDC;
R, rd, hr : TRect;
Brush, SaveBrush: HBRUSH;
Anchor,Stripped,FocusAnchor:string;
XSize,YSize,HyperLinks,MouseLink:integer;
procedure DCFrame3D(var R: TRect; const TopLeftColor, BottomRightColor: TColor);
var
Pen, SavePen: HPEN;
P: array[0..2] of TPoint;
begin
Pen := CreatePen(PS_SOLID, 1, ColorToRGB(TopLeftColor));
SavePen := SelectObject(DC, Pen);
P[0] := Point(R.Left, R.Bottom-2);
P[1] := Point(R.Left, R.Top);
P[2] := Point(R.Right-1, R.Top);
PolyLine(DC, P, 3);
SelectObject(DC, SavePen);
DeleteObject(Pen);
Pen := CreatePen(PS_SOLID, 1, ColorToRGB(BottomRightColor));
SavePen := SelectObject(DC, Pen);
P[0] := Point(R.Left, R.Bottom-1);
P[1] := Point(R.Right-1, R.Bottom-1);
P[2] := Point(R.Right-1, R.Top-1);
PolyLine(DC, P, 3);
SelectObject(DC, SavePen);
DeleteObject(Pen);
end;
begin
DC := Canvas.Handle;
R := ClientRect;
RD := ClientRect;
// Background
if FShadeEnable then
PaintShading(FShadeStartColor,FShadeEndColor,FShadeSteps,FShadeDirection = sdHorizontal)
else
begin
Brush := CreateSolidBrush(ColorToRGB(Color));
SaveBrush := SelectObject(DC, Brush);
FillRect(DC, R, Brush);
SelectObject(DC, SaveBrush);
DeleteObject(Brush);
end;
// Border
if FBorderSize = 0 then
DCFrame3D(R, cl3DLight, cl3DDkShadow)
else
begin
Canvas.Brush.Color := clBtnFace;
Canvas.Pen.Color := clBtnFace;
Canvas.Rectangle(0,0,R.Right, FBorderSize);
Canvas.Rectangle(R.Right - FBorderSize,0,R.Right, R.Bottom);
Canvas.Rectangle(0,R.Bottom - FBorderSize,R.Right, R.Bottom);
Canvas.Rectangle(0,0,FBorderSize,R.Bottom);
Canvas.Pen.Color := clWhite;
Canvas.MoveTo(0,R.Bottom);
Canvas.LineTo(0,0);
Canvas.LineTo(R.Right - 1,0);
Canvas.Pen.Color := clGray;
Canvas.LineTo(R.Right - 1,R.Bottom - 1);
Canvas.LineTo(0,R.Bottom - 1);
Canvas.MoveTo(FBorderSize,R.Bottom - FBorderSize);
Canvas.LineTo(FBorderSize,FBorderSize);
Canvas.LineTo(R.Right - FBorderSize,FBorderSize);
Canvas.Pen.Color := clWhite;
Canvas.LineTo(R.Right - FBorderSize,R.Bottom - FBorderSize);
Canvas.LineTo(FBorderSize,R.Bottom - FBorderSize);
InflateRect(R,-FBorderSize,-FBorderSize);
end;
RD.Left := R.Left + MarginX;
RD.Top := R.Top + MarginY;
RD.Bottom := R.bottom - MarginY;
RD.Right := R.Right - MarginX;
Canvas.Font.Assign(Self.Font);
HTMLDrawEx(Canvas,Caption,rd,FImages,0,0,-1,FHoverLink,1,False,False,False,False,True,FHover,True,
1.0,clBlue,clNone,clNone,clGray,Anchor,Stripped,FocusAnchor,XSize,YSize,
HyperLinks,MouseLink,hr,FImageCache,FContainer,0);
end;
constructor THTMLPopup.Create(AOwner: TComponent);
begin
inherited;
FText := TStringList.Create;
FText.OnChange := TextChanged;
FOwner := TWinControl(AOwner);
FHTMLPopupWindow := nil;
FWidth := 200;
FHeight := 200;
FColor := clInfoBk;
FShadeStartColor := clSilver;
FShadeEndColor := clGray;
FShadeSteps := 40;
FImages := nil;
FMarginX := 4;
FMarginY := 4;
FFont := TFont.Create;
FTimer := nil;
FTimeOut := 2000;
end;
procedure THTMLPopup.Hide;
begin
if Assigned(FHTMLPopupWindow) then
FHTMLPopupWindow.Visible := False;
end;
procedure THTMLPopup.TextChanged(Sender: TObject);
var
s: string;
i: Integer;
begin
if Assigned(FHTMLPopupWindow) then
begin
s := '';
for i := 1 to FText.Count do
s := s + FText.Strings[i - 1];
FHTMLPopupWindow.Caption := s;
end;
end;
procedure THTMLPopup.CreatePopup;
var
i: Integer;
s: string;
begin
if not Assigned(FHTMLPopupWindow) then
FHTMLPopupWindow := THTMLPopupWindow.Create(FOwner);
FHTMLPopupWindow.Visible := False;
FHTMLPopupWindow.Parent := nil;
FHTMLPopupWindow.ParentWindow := FOwner.Handle;
s := '';
for i := 1 to FText.Count do
s := s + FText.Strings[i - 1];
FHTMLPopupWindow.Caption := s;
FHTMLPopupWindow.AlwaysOnTop := FAlwaysOnTop;
FHTMLPopupWindow.Width := FWidth;
FHTMLPopupWindow.Height := FHeight;
FHTMLPopupWindow.Left := FLeft;
FHTMLPopupWindow.Top := FTop;
FHTMLPopupWindow.PictureContainer := FContainer;
FHTMLPopupWindow.Hover := FHover;
FHTMLPopupWindow.Images := FImages;
FHTMLPopupWindow.ShadeEnable := FShadeEnable;
FHTMLPopupWindow.ShadeStartColor := FShadeStartColor;
FHTMLPopupWindow.ShadeEndColor := FShadeEndColor;
FHTMLPopupWindow.ShadeDirection := FShadeDirection;
FHTMLPopupWindow.ShadeSteps := FShadeSteps;
FHTMLPopupWindow.MarginX := MarginX;
FHTMLPopupWindow.MarginY := MarginY;
FHTMLPopupWindow.Font.Assign(FFont);
FHTMLPopupWindow.AutoHide := FAutoHide and (FHideType = htMouseLeave);
FHTMLPopupWindow.BorderSize := FBorderSize;
FHTMLPopupWindow.Color := Color;
FHTMLPopupWindow.OnAnchorClick := WindowAnchorClick;
FHTMLPopupWindow.OnClick := WindowClick;
FHTMLPopupWindow.AutoSizeType := FAutoSizeType;
FHTMLPopupWindow.AutoSize := FAutoSize;
end;
procedure THTMLPopup.Show;
begin
CreatePopup;
FHTMLPopupWindow.Visible := True;
if FAutoHide and (FHideType = htTimeOut) then
begin
if not Assigned(FTimer) then
FTimer := TTimer.Create(self);
FTimer.Interval := FTimeout;
FTimer.OnTimer := WindowTimer;
FTimer.Enabled := true;
end;
end;
procedure THTMLPopup.SetText(const Value: TStringList);
begin
FText.Assign(Value);
end;
destructor THTMLPopup.Destroy;
begin
FText.Free;
FFont.Free;
if Assigned(FTimer) then
FreeAndNil(FTimer);
inherited;
end;
procedure THTMLPopupWindow.WMNCHitTest(var Message: TWMNCHitTest);
var
pt: TPoint;
RD,hr,r: TRect;
hl,ml: Integer;
XSize, YSize: Integer;
a,s,fa: string;
Anchor: string;
begin
pt := ScreenToClient(Point(message.Xpos,message.YPos));
r := ClientRect;
RD.Left := R.Left + MarginX;
RD.Top := R.Top + MarginY;
RD.Bottom := r.bottom - MarginY;
RD.Right := R.Right - MarginX;
InflateRect(RD,-FBorderSize,-FBorderSize);
Anchor := '';
Canvas.Font.Assign(Self.Font);
if HTMLDrawEx(Canvas,Caption,rd,FImages,pt.X,pt.Y,-1,-1,1,True,False,False,False,False,False,True,
1.0,clBlue,clNone,clNone,clGray,a,s,fa,XSize,YSize,
hl,ml,hr,FImageCache,FContainer,0) then
begin
Anchor := a;
end;
if (Anchor <> '') then
begin
Cursor := crHandPoint;
if (FHoverLink <> hl) and FHover then
InvalidateRect(Handle,@hr,True);
FHoverLink := hl;
FHoverRect := hr;
end
else
begin
Cursor := crDefault;
if (FHoverLink <> -1) and (FHover) then
InvalidateRect(Handle,@FHoverRect,True);;
FHoverLink := -1;
end;
Message.Result := HTCLIENT;
end;
procedure THTMLPopupWindow.WMSetFocus(var Msg: TWMSetFocus);
var
pt: TPoint;
RD,hr,r: TRect;
hl,ml: Integer;
XSize, YSize: Integer;
a,s,fa: string;
Anchor: string;
begin
msg.Result := 0;
GetCursorPos(pt);
pt := ScreenToClient(pt);
r := ClientRect;
RD.Left := R.Left + MarginX;
RD.Top := R.Top + MarginY;
RD.Bottom := R.bottom - MarginY;
RD.Right := R.Right - MarginX;
InflateRect(RD,-FBorderSize,-FBorderSize);
Anchor := '';
Canvas.Font.Assign(Self.Font);
if HTMLDrawEx(Canvas,Caption,rd,FImages,pt.X,pt.Y,-1,-1,1,True,False,False,False,False,False,True,
1.0,clBlue,clNone,clNone,clGray,a,s,fa,XSize,YSize,
hl,ml,hr,FImageCache,FContainer,0) then
begin
Anchor := a;
if Assigned(FOnAnchorClick) then
FOnAnchorClick(Self,a);
end;
Windows.SetFocus(ParentWindow);
if (FHoverLink <> -1) and (FHover) then
InvalidateRect(Handle,@FHoverRect,True);;
end;
procedure THTMLPopup.WindowAnchorClick(Sender: TObject; Anchor: string);
begin
if Assigned(FOnAnchorClick) then
FOnAnchorClick(Self,Anchor);
end;
procedure THTMLPopup.WindowClick(Sender: TObject);
begin
if Assigned(OnClick) then
OnClick(Self);
end;
procedure THTMLPopup.WindowTimer(Sender: TObject);
begin
Hide;
FTimer.Enabled := false;
end;
procedure THTMLPopup.RollDown;
var
t: DWORD;
r: TRect;
begin
if not Assigned(FHTMLPopupWindow) then
Exit;
SystemParametersInfo(SPI_GETWORKAREA, 0,@r,0);
while FHTMLPopupWindow.Top < r.Bottom do
begin
t := GetTickCount;
while GetTickCount - t < 50 do
Application.ProcessMessages;
FHTMLPopupWindow.Top := FHTMLPopupWindow.Top + 20;
end;
Hide;
end;
procedure THTMLPopup.RollUp;
var
t: DWORD;
r: TRect;
begin
SystemParametersInfo(SPI_GETWORKAREA, 0,@r,0);
FTop := r.Bottom;
CreatePopup;
FLeft := r.Right - FHTMLPopupWindow.Width - 20;
Show;
while FHTMLPopupWindow.Top + FHTMLPopupWindow.Height > r.Bottom do
begin
t := GetTickCount;
while GetTickCount - t < 50 do
Application.ProcessMessages;
if FHTMLPopupWindow.Top - 20 < r.Bottom - FHTMLPopupWindow.Height - FRollUpSpace then
FHTMLPopupWindow.Top := r.Bottom - FHTMLPopupWindow.Height - FRollUpSpace
else
FHTMLPopupWindow.Top := FHTMLPopupWindow.Top - 20;
end;
FHTMLPopupWindow.Top := r.Bottom - FHTMLPopupWindow.Height - FRollUpSpace;
end;
procedure THTMLPopupWindow.SetHover(const Value: Boolean);
begin
FHover := Value;
FHoverLink := -1;
end;
procedure THTMLPopup.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
if (AOperation = opRemove) and (AComponent = FContainer) then
FContainer := nil;
if (AOperation = opRemove) and (AComponent = FImages) then
FImages := nil;
inherited;
end;
procedure THTMLPopup.SetImages(const Value: TImageList);
begin
FImages := Value;
end;
procedure THTMLPopup.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
procedure THTMLPopupWindow.CMMouseLeave(var Message: TMessage);
begin
if FAutoHide then
Self.Visible := False;
end;
procedure THTMLPopupWindow.SetAlwaysOnTop(const Value: Boolean);
begin
FAlwaysOnTop := Value;
RecreateWnd;
end;
function THTMLPopup.GetVersion: string;
var
vn: Integer;
begin
vn := GetVersionNr;
Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;
function THTMLPopup.GetVersionNr: Integer;
begin
Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;
procedure THTMLPopup.SetVersion(const Value: string);
begin
end;
{$IFDEF FREEWARE}
{$I TRIAL.INC}
{$ENDIF}
end.
|
unit Entidade.TipoLancamento;
interface
uses SimpleAttributes;
type
TTIPO_LANCAMENTO=class
private
FID_PAI: Integer;
FDESCRICAO: string;
FCODIGO: string;
FID: integer;
FID_TIPO_CENTRO_CUSTO: Integer;
procedure SetCODIGO(const Value: string);
procedure SetDESCRICAO(const Value: string);
procedure SetID(const Value: integer);
procedure SetID_PAI(const Value: Integer);
procedure SetID_TIPO_CENTRO_CUSTO(const Value: Integer);
published
[PK,AutoInc]
property ID:integer read FID write SetID;
property CODIGO:string read FCODIGO write SetCODIGO;
property DESCRICAO:string read FDESCRICAO write SetDESCRICAO;
property ID_TIPO_CENTRO_CUSTO:Integer read FID_TIPO_CENTRO_CUSTO write SetID_TIPO_CENTRO_CUSTO;
property ID_PAI:Integer read FID_PAI write SetID_PAI;
end;
implementation
{ TTIPO_LANCAMENTO }
procedure TTIPO_LANCAMENTO.SetCODIGO(const Value: string);
begin
FCODIGO := Value;
end;
procedure TTIPO_LANCAMENTO.SetDESCRICAO(const Value: string);
begin
FDESCRICAO := Value;
end;
procedure TTIPO_LANCAMENTO.SetID(const Value: integer);
begin
FID := Value;
end;
procedure TTIPO_LANCAMENTO.SetID_PAI(const Value: Integer);
begin
FID_PAI := Value;
end;
procedure TTIPO_LANCAMENTO.SetID_TIPO_CENTRO_CUSTO(const Value: Integer);
begin
FID_TIPO_CENTRO_CUSTO := Value;
end;
end.
|
unit uProtoBufParserClasses;
interface
uses
System.Classes,
System.Generics.Defaults,
System.Generics.Collections,
uProtoBufParserAbstractClasses;
type
TPropKind = ( //
ptDefaultOptional, //
ptRequired, //
ptOptional, //
ptRepeated, //
ptReserved,
ptOneOf);
TScalarPropertyType = ( //
sptComplex, //
sptDouble, //
sptFloat, //
sptInt32, //
sptInt64, //
sptuInt32, //
sptUint64, //
sptSInt32, //
sptSInt64, //
sptFixed32, //
sptFixed64, //
sptSFixed32, //
sptSFixed64, //
sptBool, //
sptString, //
sptBytes);
TProtoBufPropOption = class(TAbstractProtoBufParserItem)
private
FOptionValue: string;
public
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
property OptionValue: string read FOptionValue;
end;
TProtoBufPropOptions = class(TAbstractProtoBufParserContainer<TProtoBufPropOption>)
private
function GetHasValue(const OptionName: string): Boolean;
function GetValue(const OptionName: string): string;
public
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
property HasValue[const OptionName: string]: Boolean read GetHasValue;
property Value[const OptionName: string]: string read GetValue;
end;
TProtoBufProperty = class(TAbstractProtoBufParserItem)
strict private
FPropFieldNum: integer;
FPropType: string;
FPropKind: TPropKind;
FPropOptions: TProtoBufPropOptions;
FOneOfPropertyParent: TProtoBufProperty;
public
constructor Create(ARoot: TAbstractProtoBufParserItem); override;
destructor Destroy; override;
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
property PropKind: TPropKind read FPropKind;
property PropType: string read FPropType;
property PropFieldNum: integer read FPropFieldNum;
property PropOptions: TProtoBufPropOptions read FPropOptions;
property OneOfPropertyParent: TProtoBufProperty read FOneOfPropertyParent write FOneOfPropertyParent;
end;
TProtoBufEnumValue = class(TAbstractProtoBufParserItem)
strict private
FValue: integer;
FIsHexValue: Boolean;
public
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
property Value: integer read FValue;
property IsHexValue: Boolean read FIsHexValue;
end;
TProtoBufEnum = class(TAbstractProtoBufParserContainer<TProtoBufEnumValue>)
strict private
FAllowAlias: Boolean;
FHexFormatString: string;
public
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
function GetEnumValueString(AEnumIndex: Integer): string;
property AllowAlias: Boolean read FAllowAlias;
end;
TProtoBufMessage = class(TAbstractProtoBufParserContainer<TProtoBufProperty>)
public
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
function HasPropertyOfType(const APropType: string): Boolean;
end;
TProtoBufEnumList = class(TObjectList<TProtoBufEnum>)
public
function FindByName(const EnumName: string): TProtoBufEnum;
end;
TProtoBufMessageList = class(TObjectList<TProtoBufMessage>)
public
function FindByName(const MessageName: string): TProtoBufMessage;
end;
TProtoSyntaxVersion = (psv2, psv3);
TProtoFile = class(TAbstractProtoBufParserItem)
strict private
FProtoBufMessages: TProtoBufMessageList;
FProtoBufEnums: TProtoBufEnumList;
FInImportCounter: integer;
FFileName: string;
FImports: TStrings;
FProtoSyntaxVersion: TProtoSyntaxVersion;
procedure ImportFromProtoFile(const AFileName: string);
private
procedure SetFileName(const Value: string);
public
constructor Create(ARoot: TAbstractProtoBufParserItem); override;
destructor Destroy; override;
procedure ParseEnum(const Proto: string; var iPos: integer; Comments: TStringList);
procedure ParseMessage(const Proto: string; var iPos: integer; Comments: TStringList; IsExtension: Boolean = False);
procedure ParseFromProto(const Proto: string; var iPos: integer); override;
property Imports: TStrings read FImports;
property ProtoBufEnums: TProtoBufEnumList read FProtoBufEnums;
property ProtoBufMessages: TProtoBufMessageList read FProtoBufMessages;
property FileName: string read FFileName write SetFileName;
property ProtoSyntaxVersion: TProtoSyntaxVersion read FProtoSyntaxVersion;
end;
function StrToPropertyType(const AStr: string): TScalarPropertyType;
implementation
uses
Math,
System.SysUtils,
System.StrUtils,
System.IOUtils,
Winapi.Windows,
System.Character;
function PropKindToStr(APropKind: TPropKind): string;
begin
case APropKind of
ptDefaultOptional:
Result := '';
ptRequired:
Result := 'required';
ptOptional:
Result := 'optional';
ptRepeated:
Result := 'repeated';
ptReserved:
Result := 'reserved';
ptOneOf:
Result := 'oneof';
end;
end;
function StrToPropKind(const AStr: string): TPropKind;
var
i: TPropKind;
begin
Result := Low(TPropKind);
for i := Low(TPropKind) to High(TPropKind) do
if SameStr(PropKindToStr(i), AStr) then
begin
Result := i;
Break;
end;
end;
function PropertyTypeToStr(PropType: TScalarPropertyType): string;
begin
Result := '';
case PropType of
sptComplex:
;
sptDouble:
Result := 'double';
sptFloat:
Result := 'float';
sptInt32:
Result := 'int32';
sptInt64:
Result := 'int64';
sptuInt32:
Result := 'uint32';
sptUint64:
Result := 'uint64';
sptSInt32:
Result := 'sint32';
sptSInt64:
Result := 'sint64';
sptFixed32:
Result := 'fixed32';
sptFixed64:
Result := 'fixed64';
sptSFixed32:
Result := 'sfixed32';
sptSFixed64:
Result := 'sfixed64';
sptBool:
Result := 'bool';
sptString:
Result := 'string';
sptBytes:
Result := 'bytes';
end;
end;
function StrToPropertyType(const AStr: string): TScalarPropertyType;
var
i: TScalarPropertyType;
begin
Result := Low(TScalarPropertyType);
for i := Low(TScalarPropertyType) to High(TScalarPropertyType) do
if SameStr(PropertyTypeToStr(i), AStr) then
begin
Result := i;
Break;
end;
end;
{ TProtoBufProperty }
constructor TProtoBufProperty.Create(ARoot: TAbstractProtoBufParserItem);
begin
inherited;
FPropOptions := TProtoBufPropOptions.Create(ARoot);
end;
destructor TProtoBufProperty.Destroy;
begin
FreeAndNil(FPropOptions);
inherited;
end;
procedure SkipWhitespaces(const Proto: string; var iPos: integer; ASkipParagraphSeparator: Boolean = True);
begin
while Proto[iPos].IsWhiteSpace and (iPos <= Length(Proto)) do
begin
if not ASkipParagraphSeparator then
begin
if UCS4Char(Proto[iPos]) < $FF then //IsLatin1, not accessible
begin
if Proto[iPos].IsInArray([#13, #10]) then
Break;
end else
if Proto[iPos].GetUnicodeCategory = TUnicodeCategory.ucParagraphSeparator then
Break;
end;
Inc(iPos);
end;
end;
function ReadAllTillChar(const Proto: string; var iPos: integer; BreakSymbol: array of Char): string;
begin
Result := '';
while not Proto[iPos].IsInArray(BreakSymbol) and (iPos <= Length(Proto)) do
begin
Result := Result + Proto[iPos];
Inc(iPos);
end;
end;
function ReadAllToEOL(const Proto: string; var iPos: integer): string;
begin
Result := ReadAllTillChar(Proto, iPos, [#13, #10]);
end;
procedure ReadCommentIfExists(ADestList: TStrings; AMultiLine: Boolean; const Proto: string; var iPos: integer);
var
s: string;
begin
SkipWhitespaces(Proto, iPos, False);
while (iPos < Length(Proto) - 1) and (Proto[iPos] = '/') and (Proto[iPos + 1] = '/') do
begin
Inc(iPos, 2);
SkipWhitespaces(Proto, iPos, False);
s:= ReadAllToEOL(Proto, iPos);
if Length(s) > 0 then
ADestList.Add(s);
//since we've Read to EOL, this will skip the EOL, if allowed
if AMultiLine then
SkipWhitespaces(Proto, iPos);
end;
end;
procedure SkipAllComments(const Proto: string; var iPos: integer);
begin
while True do
begin
SkipWhitespaces(Proto, iPos);
if (Proto[iPos] = '/') and (Proto[iPos + 1] = '/') then
ReadAllToEOL(Proto, iPos) else
Break;
end;
SkipWhitespaces(Proto, iPos);
end;
procedure SkipRequiredChar(const Proto: string; var iPos: integer; const RequiredChar: Char);
begin
SkipWhitespaces(Proto, iPos);
if Proto[iPos] <> RequiredChar then
raise EParserError.Create(RequiredChar + ' not found in ProtoBuf');
Inc(iPos);
end;
function ReadWordFromBuf(const Proto: string; var iPos: integer; BreakSymbols: array of Char): string;
begin
SkipWhitespaces(Proto, iPos);
Result := '';
while not Proto[iPos].IsWhiteSpace and not Proto[iPos].IsInArray(BreakSymbols) and (iPos <= Length(Proto)) do
begin
Result := Result + Proto[iPos];
Inc(iPos);
end;
end;
procedure TProtoBufProperty.ParseFromProto(const Proto: string; var iPos: integer);
var
Buf: string;
tmpOption: TProtoBufPropOption;
begin
inherited;
FPropOptions.Clear;
FComments.Clear;
{
[optional] int32 DefField1 = 1 [default = 2]; // def field 1, default value 2
int64 DefField2 = 2;
}
Buf := ReadWordFromBuf(Proto, iPos, []);
// in Buf - first word of property. Choose type
FPropKind := StrToPropKind(Buf);
if FPropKind = ptReserved then
begin
ReadAllTillChar(Proto, iPos, [';']);
SkipRequiredChar(Proto, iPos, ';');
exit; // reserved is not supported now by this parser
end;
if FPropKind <> ptDefaultOptional then // if required/optional/repeated is not skipped,
Buf := ReadWordFromBuf(Proto, iPos, []); // read type of property
FPropType := Buf;
if FPropKind = ptOneOf then
begin
FName := FPropType;
// skip '{' character
SkipRequiredChar(Proto, iPos, '{');
end else
begin
FName := ReadWordFromBuf(Proto, iPos, ['=']);
// skip '=' character
SkipRequiredChar(Proto, iPos, '=');
// read property tag
Buf := ReadWordFromBuf(Proto, iPos, [';', '[']);
FPropFieldNum := StrToInt(Buf);
SkipWhitespaces(Proto, iPos);
if Proto[iPos] = '[' then
FPropOptions.ParseFromProto(Proto, iPos);
if Assigned(FRoot) then
if TProtoFile(FRoot).ProtoSyntaxVersion = psv3 then
if not FPropOptions.HasValue['packed'] then
begin
tmpOption := TProtoBufPropOption.Create(FRoot);
FPropOptions.Add(tmpOption);
tmpOption.Name := 'packed';
tmpOption.FOptionValue := 'true';
end;
// read separator
SkipRequiredChar(Proto, iPos, ';');
end;
ReadCommentIfExists(FComments, False, Proto, iPos);
end;
{ TProtoBufPropOption }
procedure TProtoBufPropOption.ParseFromProto(const Proto: string; var iPos: integer);
begin
inherited;
{ [default = Val2, packed = true]; }
SkipWhitespaces(Proto, iPos);
FName := ReadWordFromBuf(Proto, iPos, ['=']);
// skip '=' character
SkipRequiredChar(Proto, iPos, '=');
SkipWhitespaces(Proto, iPos);
if Proto[iPos] <> '"' then
FOptionValue := ReadWordFromBuf(Proto, iPos, [',', ']'])
else
begin
Inc(iPos);
{ TODO : Solve problem with double "" in the middle of string... }
FOptionValue := Trim('"' + ReadAllTillChar(Proto, iPos, [',', ']', #13, #10]));
if not EndsStr('"', FOptionValue) then
raise EParserError.Create('no string escape in property ' + Name);
// SkipRequiredChar(Proto, iPos, '"');
end;
SkipWhitespaces(Proto, iPos);
if Proto[iPos] = ',' then
Inc(iPos);
end;
{ TProtoBufPropOptions }
function TProtoBufPropOptions.GetHasValue(const OptionName: string): Boolean;
var
i: integer;
begin
Result := False;
for i := 0 to Count - 1 do
if Items[i].Name = OptionName then
begin
Result := True;
Break;
end;
end;
function TProtoBufPropOptions.GetValue(const OptionName: string): string;
var
i: integer;
begin
Result := '';
for i := 0 to Count - 1 do
if Items[i].Name = OptionName then
begin
Result := Items[i].OptionValue;
Break;
end;
end;
procedure TProtoBufPropOptions.ParseFromProto(const Proto: string; var iPos: integer);
var
Option: TProtoBufPropOption;
begin
inherited;
SkipRequiredChar(Proto, iPos, '[');
SkipWhitespaces(Proto, iPos); // check for empty options
while Proto[iPos] <> ']' do
begin
Option := TProtoBufPropOption.Create(FRoot);
try
Option.ParseFromProto(Proto, iPos);
Add(Option);
Option := nil;
SkipWhitespaces(Proto, iPos);
finally
Option.Free;
end;
end;
SkipRequiredChar(Proto, iPos, ']');
end;
{ TProtoBufEnumValue }
procedure TProtoBufEnumValue.ParseFromProto(const Proto: string; var iPos: integer);
var
s: string;
begin
inherited;
{ Val1 = 1; }
FComments.Clear;
FName := ReadWordFromBuf(Proto, iPos, ['=']);
if Length(FName) = 0 then
raise EParserError.Create('Enumeration contains unnamed value');
SkipRequiredChar(Proto, iPos, '=');
s:= ReadWordFromBuf(Proto, iPos, [';']);
FValue := StrToInt(s);
FIsHexValue:= Pos('0x', s) = 1;
SkipRequiredChar(Proto, iPos, ';');
ReadCommentIfExists(FComments, False, Proto, iPos);
end;
{ TProtoBufEnum }
function TProtoBufEnum.GetEnumValueString(AEnumIndex: Integer): string;
var
item: TProtoBufEnumValue;
begin
item:= Items[AEnumIndex];
if item.isHexValue then
Result:= Format(FHexFormatString, [item.Value]) else
Result:= IntToStr(item.Value);
end;
procedure TProtoBufEnum.ParseFromProto(const Proto: string; var iPos: integer);
var
Item: TProtoBufEnumValue;
lPos, lMaxValue: Integer;
sOptionPeek, sOptionValue: string;
TempComments: TStringList;
begin
inherited;
(* Enum1 {
Val1 = 1;
Val2 = 2;
} *)
lMaxValue:= 0;
FName := ReadWordFromBuf(Proto, iPos, ['{']);
SkipRequiredChar(Proto, iPos, '{');
TempComments:= TStringList.Create;
try
TempComments.TrailingLineBreak:= False;
while Proto[iPos] <> '}' do
begin
TempComments.Clear;
SkipWhitespaces(Proto, iPos);
ReadCommentIfExists(TempComments, True, Proto, iPos);
if Proto[iPos] = '}' then //after reading comments, the enum might prematurly end
Continue;
lPos:= iPos;
sOptionPeek:= ReadWordFromBuf(Proto, lPos, [';']);
if SameText(sOptionPeek, 'option') then
begin
iPos:= lPos;
sOptionPeek:= ReadWordFromBuf(Proto, iPos, [';']);
SkipRequiredChar(Proto, iPos, '=');
sOptionValue:= ReadWordFromBuf(Proto, iPos, [';']);
if SameText(sOptionPeek, 'allow_alias') then
FAllowAlias:= SameText(sOptionValue, 'true') else
raise EParserError.CreateFmt('Unknown option %s while parsing enum %s', [sOptionPeek, FName]);
SkipRequiredChar(Proto, iPos, ';');
end else
begin
Item := TProtoBufEnumValue.Create(FRoot);
try
Item.ParseFromProto(Proto, iPos);
Item.AddCommentsToBeginning(TempComments);
Add(Item);
lMaxValue:= Max(lMaxValue, Item.Value);
Item := nil;
SkipWhitespaces(Proto, iPos);
finally
Item.Free;
end;
end;
end;
finally
TempComments.Free;
end;
SkipRequiredChar(Proto, iPos, '}');
ReadCommentIfExists(FComments, False, Proto, iPos);
if lMaxValue < 256 then
FHexFormatString:= '$%.2x' else
if lMaxValue < 65536 then
FHexFormatString:= '$%.4x' else
FHexFormatString:= '$%.8x';
Sort(TComparer<TProtoBufEnumValue>.Construct(
function(const Left, Right: TProtoBufEnumValue): integer
begin
Result := Left.Value - Right.Value;
end));
end;
{ TProtoBufMessage }
function TProtoBufMessage.HasPropertyOfType(const APropType: string): Boolean;
var
i: integer;
begin
Result := False;
for i := 0 to Count - 1 do
if Items[i].PropType = APropType then
begin
Result := True;
Break;
end;
end;
procedure TProtoBufMessage.ParseFromProto(const Proto: string; var iPos: integer);
var
Item, OneOfPropertyParent: TProtoBufProperty;
TempComments: TStringList;
begin
inherited;
(*
TestMsg0 {
required int32 Field1 = 1;
required int64 Field2 = 2;
}
*)
ReadCommentIfExists(FComments, True, Proto, iPos);
OneOfPropertyParent:= nil;
FName := ReadWordFromBuf(Proto, iPos, ['{']);
SkipRequiredChar(Proto, iPos, '{');
TempComments:= TStringList.Create;
try
TempComments.TrailingLineBreak:= False;
while (Proto[iPos] <> '}') or (OneOfPropertyParent <> nil) do
begin
if (OneOfPropertyParent <> nil) and (Proto[iPos] = '}') then
begin
SkipRequiredChar(Proto, iPos, '}');
SkipWhitespaces(Proto, iPos);
ReadCommentIfExists(OneOfPropertyParent.Comments, False, Proto, iPos);
OneOfPropertyParent:= nil;
SkipWhitespaces(Proto, iPos);
Continue;
end;
TempComments.Clear;
SkipWhitespaces(Proto, iPos);
ReadCommentIfExists(TempComments, True, Proto, iPos);
if Proto[iPos] = '}' then //after reading comments, the message might prematurly end
Continue;
if PosEx('enum', Proto, iPos) = iPos then
begin
Inc(iPos, Length('enum'));
if FRoot is TProtoFile then
begin
TProtoFile(FRoot).ParseEnum(Proto, iPos, TempComments);
Continue;
end;
end;
if PosEx('message', Proto, iPos) = iPos then
begin
Inc(iPos, Length('message'));
if FRoot is TProtoFile then
begin
TProtoFile(FRoot).ParseMessage(Proto, iPos, TempComments);
Continue;
end;
end;
Item := TProtoBufProperty.Create(FRoot);
try
Item.ParseFromProto(Proto, iPos);
Item.OneOfPropertyParent:= OneOfPropertyParent;
Item.AddCommentsToBeginning(TempComments);
Add(Item);
if Item.PropKind = ptOneOf then
begin
if OneOfPropertyParent <> nil then
raise EParserError.CreateFmt('Unsupported nested oneof property %s within %s', [Item.FName, OneOfPropertyParent.Name]);
OneOfPropertyParent:= Item;
end;
Item := nil;
SkipWhitespaces(Proto, iPos);
finally
Item.Free;
end;
end;
finally
TempComments.Free;
end;
SkipRequiredChar(Proto, iPos, '}');
ReadCommentIfExists(FComments, False, Proto, iPos);
//do NOT sort field definitions by FieldNumber; order is important for OneOf,
//also better to keep order of declaration the same as in .proto file
end;
{ TProtoFile }
constructor TProtoFile.Create(ARoot: TAbstractProtoBufParserItem);
begin
inherited;
FImports := TStringList.Create;
FProtoBufMessages := TProtoBufMessageList.Create;
FProtoBufEnums := TProtoBufEnumList.Create;
end;
destructor TProtoFile.Destroy;
begin
FreeAndNil(FProtoBufEnums);
FreeAndNil(FProtoBufMessages);
FreeAndNil(FImports);
inherited;
end;
function PathRelativePathTo(pszPath: PChar; pszFrom: PChar; dwAttrFrom: DWORD; pszTo: PChar; dwAtrTo: DWORD): LongBool; stdcall; external 'shlwapi.dll' Name 'PathRelativePathToW';
function PathCanonicalize(lpszDst: PChar; lpszSrc: PChar): LongBool; stdcall; external 'shlwapi.dll' Name 'PathCanonicalizeW';
function AbsToRel(const AbsPath, BasePath: string): string;
var
Path: array [0 .. MAX_PATH - 1] of Char;
begin
PathRelativePathTo(@Path[0], PChar(BasePath), FILE_ATTRIBUTE_DIRECTORY, PChar(AbsPath), 0);
Result := Path;
end;
function RelToAbs(const RelPath, BasePath: string): string;
var
Dst: array [0 .. MAX_PATH - 1] of Char;
begin
if TPath.IsRelativePath(RelPath) then
begin
PathCanonicalize(@Dst[0], PChar(IncludeTrailingPathDelimiter(BasePath) + RelPath));
Result := Dst;
end
else
Result := RelPath;
end;
procedure TProtoFile.ImportFromProtoFile(const AFileName: string);
var
SL: TStringList;
iPos: integer;
OldFileName: string;
OldName: string;
sFileName: string;
begin
if FFileName = '' then
raise EParserError.CreateFmt('Cant import from %s, because source .proto file name not specified', [AFileName]);
Inc(FInImportCounter);
try
SL := TStringList.Create;
try
sFileName := RelToAbs(AFileName, ExtractFilePath(FFileName));
SL.LoadFromFile(sFileName);
OldFileName := FFileName;
OldName := FName;
try
FileName := sFileName;
iPos := 1;
ParseFromProto(SL.Text, iPos);
FImports.Add(FName);
finally
FFileName := OldFileName;
FName := OldName;
end;
finally
SL.Free;
end;
finally
Dec(FInImportCounter);
end;
end;
procedure TProtoFile.ParseEnum(const Proto: string; var iPos: integer; Comments: TStringList);
var
Enum: TProtoBufEnum;
begin
Enum := TProtoBufEnum.Create(Self);
try
Enum.IsImported := FInImportCounter > 0;
Enum.ParseFromProto(Proto, iPos);
Enum.AddCommentsToBeginning(Comments);
FProtoBufEnums.Add(Enum);
Enum := nil;
finally
Enum.Free;
end;
end;
procedure TProtoFile.ParseFromProto(const Proto: string; var iPos: integer);
var
Buf: string;
i, j: integer;
TempComments: TStringList;
begin
// need skip comments,
// parse .proto package name
TempComments:= TStringList.Create;
try
TempComments.TrailingLineBreak:= False;
while iPos < Length(Proto) do
begin
SkipWhitespaces(Proto, iPos);
ReadCommentIfExists(TempComments, True, Proto, iPos);
SkipWhitespaces(Proto, iPos);
Buf := ReadWordFromBuf(Proto, iPos, []);
if Buf = 'package' then
begin
FName := ReadWordFromBuf(Proto, iPos, [';']);
SkipRequiredChar(Proto, iPos, ';');
TempComments.Clear;
end;
if Buf = 'syntax' then
begin
SkipRequiredChar(Proto, iPos, '=');
Buf := Trim(ReadWordFromBuf(Proto, iPos, [';']));
SkipRequiredChar(Proto, iPos, ';');
if Buf = '"proto3"' then
FProtoSyntaxVersion := psv3;
TempComments.Clear;
end;
if Buf = 'import' then
begin
Buf := Trim(ReadAllTillChar(Proto, iPos, [';']));
ImportFromProtoFile(AnsiDequotedStr(Buf, '"'));
SkipRequiredChar(Proto, iPos, ';');
TempComments.Clear;
end;
if Buf = 'enum' then
begin
ParseEnum(Proto, iPos, TempComments);
TempComments.Clear;
end;
if Buf = 'message' then
begin
ParseMessage(Proto, iPos, TempComments);
TempComments.Clear;
end;
if Buf = 'extend' then
begin
ParseMessage(Proto, iPos, TempComments, True);
TempComments.Clear;
end;
end;
finally
TempComments.Free;
end;
// can`t use QuickSort because of .proto items order
for i := 0 to FProtoBufMessages.Count - 1 do
for j := i + 1 to FProtoBufMessages.Count - 1 do
begin
if FProtoBufMessages[i].HasPropertyOfType(FProtoBufMessages[j].Name) then
FProtoBufMessages.Exchange(i, j);
end;
end;
procedure TProtoFile.ParseMessage(const Proto: string; var iPos: integer; Comments: TStringList; IsExtension: Boolean);
var
Msg: TProtoBufMessage;
i: integer;
begin
Msg := TProtoBufMessage.Create(Self);
try
Msg.IsImported := FInImportCounter > 0;
Msg.ParseFromProto(Proto, iPos);
if IsExtension then
begin
for i := 1 to High(integer) do
if FProtoBufMessages.FindByName(Msg.Name + 'Extension' + IntToStr(i)) = nil then
begin
Msg.ExtendOf := Msg.Name;
Msg.Name := Msg.Name + 'Extension' + IntToStr(i);
Break;
end;
end;
Msg.AddCommentsToBeginning(Comments);
FProtoBufMessages.Add(Msg);
Msg := nil;
finally
Msg.Free;
end;
end;
procedure TProtoFile.SetFileName(const Value: string);
begin
FFileName := Value;
FName := ChangeFileExt(ExtractFileName(Value), '');
end;
{ TProtoBufMessageList }
function TProtoBufMessageList.FindByName(const MessageName: string): TProtoBufMessage;
var
i: integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if Items[i].Name = MessageName then
begin
Result := Items[i];
Break;
end;
end;
{ TProtoBufEnumList }
function TProtoBufEnumList.FindByName(const EnumName: string): TProtoBufEnum;
var
i: integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if Items[i].Name = EnumName then
begin
Result := Items[i];
Break;
end;
end;
end.
|
PROGRAM ComplexBuiltIn;
TYPE
mystring = ARRAY[1..3] OF char;
VAR
x, y, z : complex;
PROCEDURE print(expr : mystring; VAR z : complex);
BEGIN
write(expr, ' = (', z.re:0:5, ', ', z.im:0:5, ') ');
END;
BEGIN {ComplexTest}
x.re := 3; x.im := 2; print(' x', x);
y.re := 8; y.im := -5; print(' y', y);
z := x + y; print('x+y', z);
writeln;
print(' x', x);
print(' y', y);
z := x - y; print('x-y', z);
writeln;
x.re := 4; x.im := -2; print(' x', x);
y.re := 1; y.im := -5; print(' y', y);
z := x*y; print('x*y', z);
writeln;
x.re := -3; x.im := 2; print(' x', x);
y.re := 3; y.im := -6; print(' y', y);
z := x/y; print('x/y', z);
writeln;
x.re := 5; x.im := 0; print(' x', x);
y.re := 3; y.im := 2; print(' y', y);
z := x + y; print('x+y', z);
writeln;
x.re := 5; x.im := 4; print(' x', x);
y.re := 2; y.im := 0; print(' y', y);
z := x*y; print('x*y', z);
writeln;
x.re := -2; x.im := -4; print(' x', x);
y.re := 0; y.im := 1; print(' y', y);
z := x/y; print('x/y', z);
writeln;
END {ComplexTest}. |
(*
PROBLEM 16: Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
*)
program ProjectEuler16;
const
base = 2;
exponent = 1000;
number_base = 10;
digits = 1000;
var
bignum: packed array[1..digits] of integer;
digit, carry, i, n: integer;
begin
(*
Despite my best efforts, I can't find any way to solve this without
actually computing the number. :( So here's a quick and dirty bigint
implementation.
*)
(* Compute the sum of the digits in base ^ exponent, in base number_base,
with digits of space to work with. *)
(* Populate our bignum with 1. Note that the digits are stored in reverse
order (so the units digit comes first) and numbered from 1. *)
for digit := 1 to digits do begin
bignum[digit] := 0;
end;
bignum[1] := 1;
(* Multiply it by base, exponent times. *)
for i := 1 to exponent do begin
carry := 0;
for digit := 1 to digits do begin
carry := carry + bignum[digit] * base;
bignum[digit] := carry mod number_base;
carry := carry div number_base;
end;
end;
(* Sum the digits *)
n := 0;
for digit := 1 to digits do begin
n := n + bignum[digit];
end;
(* And print the answer. *)
writeln(n);
end.
|
unit InternetAgentKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы InternetAgent }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\InternetAgent\Forms\InternetAgentKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "InternetAgentKeywordsPack" MUID: (49EC74D002B8_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, InternetAgent_Form
, tfwControlString
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *49EC74D002B8_Packimpl_uses*
//#UC END# *49EC74D002B8_Packimpl_uses*
;
type
Tkw_Form_InternetAgent = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы InternetAgent
----
*Пример использования*:
[code]форма::InternetAgent TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_InternetAgent
function Tkw_Form_InternetAgent.GetString: AnsiString;
begin
Result := 'InternetAgentForm';
end;//Tkw_Form_InternetAgent.GetString
class procedure Tkw_Form_InternetAgent.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TInternetAgentForm);
end;//Tkw_Form_InternetAgent.RegisterInEngine
class function Tkw_Form_InternetAgent.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::InternetAgent';
end;//Tkw_Form_InternetAgent.GetWordNameForRegister
initialization
Tkw_Form_InternetAgent.RegisterInEngine;
{* Регистрация Tkw_Form_InternetAgent }
TtfwTypeRegistrator.RegisterType(TypeInfo(TInternetAgentForm));
{* Регистрация типа TInternetAgentForm }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSmtpRelay;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils,{$IFDEF DEMO} Windows, Forms, clCertificate, clEncoder, clMailMessage,{$ENDIF}
{$ELSE}
System.Classes, System.SysUtils,{$IFDEF DEMO} Winapi.Windows, Vcl.Forms, clCertificate, clEncoder, clMailMessage,{$ENDIF}
{$ENDIF}
clSmtp, clDnsQuery, clMailUtils, clSocketUtils;
type
TclSmtpRelayStatus = class
private
FIsSent: Boolean;
FResponseCode: Integer;
FResponseText: string;
FMailServer: string;
FDomain: string;
FErrorCode: Integer;
FErrorText: string;
public
property Domain: string read FDomain;
property MailServer: string read FMailServer;
property ResponseCode: Integer read FResponseCode;
property ErrorCode: Integer read FErrorCode;
property ErrorText: string read FErrorText;
property ResponseText: string read FResponseText;
property IsSent: Boolean read FIsSent;
end;
TclSmtpRelayStatusList = class
private
FList: TList;
procedure Clear;
procedure Add(AItem: TclSmtpRelayStatus);
function GetCount: Integer;
function GetItem(Index: Integer): TclSmtpRelayStatus;
public
constructor Create;
destructor Destroy; override;
property Items[Index: Integer]: TclSmtpRelayStatus read GetItem; default;
property Count: Integer read GetCount;
end;
TclResolveMXEvent = procedure (Sender: TObject; const ADomain: string;
AMxList: TStrings; var Handled: Boolean) of object;
TclConnectMXEvent = procedure (Sender: TObject; const ADomain, AMailServer: string) of object;
TclRelayMessageEvent = procedure (Sender: TObject; const ADomain: string;
ARecipients: TStrings; ARelayStatus: TclSmtpRelayStatus) of object;
TclSmtpRelay = class(TclSmtp)
private
FDns: TclDnsQuery;
FStatusList: TclSmtpRelayStatusList;
FOnConnectMX: TclConnectMXEvent;
FOnDisconnectMX: TclConnectMXEvent;
FOnRelayMessage: TclRelayMessageEvent;
FOnResolveMX: TclResolveMXEvent;
FIsAborted: Boolean;
procedure SetDnsServer(const Value: string);
function GetDnsServer: string;
procedure ExtractDomains(AMailToList, ADomains: TStrings);
procedure ResolveMX(const ADomain: string; AMXList: TStrings;
AStatus: TclSmtpRelayStatus);
function ConnectMX(const ADomain, AMXServer: string;
AStatus: TclSmtpRelayStatus): Boolean;
procedure SendMx(const ADomain, AMailFrom: string; AMailData,
AMailToList: TStrings; AStatus: TclSmtpRelayStatus);
procedure DisconnectMX(const ADomain, AMXServer: string);
protected
procedure DoDestroy; override;
procedure SendMessage(const AMailFrom: string; AMailData, AMailToList: TStrings); override;
procedure DoResolveMX(const ADomain: string; AMxList: TStrings; var Handled: Boolean); dynamic;
procedure DoConnectMX(const ADomain, AMailServer: string); dynamic;
procedure DoDisconnectMX(const ADomain, AMailServer: string); dynamic;
procedure DoRelayMessage(const ADomain: string; ARecipients: TStrings;
ARelayStatus: TclSmtpRelayStatus); dynamic;
public
constructor Create(AOwner: TComponent); override;
procedure Abort;
property StatusList: TclSmtpRelayStatusList read FStatusList;
property IsAborted: Boolean read FIsAborted;
property Dns: TclDnsQuery read FDns;
published
property DnsServer: string read GetDnsServer write SetDnsServer;
property OnResolveMX: TclResolveMXEvent read FOnResolveMX write FOnResolveMX;
property OnConnectMX: TclConnectMXEvent read FOnConnectMX write FOnConnectMX;
property OnDisconnectMX: TclConnectMXEvent read FOnDisconnectMX write FOnDisconnectMX;
property OnRelayMessage: TclRelayMessageEvent read FOnRelayMessage write FOnRelayMessage;
end;
implementation
uses
clSocket, clEmailAddress, clTcpClient, clSspi;
{ TclSmtpRelay }
constructor TclSmtpRelay.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStatusList := TclSmtpRelayStatusList.Create();
FDns := TclDnsQuery.Create(nil);
FDns.IsRecursiveDesired := True;
end;
procedure TclSmtpRelay.DoConnectMX(const ADomain, AMailServer: string);
begin
if Assigned(OnConnectMX) then
begin
OnConnectMX(Self, ADomain, AMailServer);
end;
end;
procedure TclSmtpRelay.DoDisconnectMX(const ADomain, AMailServer: string);
begin
if Assigned(OnDisconnectMX) then
begin
OnDisconnectMX(Self, ADomain, AMailServer);
end;
end;
procedure TclSmtpRelay.DoRelayMessage(const ADomain: string;
ARecipients: TStrings; ARelayStatus: TclSmtpRelayStatus);
begin
if Assigned(OnRelayMessage) then
begin
OnRelayMessage(Self, ADomain, ARecipients, ARelayStatus);
end;
end;
procedure TclSmtpRelay.DoResolveMX(const ADomain: string;
AMxList: TStrings; var Handled: Boolean);
begin
if Assigned(OnResolveMX) then
begin
OnResolveMX(Self, ADomain, AMxList, Handled);
end;
end;
procedure TclSmtpRelay.ExtractDomains(AMailToList, ADomains: TStrings);
function GetEmailDomain(const AEmail: string): string;
var
ind: Integer;
s: string;
begin
GetEmailAddressParts(AEmail, s, Result);
ind := system.Pos('@', Result);
if (ind > 0) then
begin
system.Delete(Result, 1, ind);
end;
end;
var
i: Integer;
domain: string;
begin
ADomains.Clear();
for i := 0 to AMailToList.Count - 1 do
begin
domain := LowerCase(GetEmailDomain(AMailToList[i]));
if (ADomains.IndexOf(domain) < 0) then
begin
ADomains.Add(domain);
end;
end;
end;
procedure TclSmtpRelay.ResolveMX(const ADomain: string; AMXList: TStrings;
AStatus: TclSmtpRelayStatus);
var
i: Integer;
handled: Boolean;
hostInfo: TclHostInfo;
begin
try
AStatus.FDomain := ADomain;
AMXList.Clear();
handled := False;
DoResolveMX(ADomain, AMXList, handled);
if not handled then
begin
FDns.ResolveMX(ADomain);
for i := 0 to FDns.MailServers.Count - 1 do
begin
AMXList.Add(FDns.MailServers[i].Name);
end;
if (AMXList.Count = 0) then
begin
hostInfo := FDns.ResolveIP(ADomain);
if (hostInfo <> nil) then
begin
AMXList.Add(hostInfo.IPAddress);
end;
end;
end;
except
on E: EclSocketError do
begin
AStatus.FErrorCode := E.ErrorCode;
AStatus.FErrorText := E.Message;
end;
end;
end;
function TclSmtpRelay.ConnectMX(const ADomain, AMXServer: string;
AStatus: TclSmtpRelayStatus): Boolean;
begin
Assert(not Active);
AStatus.FMailServer := AMXServer;
Server := AMXServer;
try
Open();
DoConnectMX(ADomain, AMXServer);
except
on E: EclSspiError do
begin
AStatus.FErrorCode := E.ErrorCode;
AStatus.FErrorText := E.Message;
AStatus.FResponseCode := LastResponseCode;
AStatus.FResponseText := Trim(Response.Text);
Close();
end;
on E: EclSocketError do
begin
AStatus.FErrorCode := E.ErrorCode;
AStatus.FErrorText := E.Message;
AStatus.FResponseCode := LastResponseCode;
AStatus.FResponseText := Trim(Response.Text);
Close();
end;
end;
Result := Active;
end;
procedure TclSmtpRelay.DisconnectMX(const ADomain, AMXServer: string);
begin
Close();
DoDisconnectMX(ADomain, AMXServer);
end;
procedure TclSmtpRelay.SendMx(const ADomain, AMailFrom: string;
AMailData, AMailToList: TStrings; AStatus: TclSmtpRelayStatus);
var
i: Integer;
recipients: TStrings;
begin
recipients := TStringList.Create();
try
for i := 0 to AMailToList.Count - 1 do
begin
if (system.Pos('@' + ADomain, LowerCase(AMailToList[i])) > 0) then
begin
recipients.Add(AMailToList[i]);
end;
end;
try
inherited SendMessage(AMailFrom, AMailData, recipients);
AStatus.FIsSent := True;
except
on E: EclSspiError do
begin
AStatus.FErrorCode := E.ErrorCode;
AStatus.FErrorText := E.Message;
end;
on E: EclSocketError do
begin
AStatus.FErrorCode := E.ErrorCode;
AStatus.FErrorText := E.Message;
end;
end;
AStatus.FResponseCode := LastResponseCode;
AStatus.FResponseText := Trim(Response.Text);
DoRelayMessage(ADomain, recipients, AStatus);
finally
recipients.Free();
end;
end;
procedure TclSmtpRelay.SendMessage(const AMailFrom: string; AMailData, AMailToList: TStrings);
var
i, k: Integer;
status: TclSmtpRelayStatus;
domains, mxServers: TStrings;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsSmtpDemoDisplayed) and (not IsEncoderDemoDisplayed)
and (not IsCertDemoDisplayed) and (not IsMailMessageDemoDisplayed)
and (not IsDnsDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsSmtpDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsCertDemoDisplayed := True;
IsMailMessageDemoDisplayed := True;
IsDnsDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
FIsAborted := False;
FStatusList.Clear();
Close();
domains := nil;
mxServers := nil;
try
domains := TStringList.Create();
mxServers := TStringList.Create();
ExtractDomains(AMailToList, domains);
for i := 0 to domains.Count - 1 do
begin
if IsAborted then Exit;
status := TclSmtpRelayStatus.Create();
StatusList.Add(status);
ResolveMX(domains[i], mxServers, status);
for k := 0 to mxServers.Count - 1 do
begin
if IsAborted then Exit;
if ConnectMX(domains[i], mxServers[k], status) then
begin
if IsAborted then Exit;
SendMx(domains[i], AMailFrom, AMailData, AMailToList, status);
DisconnectMX(domains[i], mxServers[k]);
Break;
end;
end;
end;
finally
mxServers.Free();
domains.Free();
end;
end;
procedure TclSmtpRelay.SetDnsServer(const Value: string);
begin
if (FDns.Server <> Value) then
begin
FDns.Server := Value;
Changed();
end;
end;
function TclSmtpRelay.GetDnsServer: string;
begin
Result := FDns.Server;
end;
procedure TclSmtpRelay.Abort;
begin
FIsAborted := True;
Close();
end;
procedure TclSmtpRelay.DoDestroy;
begin
FDns.Free();
FStatusList.Free();
inherited DoDestroy();
end;
{ TclSmtpRelayStatusList }
procedure TclSmtpRelayStatusList.Add(AItem: TclSmtpRelayStatus);
begin
FList.Add(AItem);
end;
procedure TclSmtpRelayStatusList.Clear;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Items[i].Free();
end;
FList.Clear();
end;
constructor TclSmtpRelayStatusList.Create;
begin
inherited Create();
FList := TList.Create();
end;
destructor TclSmtpRelayStatusList.Destroy;
begin
Clear();
FList.Free();
inherited Destroy();
end;
function TclSmtpRelayStatusList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TclSmtpRelayStatusList.GetItem(Index: Integer): TclSmtpRelayStatus;
begin
Result := TclSmtpRelayStatus(FList[Index]);
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
{
Alterações:
25/03/16 - Primeira versão publicada - Construção
25/07/16 - refactoring na interface para acoplar o dataset.. Connector
}
unit Data.QueryIntf;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
System.Rtti, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.ExprFuncs,
{FireDAC.Phys.SQLiteDef,} FireDAC.Comp.UI,
FireDAC.Phys.SQLite, Data.DB, FireDAC.Comp.Client;
type
TDatasetClass = class of TDataset;
IQuery = interface;
// TQueryIntf = class;
TDataStorageRec = record
class function NewQuery(const Conn: TFDCustomConnection): IQuery;
overload; static;
class function NewQuery(): IQuery; overload; static;
class function NewQuery(const ATable: string; const AFields: String = '*';
const AWhere: String = ''; const AGroup: string = '';
const AOrderBy: string = ''; const AJoin: String = ''): IQuery;
overload; static;
class function SqlBuilder(const ATable: string; const AFields: String = '*';
const AWhere: String = ''; const AGroup: String = '';
const AOrderBy: string = ''; const AJoin: String = ''): string;
overload; static;
end;
IJsonDataset = interface
['{535F0BD0-6535-452B-9E84-6A9BFCFCEB91}']
function ToJson: string;
end;
IDataset = interface(IJsonDataset)
procedure Next;
procedure Prior;
procedure Last;
procedure First;
function eof: boolean;
function bof: boolean;
procedure Insert;
procedure Append;
procedure post;
procedure edit;
procedure delete;
function GetActiveQuery: boolean;
procedure SetActiveQuery(const Value: boolean);
property Active: boolean read GetActiveQuery Write SetActiveQuery;
function GetFields: TFields;
property Fields: TFields read GetFields;
function RowsAffected: integer;
function GetCommand: string;
procedure SetCommand(const ACommand: string);
property Command: string read GetCommand write SetCommand;
end;
IDatasetIntf = interface(IDataset)
function Open: IQuery;
function Close: IQuery;
function StartTransaction: IQuery;
function Commit: IQuery;
function Rollback: IQuery;
function RecordCountInt: integer;
property RecordCount: integer read RecordCountInt;
end;
IQuery = Interface(IDatasetIntf)
['{4C9E016E-41A2-42D1-899E-D820FE4FA9C4}']
function ExecSql(const AScript: string): IQuery;
function GetParams: TFDParams;
property Params: TFDParams read GetParams;
// Enumerator
function GetEnumerator: IQuery;
function GetCurrent: TFields;
property Current: TFields read GetCurrent;
function MoveNext: boolean;
procedure Reset;
// Open
function Open(const AProc: TProc<TFDParams>): IQuery; overload;
function DoLoop(const AProc: TProc<TDataset>): IQuery;
function DoQuery(const AProc: TProc<TDataset>): IQuery;
function Clone: IQuery;
// Filters
function ConnectName(texto: String): IQuery;
function Where(const texto: string): IQuery;
function Table(const texto: string): IQuery;
function Join(const texto: string): IQuery;
function GroupBy(const texto: string): IQuery;
function OrderBy(const texto: string): IQuery;
function AndWhere(const texto: string): IQuery;
function OrWhere(const texto: string): IQuery;
function FilterResult(const texto: string): IQuery;
function FieldNames(const texto: string): IQuery;
function ParamValue(const nome: string; valor: variant): IQuery;
function FieldValue(const nome: string; valor: variant): IQuery;
function GetCmdFields: string;
function GetCmdJoin: string;
function GetCmdOrderBy: string;
function GetCmdTable: string;
function GetCmdWhere: string;
procedure SetCmdWhere(const Value: string);
procedure SetCmdFiedls(const Value: string);
procedure SetCmdJoin(const Value: string);
procedure SetCmdOrderBy(const Value: string);
procedure SetCmdTable(const Value: string);
function GetCmdGroup: String;
procedure SetCmdGroup(const Value: String);
property CmdWhere: string read GetCmdWhere write SetCmdWhere;
property CmdTable: string read GetCmdTable write SetCmdTable;
property CmdFields: string read GetCmdFields write SetCmdFiedls;
property CmdJoin: string read GetCmdJoin write SetCmdJoin;
property CmdOrderBy: string read GetCmdOrderBy write SetCmdOrderBy;
property CmdGroup: string read GetCmdGroup write SetCmdGroup;
function GetDataset: TFDQuery;
procedure SetDataset(const Value: TFDQuery);
property Dataset: TFDQuery read GetDataset write SetDataset;
End;
(* IDatabase = interface
['{09A79486-12B6-4944-9F4C-8CF841D901E5}']
function Open:IDatabase;
function Close:IDatabase;
function ParamValue(sParam:string;value:variant):IDatabase;
function Driver(ADriver:string):IDatabase;
function ConnectName(ADBname:string):IDatabase;
function LoginParam(AUser:string;APass:String):IDatabase;
end;
TDatabaseIntf = class(TComponent,IDatabase)
private
FDatabase:TFDConnection;
public
class function new:IDatabase;
function Open:IDatabase;virtual;
function Close:IDatabase;virtual;
function ParamValue(sParam:string;value:variant):IDatabase;
function Driver(ADriver:string):IDatabase;
function ConnectName(ADBname:string):IDatabase;
function LoginParam(AUser:string;APass:String):IDatabase;
end;
*)
TQueryIntfBase = TFDQuery;
TQueryIntf<T:TFDQuery> = class(TComponent, IQuery)
private
FFreeOnDestroy: boolean;
FScrollRow: integer;
FDataset: TFDQuery;
FWhere: string;
FGroup: string;
FJoin: string;
FTable: string;
FFieldNames: string;
FOrderBy: string;
procedure SetFieldByName(const AField: string; const AValue: variant);
function GetActiveQuery: boolean;
procedure SetActiveQuery(const Value: boolean);
function GetCmdFields: string;
function GetCmdJoin: string;
function GetCmdOrderBy: string;
function GetCmdTable: string;
function GetCmdWhere: string;
procedure SetCmdWhere(const Value: string);
procedure SetCmdFiedls(const Value: string);
procedure SetCmdJoin(const Value: string);
procedure SetCmdOrderBy(const Value: string);
procedure SetCmdTable(const Value: string);
procedure Next;
procedure Prior;
procedure Last;
procedure First;
procedure Insert;
procedure Append;
procedure Reset;
function Clone: IQuery;
function Commit: IQuery;
function DoLoop(const AProc: TProc<TDataset>): IQuery;
function DoQuery(const AProc: TProc<TDataset>): IQuery;
function ExecSql(const AScript: string): IQuery;
function Open(const AProc: TProc<TFDParams>): IQuery; overload;
function Open: IQuery; overload;
function Rollback: IQuery;
function StartTransaction: IQuery;
function MoveBy(Distance: integer): integer;
procedure post;
procedure edit;
procedure delete;
function GetCmdGroup: String;
procedure SetCmdGroup(const Value: String);
procedure SetDataset(Const ADataset: TFDQuery);
function GetDataset: TFDQuery;
procedure SetFreeOnDestroy(const Value: boolean);
protected
public
property FreeOnDestroy:boolean read FFreeOnDestroy write SetFreeOnDestroy;
function GetQuery: T;
property Dataset: TFDQuery read GetDataset Write SetDataset;
class function New: IQuery; overload; static;
class function New(ADataset: T): IQuery; overload; static;
class function New(const AConnection: TFDCustomConnection): IQuery;
overload;
function Close: IQuery; virtual;
function ConnectName(texto: String): IQuery; virtual;
function RowsAffected: integer;
function eof: boolean;
function bof: boolean;
function GetCurrent: TFields;
function MoveNext: boolean;
function GetCommand: string;
procedure SetCommand(const ACommand: string);
procedure SetConnectionIntf(const AConn: TFDCustomConnection);
function GetConnectionIntf: TFDCustomConnection;
function GetFields: TFields;
function GetEnumerator: IQuery;
function GetParams: TFDParams;
function ParamValue(const nome: string; valor: variant): IQuery;
function FieldValue(const nome: string; valor: variant): IQuery;
function NewQuery(ATable, AFields, AWhere, AGroup, AOrderBy,
AJoin: String): IQuery;
constructor create(AOwner: TComponent); overload; override;
constructor create(); overload;
destructor Destroy; override;
function RebuildSql: IQuery;
function GroupBy(const texto: string): IQuery;
function Where(const texto: string): IQuery; virtual;
function Table(const texto: string): IQuery; virtual;
function FieldNames(const texto: string): IQuery; virtual;
function Join(const texto: string): IQuery; virtual;
function OrderBy(const texto: string): IQuery; virtual;
function AndWhere(const texto: string): IQuery; virtual;
function OrWhere(const texto: string): IQuery; virtual;
function FilterResult(const texto: string): IQuery;
function RecordCountInt: integer;
function ToJson: string;
property CmdFields: string read GetCmdFields write SetCmdFiedls;
property CmdTable: string read GetCmdTable write SetCmdTable;
property CmdWhere: string read GetCmdWhere write SetCmdWhere;
property CmdJoin: string read GetCmdJoin write SetCmdJoin;
property CmdGroup: String read GetCmdGroup write SetCmdGroup;
property CmdOrderBy: string read GetCmdOrderBy write SetCmdOrderBy;
end;
implementation
{ TQueyIntf }
function TQueryIntf<T>.Rollback: IQuery;
begin
TQueryIntfBase(FDataset) .Connection.Rollback;
result := self;
end;
function TQueryIntf<T>.RowsAffected: integer;
begin
result := TQueryIntfBase(FDataset).RowsAffected;
end;
function TQueryIntf<T>.AndWhere(const texto: string): IQuery;
begin
result := self;
if FWhere <> '' then
FWhere := FWhere + ' and ';
FWhere := FWhere + texto;
RebuildSql;
end;
procedure TQueryIntf<T>.Append;
begin
TQueryIntfBase(FDataset).Append;
end;
function TQueryIntf<T>.bof: boolean;
begin
result := TQueryIntfBase(FDataset).bof;
end;
function TQueryIntf<T>.Clone: IQuery;
begin
result := TQueryIntf<T>.create(nil) as IQuery;
if result.CmdTable <> '' then
begin
result.CmdTable := self.CmdTable;
result.CmdWhere := self.CmdWhere;
result.CmdJoin := self.CmdJoin;
result.CmdFields := self.CmdFields;
result.CmdOrderBy := self.CmdOrderBy;
result.CmdGroup := self.CmdGroup;
end
else
result.Dataset.sql.assign(TQueryIntfBase(FDataset).sql);
result.Dataset.Connection := self.Dataset.Connection;
end;
function TQueryIntf<T>.Close: IQuery;
begin
result := self;
TQueryIntfBase(FDataset).Close;
end;
function TQueryIntf<T>.Commit: IQuery;
begin
result := self;
Dataset.Connection.Commit;
end;
function TQueryIntf<T>.ConnectName(texto: String): IQuery;
begin
result := self;
Dataset.ConnectionName := texto;
end;
constructor TQueryIntf<T>.create();
begin
inherited create(nil);
FFreeOnDestroy := true;
FDataset := T.Create(nil);
if not supports(FDataset, IQuery) then
begin
FreeAndNil(FDataset);
raise exception.create('Não suporta interface IQuery');
end;
end;
constructor TQueryIntf<T>.create(AOwner: TComponent);
begin
inherited;
FFreeOnDestroy := false;
if supports(AOwner, IJsonDataset) then
FDataset := T(AOwner)
else
begin
FDataset := T.create(self);
if not supports(FDataset, IQuery) then
begin
FreeAndNil(FDataset);
raise exception.create('Não suporta interface IQuery');
end;
FFreeOnDestroy := true;
end;
FFieldNames := '*';
FScrollRow := -1;
end;
procedure TQueryIntf<T>.delete;
begin
FDataset.delete;
end;
destructor TQueryIntf<T>.Destroy;
begin
if FFreeOnDestroy then
FreeAndNil(FDataset);
inherited;
end;
function TQueryIntf<T>.DoLoop(const AProc: TProc<TDataset>): IQuery;
var
book: TBookmark;
begin
result := self;
FDataset.DisableControls;
try
book := FDataset.GetBookmark;
try
First;
while not eof do
begin
try
AProc(self.FDataset);
Next;
except
break;
end;
end;
finally
FDataset.GotoBookmark(book);
FDataset.FreeBookmark(book);
end;
finally
FDataset.EnableControls;
end;
end;
function TQueryIntf<T>.DoQuery(const AProc: TProc<TDataset>): IQuery;
begin
result := self;
AProc(self.FDataset);
end;
procedure TQueryIntf<T>.edit;
begin
FDataset.edit;
end;
function TQueryIntf<T>.eof: boolean;
begin
result := FDataset.eof;
end;
function TQueryIntf<T>.ExecSql(const AScript: string): IQuery;
begin
result := self;
FDataset.sql.Text := AScript;
FDataset.Execute();
end;
function TQueryIntf<T>.FieldNames(const texto: string): IQuery;
begin
result := self;
FFieldNames := texto;
RebuildSql;
end;
function TQueryIntf<T>.FieldValue(const nome: string; valor: variant): IQuery;
var
fld: TField;
begin
result := self;
fld := FDataset.FindField(nome);
if fld <> nil then
fld.Value := valor;
end;
function TQueryIntf<T>.FilterResult(const texto: string): IQuery;
begin
result := self;
FDataset.Filter := texto;
FDataset.Filtered := texto <> '';
end;
procedure TQueryIntf<T>.First;
begin
FDataset.First;
end;
function TQueryIntf<T>.Join(const texto: string): IQuery;
begin
result := self;
FJoin := texto;
RebuildSql;
end;
procedure TQueryIntf<T>.Last;
begin
FDataset.Last;
end;
function TQueryIntf<T>.GetActiveQuery: boolean;
begin
result := FDataset.Active;
end;
function TQueryIntf<T>.GetCommand: string;
begin
result := FDataset.sql.Text;
end;
function TQueryIntf<T>.GetConnectionIntf: TFDCustomConnection;
begin
result := FDataset.Connection;
end;
function TQueryIntf<T>.GetCurrent: TFields;
begin
result := FDataset.Fields;
end;
function TQueryIntf<T>.GetDataset: TFDQuery;
begin
result := T(FDataset);
end;
function TQueryIntf<T>.GetEnumerator: IQuery;
begin
result := self as IQuery;
end;
function TQueryIntf<T>.GetFields: TFields;
begin
result := FDataset.Fields;
end;
function TQueryIntf<T>.GetParams: TFDParams;
begin
result := FDataset.Params;
end;
function TQueryIntf<T>.GetQuery: T;
begin
result := T(FDataset);
end;
function TQueryIntf<T>.GroupBy(const texto: string): IQuery;
begin
result := self;
FGroup := texto;
RebuildSql;
end;
procedure TQueryIntf<T>.Insert;
begin
FDataset.Insert;
end;
function TQueryIntf<T>.GetCmdFields: string;
begin
result := FFieldNames;
end;
function TQueryIntf<T>.GetCmdGroup: String;
begin
result := FGroup;
end;
function TQueryIntf<T>.GetCmdJoin: string;
begin
result := FJoin;
end;
function TQueryIntf<T>.GetCmdOrderBy: string;
begin
result := FOrderBy;
end;
function TQueryIntf<T>.GetCmdTable: string;
begin
result := FTable;
end;
function TQueryIntf<T>.GetCmdWhere: string;
begin
result := FWhere;
end;
function TQueryIntf<T>.MoveBy(Distance: integer): integer;
begin
result := FDataset.MoveBy(Distance);
if eof then
FScrollRow := -1;
end;
function TQueryIntf<T>.MoveNext: boolean;
begin
if FScrollRow >= 0 then
Next;
inc(FScrollRow);
result := not eof;
end;
class function TQueryIntf<T>.New: IQuery;
begin
result := TQueryIntf<T>.create(nil) as IQuery;
end;
class function TQueryIntf<T>.New(ADataset: T): IQuery;
begin
result := TQueryIntf<T>.create(ADataset) as IQuery;
end;
class function TQueryIntf<T>.New(const AConnection
: TFDCustomConnection): IQuery;
begin
result := New() as IQuery;
result.Dataset.Connection := AConnection;
end;
function TQueryIntf<T>.NewQuery(ATable, AFields, AWhere, AGroup, AOrderBy,
AJoin: String): IQuery;
begin
result := New;
// TDataStorageRec.NewQuery(ATable, AFields, AWhere,AGroup, AOrderBy, AJoin);
result.CmdTable := ATable;
result.CmdWhere := AWhere;
result.CmdFields := AFields;
result.CmdJoin := AJoin;
result.CmdGroup := AGroup;
result.CmdOrderBy := AOrderBy;
result.Dataset.Connection := self.Dataset.Connection;
end;
procedure TQueryIntf<T>.Next;
begin
FDataset.Next;
end;
function TQueryIntf<T>.Open(const AProc: TProc<TFDParams>): IQuery;
begin
AProc(GetParams);
result := self;
FDataset.Open;
end;
function TQueryIntf<T>.OrderBy(const texto: string): IQuery;
begin
result := self;
FOrderBy := texto;
RebuildSql;
end;
function TQueryIntf<T>.OrWhere(const texto: string): IQuery;
begin
result := self;
if FWhere <> '' then
FWhere := FWhere + ' or ';
FWhere := FWhere + texto;
RebuildSql;
end;
function TQueryIntf<T>.ParamValue(const nome: string; valor: variant): IQuery;
var
prm: TFDParam;
begin
result := self;
prm := FDataset.FindParam(nome);
if prm <> nil then
prm.Value := valor;
end;
procedure TQueryIntf<T>.post;
begin
FDataset.post;
end;
procedure TQueryIntf<T>.Prior;
begin
FDataset.Prior;
end;
function TQueryIntf<T>.RebuildSql: IQuery;
begin
result := self;
SetCommand(TDataStorageRec.SqlBuilder(FTable, FFieldNames, FWhere, FGroup,
FOrderBy, FJoin));
end;
function TQueryIntf<T>.RecordCountInt: integer;
begin
result := FDataset.RecordCount;
end;
procedure TQueryIntf<T>.Reset;
begin
end;
function TQueryIntf<T>.Open: IQuery;
begin
FDataset.Open;
FScrollRow := -1;
result := self as IQuery;
end;
procedure TQueryIntf<T>.SetActiveQuery(const Value: boolean);
begin
FDataset.Active := Value;
end;
procedure TQueryIntf<T>.SetCommand(const ACommand: string);
begin
FDataset.sql.Text := ACommand;
end;
procedure TQueryIntf<T>.SetConnectionIntf(const AConn: TFDCustomConnection);
begin
FDataset.Connection := AConn;
end;
procedure TQueryIntf<T>.SetDataset(Const ADataset: TFDQuery);
begin
if FFreeOnDestroy and (not ADataset.Equals(FDataset)) then
FreeAndNil(FDataset);
FDataset := T(ADataset);
FFreeOnDestroy := false;
end;
procedure TQueryIntf<T>.SetFieldByName(const AField: string;
const AValue: variant);
begin
FDataset.FieldByName(AField).Value := AValue;
end;
procedure TQueryIntf<T>.SetFreeOnDestroy(const Value: boolean);
begin
FFreeOnDestroy := Value;
end;
procedure TQueryIntf<T>.SetCmdWhere(const Value: string);
begin
FWhere := Value;
RebuildSql;
end;
procedure TQueryIntf<T>.SetCmdFiedls(const Value: string);
begin
FFieldNames := Value;
RebuildSql;
end;
procedure TQueryIntf<T>.SetCmdGroup(const Value: String);
begin
FGroup := Value;
RebuildSql;
end;
procedure TQueryIntf<T>.SetCmdJoin(const Value: string);
begin
FJoin := Value;
RebuildSql;
end;
procedure TQueryIntf<T>.SetCmdOrderBy(const Value: string);
begin
FOrderBy := Value;
RebuildSql;
end;
procedure TQueryIntf<T>.SetCmdTable(const Value: string);
begin
FTable := Value;
RebuildSql;
end;
function TQueryIntf<T>.StartTransaction: IQuery;
begin
result := self;
FDataset.Connection.StartTransaction;
end;
function TQueryIntf<T>.Table(const texto: string): IQuery;
begin
result := self;
FTable := texto;
RebuildSql;
end;
function TQueryIntf<T>.ToJson: string;
var
Intf: IJsonDataset;
begin
if supports(FDataset, IJsonDataset, Intf) then
result := (Intf).ToJson
else
result := '{ }';
end;
function TQueryIntf<T>.Where(const texto: string): IQuery;
begin
result := self;
FWhere := texto;
RebuildSql;
end;
{ TStoreDataStorage }
class function TDataStorageRec.NewQuery: IQuery;
begin
result := TQueryIntf<TFDQuery>.create(nil) as IQuery;
end;
class function TDataStorageRec.NewQuery(const Conn
: TFDCustomConnection): IQuery;
begin
result := TDataStorageRec.NewQuery();
result.Dataset.Connection := Conn;
end;
class function TDataStorageRec.NewQuery(const ATable, AFields, AWhere, AGroup,
AOrderBy, AJoin: String): IQuery;
begin
result := NewQuery();
result.Table(ATable).Where(AWhere).OrderBy(AOrderBy).Join(AJoin)
.FieldNames(AFields);
result.GroupBy(AGroup);
end;
class function TDataStorageRec.SqlBuilder(const ATable, AFields, AWhere, AGroup,
AOrderBy, AJoin: String): string;
var
sql: TStringBuilder;
begin
sql := TStringBuilder.create;
try
if ATable <> '' then
sql.Append('select ' + AFields + ' from ' + ATable);
if AJoin <> '' then
sql.Append(' ' + AJoin);
if AWhere <> '' then
sql.Append(' where ' + AWhere);
if AGroup <> '' then
sql.Append(' group by ' + AGroup);
if AOrderBy <> '' then
sql.Append(' order by ' + AOrderBy);
result := sql.ToString;
finally
sql.Free;
end;
end;
{ TDatabaseIntf }
(*
function TDatabaseIntf.ConnectName(ADBname: string): IDatabase;
begin
result := self;
FDatabase.ConnectionName:=ADBname;
end;
function TDatabaseIntf.Driver(ADriver: string): IDatabase;
begin
result := self;
inherited driverName := ADriver;
end;
function TDatabaseIntf.LoginParam(AUser, APass: String): IDatabase;
begin
result := self
.ParamValue('USER_NAME',AUser)
.ParamValue('Password',APass);
end;
class function TDatabaseIntf.new: IDatabase;
begin
result := TDatabaseIntf.Create(nil) as IDatabase;
end;
function TDatabaseIntf.IOpen: IDatabase;
begin
result := self;
inherited Open;
end;
function TDatabaseIntf.ParamValue(sParam: string; value: variant): IDatabase;
begin
result := self;
Params.Values[sParam] := value;
end;
*)
end.
|
unit ReoptimizeRouteUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TReoptimizeRoute = class(TBaseExample)
public
procedure Execute(RouteId: String);
end;
implementation
uses DataObjectUnit, EnumsUnit, RouteParametersQueryUnit;
procedure TReoptimizeRoute.Execute(RouteId: String);
var
Parameters: TRouteParametersQuery;
ErrorString: String;
Route: TDataObjectRoute;
begin
Parameters := TRouteParametersQuery.Create;
try
Parameters.RouteId := RouteId;
Parameters.ReOptimize := True;
Route := Route4MeManager.Route.Update(Parameters, ErrorString);
WriteLn('');
try
if (Route <> nil) then
begin
WriteLn('ReoptimizeRoute executed successfully');
WriteLn(Format('Route ID: %s', [Route.RouteId]));
end
else
WriteLn(Format('ReoptimizeRoute error: "%s"', [ErrorString]));
finally
FreeAndNil(Route);
end;
finally
FreeAndNil(Parameters);
end;
end;
end.
|
unit PlayerControl;
interface
uses
Math, TypeControl;
type
TPlayer = class
private
FId: Int64;
FMe: Boolean;
FStrategyCrashed: Boolean;
FScore: LongInt;
FRemainingActionCooldownTicks: LongInt;
FRemainingNuclearStrikeCooldownTicks: LongInt;
FNextNuclearStrikeVehicleId: Int64;
FNextNuclearStrikeTickIndex: LongInt;
FNextNuclearStrikeX: Double;
FNextNuclearStrikeY: Double;
public
constructor Create(const id: Int64; const me: Boolean; const strategyCrashed: Boolean; const score: LongInt;
const remainingActionCooldownTicks: LongInt; const remainingNuclearStrikeCooldownTicks: LongInt;
const nextNuclearStrikeVehicleId: Int64; const nextNuclearStrikeTickIndex: LongInt;
const nextNuclearStrikeX: Double; const nextNuclearStrikeY: Double); overload;
constructor Create(const player: TPlayer); overload;
function GetId: Int64;
property Id: Int64 read GetId;
function GetMe: Boolean;
property IsMe: Boolean read GetMe;
function GetStrategyCrashed: Boolean;
property IsStrategyCrashed: Boolean read GetStrategyCrashed;
function GetScore: LongInt;
property Score: LongInt read GetScore;
function GetRemainingActionCooldownTicks: LongInt;
property RemainingActionCooldownTicks: LongInt read GetRemainingActionCooldownTicks;
function GetRemainingNuclearStrikeCooldownTicks: LongInt;
property RemainingNuclearStrikeCooldownTicks: LongInt read GetRemainingNuclearStrikeCooldownTicks;
function GetNextNuclearStrikeVehicleId: Int64;
property NextNuclearStrikeVehicleId: Int64 read GetNextNuclearStrikeVehicleId;
function GetNextNuclearStrikeTickIndex: LongInt;
property NextNuclearStrikeTickIndex: LongInt read GetNextNuclearStrikeTickIndex;
function GetNextNuclearStrikeX: Double;
property NextNuclearStrikeX: Double read GetNextNuclearStrikeX;
function GetNextNuclearStrikeY: Double;
property NextNuclearStrikeY: Double read GetNextNuclearStrikeY;
destructor Destroy; override;
end;
TPlayerArray = array of TPlayer;
implementation
constructor TPlayer.Create(const id: Int64; const me: Boolean; const strategyCrashed: Boolean; const score: LongInt;
const remainingActionCooldownTicks: LongInt; const remainingNuclearStrikeCooldownTicks: LongInt;
const nextNuclearStrikeVehicleId: Int64; const nextNuclearStrikeTickIndex: LongInt; const nextNuclearStrikeX: Double;
const nextNuclearStrikeY: Double);
begin
FId := id;
FMe := me;
FStrategyCrashed := strategyCrashed;
FScore := score;
FRemainingActionCooldownTicks := remainingActionCooldownTicks;
FRemainingNuclearStrikeCooldownTicks := remainingNuclearStrikeCooldownTicks;
FNextNuclearStrikeVehicleId := nextNuclearStrikeVehicleId;
FNextNuclearStrikeTickIndex := nextNuclearStrikeTickIndex;
FNextNuclearStrikeX := nextNuclearStrikeX;
FNextNuclearStrikeY := nextNuclearStrikeY;
end;
constructor TPlayer.Create(const player: TPlayer);
begin
FId := player.Id;
FMe := player.IsMe;
FStrategyCrashed := player.IsStrategyCrashed;
FScore := Score;
FRemainingActionCooldownTicks := player.RemainingActionCooldownTicks;
FRemainingNuclearStrikeCooldownTicks := player.RemainingNuclearStrikeCooldownTicks;
FNextNuclearStrikeVehicleId := player.NextNuclearStrikeVehicleId;
FNextNuclearStrikeTickIndex := player.NextNuclearStrikeTickIndex;
FNextNuclearStrikeX := player.NextNuclearStrikeX;
FNextNuclearStrikeY := player.NextNuclearStrikeY;
end;
function TPlayer.GetId: Int64;
begin
result := FId;
end;
function TPlayer.GetMe: Boolean;
begin
result := FMe;
end;
function TPlayer.GetStrategyCrashed: Boolean;
begin
result := FStrategyCrashed;
end;
function TPlayer.GetScore: LongInt;
begin
result := FScore;
end;
function TPlayer.GetRemainingActionCooldownTicks: LongInt;
begin
result := FRemainingActionCooldownTicks;
end;
function TPlayer.GetRemainingNuclearStrikeCooldownTicks: LongInt;
begin
result := FRemainingNuclearStrikeCooldownTicks;
end;
function TPlayer.GetNextNuclearStrikeVehicleId: Int64;
begin
result := FNextNuclearStrikeVehicleId;
end;
function TPlayer.GetNextNuclearStrikeTickIndex: LongInt;
begin
result := FNextNuclearStrikeTickIndex;
end;
function TPlayer.GetNextNuclearStrikeX: Double;
begin
result := FNextNuclearStrikeX;
end;
function TPlayer.GetNextNuclearStrikeY: Double;
begin
result := FNextNuclearStrikeY;
end;
destructor TPlayer.Destroy;
begin
inherited;
end;
end.
|
unit TestuPareto;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, uPareto, System.Generics.Collections;
type
// Test methods for class TPareto
TestTPareto = class(TTestCase)
strict private
FPareto: TPareto;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure Несравнимые_Одинаковые_Значения;
procedure Несравнимые_Значения;
procedure А_Больше_Б;
procedure Б_Больше_А;
procedure МерскаяЗадачаСравнение;
procedure МерскаяЗадача;
procedure Задача_В_Универе;
procedure Вязка_Элементов;
end;
implementation
{ TestTPareto }
procedure TestTPareto.SetUp;
begin
inherited SetUp;
FPareto := TPareto.Create;
end;
procedure TestTPareto.TearDown;
begin
inherited TearDown;
FPareto.Free;
FPareto := nil;
end;
procedure TestTPareto.А_Больше_Б;
begin
FPareto.AddRange([ //
TParetoItem.Create(3, 4, 'A1'), TParetoItem.Create(1, 3, 'A2')]);
CheckEquals(FPareto.Compare(0, 1), 1);
FPareto.Clear;
end;
procedure TestTPareto.Б_Больше_А;
begin
FPareto.AddRange([ //
TParetoItem.Create(1, 2, 'A1'), TParetoItem.Create(1, 3, 'A2')]);
CheckEquals(FPareto.Compare(0, 1), -1);
FPareto.Clear;
end;
procedure TestTPareto.Вязка_Элементов;
begin
CheckEquals(Length(TPareto.WebElement([1, 3, 5, 6])), 6);
end;
procedure TestTPareto.Задача_В_Универе;
begin
FPareto.MaxB := false;
FPareto.AddRange([ //
TParetoItem.Create(58, 14, 'A1'), //
TParetoItem.Create(58, 18.3, 'A2'), //
TParetoItem.Create(57, 7.8, 'A3'), //
TParetoItem.Create(56, 9.2, 'A4'), //
TParetoItem.Create(55, 10, 'A5'), //
TParetoItem.Create(62.5, 15.2, 'A6')
{ } ]);
// CheckEquals(FPareto.Compare(0, 3), 1);
CheckEquals(FPareto.Compress, 3);
FPareto.Clear;
end;
procedure TestTPareto.МерскаяЗадача;
begin
FPareto.MaxB := false;
FPareto.AddRange([ //
TParetoItem.Create(4, 4.2, 'A1'), //
TParetoItem.Create(2.9, 3.3, 'A2'), //
TParetoItem.Create(1.9, 2.2, 'A3'), //
TParetoItem.Create(3.35, 4.2, 'A4')
{ } ]);
CheckEquals(FPareto.Compare(0, 3), 1);
CheckEquals(FPareto.Compress, 3);
FPareto.Clear;
end;
procedure TestTPareto.МерскаяЗадачаСравнение;
begin
FPareto.AddRange([ //
TParetoItem.Create(3, 1, 'A1'), TParetoItem.Create(1, 3, 'A2')]);
CheckEquals(FPareto.Compare(0, 1), 0);
FPareto.Clear;
end;
procedure TestTPareto.Несравнимые_Значения;
begin
FPareto.MaxB := false;
FPareto.AddRange([ //
TParetoItem.Create(4, 4.2, 'A1'), TParetoItem.Create(3.35, 4.2, 'A2')]);
CheckEquals(FPareto.Compare(0, 1), 1);
FPareto.Clear;
end;
procedure TestTPareto.Несравнимые_Одинаковые_Значения;
begin
FPareto.AddRange([TParetoItem.Create(1, 1, 'A1'), TParetoItem.Create(1,
1, 'A2')]);
CheckEquals(FPareto.Compare(0, 1), 0);
FPareto.MaxA := false;
CheckEquals(FPareto.Compare(0, 1), 0);
FPareto.MaxB := false;
CheckEquals(FPareto.Compare(0, 1), 0);
FPareto.Clear;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTPareto.Suite);
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_FileBrowser
* Implements a file browser widget
***********************************************************************************************************************
}
Unit TERRA_UIFileBrowser;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Utils, TERRA_UI, TERRA_Widgets, TERRA_FileSearch, TERRA_Collections,
TERRA_Vector2D, TERRA_Vector3D, TERRA_Color, TERRA_SpriteManager, TERRA_ClipRect;
Type
UIFileBrowser = Class(UIWindow)
Protected
_InnerWnd:UIWindow;
_Scroll:UIScrollbar;
_ClipRect:ClipRect;
_OfsY:Single;
_BorderX:Single;
_BorderY:Single;
_TopBorder:Single;
_BottomBorder:Single;
_ExtraWndBorder:Single;
_ExtraScrollBorder:Single;
_IconFolder:Integer;
_IconFile:Integer;
_ListSubFolders:Boolean;
_SourceChanged:Boolean;
_Folder:TERRAString;
_Filter:TERRAString;
_FileList:List;
_FolderList:List;
_SelectedItem:Integer;
Procedure UpdateWorkArea();
Procedure UpdateContent(); Virtual;
Procedure CreateButtons(); Virtual;
Public
Constructor Create(Name:TERRAString; UI:UI; X,Y,Z:Single; Width, Height:Integer; ComponentBG:TERRAString=''); Overload;
Procedure Render; Override;
Procedure SetBorders(TopBorder, BottomBorder:Integer);
Function OnMouseDown(X,Y:Integer;Button:Word):Boolean; Override;
Function OnMouseUp(X,Y:Integer;Button:Word):Boolean; Override;
Procedure SetFilter(Filter:TERRAString);
Procedure SetFolder(Folder:TERRAString);
End;
Implementation
{ UIFileBrowser }
Constructor UIFileBrowser.Create(Name:TERRAString; UI:UI; X, Y, Z: Single; Width, Height: Integer; ComponentBG:TERRAString);
Begin
Inherited Create(Name, UI, X, Y, Z, Width, Height, ComponentBG);
_BorderX := 20;
_BorderY := 20;
_TopBorder := 0;
_BottomBorder := 0;
_IconFolder := Self.LoadComponent('ui_folder');
_IconFile := Self.LoadComponent('ui_file');
_ListSubFolders := True;
_InnerWnd := UIWindow.Create(Name+'_inner', UI, Self, 0, 0 , 0.5, 1, 1, 'ui_list');
_Scroll := UIScrollbar.Create(Name+'_scroll', UI, Self, 0, 0, 1.0, 5, False);
Self.AddChild(_InnerWnd);
Self.CreateButtons();
Self.UpdateWorkArea();
End;
Procedure UIFileBrowser.CreateButtons;
Begin
End;
Function UIFileBrowser.OnMouseDown(X, Y: Integer; Button: Word): Boolean;
Var
Pos:Vector2D;
YY:Single;
Begin
Result := _Scroll.OnMouseDown(X, Y, Button);
If Result Then
Exit;
Result := _InnerWnd.OnMouseDown(X, Y, Button);
If Result Then
Begin
Pos := _InnerWnd.GetAbsolutePosition();
YY := Y - Pos.Y - _OfsY;
_SelectedItem := Trunc(YY / _InnerWnd.Layout.GCSY(1));
Exit;
End;
Result := False;
End;
Function UIFileBrowser.OnMouseUp(X, Y: Integer; Button: Word): Boolean;
Begin
Result := Inherited OnMouseUp(X,Y, Button);
End;
Procedure UIFileBrowser.Render;
Var
I,PY:Integer;
It:CollectionObject;
Info:FileInfo;
Begin
If (_SourceChanged) Then
Begin
_SourceChanged := False;
Self.UpdateContent();
End;
Inherited;
_ClipRect.X := _InnerWnd.Position.X;
_ClipRect.Y := _InnerWnd.Position.Y;
_ClipRect.Width := _InnerWnd.Size.X;
_ClipRect.Height := _InnerWnd.Size.Y;
_OfsY := -_Scroll.Value * _InnerWnd.Layout.GCSY(1);
PY := 0;
If Assigned(_FileList) Then
Begin
It := _FileList.First;
While Assigned(It) Do
Begin
Info := FileInfo(It);
If (PY = Self._SelectedItem) Then
Begin
For I:=0 To _InnerWnd.Width Do
_InnerWnd.DrawComponent(0, VectorCreate(_InnerWnd.Layout.GCSX(1)*Pred(I), _OfsY + _InnerWnd.Layout.GCSY(1)*Pred(PY), 0.75), _InnerWnd.Layout.X[1], _InnerWnd.Layout.Y[1], _InnerWnd.Layout.X[2], _InnerWnd.Layout.Y[2], ColorBlack);
End;
_InnerWnd.ClipRect := _ClipRect;
_InnerWnd.DrawText(Info.Name, VectorCreate(5, _OfsY + _InnerWnd.Layout.GCSY(1) * PY, 1.0), ColorWhite, 1.0);
_InnerWnd.ClipRect.Style := clipNothing;
Inc(PY);
It := It.Next;
End;
End;
End;
Procedure UIFileBrowser.SetBorders(TopBorder, BottomBorder: Integer);
Begin
_TopBorder := TopBorder;
_BottomBorder := BottomBorder;
Self.UpdateWorkArea();
End;
Procedure UIFileBrowser.SetFilter(Filter:TERRAString);
Begin
If (Filter = _Filter) Then
Exit;
Self._Filter := Filter;
Self._SourceChanged := True;
End;
Procedure UIFileBrowser.SetFolder(Folder:TERRAString);
Begin
If (Folder = _Folder) Then
Exit;
Self._Folder := Folder;
Self._SourceChanged := True;
End;
Procedure UIFileBrowser.UpdateWorkArea;
Var
TargetWidth, TargetHeight:Single;
Begin
TargetWidth := (Self.Size.X-_BorderX*2);
_InnerWnd.Width := 0;
Repeat
_InnerWnd.Width := _InnerWnd.Width + 1;
Until (_InnerWnd.Size.X > TargetWidth);
_InnerWnd.Width := _InnerWnd.Width - 1;
TargetHeight := (Self.Size.Y - (_BorderY*2 + _TopBorder + _BottomBorder));
_InnerWnd.Height := 0;
Repeat
_InnerWnd.Height := _InnerWnd.Height + 1;
Until (_InnerWnd.Size.Y>TargetHeight);
_InnerWnd.Height := _InnerWnd.Height - 1;
_ExtraWndBorder := TargetHeight - _InnerWnd.Size.Y;
_Scroll.ScrollSize := 0;
Repeat
_Scroll.ScrollSize := _Scroll.ScrollSize + 1;
Until (_Scroll.Size.Y>TargetHeight);
_Scroll.ScrollSize := _Scroll.ScrollSize - 1;
_ExtraScrollBorder := TargetHeight - _Scroll.Size.Y;
_InnerWnd.Position := VectorCreate2D(0, _TopBorder + _BorderY + _ExtraWndBorder * 0.5);
_InnerWnd.Align := waTopCenter;
_Scroll.Position := VectorCreate2D(_BorderX, _TopBorder + _BorderY + _ExtraScrollBorder * 0.5);
_Scroll.Align := waTopRight;
End;
Procedure UIFileBrowser.UpdateContent;
Var
VisibleItems:Integer;
Begin
ReleaseObject(_FileList);
ReleaseObject(_FolderList);
If (_Folder = '') Or (_Filter = '') Then
Exit;
_FileList := SearchFiles(_Folder, _Filter, False);
_FolderList := SearchFolders(_Folder);
VisibleItems := 1 + Trunc(_InnerWnd.Size.Y / _InnerWnd.Layout.GCSY(1));
_Scroll.Max := _FileList.Count - VisibleItems;
_Scroll.Value := 0;
_Scroll.Visible := (_Scroll.Max>0);
_SelectedItem := -1;
End;
End. |
unit UFiles;
interface
(*
2007-07-06
o ReadDir and CreateFileList adjusted: The List parameter may be nil now.
o Added easy-access properties to TSearchRecObject
2005-11-11
o DirectorySynchronizer weggegooid
//2003-06-12: ReadDir aangepast: FindClose toegevoegd
*)
uses
Windows, Classes, Sysutils, Contnrs,
UMisc, UTools;
{ extra file-attributen sinds windows NT, zie ook windows.pas en de help bij
windows.getfileattributes }
const
(*
FILE_ATTRIBUTE_READONLY = $00000001;
FILE_ATTRIBUTE_HIDDEN = $00000002;
FILE_ATTRIBUTE_SYSTEM = $00000004;
FILE_ATTRIBUTE_DIRECTORY = $00000010;
FILE_ATTRIBUTE_ARCHIVE = $00000020;
FILE_ATTRIBUTE_NORMAL = $00000080;
FILE_ATTRIBUTE_TEMPORARY = $00000100;
FILE_ATTRIBUTE_COMPRESSED = $00000800;
FILE_ATTRIBUTE_OFFLINE = $00001000;
*)
{ sysutils
faReadOnly = $00000001; = bit0
faHidden = $00000002; = bit1
faSysFile = $00000004; = bit2
faVolumeID = $00000008; = bit3
faDirectory = $00000010; = bit4
faArchive = $00000020; = bit5
faAnyFile = $0000003F; = de vorige bij elkaar opgeteld
}
faNormal = $00000080; { = bit 7 }
faTemporary = $00000100; { = bit 8 }
faCompressed = $00000800; { = bit 11 }
faOffLine = $00001000; { = bit 12 }
faNoIndex = $00002000; { = bit 13 }
faAllFiles = faAnyFile + faNormal + faTemporary + faCompressed + faOffLine + faNoIndex;
faFileMask = faAllFiles and not faDirectory;
faDirMask = faDirectory + faReadOnly + faHidden + faSysFile + faArchive +
faNormal + faTemporary + faCompressed + faOffLine + faNoIndex;
type
TSearchRecObject = class
private
fSearchRec: TSearchRec;
public
constructor Create(const ASearchRec: TSearchRec);
property SearchRec: TSearchRec read fSearchRec;
{ easy access }
property Time: Integer read fSearchRec.Time;
property Size: Integer read fSearchRec.Size;
property Attr: Integer read fSearchRec.Attr;
property Name: TFileName read fSearchRec.Name;
property ExcludeAttr: Integer read fSearchRec.ExcludeAttr;
property FindHandle: THandle read fSearchRec.FindHandle;
property FindData: TWin32FindData read fSearchRec.FindData;
{ }
function IsDirectory: Boolean;
end;
type
{ stringlist met TSearchRecObjecten eraan vast }
TFileList = class(TStringList)
public
// procedure AddFile(const aFileName: string);
end;
{ file functies }
type
TAddSearchRecEvent = procedure(const ASearchRec: TSearchRec; const aFullName: string; out DoAdd: boolean;
out AObject: TObject) of object;
function ValidFileName(const S: string): boolean;
function IsRel(const R: TSearchRec): boolean;
function IsDir(const R: TSearchRec): boolean;
function IsDirectory(const aFileName: string): boolean;
procedure CreateFileList(AList: TStrings;//List;
const Path: string;
Attribs: integer;
FullFileName: boolean = True;
Recursive: boolean = False;
OnAddSearchRec: TAddSearchRecEvent = nil);
{ Maakt een stringlist van de aanwezige files, geef <path> inclusief wildcard
Voegt TSearchRecObjects toe als AddObjects = True }
function AttribStr(Attrib: integer; Points: boolean = False): string;
function GetSearchRec(const aFileName: string): TSearchRec;
implementation
{ TSearchRecObject }
constructor TSearchRecObject.Create(const ASearchRec: TSearchRec);
begin
inherited Create;
FSearchRec := ASearchRec;
end;
function TSearchRecObject.IsDirectory: Boolean;
begin
Result := Attr and faDirectory <> 0;
end;
function GetSearchRec(const aFileName: string): TSearchRec;
begin
FillChar(Result, SizeOf(Result), 0);
try
FindFirst(aFileName, faAllFiles, Result);
finally
FindClose(Result)
end;
end;
function ValidFileName(const S: string): boolean;
const
InvChars: string = '\/:*?"<>|';
var
i: integer;
F: string;
begin
Result := False;
if Length(S) = 0 then Exit;
for i := 4 to Length(InvChars) do
if Pos(InvChars[i], S) > 0 then
Exit;
F := ExtractFileName(S);
if Length(F) = 0 then Exit;
for i := 1 to Length(InvChars) do
if Pos(InvChars[i], F) > 0 then
Exit;
Result := True;
end;
function IsRel(const R: TSearchRec): boolean;
begin
Result := (R.Name = '.') or (R.Name = '..');
end;
function IsDir(const R: TSearchRec): boolean;
begin
Result := (R.Attr and faDirectory <> 0) and not IsRel(R)
end;
function IsDirectory(const aFileName: string): boolean;
var
sr: TSearchRec;
begin
Result := False;
if FindFirst(aFileName, faAllFiles, sr) = 0 then
begin
Result := IsDir(sr);
FindClose(sr);
end;
end;
procedure ReadDir(const Path: string;
Attribs: integer;
FullFileNames: boolean;
Recursive: boolean;
OnAddSearchRec: TAddSearchRecEvent;
List: TStrings);
{-------------------------------------------------------------------------------
2007-07-06: List parameter can be nil. Then this procedure can be used to
scan files only.
-------------------------------------------------------------------------------}
var
sr: TSearchRec;
LFN, LFP, WildCard: string;
O: TObject;
DoAdd: boolean;
procedure AddFile;
function GetName: string;
begin
if FullFileNames then Result := LFP + sr.Name else Result := sr.Name;
end;
begin
if not Assigned(OnAddSearchRec) then
begin
if Assigned(List) then
if (sr.Attr and Attribs <> 0) then // ### toegevoegd 2005-01-10
List.Add(GetName)
end
else begin
if (sr.Attr and Attribs <> 0) then // ### toegevoegd 2005-01-10
begin
DoAdd := True;
OnAddSearchRec(sr, LFP + sr.Name, DoAdd, O); // fire event
if Assigned(List) then
if DoAdd then
List.AddObject(GetName, O);
end;
end;
//Log([GetName]);
end;
begin
LFN := ExpandFileName(Path);
LFP := ExtractFilePath(LFN); { is altijd met backslash }
WildCard := ExtractFileName(LFN);
// DirAttribs := Attribs;
{ recursief inlezen }
// ## EL veranderd 2005-01-10: faDirectory ipv faAllFiles
// ## EL veranderd 2005-01-14: weer terugveranderd in faAllFiles
if Recursive and (FindFirst(LFP + '*.*', faAllFiles, sr) = 0) then
try
repeat
if IsDir(sr) then
begin
// if (faDirectory and Attribs <> 0) then
// AddFile;
ReadDir(LFP + sr.Name + '\' + WildCard, Attribs, FullFileNames, Recursive, OnAddSearchRec, List);
end;
until FindNext(sr) <> 0;
finally
FindClose(sr); // 2003-06-12: toegevoegd, dit was een bug!
end;
{ toevoegen }
if FindFirst(LFN, Attribs, sr) = 0 then
try //2003-06-12 try finally statement toegevoegd
repeat
if not IsRel(sr) then
AddFile
until FindNext(sr) <> 0;
finally
FindClose(sr);
end;
end;
{ file functions }
procedure CreateFileList(aList: TStrings;
const Path: string;
Attribs: integer;
FullFileName: boolean = True;
Recursive: boolean = False;
OnAddSearchRec: TAddSearchRecEvent = nil);
begin
ReadDir(Path, Attribs, FullFileName, Recursive, OnAddSearchRec, aList);
end;
function AttribStr(Attrib: integer; Points: boolean = False): string;
//var
//i: integer;
begin
Result := '';
case Points of
True:
begin
Result := Result + IIF(Attrib and faReadOnly = 0, '.', 'R');
Result := Result + IIF(Attrib and faHidden = 0, '.', 'H');
Result := Result + IIF(Attrib and faSysfile = 0, '.', 'S');
Result := Result + IIF(Attrib and faVolumeID = 0, '.', 'V');
Result := Result + IIF(Attrib and faDirectory = 0, '.', 'D');
Result := Result + IIF(Attrib and faArchive = 0, '.', 'A');
Result := Result + IIF(Attrib and faNormal = 0, '.', 'N');
Result := Result + IIF(Attrib and faTemporary = 0, '.', 'T');
Result := Result + IIF(Attrib and faCompressed = 0, '.', 'C');
Result := Result + IIF(Attrib and faOffLine = 0, '.', 'O');
Result := Result + IIF(Attrib and faNoIndex = 0, '.', 'X');
end;
False:
begin
Result := Result + IIF(Attrib and faReadOnly = 0, '', 'R');
Result := Result + IIF(Attrib and faHidden = 0, '', 'H');
Result := Result + IIF(Attrib and faSysfile = 0, '', 'S');
Result := Result + IIF(Attrib and faVolumeID = 0, '', 'V');
Result := Result + IIF(Attrib and faDirectory = 0, '', 'D');
Result := Result + IIF(Attrib and faArchive = 0, '', 'A');
Result := Result + IIF(Attrib and faNormal = 0, '', 'N');
Result := Result + IIF(Attrib and faTemporary = 0, '', 'T');
Result := Result + IIF(Attrib and faCompressed = 0, '', 'C');
Result := Result + IIF(Attrib and faOffLine = 0, '', 'O');
Result := Result + IIF(Attrib and faNoIndex = 0, '', 'X');
end;
end;
{ for i := 0 to 31 do
Result := Result + IIF(attrib and (1 shl i) > 0, '1', '.');
exit;}
end;
end.
|
unit l3StringList;
{ Библиотека "L3 (Low Level Library)" }
{ Автор: Люлин А.В. © }
{ Модуль: l3StringList - }
{ Начат: 06.02.2008 12:58 }
{ $Id: l3StringList.pas,v 1.17 2012/03/14 11:34:46 lulin Exp $ }
// $Log: l3StringList.pas,v $
// Revision 1.17 2012/03/14 11:34:46 lulin
// {RequestLink:344754594}
//
// Revision 1.16 2009/07/21 13:03:52 lulin
// - более правильно приводим к константным строкам.
//
// Revision 1.15 2008/03/03 20:06:08 lulin
// - <K>: 85721135.
//
// Revision 1.14 2008/02/21 16:32:54 lulin
// - cleanup.
//
// Revision 1.13 2008/02/19 14:58:59 lulin
// - переводим сортировку списков на новые, менее виртуальные, рельсы.
//
// Revision 1.12 2008/02/18 19:05:12 lulin
// - распиливаем поиск.
//
// Revision 1.11 2008/02/18 11:07:54 lulin
// - выпилил часть виртуальной функциональности списков.
//
// Revision 1.10 2008/02/13 16:03:14 lulin
// - убраны излишне гибкие методы поиска.
//
// Revision 1.9 2008/02/13 12:26:22 lulin
// - <TDN>: 72.
//
// Revision 1.8 2008/02/12 19:32:36 lulin
// - избавляемся от универсальности списков.
//
// Revision 1.7 2008/02/12 17:23:04 lulin
// - метод чтения элемента списка переехал на примесь.
//
// Revision 1.6 2008/02/12 15:01:31 lulin
// - вычищен тип элементов списка.
//
// Revision 1.5 2008/02/12 14:39:42 lulin
// - методы для чтения списка переехали на примесь.
//
// Revision 1.4 2008/02/12 11:42:56 lulin
// - методы для сохранения списка переехали на примесь.
//
// Revision 1.3 2008/02/12 10:31:25 lulin
// - избавляемся от излишнего метода на базовом классе.
//
// Revision 1.2 2008/02/06 12:32:23 lulin
// - базовый список ссылок на объекты переехал в отдельный файл.
//
// Revision 1.1 2008/02/06 11:44:42 lulin
// - список строк переехал в отдельный файл.
//
{$Include l3Define.inc }
interface
uses
Classes,
l3Interfaces,
l3Types,
l3Base,
l3StringListPrim,
l3StringList2
;
type
Tl3StringList = class(Tl3StringList2)
protected
// property methods
function GetW(anIndex: Integer): Tl3WString;
procedure PutW(anIndex: Integer; const aValue: Tl3WString);
{-}
function Get_ItemC(anIndex: Integer): Il3CString;
procedure Set_ItemC(anIndex: Integer; const aValue: Il3CString);
{-}
protected
// internal methods
function CStrToItem(const aStr: Il3CString): Tl3CustomString;
virtual;
{-}
public
// public methods
function IndexOf(const aSt: Tl3WString): Integer;
reintroduce;
overload;
{-}
function IndexOf(const aSt: Il3CString): Integer;
reintroduce;
overload;
{-}
function IndexOf(const S: string): Integer;
reintroduce;
overload;
{-}
function Add(const Item: Il3CString): Long;
overload;
{* - добавить в список строку. }
function Add(const Item: String): Long;
overload;
{* - добавить в список строку. }
procedure Insert(Index: Long; const Item: Tl3WString);
overload;
procedure Insert(Index: Long; const Item: Il3CString);
overload;
{* - вставить в список строку. }
procedure Insert(aIndex: Integer; const aStr: string);
overload;
{-}
public
// public properties
property ItemW[anIndex: Integer]: Tl3WString
read GetW
write PutW;
{* - элементы списка. }
property ItemC[anIndex: Integer]: Il3CString
read Get_ItemC
write Set_ItemC;
{* - элементы списка. }
end;//Tl3StringList
implementation
uses
l3String,
l3Chars
;
// start class Tl3StringList
function Tl3StringList.IndexOf(const aSt: Tl3WString): Integer;
//overload;
{-}
begin
if not FindData(aSt, Result) then
Result := -1;
end;
function Tl3StringList.IndexOf(const aSt: Il3CString): Integer;
//reintroduce;
//overload;
{-}
begin
if not FindData(l3PCharLen(aSt), Result) then
Result := -1;
end;
function Tl3StringList.IndexOf(const S: string): Integer;
{-}
begin
if not FindData(S, Result) then
Result := -1;
end;
function Tl3StringList.Add(const Item: Il3CString): Long;
//overload;
var
l_S : Tl3CustomString;
begin
l_S := CStrToItem(Item);
try
Result := Add(l_S);
finally
l3Free(l_S);
end;//try..finally
end;
function Tl3StringList.Add(const Item: String): Long;
//overload;
{* - добавить в список строку. }
begin
Result := Add(l3PCharLen(Item));
end;
procedure Tl3StringList.Insert(Index: Long; const Item: Tl3WString);
{overload;}
{-}
var
l_S : Tl3CustomString;
begin
l_S := WStrToItem(Item);
try
Insert(Index, l_S);
finally
l3Free(l_S);
end;{try..finally}
end;
procedure Tl3StringList.Insert(Index: Long; const Item: Il3CString);
//overload;
var
l_S : Tl3CustomString;
begin
l_S := CStrToItem(Item);
try
Insert(Index, l_S);
finally
l3Free(l_S);
end;//try..finally
end;
procedure Tl3StringList.Insert(aIndex: Integer; const aStr: string);
//overload;
{-}
begin
Insert(aIndex, l3PCharLen(aStr));
end;
function Tl3StringList.CStrToItem(const aStr: Il3CString): Tl3CustomString;
//virtual;
{-}
begin
Result := Tl3IntfString.Make(aStr);
end;
function Tl3StringList.GetW(anIndex: Integer): Tl3WString;
{-}
begin
Result := Items[anIndex].AsWStr;
end;
procedure Tl3StringList.PutW(anIndex: Integer; const aValue: Tl3WString);
{-}
begin
Items[anIndex].AsWStr := aValue;
end;
function Tl3StringList.Get_ItemC(anIndex: Integer): Il3CString;
{-}
var
l_S : Tl3PrimString;
begin
l_S := Items[anIndex];
if (l_S = nil) then
Result := nil
else
if l3IFail(l_S.QueryInterface(Il3CString, Result)) then
Assert(false);
end;
procedure Tl3StringList.Set_ItemC(anIndex: Integer; const aValue: Il3CString);
{-}
var
l_S : Tl3CustomString;
begin
l_S := CStrToItem(aValue);
try
Items[anIndex] := l_S;
finally
l3Free(l_S);
end;//try..finally
end;
end.
|
unit InfoLSOANOTSTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoLSOANOTSRecord = record
PLenderID: String[4];
PModCount: Integer;
End;
TInfoLSOANOTSClass2 = class
public
PLenderID: String[4];
PModCount: Integer;
End;
// function CtoRInfoLSOANOTS(AClass:TInfoLSOANOTSClass):TInfoLSOANOTSRecord;
// procedure RtoCInfoLSOANOTS(ARecord:TInfoLSOANOTSRecord;AClass:TInfoLSOANOTSClass);
TInfoLSOANOTSBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoLSOANOTSRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoLSOANOTS = (InfoLSOANOTSPrimaryKey);
TInfoLSOANOTSTable = class( TDBISAMTableAU )
private
FDFLenderID: TStringField;
FDFModCount: TIntegerField;
FDFNotes: TBlobField;
procedure SetPLenderID(const Value: String);
function GetPLenderID:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetEnumIndex(Value: TEIInfoLSOANOTS);
function GetEnumIndex: TEIInfoLSOANOTS;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoLSOANOTSRecord;
procedure StoreDataBuffer(ABuffer:TInfoLSOANOTSRecord);
property DFLenderID: TStringField read FDFLenderID;
property DFModCount: TIntegerField read FDFModCount;
property DFNotes: TBlobField read FDFNotes;
property PLenderID: String read GetPLenderID write SetPLenderID;
property PModCount: Integer read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEIInfoLSOANOTS read GetEnumIndex write SetEnumIndex;
end; { TInfoLSOANOTSTable }
TInfoLSOANOTSQuery = class( TDBISAMQueryAU )
private
FDFLenderID: TStringField;
FDFModCount: TIntegerField;
FDFNotes: TBlobField;
procedure SetPLenderID(const Value: String);
function GetPLenderID:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoLSOANOTSRecord;
procedure StoreDataBuffer(ABuffer:TInfoLSOANOTSRecord);
property DFLenderID: TStringField read FDFLenderID;
property DFModCount: TIntegerField read FDFModCount;
property DFNotes: TBlobField read FDFNotes;
property PLenderID: String read GetPLenderID write SetPLenderID;
property PModCount: Integer read GetPModCount write SetPModCount;
published
property Active write SetActive;
end; { TInfoLSOANOTSTable }
procedure Register;
implementation
procedure TInfoLSOANOTSTable.CreateFields;
begin
FDFLenderID := CreateField( 'LenderID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFNotes := CreateField( 'Notes' ) as TBlobField;
end; { TInfoLSOANOTSTable.CreateFields }
procedure TInfoLSOANOTSTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoLSOANOTSTable.SetActive }
procedure TInfoLSOANOTSTable.SetPLenderID(const Value: String);
begin
DFLenderID.Value := Value;
end;
function TInfoLSOANOTSTable.GetPLenderID:String;
begin
result := DFLenderID.Value;
end;
procedure TInfoLSOANOTSTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TInfoLSOANOTSTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TInfoLSOANOTSTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderID, String, 4, N');
Add('ModCount, Integer, 0, N');
Add('Notes, Memo, 0, N');
end;
end;
procedure TInfoLSOANOTSTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderID, Y, Y, N, N');
end;
end;
procedure TInfoLSOANOTSTable.SetEnumIndex(Value: TEIInfoLSOANOTS);
begin
case Value of
InfoLSOANOTSPrimaryKey : IndexName := '';
end;
end;
function TInfoLSOANOTSTable.GetDataBuffer:TInfoLSOANOTSRecord;
var buf: TInfoLSOANOTSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderID := DFLenderID.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoLSOANOTSTable.StoreDataBuffer(ABuffer:TInfoLSOANOTSRecord);
begin
DFLenderID.Value := ABuffer.PLenderID;
DFModCount.Value := ABuffer.PModCount;
end;
function TInfoLSOANOTSTable.GetEnumIndex: TEIInfoLSOANOTS;
var iname : string;
begin
result := InfoLSOANOTSPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoLSOANOTSPrimaryKey;
end;
procedure TInfoLSOANOTSQuery.CreateFields;
begin
FDFLenderID := CreateField( 'LenderID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFNotes := CreateField( 'Notes' ) as TBlobField;
end; { TInfoLSOANOTSQuery.CreateFields }
procedure TInfoLSOANOTSQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoLSOANOTSQuery.SetActive }
procedure TInfoLSOANOTSQuery.SetPLenderID(const Value: String);
begin
DFLenderID.Value := Value;
end;
function TInfoLSOANOTSQuery.GetPLenderID:String;
begin
result := DFLenderID.Value;
end;
procedure TInfoLSOANOTSQuery.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TInfoLSOANOTSQuery.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
function TInfoLSOANOTSQuery.GetDataBuffer:TInfoLSOANOTSRecord;
var buf: TInfoLSOANOTSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderID := DFLenderID.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoLSOANOTSQuery.StoreDataBuffer(ABuffer:TInfoLSOANOTSRecord);
begin
DFLenderID.Value := ABuffer.PLenderID;
DFModCount.Value := ABuffer.PModCount;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoLSOANOTSTable, TInfoLSOANOTSQuery, TInfoLSOANOTSBuffer ] );
end; { Register }
function TInfoLSOANOTSBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..2] of string = ('LENDERID','MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 2) and (flist[x] <> s) do inc(x);
if x <= 2 then result := x else result := 0;
end;
function TInfoLSOANOTSBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftInteger;
end;
end;
function TInfoLSOANOTSBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderID;
2 : result := @Data.PModCount;
end;
end;
end.
|
unit StanEditLS;
//*****************************************************************************
// Процедуры сохранения и загрузки описания объектов зависимостей станции
//*****************************************************************************
interface
uses
SysUtils,
Classes,
StanEditTypes,
interpritator,
TypeALL;
const
// перечень имен файлов с описанием зависимостей станции
filenameObjDat = 'Objects.dat';
filenameConDat = 'Connects.dat';
filenameIIObjDat = 'IIObj.dat';
filenameOIObjDat = 'OIObj.dat';
function SaveObjParams(FileName: string; start, len: Integer) : integer; // сохранить параметры объектов
function LoadObjParams(FileName: string; start: Integer) : integer; // загрузить параметры объектов
function SaveConParams(FileName: string; start, len: Integer) : integer; // сохранить описания соединений
function LoadConParams(FileName: string; start: Integer) : integer; // загрузить описания соединений
function SaveIIObjList(FileName: string; start, len: Integer) : integer; // сохранить список входных интерфейсов объектов
function LoadIIObjList(FileName: string; start: Integer) : integer; // загрузить список входных интерфейсов объектов
function SaveOIObjList(FileName: string; start, len: Integer) : integer; // сохранить список выходных интерфейсов объектов
function LoadOIObjList(FileName: string; start: Integer) : integer; // загрузить список выходных интерфейсов объектов
implementation
function SaveObjParams(FileName: string; start, len: Integer) : integer; // сохранить параметры объектов
var
sl0 : TStringList;
i : integer;
begin
sl0 := TStringList.Create;
try
if len = 0 then
begin
for i := 1 to Length(objects) do
if objects[i].index <> 0 then
sl0.Add(IntToStr(objects[i].Index)+ ';'+ objects[i].name+ ';'+ IntToStr(objects[i].Line)+ ';'+ IntToStr(objects[i].Col)+ ';'+ IntToStr(objects[i].IDO)+ ';'+ IntToStr(objects[i].Jmp1)+ ';'+ IntToStr(objects[i].Jmp2)+ ';'+ IntToStr(objects[i].Jmp3)+ ';'+ objects[i].TmpName+ ';'+ objects[i].params);
end else
begin
for i := start to start+len do
if objects[i].index <> 0 then
sl0.Add(IntToStr(objects[i].Index)+ ';'+ objects[i].name+ ';'+ IntToStr(objects[i].Line)+ ';'+ IntToStr(objects[i].Col)+ ';'+ IntToStr(objects[i].IDO)+ ';'+ IntToStr(objects[i].Jmp1)+ ';'+ IntToStr(objects[i].Jmp2)+ ';'+ IntToStr(objects[i].Jmp3)+ ';'+ objects[i].TmpName+ ';'+ objects[i].params);
end;
sl0.SaveToFile(FileName);
finally
result := sl0.Count; // вернуть количество сохраненных объектов
sl0.Free;
end;
end;
//========================================================================================
//----------------------------------------------------------- загрузить параметры объектов
function LoadObjParams(FileName: string; start: Integer) : integer;
var
sla : TStringList;
s,p : string;
i,j,z : integer;
begin
result := -1;
sla := TStringList.Create;
try
sla.LoadFromFile(FileName);
if sla.Count > 0 then
begin
for i := 0 to sla.Count-1 do
begin
s := sla.Strings[i];
if Length(s) > 0 then
begin
p := ''; j := 1;
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try z := StrToInt(p) except z := -1 end;//--------------------- Индекс объекта
if z > 0 then
begin
objects[z + start].index := z + start;
//------------------------------------------------------ Загрузить имя объекта
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
objects[z+start].name := p;
//------------------------------------------------ Загрузить номер линии сетки
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try objects[z+start].line := StrToint(p) except exit end;
//---------------------------------------------- Загрузить номер столбца сетки
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try objects[z+start].col := StrToint(p) except exit end;
//--------------------------------------- Загрузить идентификатор типа объекта
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try objects[z+start].IDO := StrToint(p) except exit end;
//-------------------- Загрузить ссылку на переход, подключенный к 1-му выходу
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try objects[z+start].jmp1 := StrToint(p) except exit end;
//------------------- Загрузить ссылку на переход, подключенный ко 2-му выходу
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try objects[z+start].jmp2 := StrToint(p) except exit end;
//-------------------- Загрузить ссылку на переход, подключенный к 3-му выходу
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
try objects[z+start].jmp3 := StrToint(p) except exit end;
//--------------------- Загрузить шаблон для имен входных\выходных интерфейсов
p := '';
while s[j] <> ';' do
begin
p := p + s[j];
inc(j);
if j > Length(s) then break;
end;
inc(j);
objects[z+start].TmpName := p;
//----------------------------------------- Загрузить описание свойств объекта
p := '';
while j <= Length(s) do
begin
p := p + s[j];
inc(j);
end;
objects[z+start].params := p;
end;
end;
end;
result := sla.Count; //--------------------- Вернуть количество загруженных объектов
end;
finally
sla.Free;
end;
end;
//========================================================================================
//---------------------------------------------------------- сохранить описания соединений
function SaveConParams(FileName: string; start, len: Integer) : integer;
var
slb : TStringList;
i : integer;
begin
slb := TStringList.Create;
try
if len = 0 then
begin
for i := 1 to Length(connects) do
if connects[i].index <> 0 then
slb.Add(IntToStr(connects[i].Index) + ';' +
IntToStr(connects[i].IDO) + ';' +
IntToStr(connects[i].BeginObj) + ';' +
IntToStr(connects[i].BeginPin) + ';' +
IntToStr(connects[i].EndObj) + ';' +
IntToStr(connects[i].EndPin)+ ';');
end else
begin
for i := start to start+len do
slb.Add(IntToStr(connects[i].Index) + ';' +
IntToStr(connects[i].IDO) + ';'+
IntToStr(connects[i].BeginObj) + ';' +
IntToStr(connects[i].BeginPin) + ';' +
IntToStr(connects[i].EndObj) + ';' +
IntToStr(connects[i].EndPin) + ';');
end;
slb.SaveToFile(FileName);
finally
result := slb.Count; //--------------------- вернуть количество сохраненных соединений
slb.Free;
end;
end;
function LoadConParams(FileName: string; start: Integer) : integer; // загрузить описания соединений
var
slc : TStringList; s,p : string; i,j : integer; z : integer;
begin
result := -1;
slc := TStringList.Create;
try
slc.LoadFromFile(FileName);
if slc.Count > 0 then
begin
for i := 0 to slc.Count-1 do
begin
s := slc.Strings[i];
if Length(s) > 0 then
begin
p := ''; j := 1; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j);
try z := StrToInt(p) except z := -1 end; // Индекс соединения
if z > 0 then
begin
connects[z + start].index := z + start;
// Загрузить идентификатор типа соединения
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); try connects[z+start].IDO := StrToint(p) except exit end;
// Загрузить номер объекта начала
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); try connects[z+start].BeginObj := StrToint(p) except exit end;
// Загрузить номер контакта начала
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); try connects[z+start].BeginPin := StrToint(p) except exit end;
// Загрузить номер объекта конца
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); try connects[z+start].EndObj := StrToint(p) except exit end;
// Загрузить номер контакта конца
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; try connects[z+start].EndPin := StrToint(p) except exit end;
end;
end;
end;
result := slc.Count; // Вернуть количество загруженных соединений
end;
finally
slc.Free;
end;
end;
function SaveIIObjList(FileName: string; start, len: Integer) : integer; // сохранить список входных интерфейсов объектов
var sld : TStringList; i : integer;
begin
sld := TStringList.Create;
try
if len = 0 then
begin
for i := 1 to Length(IIObjects) do
if IIObjects[i].index <> 0 then
sld.Add(IntToStr(IIObjects[i].Index)+ ';'+ IIObjects[i].NameObj+ ';'+ IIObjects[i].NameKey+ ';'+ IIObjects[i].NameInterface+ ';'+ IIObjects[i].Hint+ ';');
end else
begin
for i := start to start+len do
if IIObjects[i].index <> 0 then
sld.Add(IntToStr(IIObjects[i].Index)+ ';'+ IIObjects[i].NameObj+ ';'+ IIObjects[i].NameKey+ ';'+ IIObjects[i].NameInterface+ ';'+ IIObjects[i].Hint+ ';');
end;
sld.SaveToFile(FileName);
finally
result := sld.Count; // вернуть количество сохраненных объектов
sld.Free;
end;
end;
function LoadIIObjList(FileName: string; start: Integer) : integer; // загрузить список входных интерфейсов объектов
var sle : TStringList; s,p : string; i,j : integer; z : integer;
begin
result := -1;
sle := TStringList.Create;
try
sle.LoadFromFile(FileName);
if sle.Count > 0 then
begin
for i := 0 to sle.Count-1 do
begin
s := sle.Strings[i];
if Length(s) > 0 then
begin
p := ''; j := 1; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j);
try z := StrToInt(p) except z := -1 end; // Индекс объекта
if z > 0 then
begin
IIObjects[z + start].index := z + start;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); IIObjects[z+start].NameObj := p;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); IIObjects[z+start].NameKey := p;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); IIObjects[z+start].NameInterface := p;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; IIObjects[z+start].Hint := p;
end;
end;
end;
result := sle.Count; // Вернуть количество загруженных объектов
end;
finally
sle.Free;
end;
end;
function SaveOIObjList(FileName: string; start, len: Integer) : integer; // сохранить список выходных интерфейсов объектов
var slf : TStringList; i : integer;
begin
slf := TStringList.Create;
try
if len = 0 then
begin
for i := 1 to Length(objects) do
if OIObjects[i].index <> 0 then
slf.Add(IntToStr(OIObjects[i].Index)+ ';'+ OIObjects[i].NameObj+ ';'+ OIObjects[i].NameKey+ ';'+ OIObjects[i].NameInterface+ ';'+ OIObjects[i].Hint+ ';');
end else
begin
for i := start to start+len do
if OIObjects[i].index <> 0 then
slf.Add(IntToStr(OIObjects[i].Index)+ ';'+ OIObjects[i].NameObj+ ';'+ OIObjects[i].NameKey+ ';'+ OIObjects[i].NameInterface+ ';'+ OIObjects[i].Hint+ ';');
end;
slf.SaveToFile(FileName);
finally
result := slf.Count; // вернуть количество сохраненных объектов
slf.Free;
end;
end;
function LoadOIObjList(FileName: string; start: Integer) : integer; // загрузить список выходных интерфейсов объектов
var slg : TStringList; s,p : string; i,j : integer; z : integer;
begin
result := -1;
slg := TStringList.Create;
try
slg.LoadFromFile(FileName);
if slg.Count > 0 then
begin
for i := 0 to slg.Count-1 do
begin
s := slg.Strings[i];
if Length(s) > 0 then
begin
p := ''; j := 1; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j);
try z := StrToInt(p) except z := -1 end; // Индекс объекта
if z > 0 then
begin
OIObjects[z + start].index := z + start;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); OIObjects[z+start].NameObj := p;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); OIObjects[z+start].NameKey := p;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; inc(j); OIObjects[z+start].NameInterface := p;
// Загрузить имя объекта
p := ''; while s[j] <> ';' do begin p := p + s[j]; inc(j); if j > Length(s) then break; end; OIObjects[z+start].Hint := p;
end;
end;
end;
result := slg.Count; // Вернуть количество загруженных объектов
end;
finally
slg.Free;
end;
end;
end.
|
unit FormMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFrmMain = class(TForm)
Button1: TButton;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
public
FStop: boolean;
FIsStoped: boolean;
FFree: boolean;
end;
var
FrmMain: TFrmMain;
MyThread: TMyThread;
ThreadCnt: integer;
implementation
{$R *.dfm}
procedure TMyThread.Execute;
var
Idx: integer;
begin
FreeOnTerminate:=True;
while (not FFree) do
begin
if (not FStop) then
begin
FIsStoped:=False;
for Idx:=0 to 99999 do
ThreadCnt:=ThreadCnt+1;
end;
if (FStop) then FIsStoped:=True;
end;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
SetPriorityClass(GetCurrentProcess, HIGH_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_HIGHEST);
MyThread:=TMyThread.Create(True);
MyThread.FStop:=False;
MyThread.FFree:=False;
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
MyThread.FFree:=True;
end;
procedure TFrmMain.Button1Click(Sender: TObject);
var
TimeStart: int64;
TimeEnd: int64;
TimeFrq: int64;
TimeS: double;
begin
QueryPerformanceCounter(TimeStart);
ThreadCnt:=0;
MyThread.FStop:=False;
MyThread.Resume;
while (ThreadCnt < 1000000) do;
MyThread.FStop:=True;
while (not MyThread.FIsStoped) do;
MyThread.Suspend;
Label3.Caption:=IntToStr(ThreadCnt);
QueryPerformanceCounter(TimeEnd);
QueryPerformanceFrequency(TimeFrq);
TimeS:=(TimeEnd-TimeStart) / TimeFrq;
Label1.Caption:=Format('%1.8f s', [TimeS]);
end;
procedure TFrmMain.Button2Click(Sender: TObject);
var
TimeStart: int64;
TimeEnd: int64;
TimeFrq: int64;
TimeS: double;
Idx: integer;
begin
QueryPerformanceCounter(TimeStart);
ThreadCnt:=0;
Idx:=0;
while (Idx < 1000) do
begin
ThreadCnt:=0;
MyThread.FStop:=False;
MyThread.Resume;
while (ThreadCnt < 1) do;
MyThread.FStop:=True;
while (not MyThread.FIsStoped) do;
MyThread.Suspend;
// Label3.Caption:=IntToStr(Idx);
// Label3.Repaint;
Idx:=Idx+1;
end;
Label4.Caption:=IntToStr(ThreadCnt);
QueryPerformanceCounter(TimeEnd);
QueryPerformanceFrequency(TimeFrq);
TimeS:=(TimeEnd-TimeStart) / TimeFrq;
Label2.Caption:=Format('%1.8f s', [TimeS]);
end;
end.
|
unit UMemBlockAccount;
interface
uses
UMemOperationBlock, UConst, UMemAccount, U32Bytes, UBlockAccount;
{$include MemoryReductionSettings.inc}
{$IFDEF uselowmem}
type
TMemBlockAccount = Record // TBlockAccount with less memory usage
blockchainInfo : TMemOperationBlock;
accounts : Array[0..CT_AccountsPerBlock-1] of TMemAccount;
block_hash: T32Bytes; // 32 direct bytes instead of use an AnsiString (-8 bytes)
accumulatedWork : UInt64;
end;
{$ELSE}
Type
TMemBlockAccount = TBlockAccount;
{$ENDIF}
procedure ToTMemBlockAccount(const source : TBlockAccount; var dest : TMemBlockAccount);
procedure ToTBlockAccount(const source : TMemBlockAccount; block_number : Cardinal; var dest : TBlockAccount);
implementation
uses
URawBytes, UAccountKeyStorage, UBaseType;
procedure ToTMemBlockAccount(const source : TBlockAccount; var dest : TMemBlockAccount);
{$IFDEF uselowmem}
var i : Integer;
var raw : TRawBytes;
{$ENDIF}
Begin
{$IFDEF uselowmem}
{$IFDEF useAccountKeyStorage}
dest.blockchainInfo.account_keyKS:=TAccountKeyStorage.KS.AddAccountKey(source.blockchainInfo.account_key);
{$ELSE}
TAccountComp.AccountKey2RawString(source.blockchainInfo.account_key,raw);
TBaseType.To256RawBytes(raw,dest.blockchainInfo.account_key);
{$ENDIF}
dest.blockchainInfo.reward:=source.blockchainInfo.reward;
dest.blockchainInfo.fee:=source.blockchainInfo.fee;
dest.blockchainInfo.protocol_version:=source.blockchainInfo.protocol_version;
dest.blockchainInfo.protocol_available:=source.blockchainInfo.protocol_available;
dest.blockchainInfo.timestamp:=source.blockchainInfo.timestamp;
dest.blockchainInfo.compact_target:=source.blockchainInfo.compact_target;
dest.blockchainInfo.nonce:=source.blockchainInfo.nonce;
TBaseType.To256RawBytes(source.blockchainInfo.block_payload,dest.blockchainInfo.block_payload);
TBaseType.To32Bytes(source.blockchainInfo.initial_safe_box_hash,dest.blockchainInfo.initial_safe_box_hash);
TBaseType.To32Bytes(source.blockchainInfo.operations_hash,dest.blockchainInfo.operations_hash);
TBaseType.To32Bytes(source.blockchainInfo.proof_of_work,dest.blockchainInfo.proof_of_work);
for i := Low(source.accounts) to High(source.accounts) do begin
ToTMemAccount(source.accounts[i],dest.accounts[i]);
end;
TBaseType.To32Bytes(source.block_hash,dest.block_hash);
dest.accumulatedWork := source.accumulatedWork;
{$ELSE}
dest := source;
{$ENDIF}
end;
procedure ToTBlockAccount(const source : TMemBlockAccount; block_number : Cardinal; var dest : TBlockAccount);
{$IFDEF uselowmem}
var i : Integer;
raw : TRawBytes;
{$ENDIF}
begin
{$IFDEF uselowmem}
dest.blockchainInfo.block:=block_number;
{$IFDEF useAccountKeyStorage}
dest.blockchainInfo.account_key := source.blockchainInfo.account_keyKS^;
{$ELSE}
TBaseType.ToRawBytes(source.blockchainInfo.account_key,raw);
TAccountComp.RawString2Accountkey(raw,dest.blockchainInfo.account_key);
{$ENDIF}
dest.blockchainInfo.reward:=source.blockchainInfo.reward;
dest.blockchainInfo.fee:=source.blockchainInfo.fee;
dest.blockchainInfo.protocol_version:=source.blockchainInfo.protocol_version;
dest.blockchainInfo.protocol_available:=source.blockchainInfo.protocol_available;
dest.blockchainInfo.timestamp:=source.blockchainInfo.timestamp;
dest.blockchainInfo.compact_target:=source.blockchainInfo.compact_target;
dest.blockchainInfo.nonce:=source.blockchainInfo.nonce;
TBaseType.ToRawBytes(source.blockchainInfo.block_payload,dest.blockchainInfo.block_payload);
TBaseType.ToRawBytes(source.blockchainInfo.initial_safe_box_hash,dest.blockchainInfo.initial_safe_box_hash);
TBaseType.ToRawBytes(source.blockchainInfo.operations_hash,dest.blockchainInfo.operations_hash);
TBaseType.ToRawBytes(source.blockchainInfo.proof_of_work,dest.blockchainInfo.proof_of_work);
for i := Low(source.accounts) to High(source.accounts) do begin
ToTAccount(source.accounts[i],(block_number*CT_AccountsPerBlock)+i,dest.accounts[i]);
end;
TBaseType.ToRawBytes(source.block_hash,dest.block_hash);
dest.accumulatedWork := source.accumulatedWork;
{$ELSE}
dest := source;
{$ENDIF}
end;
end.
|
unit l3EventedRecListView;
// Модуль: "w:\common\components\rtl\Garant\L3\l3EventedRecListView.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tl3EventedRecListView" MUID: (4DEFC812022F)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, l3CustomRecListView
, l3ProtoPtrRecListPrim
;
type
Tl3CompareItemsEvent = function(anItem1: PItemType;
anItem2: PItemType): Integer of object;
Tl3EventedRecListView = class(Tl3CustomRecListView)
private
f_CompareItemsEvent: Tl3CompareItemsEvent;
protected
function CompareRecs(aRec1: PRecForCompare;
aRec2: PRecForCompare): Integer; override;
public
constructor Create(aList: Tl3ProtoPtrRecListPrim;
aCompareItemsEvent: Tl3CompareItemsEvent); reintroduce;
end;//Tl3EventedRecListView
implementation
uses
l3ImplUses
//#UC START# *4DEFC812022Fimpl_uses*
//#UC END# *4DEFC812022Fimpl_uses*
;
constructor Tl3EventedRecListView.Create(aList: Tl3ProtoPtrRecListPrim;
aCompareItemsEvent: Tl3CompareItemsEvent);
//#UC START# *4DEFC86E0263_4DEFC812022F_var*
//#UC END# *4DEFC86E0263_4DEFC812022F_var*
begin
//#UC START# *4DEFC86E0263_4DEFC812022F_impl*
Assert(Assigned(aCompareItemsEvent));
f_CompareItemsEvent := aCompareItemsEvent;
inherited Create(aList);
//#UC END# *4DEFC86E0263_4DEFC812022F_impl*
end;//Tl3EventedRecListView.Create
function Tl3EventedRecListView.CompareRecs(aRec1: PRecForCompare;
aRec2: PRecForCompare): Integer;
//#UC START# *4DEFCA7603C4_4DEFC812022F_var*
//#UC END# *4DEFCA7603C4_4DEFC812022F_var*
begin
//#UC START# *4DEFCA7603C4_4DEFC812022F_impl*
Result := f_CompareItemsEvent(aRec1, aRec2);
//#UC END# *4DEFCA7603C4_4DEFC812022F_impl*
end;//Tl3EventedRecListView.CompareRecs
end.
|
unit filter_rbj;
{$mode delphi} {$H+}
//http://en.wikipedia.org/wiki/Digital_biquad_filter
//http://www.musicdsp.org/archive.php?classid=3#225
//http://www.musicdsp.org/showone.php?id=197
//http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
// http://www.musicdsp.org/archive.php?classid=3#225
//http://www.musicdsp.org/showArchiveComment.php?ArchiveID=225
{
RBJ Audio EQ Cookbook Filters
A pascal conversion of arguru[AT]smartelectronix[DOT]com's
c++ implementation.
WARNING:This code is not FPU undernormalization safe.
}
interface
uses math;
const
kLowPass=0;//-LowPass
kHighPass=1;//-HiPass
kBandPassCSG=2;//-BandPass CSG
kBandPassCZPG=3;//-BandPass CZPG
kNotch=4;//-Notch
kAll=5;//-AllPass
kPeaking=6;//-Peaking
kLowShelf=7;//-LowShelf
kHighShelf=8;//-HiShelf
type
TRbjEqFilter=class
private
b0a0,b1a0,b2a0,a1a0,a2a0:single;
in1,in2,ou1,ou2:single;
fSampleRate:single;
fMaxBlockSize:integer;
fFilterType:integer;
fFreq,fQ,fDBGain:single;
fQIsBandWidth:boolean;
procedure SetQ(NewQ:single);
public
out1:array of single;
constructor create(SampleRate:single;MaxBlockSize:integer);
procedure CalcFilterCoeffs(pFilterType:integer;pFreq,pQ,pDBGain:single;pQIsBandWidth:boolean);overload;
procedure CalcFilterCoeffs;overload;
function Process(input:single):single; overload;
procedure Process(Input:psingle;sampleframes:integer); overload;
property FilterType:integer read fFilterType write fFilterType;
property Freq:single read fFreq write fFreq;
property q:single read fQ write SetQ;
property DBGain:single read fDBGain write fDBGain;
property QIsBandWidth:boolean read fQIsBandWidth write fQIsBandWidth;
end;
implementation
constructor TRbjEqFilter.create(SampleRate:single;MaxBlockSize:integer);
begin
fMaxBlockSize:=MaxBlockSize;
setLength(out1,fMaxBlockSize);
fSampleRate:=SampleRate;
fFilterType:=0;
fFreq:=500;
fQ:=0.3;
fDBGain:=0;
fQIsBandWidth:=true;
in1:=0;
in2:=0;
ou1:=0;
ou2:=0;
end;
procedure TRbjEqFilter.SetQ(NewQ:single);
begin
fQ:=(1-NewQ)*0.98;
end;
procedure TRbjEqFilter.CalcFilterCoeffs(pFilterType:integer;pFreq,pQ,pDBGain:single;pQIsBandWidth:boolean);
begin
FilterType:=pFilterType;
Freq:=pFreq;
Q:=pQ;
DBGain:=pDBGain;
QIsBandWidth:=pQIsBandWidth;
CalcFilterCoeffs;
end;
procedure TRbjEqFilter.CalcFilterCoeffs;
var
alpha,a0,a1,a2,b0,b1,b2:single;
A,beta,omega,tsin,tcos:single;
begin
a0 := 0;
a1 := 0;
a2 := 0;
b0 := 0;
b1 := 0;
b2 := 0;
//peaking, LowShelf or HiShelf
if fFilterType>=6 then
begin
A:=power(10.0,(DBGain/40.0));
omega:=2*pi*fFreq/fSampleRate;
tsin:=sin(omega);
tcos:=cos(omega);
if fQIsBandWidth then
alpha:=tsin*sinh(log2(2.0)/2.0*fQ*omega/tsin)
else
alpha:=tsin/(2.0*fQ);
beta:=sqrt(A)/fQ;
// peaking
if fFilterType=6 then
begin
b0:=1.0+alpha*A;
b1:=-2.0*tcos;
b2:=1.0-alpha*A;
a0:=1.0+alpha/A;
a1:=-2.0*tcos;
a2:=1.0-alpha/A;
end else
// lowshelf
if fFilterType=7 then
begin
b0:=(A*((A+1.0)-(A-1.0)*tcos+beta*tsin));
b1:=(2.0*A*((A-1.0)-(A+1.0)*tcos));
b2:=(A*((A+1.0)-(A-1.0)*tcos-beta*tsin));
a0:=((A+1.0)+(A-1.0)*tcos+beta*tsin);
a1:=(-2.0*((A-1.0)+(A+1.0)*tcos));
a2:=((A+1.0)+(A-1.0)*tcos-beta*tsin);
end;
// hishelf
if fFilterType=8 then
begin
b0:=(A*((A+1.0)+(A-1.0)*tcos+beta*tsin));
b1:=(-2.0*A*((A-1.0)+(A+1.0)*tcos));
b2:=(A*((A+1.0)+(A-1.0)*tcos-beta*tsin));
a0:=((A+1.0)-(A-1.0)*tcos+beta*tsin);
a1:=(2.0*((A-1.0)-(A+1.0)*tcos));
a2:=((A+1.0)-(A-1.0)*tcos-beta*tsin);
end;
end else //other filter types
begin
omega:=2*pi*fFreq/fSampleRate;
tsin:=sin(omega);
tcos:=cos(omega);
if fQIsBandWidth then
alpha:=tsin*sinh(log2(2)/2*fQ*omega/tsin)
else
alpha:=tsin/(2*fQ);
//lowpass
if fFilterType=0 then
begin
b0:=(1-tcos)/2;
b1:=1-tcos;
b2:=(1-tcos)/2;
a0:=1+alpha;
a1:=-2*tcos;
a2:=1-alpha;
end else //hipass
if fFilterType=1 then
begin
b0:=(1+tcos)/2;
b1:=-(1+tcos);
b2:=(1+tcos)/2;
a0:=1+alpha;
a1:=-2*tcos;
a2:=1-alpha;
end else //bandpass CSG
if fFilterType=2 then
begin
b0:=tsin/2;
b1:=0;
b2:=-tsin/2;
a0:=1+alpha;
a1:=-1*tcos;
a2:=1-alpha;
end else //bandpass CZPG
if fFilterType=3 then
begin
b0:=alpha;
b1:=0.0;
b2:=-alpha;
a0:=1.0+alpha;
a1:=-2.0*tcos;
a2:=1.0-alpha;
end else //notch
if fFilterType=4 then
begin
b0:=1.0;
b1:=-2.0*tcos;
b2:=1.0;
a0:=1.0+alpha;
a1:=-2.0*tcos;
a2:=1.0-alpha;
end else //allpass
if fFilterType=5 then
begin
b0:=1.0-alpha;
b1:=-2.0*tcos;
b2:=1.0+alpha;
a0:=1.0+alpha;
a1:=-2.0*tcos;
a2:=1.0-alpha;
end;
end;
if a0 = 0 then
exit;
b0a0:=b0/a0;
b1a0:=b1/a0;
b2a0:=b2/a0;
a1a0:=a1/a0;
a2a0:=a2/a0;
end;
function TRbjEqFilter.Process(input:single):single;
var
LastOut:single;
begin
// filter
LastOut:= b0a0*input + b1a0*in1 + b2a0*in2 - a1a0*ou1 - a2a0*ou2;
// push in/out buffers
in2:=in1;
in1:=input;
ou2:=ou1;
ou1:=LastOut;
// return output
result:=LastOut;
end;
{
the process method is overloaded.
use Process(input:single):single;
for per sample processing
use Process(Input:psingle;sampleframes:integer);
for block processing. The input is a pointer to
the start of an array of single which contains
the audio data.
i.e.
RBJFilter.Process(@WaveData[0],256);
}
procedure TRbjEqFilter.Process(Input:psingle;sampleframes:integer);
var
i:integer;
LastOut:single;
begin
for i:=0 to SampleFrames-1 do
begin
// filter
LastOut:= b0a0*(input^)+ b1a0*in1 + b2a0*in2 - a1a0*ou1 - a2a0*ou2;
//LastOut:=input^;
// push in/out buffers
in2:=in1;
in1:=input^;
ou2:=ou1;
ou1:=LastOut;
Out1[i]:=LastOut;
inc(input);
end;
end;
end.
|
unit udmRotasTabCarreteiros;
interface
uses
System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS;
type
TdmRotasTabCarreteiros = class(TdmPadrao)
qryManutencaoCID_ORIG: TStringField;
qryManutencaoEST_ORIG: TStringField;
qryManutencaoCID_DEST: TStringField;
qryManutencaoEST_DEST: TStringField;
qryManutencaoTP_VEIC: TSmallintField;
qryManutencaoTONELADA: TFloatField;
qryManutencaoTON_MINIMA: TFloatField;
qryManutencaoPEDAGIO: TFloatField;
qryManutencaoTX_ENTREGA: TFloatField;
qryManutencaoDESCARGA: TFloatField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoOPERADOR: TStringField;
qryLocalizacaoCID_ORIG: TStringField;
qryLocalizacaoEST_ORIG: TStringField;
qryLocalizacaoCID_DEST: TStringField;
qryLocalizacaoEST_DEST: TStringField;
qryLocalizacaoTP_VEIC: TSmallintField;
qryLocalizacaoTONELADA: TFloatField;
qryLocalizacaoTON_MINIMA: TFloatField;
qryLocalizacaoPEDAGIO: TFloatField;
qryLocalizacaoTX_ENTREGA: TFloatField;
qryLocalizacaoDESCARGA: TFloatField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryManutencaoAJUDANTE: TFloatField;
qryManutencaoADIANTAMENTO: TFloatField;
qryLocalizacaoAJUDANTE: TFloatField;
qryLocalizacaoADIANTAMENTO: TFloatField;
qryManutencaoTIPOVEICULO: TStringField;
qryLocalizacaoTIPOVEICULO: TStringField;
qryManutencaoDURACAOVIAGEM: TIntegerField;
qryLocalizacaoDURACAOVIAGEM: TIntegerField;
private
{ Private declarations }
FOrig_Cidade : String;
FOrig_Estado : String;
FDest_Cidade : string;
FDest_Estado : string;
FTpo_Veiculo : integer;
function Get_Sql_Default: string;
public
{ Public declarations }
property Tpo_Veiculo: Integer read FTpo_Veiculo write FTpo_Veiculo;
property Orig_Cidade : string read FOrig_Cidade write FOrig_Cidade;
property Orig_Estado : string read FOrig_Estado write FOrig_Estado;
property Dest_Cidade : string read FDest_Cidade write FDest_Cidade;
property Dest_Estado : string read FDest_Estado write FDest_Estado;
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
end;
const
SQL_DEFAULT = 'SELECT ' +
' ROTACR.CID_ORIG, ' +
' ROTACR.EST_ORIG, ' +
' ROTACR.CID_DEST, ' +
' ROTACR.EST_DEST, ' +
' ROTACR.TP_VEIC, ' +
' ROTACR.TONELADA, ' +
' ROTACR.TON_MINIMA, ' +
' ROTACR.PEDAGIO, ' +
' ROTACR.TX_ENTREGA,' +
' ROTACR.DESCARGA, ' +
' ROTACR.AJUDANTE,' +
' ROTACR.ADIANTAMENTO,' +
' ROTACR.DT_ALTERACAO, ' +
' ROTACR.OPERADOR, ' +
' ROTACR.DURACAOVIAGEM,'+
' TPV.DESCRICAO TIPOVEICULO ' +
' FROM STWOPETROTACR ROTACR' +
' LEFT JOIN STWOPETTPVE TPV ON ROTACR.TP_VEIC = TPV.CODIGO';
var
dmRotasTabCarreteiros: TdmRotasTabCarreteiros;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdmRotasTabCarreteiros }
function TdmRotasTabCarreteiros.Get_Sql_Default: string;
begin
Result := SQL_DEFAULT;
end;
procedure TdmRotasTabCarreteiros.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE ROTACR.CID_ORIG = :CID_ORIG');
SQL.Add(' AND ROTACR.EST_ORIG = :EST_ORIG');
SQL.Add(' AND ROTACR.CID_DEST = :CID_DEST');
SQL.Add(' AND ROTACR.EST_DEST = :EST_DEST');
SQL.Add(' AND ROTACR.TP_VEIC = :TP_VEIC');
Params[0].AsString := FOrig_Cidade;
Params[1].AsString := FOrig_Estado;
Params[2].AsString := FDest_Cidade;
Params[3].AsString := FDest_Estado;
Params[4].AsInteger := FTpo_Veiculo;
end;
end;
procedure TdmRotasTabCarreteiros.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('ORDER BY ROTACR.CID_ORIG, ROTACR.EST_ORIG, ROTACR.CID_DEST, ROTACR.EST_DEST');
end;
end;
end.
|
unit PathUtils;
(*************************************************************
Copyright © 2012 Toby Allen (https://github.com/tobya)
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, sub-license, 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 every other copyright notice found in this software, and all the attributions in every file, 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 NON-INFRINGEMENT.
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, Classes;
type
TPath = Class
Private
FPath : String;
FParts : TStringList;
function GetParts: TStringList;
function GetExt: String;
function GetFileExists: Boolean;
public
Constructor Create(Path : String);
Destructor Destroy; override;
Property Parts : TStringList read GetParts;
Property Extension : String read GetExt;
Property Exists : Boolean read GetFileExists;
function NewFileName(NewExtension : String) : String;
End;
implementation
{ TPath }
constructor TPath.Create(Path: String);
begin
FPath := Path;
end;
destructor TPath.Destroy;
begin
if Assigned(FParts) then FParts.Free;
inherited destroy;
end;
function TPath.GetExt: String;
begin
result := ExtractFileExt(FPath);
end;
function TPath.GetFileExists: Boolean;
begin
Result := FileExists(FPath) ;
end;
function TPath.GetParts: TStringList;
var
Drive, Folder, Filename : String;
begin
Drive := ExtractFileDrive(FPath);
Folder := ExtractFileDir(FPath);
Filename := ExtractFileName(FPath);
if not assigned(FParts) then FParts := TStringlist.Create();
FParts.Add('Drive=' + Drive + ':\');
FParts.Add('Folder=' + Folder);
FParts.Add('Filename=' + Filename);
FParts.Add('Ext=' + Extension);
Result := FParts;
end;
function TPath.NewFileName(NewExtension: String): String;
begin
end;
end.
|
unit AddOrder;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,
Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.Buttons, Data.Win.ADODB, Vcl.WinXPickers, DateUtils,
IBX.IBCustomDataSet, IBX.IBQuery;
type
TfmOrder = class(TForm)
lbAddres: TLabel;
btnAddAddress: TButton;
eOrderer: TEdit;
lbOrderer: TLabel;
dbgProducts: TDBGrid;
btnShowMenu: TButton;
dsProducts: TDataSource;
btnCancel: TBitBtn;
btnOk: TBitBtn;
lbNumber: TLabel;
edPhone: TEdit;
Label1: TLabel;
pnlAddress: TPanel;
tpTimeOfDelivery: TTimePicker;
cbTimeOfDelivery: TCheckBox;
lbOrderNumber: TLabel;
btnRefresh: TButton;
lbSetAddress: TLabel;
procedure btnOkClick(Sender: TObject);
procedure btnAddAddressClick(Sender: TObject);
procedure btnShowMenuClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure cbTimeOfDeliveryClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmOrder: TfmOrder;
orderNum :integer = 0; // номер заказа для Caption на новой кнопке (потом использовать ID в бд)
addrID :integer;
addressString, time: string;
implementation
uses main, addAddress, Menu, dm, ChooseAddress;
{$R *.dfm}
//================== ДОБАВЛЕНИЕ АДРЕСА ==================//
procedure TfmOrder.btnAddAddressClick(Sender: TObject);
begin
dsProducts.DataSet := nil;
fmChooseAddress.ShowModal;
lbSetAddress.Caption := addressString;
end;
//*******************************************************//
procedure TfmOrder.btnCancelClick(Sender: TObject);
begin
//удалякм врЕменный заказ из БД при отмене
dmMy.smDeleteOrder(orderNum);
end;
//========= ДОБАВЛЕНИЕ ПАНЕЛИ ПО НАЖАТИЮ КНОПКИ =========//
procedure TfmOrder.btnOkClick(Sender: TObject);
var
Panel: Tpanel;
begin
// orderNum:= orderNum+1;
Panel:= TPanel.Create(fmMain.sboxOrders);
Panel.Parent:= fmMain.sboxOrders;
Panel.Align:= alTop;
Panel.Width:= fmMain.sboxOrders.Width;
Panel.Height:= 50;
Panel.Caption:= 'Заказ № ' + IntToStr(orderNum);
Panel.DragMode:= dmAutomatic;
time := TimeToStr(tpTimeOfDelivery.Time);
Delete(time, length(TimeToStr(tpTimeOfDelivery.Time))-2,length(TimeToStr(tpTimeOfDelivery.Time)));
try
dmMy.smUpdateOrder(orderNum, 1, eOrderer.Text, edPhone.Text, addrID, 4, 3, Now, time, 0);
except
MessageDlg('Ошибка записи заказа', mtError, [mbOk], 0)
end;
//
eOrderer.Text := '';
edPhone.Text := '';
lbSetAddress.Caption := '';
cbTimeOfDelivery.Checked := true;
//
fmOrder.Close;
end;
procedure TfmOrder.btnRefreshClick(Sender: TObject);
var SQL_Line: string;
begin
SQL_Line := 'select menu.name, categories.name, order_info.quantity, order_info.price, order_info.order_id' +
' from order_info join menu ON order_info.product_id = menu.product_id' +
' join categories ON menu.category_id= categories.category_id where order_id = ' + orderNum.ToString;
dmMY.smSQLClear;
dmMy.smSQLAddString(SQL_Line);
dmMy.smSQLExecute;
dsProducts.DataSet := dmMy.IBQuery1;
dsProducts.DataSet.Open;
//Настройка dbgrid
dbgProducts.Fields[0].DisplayLabel := 'Наименование';
dbgProducts.Fields[0].DisplayWidth := 30;
dbgProducts.Fields[1].DisplayLabel := 'Категория';
dbgProducts.Fields[1].DisplayWidth := 15;
dbgProducts.Fields[2].DisplayLabel := 'Количество';
dbgProducts.Fields[2].DisplayWidth := 10;
dbgProducts.Fields[3].DisplayLabel := 'Цена';
dbgProducts.Fields[3].DisplayWidth := 5;
dbgProducts.Fields[4].Visible := false;
dbgProducts.Refresh;
end;
//*******************************************************//
//==================== ПОКАЗАТЬ МЕНЮ ====================//
procedure TfmOrder.btnShowMenuClick(Sender: TObject);
begin
// показать меню выбора продуктов
// если выбрали продукт и нажали Ок, добавляем выбранный продукт в таблицу, а потом в DBGrid
fmMenu.edQuantity.Text := '';
fmMenu.ShowModal;
fmMenu.btnChoose.Enabled := false;
end;
procedure TfmOrder.cbTimeOfDeliveryClick(Sender: TObject);
begin
tpTimeOfDelivery.Enabled := not(cbTimeOfDelivery.Checked);
tpTimeOfDelivery.Time := IncHour(Now);
end;
procedure TfmOrder.FormActivate(Sender: TObject);
begin
//TODO: Создать записи в БД для врЕменных заказов
orderNum := dmMy.smUpdateOrder(0, 1, '', '', 4, 4, 3, Now, '', 0);
lbOrderNumber.Caption := 'Номер заказа ' + orderNum.ToString;
if cbTimeOfDelivery.Checked = true then begin
tpTimeOfDelivery.Time := IncHour(Now);
tpTimeOfDelivery.Enabled := false;
end
else begin
tpTimeOfDelivery.Enabled := true;
end;
btnRefreshClick(self);
end;
procedure TfmOrder.FormCreate(Sender: TObject);
begin
end;
//*******************************************************//
end.
|
{ Mark Sattolo 428500
CSI-1100A DGD-1 TA: Chris Lankester
Assignment 8, Question 1 }
program PowerStars (input,output);
{ ****************************************************************************** }
procedure PowerFast(X:real; N:integer; var Answer:Real);
{ Compute X^N recursively }
{ Data Dictionary
Givens: X - a real number.
N - an integer >= 0.
Results: Answer - the value of X^N.
Intermediates: temp - the value of the recursive calls. }
var
temp : real;
begin { procedure PowerFast }
if N = 0 then
Answer := 1
else if (N mod 2) = 0 then
begin
PowerFast(X, N div 2, temp);
Answer := temp * temp;
end { if N mod 2 = 0 }
else
begin
PowerFast(X, ((N-1) div 2), temp);
Answer := temp * temp * X;
end; { else }
end; { procedure PowerFast }
{**********************************************************************************}
procedure Stars(K:integer);
{ Print out K rows of K stars. }
{ Data Dictionary
Givens: K - an integer.
Results: (none)
Intermediates: i,j - outer and inner index, respectively, in the nested for loop
used to print out K by K stars. }
var
i,j : integer;
begin { procedure Stars }
for i := 1 to K do
begin
for j := 1 to K do
write('*');
writeln;
end; { for i := 1 to K }
end; { procedure Stars }
{*********************************************************************************}
{ program PowerStars: using procedures PowerFast and Stars, calculate X^N and then
print out that many stars. }
{ Data Dictionary
Givens: X - a user-defined integer that is >= 1.
N - a user-defined integer that is >= 0.
Results: Ans - the value of X^N.
Intermediates: AnsOdd - the value of X^(N-1), used to produce X^N stars when N is odd.
K2 - the value to pass to Stars to print X^N stars.
L - number of times to loop through Stars.
E - an index for the loop through Stars.
Uses: Stars, PowerFast }
var
X, N, L, E : integer;
Ans, AnsOdd, K2 : real;
begin { Main Program }
{ input }
Write ('Please enter the value for X: ');
Readln (X);
Write ('Please enter the value for N: ');
Readln (N);
{ computations }
PowerFast(X, N, Ans);
if (N mod 2) = 0 then { N even}
begin
K2 := SQRT(Ans);
L := 1;
end { if }
else { N odd }
begin
PowerFast(X, N-1, AnsOdd);
K2 := SQRT(AnsOdd);
L := X;
end; { else }
{ write out the results }
writeln;
writeln('************************************************');
writeln('Mark Sattolo 428500');
writeln('CSI-1100A DGD-1 TA: Chris Lankester');
writeln('Assignment 8, Question 1');
writeln('************************************************');
writeln;
writeln('The value of ', X, '^', N, ' is ', Ans:1:0, '.');
writeln;
writeln('Here are ', Ans:1:0, ' stars:');
writeln;
for E := 1 to L do
Stars(Round(K2));
end.
|
{-----------------------------------------------------------------------------
Project: New Data Pull
Unit Name: formMain
Author: J. L. Vasser, FMCSA
Date: 2017-10-02
Purpose: This utility reads data from the Production SAFER database schema
to create a Carrier Data database for Aspen 3.x (and future ISS 4.x)
This utility requires the user to be connected to the AWS environment,
either by VPN or by running this from a server within the AWS cloud.
The Aspen ISS_FED_DATA.FDB Firebird data file must be present and
accessible to the utility. An Oracle TNSNAMES.ORA file with the
connection information for production SAFER must be in the same
directory with the application.
History: This is based on code and concept of Dottie West, UGPTI (NDSU)
The utility was modified to use Devart UniDAC components for faster
response.
Additionally, the GUI was modified some to provide progress feedback.
2018-02-05 JLV -
Changes to SAFER Queries. See data module.
2018-02-07 JLV -
Modifed query on UCR to limit the amount of (useless) data returned.
See DoUCRLoad function.
2018-02-14 JLV -
Removed unused procedures and functions. General code clean-up
2018-08-13 JLV -
Added Secure BlackBox Zip component to dlgZipProgess.
File compression within this utility now works
2019-02-03 JLV -
Modifications to also create ISS data in SQLite format for speed
and smaller size. The Firebird database is being maintained for
compatibility with Aspen 3.0. The SQLite version will be for Aspen
versions 3.2 and later. (There is no 3.1).
2019-02-04 JLV -
Added global variable "dbSelected". Set by radio buttons on the
main form, 0 indicates the user has selected the Firebird database
while 1 indicates the user has selected the SQLite database.
2019-04-16 JLV -
Added short code snippet and dialog to allow for quick changing
between AWS and ADDOT
2019-04-24 JLV -
Due to issues with starting the application, renamed data module
"dmPull" to "dmSAFER" and recreated the Oracle UniDAC connection.
2019-04-29 JLV -
Added new data module "dmReference" [dataModReference.pas] to
have a static USDOT# set for creating all child tables
-----------------------------------------------------------------------------}
unit formMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, System.UITypes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, RzLabel, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Mask,
RzDTP, RzEdit, RzPrgres, RzButton, RzPanel, RzDlgBtn, RzTabs, RzBtnEdt,
RzShellDialogs, Uni, DALoader, UniLoader, Data.DB, MemDS, DBAccess,
System.Zip, Vcl.Buttons, Vcl.Menus;
type
TfrmMain = class(TForm)
ButtonBar: TRzDialogButtons;
btnStart: TRzBitBtn;
memoLog: TRzRichEdit;
RzLabel1: TRzLabel;
edtDataDate: TRzEdit;
progBarOverall: TRzProgressBar;
RzLabel2: TRzLabel;
RzLabel3: TRzLabel;
edtDataPath: TRzButtonEdit;
lblDataPath: TLabel;
dlgDataPath: TRzOpenDialog;
btnGetMonthYear: TSpeedButton;
btnMakeZip: TBitBtn;
progBarTable: TProgressBar;
lblPrct: TRzLabel;
lblTotalRecords: TRzLabel;
grpTargetSystem: TRadioGroup;
Label1: TRzLabel;
menuMain: TMainMenu;
menuFile: TMenuItem;
menuFileEnv: TMenuItem;
menuFileSeparator1: TMenuItem;
menuFileExit: TMenuItem;
menuFileZip: TMenuItem;
menuHelp: TMenuItem;
menuHelpHowTo: TMenuItem;
menuHelpSeparator1: TMenuItem;
menuHelpAbout: TMenuItem;
menuFileRefTbl: TMenuItem;
procedure btnStartClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtDataPathButtonClick(Sender: TObject);
procedure ButtonBarClickOk(Sender: TObject);
procedure btnGetMonthYearClick(Sender: TObject);
procedure btnMakeZipClick(Sender: TObject);
procedure grpTargetSystemClick(Sender: TObject);
procedure edtDataPathEnter(Sender: TObject);
procedure menuFileEnvClick(Sender: TObject);
procedure menuFileRefTblClick(Sender: TObject);
private
{ Private declarations }
function MakeDataDate: String;
function DoCarrierLoad: Boolean;
function DoLegalNameLoad: Boolean;
function DoDbaNameLoad: Boolean;
function DoISSLoad: Boolean;
function DoHMLoad: Boolean;
function DoInsLoad: Boolean;
function DoUcrLoad: Boolean;
function DoBasicsLoad: Boolean;
function DoRefLoad: Boolean; //2019-05-07 JLV: load ref table first.
function CheckSnapshot: string;
procedure BetweenSteps;
public
{ Public declarations }
StartTime: TDateTime;
EndTime: TDateTime;
ZipComplete: Boolean;
dbSelected: integer; //dbSelected 0 := Firebird, 1 := SQLite;
dmSelected: TDataModule; // sets the selected data module
LogPath: string;
procedure ClearData(tblname: string);
procedure WriteStatus(msg: string; XtraLine: Boolean);
procedure ShowProgress;
procedure TableProgress;
procedure ProcessBatch;
procedure CallActivateIndex;
function GetTimeElapsed: string;
function CreateZipFile: Boolean;
function TimeStamp: string;
function SetGenId: Boolean;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses dataModSAFER, dialogZipProgress, dataModISS_Firebird, dataModISS_SQLite,
dialogEnvironment, dataModReference;
{-----------------------------------------------------------------------------
Function: DoRefLoad
Author: J. L. Vasser, FMCSA, 2019-05-07
Comments: Loads basic data in the Reference DB "Snapshot" table.
This is then used for building all other datasets.
-----------------------------------------------------------------------------}
function TfrmMain.DoRefLoad: Boolean;
var i,t : integer;
begin
Result := False;
if CheckSnapshot = 'KEEP' then begin //check for existing data.
Result := True;
Exit; // If user elects to keep, exit procedure
end;
i := 1;
t := 0;
Result := False;
Application.ProcessMessages;
try
Screen.Cursor := crSqlWait;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not dmSAFER.qryCensus.Active then
dmSAFER.qryCensus.Open;
dmSAFER.qryCensus.First;
if not dmReference.dbReference.Connected then
dmReference.dbReference.Connect;
if dmReference.refTransaction.Active then
dmReference.refTransaction.Rollback;
finally
Screen.Cursor := crDefault;
end;
with dmSAFER.qryCensus do begin
if not dmReference.qrySnapshot.Active then
dmReference.qrySnapshot.Open;
WriteStatus('Loading Reference Table ......',False);
ProgBarTable.Max := RecordCount;
ProgBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
Application.ProcessMessages;
repeat
if not dmReference.refTransaction.Active then
dmReference.refTransaction.StartTransaction;
dmReference.qrySnapshot.Append;
dmReference.qrySnapshot.FieldByName('CARRIER_ID_NUMBER').AsInteger := FieldByName('CARRIER_ID_NUMBER').AsInteger;
dmReference.qrySnapshot.FieldByName('USDOTNUM').AsString := FieldByName('USDOTNUM').AsString;
dmReference.qrySnapshot.FieldByName('STATUS').AsString := FieldByName('STATUS').AsString;
dmReference.qrySnapshot.FieldByName('LAST_UPDATE_DATE').AsString := FieldByName('LAST_UPDATE_DATE').AsString;
dmReference.qrySnapshot.Post;
Inc(i);
Inc(t);
if i = 10000 then begin
if dmReference.refTransaction.Active then
dmReference.refTransaction.Commit;
WriteStatus('Loaded 10,000 Census records and committed.'+#10#13+'Total '+IntToStr(t)+' records '+DateTimeToStr(now),True);
i := 1;
end;
TableProgress;
Next;
until EOF;
try
WriteStatus('Saving reference table data ...',False);
if dmReference.refTransaction.Active then
dmReference.refTransaction.Commit;
Result := True;
WriteStatus('Successfully saved reference data.',True);
except on E: Exception do begin
MessageDlg('Error commiting dbReference: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error commiting dbReference: "'+E.Message+'"',True);
end;
end;
end;
dmSAFER.qryCensus.Close;
end;
{-----------------------------------------------------------------------------
Procedure: CheckSnapshot
Author: J. L. Vasser, FMCSA, 2019-05-07
Comments: Checks for data in the snapshot file, shows date.
Allows user to clear the table and start fresh, or reuse the data.
-----------------------------------------------------------------------------}
function TfrmMain.CheckSnapshot: string;
var d : string;
c : integer;
begin
Result := '';
d := '';
c := 0;
WriteStatus('Checking Snapshot Reference table',True);
if not dmReference.dbReference.Connected then
dmReference.dbReference.Connect;
with dmReference.qrySnapshot do begin
if not Active then Open;
c := RecordCount;
if c > 0 then begin
//First; in theory, the date of the last record should have the latest Last Update Date
Last;
d := DateTimeToStr(FieldByName('LAST_UPDATE_DATE').AsDateTime);
writestatus('Reference table contains '+IntToStr(c)+' records dated '+d,False);
if MessageDlg('Snapshot contains '+IntToStr(c)+' records dated '+d+'. Empty the Snapshot table?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin
dmReference.sqlDelete.Execute;
writestatus('User selected to purge table',true);
Result := 'PURGE';
end
else begin
WriteStatus('User selected to retain records',true);
ShowMessage('Snapshot records retained');
Result := 'KEEP';
end;
end
else
WriteStatus('Reference table is empty. Process continues',True);
if Active then Close;
end;
end;
{-----------------------------------------------------------------------------
Procedure: grpTargetSystemClick
Author: J. L. Vasser, FMCSA, 2019-02-04
Comments: Sets the value of the global variable "dbSelected".
This variable indicates to produce a Firedbird or SQLIte output
-----------------------------------------------------------------------------}
procedure TfrmMain.grpTargetSystemClick(Sender: TObject);
var dmISS_FB : TdmISS_FB;
dmISS_SQLite : TdmISS_SQLite;
begin
dbSelected := grpTargetSystem.ItemIndex;
if dbSelected = 0 then begin
lblDataPath.Caption := 'Local Data Path (Firebird database)';
WriteStatus('User selected Aspen 3.0 target (Firebird)',True);
dmSelected := dmISS_FB;
end
else begin
lblDataPath.Caption := 'Local Data Path (SQLite database)';
dmSelected := dmISS_SQLite;
WriteStatus('User selected Aspen 3.2 target (SQLite)',True);
end;
if progBarOverall.PartsComplete > 0 then begin
progBarOverall.PartsComplete := 0;
progBarOverall.Percent := 0;
progBarTable.Position := 0;
end;
end;
{-----------------------------------------------------------------------------
Function: TimeStamp
Author: J. L. Vasser, FMCSA
Date: 2017-11-14
Arguments: None
Return: string
Comments: Returns the current time in ISO format
-----------------------------------------------------------------------------}
function TfrmMain.TimeStamp:string;
var TimeNow : TDateTime;
TimeStr : string;
begin
TimeNow := now; // Need this for the following function
DateTimeToString(TimeStr,'yyyy-mm-dd_hh-mm-ss',TimeNow); // this statement wouldn't work with the function "now"
Result := TimeStr;
end;
{-----------------------------------------------------------------------------
Function: MakeDataDate
Author: J. L. Vasser, FMCSA
Date: 2017-11-13
Arguments: None
Return: string
Comments: Creates the default Data Date label of MonthYear
-----------------------------------------------------------------------------}
function TfrmMain.MakeDataDate:string;
var monthYear : string ;
begin
Result := '';
DateTimeToString(monthYear,'mmmmyyyy',now);
Result := monthYear;
end;
{-----------------------------------------------------------------------------
Procedure: btnGetMonthYearClick
Author: J. L. Vasser, FMCSA, 2017-11-13
Comments: Calls the MakeDataDate function
-----------------------------------------------------------------------------}
procedure TfrmMain.btnGetMonthYearClick(Sender: TObject);
begin
edtDataDate.Text := MakeDataDate;
end;
{-----------------------------------------------------------------------------
Procedure: ButtonBarClickOk
Author: J. L. Vasser, FMCSA, 2017-10-12
Comments: Check for data connections and close utility
-----------------------------------------------------------------------------}
procedure TfrmMain.ButtonBarClickOk(Sender: TObject);
begin
if not ZipComplete then begin
if MessageDlg('Create Zip file now?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin
if not CreateZipFile then
WriteStatus('Zip file creation failed. Try external to this utility', true);
end
else begin
MessageDlg('Remember to create the Zip file and ensure the name starts with "AspenCarrierDataUpdate"',mtInformation,[mbOK],0);
WriteStatus('Remember to create the Zip file and ensure the name starts with "AspenCarrierDataUpdate"',False);
end;
end;
if MessageDlg('Save log file?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin
memoLog.Lines.SaveToFile(LogPath);
end;
dmSAFER.dbSAFER.Disconnect;
case dbSelected of
0 : with dmISS_FB.dbISS_LOCAL do begin
//if InTransaction then Commit;
//if Connected then Disconnect;
end;
1 : with dmISS_SQLite.dbISS_Local do begin
if Connected then Disconnect;
end;
end;
Close; {application}
end;
{-----------------------------------------------------------------------------
Function: CreateZipFile
Author: J. L. Vasser, FMCSA
Date: 2017-11-13
Arguments: None
Return: Boolean
Comments: Creates the Zip file and returns true if successful
2019-02-06 j -
Changes for SQLite version, using 7-zip
2019-02-06 j -
Corrected issue where the source file was never assigned to the
zipWriter component, thus all files in the directory were included.
-----------------------------------------------------------------------------}
function TfrmMain.CreateZipFile: Boolean;
var dlgZip : TdlgZipStatus;
sZipFile, sFdbFile, sDataDate : string;
begin
sZipFile := '';
sFdbFile := edtDataPath.Text;
if sFdbFile = '' then begin
MessageDlg('Source file name required.',mtError,[mbRetry],0);
Exit;
end;
sDataDate := edtDataDate.Text;
if sDataDate = '' then begin
MessageDlg('Data Date value is required.',mtError,[mbRetry],0);
Exit;
end;
try
dmISS_FB.dbISS_LOCAL.Close; // can't zip a file that is in use
dmISS_FB.dbReference.Close;
dmISS_SQLite.dbISS_Local.Close; // SQLite tables 2019-02-06
//dmISS_SQLite.dbReference.Close;
dmSAFER.dbSAFER.Close; // just for good measure
if dbSelected = 0 then
sZipFile := ExtractFilePath(Application.ExeName)+'zips\AspenCarrierDataUpdate_'+sDataDate+'.zip'
else
sZipFile := ExtractFilePath(Application.ExeName)+'zips\AspenCarrierDataUpdate_'+sDataDate+'.7z';
dlgZip := TdlgZipStatus.Create(nil);
Application.ProcessMessages;
try
if dbSelected = 0 then begin
dlgZip.zipWriter.CompressionAlgorithm := 8;
dlgZip.zipWriter.CompressionLevel := 9;
WriteStatus('Compression Algorithm set to DEFLATE',True);
end
else begin
dlgZip.zipWriter.CompressionAlgorithm := 14;
dlgZip.zipWriter.CompressionLevel := 9;
WriteStatus('Compression Algorithm set to LZMA',True);
end;
WriteStatus('Begin writing Zip file '+DateTimeToStr(Now),True);
if FileExists(sZipFile) then
DeleteFile(sZipFile);
with dlgZip do begin
SourceFile := sFdbFile;
Application.ProcessMessages;
ArchiveFile := sZipFile;
Application.ProcessMessages;
if ShowModal = mrOK then begin
WriteStatus('Zip file created at '+TimeStamp+#10#13+sZipFile,True);
Result := True;
end
else begin
Result := False;
WriteStatus('Failed to successfully create zip file',True);
end;
end;
except
on E:Exception do begin
WriteStatus('Exception creating Zip file',False);
WriteStatus(E.Message,True);
Result := False;
end;
end;
finally
dlgZip.Free;
ZipComplete := Result;
end;
end;
{-----------------------------------------------------------------------------
Procedure: btnMakeZipClick
Author: J. L. Vasser, FMCSA, 2017-11-13
Comments: calls the CreateZipFile function
-----------------------------------------------------------------------------}
procedure TfrmMain.btnMakeZipClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
try
if CreateZipFile = True then
MessageDlg('File successfully Zipped.'+#10#13+'See log for file name',mtInformation,[mbOK],0)
else
MessageDlg('Failed to create zip file.'+#10#13+'Please create the zip file outside this utility',mtWarning,[mbOK],0);
finally
Screen.Cursor := crDefault;
end;
end;
{-----------------------------------------------------------------------------
Procedure: WriteStatus
Author: J. L. Vasser, FMCSA
Date: 2017-10-12
Arguments: msg: string;XtraLine: Boolean
Comments: Writes status information to window, for optional save to log.
2018-02-13 JLV -
Added lines to move cursor to end. This updates the display to show the latest line.
-----------------------------------------------------------------------------}
procedure TfrmMain.WriteStatus(msg: string; XtraLine: Boolean);
var lin, col : integer; // cursor position variables
begin
memoLog.Lines.Add(msg);
if XtraLine = True then
memoLog.Lines.Add('');
lin := memoLog.Line; // cursor line position
col := memoLog.Column; // cursor column position
memoLog.JumpTo(lin,col); // force the cursor to that position
memoLog.Repaint; // force the display to refresh
end;
{-----------------------------------------------------------------------------
Procedure: ClearData
Author: J. L. Vasser, FMCSA
Date: 2017-10-13
Arguments: tblname: string
Result: None
Comments: Deletes all data from existing database
2019-02-04 j -
Moved the body to the data module for each database target
-----------------------------------------------------------------------------}
procedure TfrmMain.ClearData(tblname: string);
begin
if dbSelected = 0 then
dmISS_FB.EmptyDatabase(tblname)
else
dmISS_SQLite.EmptyDatabase(tblname);
end;
{-----------------------------------------------------------------------------
Procedure: edtDataPathButtonClick
Author: J. L. Vasser, FMCSA
Date: 2017-10-13
Arguments: Sender: TObject
Result: None
Comments: Allows user to select the path to the local database
2018-01-24 JLV -
Added "dbReference" to the connection setup. This is used to
open a second query to the local "carriers" to provide a static
snapshot of the sourcedata as other tables are built over 15 hours.
2019-02-04 JLV -
Changes to support 2 database targets
2019-04-17 JLV -
Commented-out "dbReference" since I don't know why it's there.
-----------------------------------------------------------------------------}
procedure TfrmMain.edtDataPathButtonClick(Sender: TObject);
var db : string;
begin
dlgDataPath.InitialDir := GetCurrentDir;
if dbSelected = 0 then
dlgDataPath.Filter := 'Firebird Database|ISS_FED_DATA.FDB|All Files|*.*'
else
dlgDataPath.Filter := 'SQLite Database|ISS_FED_DATA.db|All Files|*.*';
dlgDataPath.Execute;
db := dlgDataPath.FileName;
edtDataPath.Text := db;
WriteStatus('User selected database at "'+edtDataPath.Text+'"',True);
if dbSelected = 0 then
try
with dmISS_FB.dbISS_LOCAL do begin
if Connected then Disconnect;
ConnectString := '';
Server := '';
ProviderName := 'Interbase';
SpecificOptions.Values['ClientLibrary'] := 'fbclient.dll';
Database := edtDataPath.Text;
UserName := 'SYSDBA';
Password := 'masterkey';
Connect;
end;
btnStart.Enabled := dmISS_FB.dbISS_LOCAL.Connected;
except on E: Exception do begin
MessageDlg('Database not found. "'+E.Message+'". Please try again',mtError,[mbRetry],0);
if edtDataPath.CanFocus then
edtDataPath.SetFocus;
end;
end
else // SQLite database (Aspen 3.2)
try
dmISS_SQLite.dbISS_LOCAL.Database := edtDataPath.Text;
dmISS_SQLite.dbISS_LOCAL.Connect;
btnStart.Enabled := dmISS_SQLite.dbISS_LOCAL.Connected;
except on E: Exception do begin
MessageDlg('Database not found. Please try again',mtError,[mbRetry],0); showmessage(E.Message);
if edtDataPath.CanFocus then
edtDataPath.SetFocus;
end;
end;
if btnStart.Enabled then
WriteStatus(' Target Database is opened',True);
end;
procedure TfrmMain.edtDataPathEnter(Sender: TObject);
begin
if dbSelected < 0 then
MessageDlg('You must select a database target first!',mtError,[mbRetry],0);
end;
{-----------------------------------------------------------------------------
Procedure: FormShow
Author: J. L. Vasser, FMCSA
Date: 2017-10-12
Arguments: Sender: TObject
Result: None
Comments: Application initialization steps
2019-04-29 JLV -
Changed loggin from RTF to TXT format
-----------------------------------------------------------------------------}
procedure TfrmMain.FormShow(Sender: TObject);
begin
btnStart.Enabled := False;
edtDataPath.Text := '';
ZipComplete := False;
LogPath := ExtractFilePath(application.ExeName)+'Logs\CarrierDataPullLog_'+TimeStamp+'.txt';
end;
procedure TfrmMain.ShowProgress;
begin
progBarOverall.IncPartsByOne;
end;
{-----------------------------------------------------------------------------
Procedure: TableProgress
Author: J. L. Vasser, FMCSA, 2017-10-12
Comments: Shows progress on the current table being imported
-----------------------------------------------------------------------------}
procedure TfrmMain.TableProgress;
var pct : double;
begin
progBarTable.StepIt;
pct := (progBarTable.Position * 100) div progBarTable.Max;
lblPrct.Caption := IntToStr(progBarTable.Position)+' ('+FormatFloat('0.###',(pct))+'%)';
lblPrct.Repaint;
progBarTable.Repaint;
Application.ProcessMessages;
end;
{-----------------------------------------------------------------------------
Function: GetTimeElapsed
Author: J. L. Vasser, FMCSA, 2017-10-12
Comments: Returns string of elapsed time since process started.
-----------------------------------------------------------------------------}
function TfrmMain.GetTimeElapsed: string;
var DeltaTime : TDateTime;
Hrs, Min, Sec, mSec : word;
begin
Result := '';
DeltaTime := EndTime - StartTime;
DecodeTime(DeltaTime,Hrs,Min,Sec,mSec);
Result := 'Time Elapsed: '+IntToStr(Hrs)+' hours, '+IntToStr(Min)+' minutes, '+IntToStr(Sec)+' seconds.';
end;
{-----------------------------------------------------------------------------
Procedure: btnStartClick
Author: J. L. Vasser, FMCSA
Date: 2017-10-12
Arguments: Sender: TObject
Result: None
Comments: The actual data extract process begins here
2017-11-20 JLV -
Replaced the LoadData function with specific functions for each dataset.
2017-11-22 JLV -
Added "OneByOne" variable. For unknown reason, the process can't find
a USDOT number when running sequentially. Running one-by-one doesn't
have that issue.
2018-01-30 JLV -
Commented "OneByOne" variable and related procedures now that
the data generation is working correctly.
2018-02-14 JLV -
Remove the one-by-one option entirely. Batch process now working as intended.
-----------------------------------------------------------------------------}
procedure TfrmMain.btnStartClick(Sender: TObject);
var sNow : string;
db : TUniConnection;
begin
if edtDataDate.Text = '' then begin
MessageDlg('Please enter a "Data Date"',mtError,[mbRetry],0);
if edtDataDate.CanFocus then
edtDataDate.SetFocus;
Exit;
end;
sNow := '';
StartTime := Now;
{ set the target database via its data module }
if dbSelected = 0 then
db := dmISS_FB.dbISS_LOCAL
else
db := dmISS_SQLite.dbISS_Local;
try
DateTimeToString(sNow, 'dddd, mmm d, yyyy, hh:mm:ss',StartTime);
WriteStatus('Starting Data Pull '+sNow, true);
//step 1.0
try
if not db.Connected then db.Connect;
ShowProgress;
except on E: Exception do begin
MessageDlg('Unable to connect to LOCAL ISS data',mtError,[mbAbort],0);
Exit;
end;
end;
// step 1.1
try
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
ShowProgress;
Application.ProcessMessages;
except on E: Exception do begin
MessageDlg('Unable to connect to SAFER database.'+#13#10+
'Ensure you are connected to the AWS VPN'+#13#10+
'App will now exit. Check VPN and restart.',mtError,[mbAbort],0);
WriteStatus('Unable to connect to SAFER database',False);
WriteStatus('Ensure you are connected to the AWS VPN',False);
WriteStatus('Check VPN and restart.',True);
DateTimeToString(sNow, 'dddd, mmm d, yyyy, hh:mm:ss',Now);
WriteStatus('Application terminated '+sNow,False);
memoLog.Lines.SaveToFile(LogPath);
Application.ProcessMessages;
Application.Terminate;
Exit;
end;
end;
//step 2.0
WriteStatus('Clearing Tables.................'+DateTimeToStr(now), false);
WriteStatus(' Carriers', false);
ClearData('CARRIERS');
Application.ProcessMessages;
ShowProgress;
//step 3
WriteStatus(' ISS', false);
ClearData('ISS');
Application.ProcessMessages;
ShowProgress;
//step 4
WriteStatus(' Insurance', false);
ClearData('CARRINS');
Application.ProcessMessages;
ShowProgress;
Application.ProcessMessages;
//step 5
WriteStatus(' UCR', false);
ClearData('UCR');
Application.ProcessMessages;
ShowProgress;
//step 6
WriteStatus(' HM Permit', false);
ClearData('HMPERMIT');
Application.ProcessMessages;
ShowProgress;
// step 7
WriteStatus(' Carrier Names', false);
ClearData('CARRNAME');
Application.ProcessMessages;
ShowProgress;
// step 8
WriteStatus(' BASICs', false);
ClearData('BASICSDETAIL');
Application.ProcessMessages;
ShowProgress;
// step 9
Application.ProcessMessages;
WriteStatus('..... Tables emptied', true);
//inactivate the indexes//
frmMain.Repaint;
WriteStatus('Inactivating Indexes..............', false);
if dbSelected = 0 then
dmISS_FB.scriptInactivateIdx.Execute // also resets the UCR Table generator to zero //
else
dmISS_SQLite.scriptInactivateIndex.Execute;
ShowProgress;
Application.ProcessMessages;
WriteStatus('..... DONE', true);
ShowProgress;
// step 10.0
if MessageDlg('Ready to begin loading data. Continue?',mtConfirmation,[mbOK,mbCancel],0) = mrCancel then begin
WriteStatus('User aborted operation at '+TimeStamp,true);
Exit;
end;
frmMain.Repaint;
Application.ProcessMessages;
// step 10.1
WriteStatus('Updating Data Date...............', false);
if dbSelected = 0 then begin
with dmISS_FB.sqlDataDate do begin
ParamByName('newDate').Clear;
ParamByName('newDate').AsString := edtDataDate.Text;
Execute;
dmISS_FB.dbISS_LOCAL.Commit;
end;
end
else begin
with dmISS_SQLite.sqlDataDate do begin
dmISS_SQLite.dbISS_Local.StartTransaction;
ParamByName('newDate').Clear;
ParamByName('newDate').AsString := edtDataDate.Text;
Execute;
dmISS_SQLite.dbISS_Local.Commit;
end;
end;
Application.ProcessMessages;
WriteStatus('...............DONE', true);
//step 10.2
ShowProgress;
if not DoRefLoad then begin
MessageDlg('An error occurred loading the SNAPSHOT QUERY table',mtError,[mbAbort],0);
Exit;
end;
BetweenSteps;
//step 11
ProcessBatch;
// step 19
WriteStatus('Process Complete! '+ DateTimeToStr(now), true);
frmMain.Repaint;
finally
dmSAFER.dbSAFER.Close; // step 20
//ShowProgress;
if dmISS_FB.dbISS_LOCAL.Connected then
dmISS_FB.dbISS_LOCAL.Close;
if dmISS_SQLite.dbISS_LOCAL.Connected then
dmIss_SQLite.dbISS_Local.Close;
ShowProgress;
EndTime := Now;
WriteStatus(GetTimeElapsed,true);
end;
end;
{-----------------------------------------------------------------------------
Function: DoISSLoad
Author: J. L. Vasser, FMCSA, 2017-11-15
Comments: Populate ISS Local table with ISS Score Values
2018-01-16 JLV -
Changed to use the already-populated CARRIERS table USDOT number
as the parameter for selecting the ISS data to load.
2018-01-24 JLV -
Moved "qryISS_DOTNUM" to new "dbReference" connection.
Commits to the dbISS_Local connection were closing the qryReference
not allowing it to loop to the next record.
-----------------------------------------------------------------------------}
function TfrmMain.DoISSLoad: Boolean;
var d, i, t : integer;
dPad, dot : string;
db, ref : TUniConnection;
qry, sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblISS;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblISS;
end;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
sfr := dmSAFER.qryISS;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
if not qry.Active then
qry.Open;
qry.First;
Result := False;
i := 0;
t := 0;
//d := 0;
//dot := '';
//dPad := '';
try
with qry do begin
if not Active then
Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
{
d := 0;
dPad := FieldByName('USDOTNUM').AsString;
TryStrToInt(dPad, d);
dot := IntToStr(d);
if dmSAFER.qryISS.Active then begin
dmSAFER.qryISS.Close;
end;
dmSAFER.qryISS.ParamByName('sDOT').Clear;
dmSAFER.qryISS.ParamByName('sDOT').AsString := dot;
dmSAFER.qryISS.Open;
}
if qry.RecordCount > 0 then begin
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := dPad;
tbl.FieldByName('TOTAL_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('QUANTITY_INSPECTIONS_LAST30').AsFloat);
tbl.FieldByName('VEHICLE_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('VEHICLE_INSPECTIONS_LAST30').AsFloat);
tbl.FieldByName('DRIVER_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('DRIVER_INSPECTIONS_LAST30').AsFloat);
tbl.FieldByName('HAZMAT_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('QUANTITY_HAZMAT_PRESENT_LAST30').AsFloat);
tbl.FieldByName('OOS_TOTAL').AsString := FloatToStr(sfr.FieldByName('OOS_ALL_TYPES_LAST30').AsFloat);
tbl.FieldByName('OOS_VEHICLE').AsString := FloatToStr(sfr.FieldByName('OOS_VEHICLE_INSPECTIONS_LAST30').AsFloat);
tbl.FieldByName('OOS_DRIVER').AsString := FloatToStr(sfr.FieldByName('OOS_DRIVER_INSPECTIONS_LAST30').AsFloat);
tbl.FieldByName('SAFETY_RATING').AsString := sfr.FieldByName('SAFETY_RATING').AsString;
tbl.FieldByName('RATING_DATE').AsDateTime := sfr.FieldByName('RATING_DATE').AsDateTime;
tbl.FieldByName('VIOL_BRAKES').AsString := FloatToStr(sfr.FieldByName('VIOLATION_BRAKES').AsFloat);
tbl.FieldByName('VIOL_WHEELS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_WHEELS').AsFloat);
tbl.FieldByName('VIOL_STEERING').AsString := FloatToStr(sfr.FieldByName('VIOLATION_STEERING').AsFloat);
tbl.FieldByName('VIOL_MEDICAL').AsString := FloatToStr(sfr.FieldByName('VIOLATION_MEDICAL_CERTIFICATE').AsFloat);
tbl.FieldByName('VIOL_LOGS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_LOGS').AsFloat);
tbl.FieldByName('VIOL_HOURS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_HOURS').AsFloat);
tbl.FieldByName('VIOL_DISQUAL').AsString := FloatToStr(sfr.FieldByName('VIOLATION_LICENSE').AsFloat);
tbl.FieldByName('VIOL_DRUGS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_DRUGS').AsFloat);
tbl.FieldByName('VIOL_TRAFFIC').AsString := FloatToStr(sfr.FieldByName('VIOLATION_TRAFFIC').AsFloat);
tbl.FieldByName('VIOL_HMPAPER').AsString := FloatToStr(sfr.FieldByName('VIOLATION_PAPERS').AsFloat);
tbl.FieldByName('VIOL_HMPLAC').AsString := FloatToStr(sfr.FieldByName('VIOLATION_PLACARDS').AsFloat);
tbl.FieldByName('VIOL_HMOPER').AsString := FloatToStr(sfr.FieldByName('VIOLATION_OP_EMER_RESP').AsFloat);
tbl.FieldByName('VIOL_HMTANK').AsString := FloatToStr(sfr.FieldByName('VIOLATION_TANK').AsFloat);
tbl.FieldByName('VIOL_HMOTHR').AsString := FloatToStr(sfr.FieldByName('VIOLATION_OTHER').AsFloat);
tbl.Post;
Inc(i);
end;
Inc(t);
TableProgress;
if i = 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 ISS records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next; //dmSAFER.qryISS_DOTNUM.Next;
until EOF;
db.Commit;
//if dmSAFER.TransactionLocal.Active then
// dmSAFER.TransactionLocal.Commit;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating ISS Scores table at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating ISS Scores Table at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoHMLoad
Author: J. L. Vasser, FMCSA, 2017-11-16
Comments: Populate ISS Local table with HM Violation data
-----------------------------------------------------------------------------}
function TfrmMain.DoHMLoad: Boolean;
var d, i, t : integer;
dPad, dot : string;
db, ref : TUniConnection;
qry, sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblHMPermit;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblHMPermit;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
Result := False;
i := 0;
t := 0;
//d := 0;
//dot := '';
//dPad := '';
try
with qry do begin
if not Active then
Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
{
d := 0;
dPad := FieldByName('USDOTNUM').AsString;
TryStrToInt(dPad, d);
dot := IntToStr(d);
if dmSAFER.qryHMPermit.Active then
dmSAFER.qryHMPermit.Close;
dmSAFER.qryHMPermit.ParamByName('sDOT').Clear;
dmSAFER.qryHMPermit.ParamByName('sDOT').AsString := dot;
dmSAFER.qryHMPermit.Open;
}
if dmSAFER.qryHMPermit.RecordCount > 0 then begin
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString;
tbl.FieldByName('PERMIT_TYPE').AsString := sfr.FieldByName('HM_PERMIT_TYPE').AsString;
tbl.FieldByName('PERMIT_STATUS').AsString := sfr.FieldByName('HM_PERMIT_STATUS').AsString;
if not tbl.FieldByName('HM_PERMIT_EFFECTIVE_DATE').IsNull then
tbl.FieldByName('EFFECTIVE_DATE').AsDateTime := sfr.FieldByName('HM_PERMIT_EFFECTIVE_DATE').AsDateTime;
if not tbl.FieldByName('HM_PERMIT_EXPIRATION_DATE').IsNull then
tbl.FieldByName('EXPIRATION_DATE').AsDateTime := sfr.FieldByName('HM_PERMIT_EXPIRATION_DATE').AsDateTime;
tbl.FieldByName('OPERATING_UNDER_APPEAL').AsString := sfr.FieldByName('OPERATING_UNDER_APPEAL_FLAG').AsString;
tbl.Post;
if tbl.State in [dsEdit,dsInsert] then
tbl.Post;
Inc(i);
end;
Inc(t);
TableProgress;
if i = 1000 then begin
db.Commit;
WriteStatus('Inserted 10,000 HM Permit records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next;
until EOF;
db.Commit;
//if dmSAFER.TransactionLocal.Active then
// dmSAFER.TransactionLocal.Commit;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating HM Permit table at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating HM Permit Table at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoCarrierLoad
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Populate ISS Local table with all Active Carriers
2018-01-18 JLV -
Programming note: The underlying query left-pads the USDOT number
with zeroes. This hampers use of the USDOTNUM field as a variable
to search other SOURCE tables. Keep this in mind.
-----------------------------------------------------------------------------}
function TfrmMain.DoCarrierLoad: Boolean;
var i,t : integer;
db, ref : TUniConnection;
qry : TUniQuery;
tbl : TUniTable;
sfr : TUniQuery;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblCarriers;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblCarriers;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
sfr := dmSAFER.qryCarrier;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
if not qry.Active then
qry.Open;
Result := False;
i := 0;
t := 0;
try
//with dmSAFER.qryCarrier do begin
with qry do begin
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('dot').Clear;
sfr.ParamByName('dot').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
if dbSelected = 1 then
dmISS_SQLite.dbISS_Local.StartTransaction;
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString;
tbl.FieldByName('ADDRESS').AsString := sfr.FieldByName('ADDRESS').AsString;
tbl.FieldByName('ZIPCODE').AsString := sfr.FieldByName('ZIPCODE').AsString;
tbl.FieldByName('COUNTRY').AsString := sfr.FieldByName('COUNTRY').AsString;
tbl.FieldByName('PHONE').AsString := sfr.FieldByName('PHONE').AsString;
{ to allow for Aspen 3.0 not accepting longer docket numbers }
if dbSelected = 0 then begin
if length(sfr.FieldByName('ICC_NUM').AsString) > 6 then
tbl.FieldByName('ICC_NUM').AsString := '';
end
else
tbl.FieldByName('ICC_NUM').AsString := trim(sfr.FieldByName('ICC_NUM').AsString);
{----------------------------------------------------------------------}
//tblCarriers.FieldByName('RFC_NUM').AsString := FieldByName(' {* there's no RFC_NUM in SAFER? *}
tbl.FieldByName('INSPECTION_VALUE').AsString := sfr.FieldByName('INSPECTION_VALUE').AsString;
tbl.FieldByName('INDICATOR').AsString := sfr.FieldByName('INDICATOR').AsString;
tbl.FieldByName('TOTAL_VEHICLES').AsInteger := sfr.FieldByName('TOTAL_VEHICLES').AsInteger;
tbl.FieldByName('TOTAL_DRIVERS').AsInteger := sfr.FieldByName('TOTAL_DRIVERS').AsInteger;
tbl.FieldByName('CARRIER_OPERATION').AsString := sfr.FieldByName('CARRIER_OPERATION').AsString;
tbl.FieldByName('NEW_ENTRANT_CODE').AsString := sfr.FieldByName('NEW_ENTRANT_CODE').AsString;
tbl.FieldByName('STATUS').AsString := sfr.FieldByName('STATUS').AsString;
if sfr.FieldByName('LAST_UPDATE_DATE').AsString <> '' then
tbl.FieldByName('LAST_UPDATE_DATE').AsDateTime := sfr.FieldByName('LAST_UPDATE_DATE').AsDateTime;
tbl.FieldByName('ENTITY_TYPE').AsString := sfr.FieldByName('ENTITY_TYPE').AsString;
tbl.FieldByName('UNDELIVERABLE_PA').AsString := sfr.FieldByName('UNDELIVERABLE_PA').AsString;
tbl.FieldByName('UNDELIVERABLE_MA').AsString := sfr.FieldByName('UNDELIVERABLE_MA').AsString;
tbl.FieldByName('HAS_POWER_UNITS').AsString := sfr.FieldByName('HAS_POWER_UNITS').AsString;
tbl.FieldByName('OPER_AUTH_STATUS').AsString := sfr.FieldByName('OPER_AUTH_STATUS').AsString;
if sfr.FieldByName('OOS_DATE').AsString <> '' then
tbl.FieldByName('OOS_DATE').AsDateTime := sfr.FieldByName('OOS_DATE').AsDateTime;
tbl.FieldByName('OOS_TEXT').AsString := sfr.FieldByName('OOS_TEXT').AsString;
tbl.FieldByName('OOS_REASON').AsString := sfr.FieldByName('OOS_REASON').AsString;
tbl.FieldByName('MCSIP_STATUS').AsString := sfr.FieldByName('MCSIP_STATUS').AsString;
tbl.Post;
Inc(i);
Inc(t);
TableProgress;
if i = 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 Carriers records and committed.'+#10#13+'Total '+IntToStr(t)+' records '+DateTimeToStr(now),True);
i := 0;
end;
Next;
until EOF;
//until t = 10000;
if db.InTransaction then
db.Commit;
if dbSelected = 0 then begin
if dmISS_FB.TransactionLocal.Active then
dmISS_FB.TransactionLocal.Commit;
end
else begin
if dmISS_SQLite.transactionLocal.Active then
dmISS_SQLite.transactionLocal.Commit;
end;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating Carriers table at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating Carriers Table at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoLegalNameLoad
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Populate ISS Local table with Carrier Legal Name values
-----------------------------------------------------------------------------}
function TfrmMain.DoLegalNameLoad: Boolean;
var d,i,t : integer;
dot, dPad : string;
db, ref : TUniConnection;
qry : TUniQuery;
sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblCarriers;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblCarriers;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
sfr := dmSAFER.qryNAME;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
Result := False;
i := 0; // commit counter: issue a database commit when counter reaches 10K
t := 0; // progress counter: shows progress of iterating through the table
//d := 0;
//dot := '';
//dPad := '';
try
with qry do begin
if not Active then Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
if dbSelected = 1 then
dmISS_SQLite.dbISS_Local.StartTransaction;
{
d := 0;
dPad := FieldByName('USDOTNUM').AsString; //get zero-padded USDOT # from Carrier table
TryStrToInt(dPad, d); // convert zero-padded USDOT # to its integer value (d)
dot := IntToStr(d); // convert USDOT # from integer to string because some idiot designed the database that way
if dmSAFER.qryNAME.Active then
dmSAFER.qryNAME.Close;
dmSAFER.qryNAME.ParamByName('sDOT').Clear;
dmSAFER.qryNAME.ParamByName('sDOT').AsString := dot;
dmSAFER.qryNAME.Open;
}
if sfr.RecordCount > 0 then begin
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString;
tbl.FieldByName('NAME').AsString := sfr.FieldByName('NAME').AsString;
tbl.FieldByName('CITY').AsString := sfr.FieldByName('CITY').AsString;
tbl.FieldByName('STATE').AsString := sfr.FieldByName('STATE').AsString;
tbl.FieldByName('NAME_TYPE_ID').AsString := '1';
tbl.Post;
Inc(i);
end
else begin
WriteStatus('LEGAL NAME value not found for USDOT # '+dot+' at record '+IntToStr(t),False);
end;
Inc(t);
TableProgress;
if i = 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 Carrier Name records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next;
until EOF;
db.Commit;
if dbSelected = 0 then begin
if dmISS_FB.TransactionLocal.Active then
dmISS_FB.TransactionLocal.Commit;
end
else begin
if dmISS_SQLite.transactionLocal.Active then
dmISS_SQLite.transactionLocal.Commit;
end;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating Carrier Name table (Legal Name) at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating Carrier Name table (Legal Name)for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoDbaNameLoad
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Populate ISS Local table with Carrier Operating Name (DBA) values
2019-05-07 JLV -
Added variable "sfr" for dmSAFER.qryNAME2
-----------------------------------------------------------------------------}
function TfrmMain.DoDbaNameLoad: Boolean;
var d,i,t : integer;
dot, dPad : string;
db, ref : TUniConnection;
qry,sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblName2;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblName2;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
sfr := dmSAFER.qryNAME2;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
Result := False;
i := 0;
t := 0;
//d := 0;
//dot := '';
//dPad := '';
try
with qry do begin
if not Active then Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
if dbSelected = 1 then
dmISS_SQLite.dbISS_Local.StartTransaction;
{
d := 0;
dPad := FieldByName('USDOTNUM').AsString;
TryStrToInt(dPad, d);
dot := IntToStr(d);
if dmSAFER.qryName2.Active then begin
dmSAFER.qryName2.Close;
end;
dmSAFER.qryName2.ParamByName('sDOT').Clear;
dmSAFER.qryName2.ParamByName('sDOT').AsString := dot;
dmSAFER.qryName2.Open;
}
if qry.RecordCount > 0 then begin (* While each USDOT# must have a LEGAL NAME, many will not have a "DBA" name *)
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString;
tbl.FieldByName('NAME').AsString := sfr.FieldByName('NAME').AsString;
tbl.FieldByName('CITY').AsString := sfr.FieldByName('CITY').AsString;
tbl.FieldByName('STATE').AsString := sfr.FieldByName('STATE').AsString;
tbl.FieldByName('NAME_TYPE_ID').AsString := '2';
tbl.Post;
Inc(i);
end;
Inc(t);
TableProgress;
if i = 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 Carrier DBA Name records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next;
until EOF;
db.Commit;
//if dmSAFER.TransactionLocal.Active then
//dmSAFER.TransactionLocal.Commit;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating Carrier Name table (DBA Name) at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating Carrier Name table (DBA Name) for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoInsLoad
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Populate ISS Local table with Carrier Insurance data
-----------------------------------------------------------------------------}
function TfrmMain.DoInsLoad:Boolean;
var d,i,t : integer;
dot, dPad : string;
db, ref : TUniConnection;
qry,sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblCarrIns;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblCarrIns;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
sfr := dmSAFER.qryINS;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
Result := False;
i := 0;
t := 0;
//d := 0;
//dot := '';
//dPad := '';
try
with qry do begin
if not Active then Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
if dbSelected = 1 then
dmISS_SQLite.dbISS_Local.StartTransaction;
{
dPad := FieldByName('USDOTNUM').AsString;
TryStrToInt(dPad, d);
dot := IntToStr(d);
if dmSAFER.qryIns.Active then
dmSAFER.qryIns.Close;
dmSAFER.qryIns.ParamByName('sDOT').Clear;
dmSAFER.qryIns.ParamByName('sDOT').AsString := dot;
dmSAFER.qryIns.Open;
}
if sfr.RecordCount > 0 then begin
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString;
tbl.FieldByName('LIABILITY_STATUS').AsString := sfr.FieldByName('LIABILITY_STATUS').AsString;
tbl.FieldByName('LIABILITY_REQUIRED').AsInteger := sfr.FieldByName('LIABILITY_REQUIRED').AsInteger;
tbl.FieldByName('CARGO_STATUS').AsString := sfr.FieldByName('CARGO_STATUS').AsString;
tbl.FieldByName('BOND_STATUS').AsString := sfr.FieldByName('BOND_STATUS').AsString;
tbl.FieldByName('MEX_TERRITORY').AsString := sfr.FieldByName('MEX_TERRITORY').AsString;
tbl.Post;
Inc(i);
end;
Inc(t);
TableProgress;
if i = 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 Carrier Insurance records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next;
until EOF;
db.Commit;
//if dmSAFER.TransactionLocal.Active then
// dmSAFER.TransactionLocal.Commit;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating Carrier Insurance table at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating Carrier Insurance table for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoUcrLoad
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Populate ISS Local table with Carrier UCR Payment data
2018-01-30 JLV -
Added repeat loop around the insert statements.
USDOT# to UCR is a one-to-many relationship.
2018-02-07 JLV -
Changed dmSAFER.qryUCR to accept a parameter for "and REGISTRATION_YEAR > :iRegYear" clause.
The query has been running as "> 2011" since inception and this was
generating millions of records not used. The new query variable "iRegYear"
will be passed the result of a variable "iRgYr" which is calcualted
in this function as (current year - 3). This will then make the query
clause equivelent to "and REGISTRATION_YEAR > [current year - 3]"
For example, current year is 2018. iRgYr would calculate to 2015.
The query clause would interpret as "and REGISTRATION_YEAR > 2015"
resulting in UCR records for 2016, 2017, and 2018.
This concept was concurred upon by SMEs Mike Wilson (Indiana State Police),
Holly Skaar (Idaho State police), Ken Keiper (Washington State Patrol),
Renee Hill (Arkansas Highway Police), and Tom Kelly (FMCSA).
2018-02-12 JLV -
Made changes to fix the looping of adding records. What a mess.
-----------------------------------------------------------------------------}
function TfrmMain.DoUcrLoad: Boolean;
var d,i,t, ct, lp : integer;
dot, dPad : string;
iRgYr : integer;
db, ref : TUniConnection;
qry, sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblUCR;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblName2;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
sfr := dmSAFER.qryUCR;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
Result := False;
i := 0;
t := 0;
//d := 0;
//dot := '';
//dPad := '';
{ get current year value as integer }
iRgYr := (CurrentYear - 3); //System.SysUtils.CurrentYear
{ --------------------------------- }
try
with qry do begin
if not Active then
Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
if dbSelected = 1 then
dmISS_SQLite.dbISS_Local.StartTransaction;
d := 0;
lp := 1; // itteration through loop
ct := 0; // count of matching records
{
dPad := FieldByName('USDOTNUM').AsString;
TryStrToInt(dPad, d);
dot := IntToStr(d);
if dmSAFER.qryUCR.Active then begin
dmSAFER.qryUCR.Close;
end;
dmSAFER.qryUCR.ParamByName('sDot').Clear;
dmSAFER.qryUCR.ParamByName('sDOT').AsString := dot;
// narrow down year selection
dmSAFER.qryUCR.ParamByName('iRegYear').AsInteger := iRgYr;
//
dmSAFER.qryUCR.Open;
}
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('iRegYear').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
sfr.ParamByName('iRegYear').AsInteger := iRgYr;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
ct := sfr.RecordCount; //how many UCR records exist for this USDOT#?
if ct > 0 then begin // if more than Zero,
for lp := lp to ct do begin // loop this code once for each UCR record
if sfr.FieldByName('USDOTNUM').AsString <> '' then begin //double check that there is a valid record.
if not tbl.Active then tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString;
tbl.FieldByName('BASE_STATE').AsString := sfr.FieldByName('BASE_STATE').AsString;
tbl.FieldByName('PAYMENT_FLAG').AsString := sfr.FieldByName('PAYMENT_FLAG').AsString;
tbl.FieldByName('REGISTRATION_YEAR').AsString := sfr.FieldByName('REGISTRATION_YEAR').AsString;
if sfr.FieldByName('PAYMENT_DATE').AsString <> '' then
tbl.FieldByName('PAYMENT_DATE').AsDateTime := sfr.FieldByName('PAYMENT_DATE').AsDateTime;
tbl.FieldByName('INTRASTATE_VEHICLES').AsString := sfr.FieldByName('INTRASTATE_VEHICLES').AsString;
end;
tbl.Post;
sfr.Next;
Inc(i);
end; // if dot <> '' begin
end; // if count > zero
Inc(t);
TableProgress;
if i >= 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 Carrier UCR records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next;
until EOF;
db.Commit;
//if dmSAFER.TransactionLocal.Active then
// dmSAFER.TransactionLocal.Commit;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating Carrier UCR table at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating Carrier UCR table for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Function: DoBasicsLoad
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Populate ISS Local table with Carrier BASICs values
Primary key is USDOT # + BASIC
2018-01-30 JLV -
Added repeat loop around the insert statements.
USDOT# to BASICS is a one-to-many relationship.
-----------------------------------------------------------------------------}
function TfrmMain.DoBasicsLoad: Boolean;
var d,i,t, ct, lp : integer;
dot, dPad : string;
db, ref : TUniConnection;
qry,sfr : TUniQuery;
tbl : TUniTable;
begin
if dbSelected = 0 then begin
db := dmISS_FB.dbISS_LOCAL;
tbl := dmISS_FB.tblBasicsDetail;
end
else begin
db := dmISS_SQLite.dbISS_Local;
tbl := dmISS_SQLite.tblBasicsDetail;
end;
ref := dmReference.dbReference;
qry := dmReference.qrySnapshot;
sfr := dmSAFER.qryBASICS;
if not dmSAFER.dbSAFER.Connected then
dmSAFER.dbSAFER.Connect;
if not db.Connected then
db.Connect;
if not ref.Connected then
ref.Connect;
Result := False;
i := 0;
t := 0;
//d := 0;
//dot := '';
//dPad := '';
try
with qry do begin
if not Active then Open;
progBarTable.Max := RecordCount;
progBarTable.Position := 0;
lblTotalRecords.Caption := IntToStr(progBarTable.Max);
First;
repeat
sfr.Close;
sfr.ParamByName('sDOT').Clear;
sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger;
try
sfr.Open;
except on E: Exception do begin
MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0);
WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True);
Exit;
end;
end;
if dbSelected = 1 then
dmISS_SQLite.dbISS_Local.StartTransaction;
//d := 0;
lp := 1; //set the loop counter to 1, otherwise change the loop to "lp to (ct -1)"
ct := 0;
{
dPad := FieldByName('USDOTNUM').AsString; //showmessage('dPad = '+dPad);
TryStrToInt(dPad, d);
dot := IntToStr(d); //showmessage('dot = '+dot);
if dmSAFER.qryBASICS.Active then begin
dmSAFER.qryBASICS.Close;
end;
dmSAFER.qryBASICS.ParamByName('sDOT').Clear;
dmSAFER.qryBASICS.ParamByName('sDOT').AsString := dot;
dmSAFER.qryBASICS.Open;
}
//if dmSAFER.qryBASICS.RecordCount > 0 then begin
ct := dmSAFER.qryBASICS.RecordCount; //showmessage('ct = '+inttostr(ct));
if ct > 0 then begin //showmessage('ct > zero');
for lp := lp to ct do begin //showmessage('start for ... loop');
//repeat
if not tbl.Active then
tbl.Open;
tbl.Append;
tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; //showmessage('BASIC = '+inttostr(dmSAFER.qryBASICS.FieldByName('BASIC').AsInteger));
tbl.FieldByName('BASIC').AsInteger := sfr.FieldByName('BASIC').AsInteger;
tbl.FieldByName('BASICPERCENTILE').AsInteger := sfr.FieldByName('BASICPERCENTILE').AsInteger;
tbl.FieldByName('BASICSDEFIND').AsString := sfr.FieldByName('BASICSDEFIND').AsString;
if dmSAFER.qryBASICS.FieldByName('BASICSRUNDATE').AsString <> '' then
tbl.FieldByName('BASICSRUNDATE').AsDateTime := sfr.FieldByName('BASICSRUNDATE').AsDateTime;
if dmSAFER.qryBASICS.FieldByName('INVESTIGATIONDATE').AsString <> '' then
tbl.FieldByName('INVESTIGATIONDATE').AsDateTime := sfr.FieldByName('INVESTIGATIONDATE').AsDateTime;
tbl.FieldByName('ROAD_DISPLAY_TEXT').AsString := sfr.FieldByName('ROAD_DISPLAY_TEXT').AsString;
tbl.FieldByName('INVEST_DISPLAY_TEXT').AsString := sfr.FieldByName('INVEST_DISPLAY_TEXT').AsString;
tbl.FieldByName('OVERALL_DISPLAY_TEXT').AsString := sfr.FieldByName('OVERALL_DISPLAY_TEXT').AsString;
tbl.Post;
sfr.Next;
Inc(i);
end;
//until EOF;
end;
Inc(t);
TableProgress;
if i >= 10000 then begin
db.Commit;
WriteStatus('Inserted 10,000 Carrier BASICs records and committed '+DateTimeToStr(now),false);
i := 0;
end;
Next;
until EOF;
db.Commit;
if dbSelected = 0 then begin
if dmISS_FB.TransactionLocal.Active then
dmISS_FB.TransactionLocal.Commit;
end
else begin
if dmISS_SQLite.transactionLocal.Active then
dmISS_SQLite.transactionLocal.Commit;
end;
end;
Result := True;
except on E: Exception do begin
MessageDlg('Error updating Carrier BASICS table at record '+IntToStr(t)+':'+#13#10+E.Message,mtError,[mbAbort],0);
WriteStatus('Error updating Carrier BASICS table for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message,True);
Exit;
end;
end;
end;
{-----------------------------------------------------------------------------
Procedure: ProcessBatch
Author: J. L. Vasser, FMCSA, 2017-11-20
Comments: Call procedures to load datasets
-----------------------------------------------------------------------------}
procedure TfrmMain.ProcessBatch;
begin
// step 11 (continued)
WriteStatus('Loading Carrier data ............'+DateTimeToStr(now), false);
if not DoCarrierLoad then begin
WriteStatus('Carrier data load FAILED', false);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// Step 12
WriteStatus('Loading ISS Score data...........'+DateTimeToStr(now), false);
if not DoIssLoad then begin
WriteStatus('ISS Score data load FAILED', true);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// step 13
WriteStatus('Loading Carrier Name data .......'+DateTimeToStr(now), false);
if not DoLegalNameLoad then begin
WriteStatus('Carrier Name data load FAILED', false);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// step 14
WriteStatus('Loading Carrier DBA Name data...'+DateTimeToStr(now), false);
if not DoDbaNameLoad then begin
WriteStatus('Carrier DBA Name data load FAILED', false);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// step 15
WriteStatus('Loading HM Permit data...........'+DateTimeToStr(now), false);
if not DoHMLoad then begin
WriteStatus('HM Permit data load FAILED', true);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// step 16
WriteStatus('Loading Insurance data...........'+DateTimeToStr(now), false);
if not DoInsLoad then begin
WriteStatus('Insurance data load FAILED', false);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// step 17
WriteStatus('Loading UCR data.................'+DateTimeToStr(now), false);
if not DoUcrLoad then begin
WriteStatus('UCR data load FAILED', true);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
// step 18
WriteStatus('Loading BASICs Score data........'+DateTimeToStr(now), false);
if not DoBasicsLoad then begin
WriteStatus('BASICs Score data load FAILED', false);
WriteStatus(DateTimeToStr(now),true);
Exit;
end;
BetweenSteps;
end;
{-----------------------------------------------------------------------------
Procedure: BetweenSteps
Author: J. L. Vasser, FMCSA, 2018-02-14
Comments: Repetitive code between loading table steps
-----------------------------------------------------------------------------}
procedure TfrmMain.BetweenSteps;
begin
WriteStatus('..........DONE '+DateTimeToStr(now), true);
ShowProgress;
memoLog.Repaint;
Application.ProcessMessages;
end;
procedure TfrmMain.CallActivateIndex;
var bSuccess : Boolean;
begin
bSuccess := False;
if dbSelected = 0 then
bSuccess := dmISS_FB.RebuildIdx
else
bSuccess := dmISS_SQLite.RebuildIdx;
if bSuccess = False then
WriteStatus('Index Activation and Rebuild Failed',True)
else
WriteStatus('Index Activation and Rebuild was successful',True);
end;
{-----------------------------------------------------------------------------
Function: SetGenId
Author: J. L. Vasser, FMCSA
Date: 2018-02-20
Arguments: None
Return: Boolean
Comments: Sets the UCR table sequence (generator) ahead by 10 after completion.
Having the next value was causing a conflict in Aspen.
2019-02-05 j -
Is this needed for SQLite?
-----------------------------------------------------------------------------}
function TfrmMain.SetGenId: Boolean;
var i : integer;
begin
Result := False;
try
with dmISS_FB.qryGenValue do begin
SQL.Clear;
SQL.add('select GEN_ID(UCR_UCR_SEQ_NUM_GEN,0) from RDB$DATABASE');
ExecSql;
i := FieldByName('GEN_ID').AsInteger;
SQL.Clear;
SQL.Add('set generator UCR_UCR_SEQ_NUM_GEN to '+IntToStr(i+10));
ExecSQL;
Result := True;
end;
except on E: Exception do begin
MessageDlg('Unable to advance UCR table Generator.'+#13#10+'Set this value manually',mtError,[mbOK],0);
WriteStatus('Unable to advance UCR table Generator.'+#13#10+'Set this value manually',True);
end;
end;
end;
{-----------------------------------------------------------------------------
Procedure: menuFileEnvClick
Author: J. L. Vasser, FMCSA
Date: 2019-04-16
Arguments: Sender: TObject
Result: None
Comments: Allows user (me) to select the database by IP address for
development within the AD DOT network
-----------------------------------------------------------------------------}
procedure TfrmMain.menuFileEnvClick(Sender: TObject);
var dlgDBEnvironment : TdlgDBEnvironment;
begin
try
dlgDBEnvironment := TdlgDBEnvironment.Create(self);
try
if dlgDBEnvironment.ShowModal = mrOK then begin
Screen.Cursor := crSQLWait;
if dlgDBEnvironment.grpSelectEnv.ItemIndex = 0 then begin
dmSAFER.dbSAFER.Server := 'safer.safersys.org:1526/safer.safersys.org';
dmSAFER.dbSAFER.Connect;
end
else begin
dmSAFER.dbSAFER.Server := '10.75.161.103:1526/safer.safersys.org';
dmSAFER.dbSAFER.Connect;
end;
end;
except on E: Exception do begin
MessageDlg('Error connecting to the SAFER database: '+E.Message,mtError,[mbAbort],0);
Exit;
end;
end;
finally
Screen.Cursor := crDefault;
dlgDBEnvironment.Free;
end;
end;
{-----------------------------------------------------------------------------
Procedure: menuFileRefTblClick
Author: J. L. Vasser, FMCSA, 2019-05-03
Comments: Find reference database file location.
-----------------------------------------------------------------------------}
procedure TfrmMain.menuFileRefTblClick(Sender: TObject);
var db : string;
begin
dlgDataPath.InitialDir := GetCurrentDir;
dlgDataPath.Filter := 'SQLite Database|DataPullRef.db|All Files|*.*';
dlgDataPath.Execute;
db := dlgDataPath.FileName;
WriteStatus('User selected reference database at "'+db+'"',True);
try
dmReference.dbReference.Database := db;
dmReference.dbReference.Connect;
except on E: Exception do begin
MessageDlg('Reference Database not found. Please try again',mtError,[mbRetry],0); showmessage(E.Message);
end;
end;
end;
end.
|
unit DaemonScheduler;
interface
uses
Windows, Classes, ExtCtrls, SyncObjs, RDOInterfaces, WinSockRDOConnection, RDOObjectProxy,
DirServerSession, Daemons;
type
TDaemonScheduler =
class
public
constructor Create(MaxDaemonThreads : integer);
destructor Destroy; override;
public
function Start(const DSAddr : string; DSPort : integer) : boolean;
procedure Stop;
procedure Schedule(const Daemon : IDaemon);
private
fDaemons : TList;
procedure LoadDaemons(const DSAddr : string; DSPort : integer);
procedure FreeDaemons;
private
function GetDaemonCount : integer;
function GetDaemon(i : integer) : IDaemon;
public
property DaemonCount : integer read GetDaemonCount;
property Daemons[i : integer] : IDaemon read GetDaemon;
private
fTimer : TTimer;
fReadyDaemons : TList;
fReadyDaemonsLock : TCriticalSection;
fDaemonThreads : TList;
fDaemonReadyEvent : THandle;
fDoneEvent : THandle;
private
procedure SchedulerTimer(Sender : TObject);
procedure OnIdle(Sender: TObject; var Done: Boolean);
end;
const
cLogId = 'Daemon Scheduler';
implementation
uses
SysUtils, Logs, Clipbrd, Forms;
type
TDaemonThread =
class(TThread)
private
constructor Create(Scheduler : TDaemonScheduler);
private
fScheduler : TDaemonScheduler;
protected
procedure Execute; override;
end;
// TDaemonThread
constructor TDaemonThread.Create(Scheduler : TDaemonScheduler);
begin
inherited Create(true);
fScheduler := Scheduler;
Resume;
end;
procedure TDaemonThread.Execute;
var
DaemonThreadEvents : array [0..1] of THandle;
Daemon : IDaemon;
begin
with fScheduler do
begin
DaemonThreadEvents[0] := fDaemonReadyEvent;
DaemonThreadEvents[1] := fDoneEvent;
while not Terminated do
begin
fReadyDaemonsLock.Enter;
try
if fReadyDaemons.Count > 0
then
begin
Daemon := IDaemon(fReadyDaemons[0]);
fReadyDaemons.Delete(0);
end
else
begin
Daemon := nil;
ResetEvent(fDaemonReadyEvent);
end;
finally
fReadyDaemonsLock.Leave;
end;
if (Daemon <> nil) and not Daemon.IsRunning
then Daemon.Run;
WaitForMultipleObjects(2, @DaemonThreadEvents[0], false, INFINITE);
end;
end;
end;
// TDaemonScheduler
constructor TDaemonScheduler.Create(MaxDaemonThreads : integer);
var
i : integer;
begin
inherited Create;
fDaemons := TList.Create;
fTimer := TTimer.Create(nil);
fTimer.Enabled := false;
fTimer.Interval := 10;
fTimer.OnTimer := SchedulerTimer;
Application.OnIdle := OnIdle;
fReadyDaemons := TList.Create;
fReadyDaemonsLock := TCriticalSection.Create;
fDaemonThreads := TList.Create;
fDaemonReadyEvent := CreateEvent(nil, true, false, nil);
fDoneEvent := CreateEvent(nil, true, false, nil);
for i := 0 to pred(MaxDaemonThreads) do
fDaemonThreads.Add(TDaemonThread.Create(Self));
end;
destructor TDaemonScheduler.Destroy;
var
i : integer;
begin
Stop;
SetEvent(fDoneEvent);
for i := 0 to pred(fDaemonThreads.Count) do
TDaemonThread(fDaemonThreads[i]).Free;
CloseHandle(fDoneEvent);
CloseHandle(fDaemonReadyEvent);
fDaemonThreads.Free;
fReadyDaemonsLock.Free;
fReadyDaemons.Free;
fTimer.Free;
FreeDaemons;
fDaemons.Free;
inherited;
end;
function TDaemonScheduler.Start(const DSAddr : string; DSPort : integer) : boolean;
begin
try
if fDaemons.Count = 0
then LoadDaemons(DSAddr, DSPort);
if fDaemons.Count = 0
then Log(cLogId, 'No daemons loaded');
fTimer.Enabled := true;
Result := true;
except
Result := false;
end;
end;
procedure TDaemonScheduler.Stop;
begin
fTimer.Enabled := false;
end;
procedure TDaemonScheduler.Schedule(const Daemon : IDaemon);
begin
if not Daemon.IsRunning
then
begin
Log(cLogId, 'Scheduling daemon "' + Daemon.GetName + '"');
fReadyDaemonsLock.Enter;
try
fReadyDaemons.Add(pointer(Daemon));
if fReadyDaemons.Count > 0//= 1
then SetEvent(fDaemonReadyEvent);
finally
fReadyDaemonsLock.Leave;
end;
end;
end;
procedure TDaemonScheduler.LoadDaemons(const DSAddr : string; DSPort : integer);
var
info : TSearchRec;
ok : boolean;
dllhandle : THandle;
daemoncreator : TDaemonCreatorRoutine;
Daemon : IDaemon;
begin
ok := FindFirst('*.dll', faAnyFile, info) = 0;
try
while ok do
begin
dllhandle := LoadLibrary(pchar(info.Name));
if dllhandle <> 0
then
begin
daemoncreator := GetProcAddress(dllhandle, cDaemonCreatorRoutineName);
if @daemoncreator <> nil
then
begin
Daemon := daemoncreator(DSAddr, DSPort);
Daemon._AddRef;
fDaemons.Add(pointer(Daemon));
Log(cLogId, Daemon.GetName + ' loaded');
end;
end;
ok := FindNext(info) = 0;
end;
finally
FindClose(info);
end;
end;
procedure TDaemonScheduler.FreeDaemons;
var
i : integer;
begin
for i := 0 to pred(fDaemons.Count) do
begin
IDaemon(fDaemons[i])._Release;
fDaemons[i] := nil
end;
fDaemons.Pack;
end;
function TDaemonScheduler.GetDaemonCount;
begin
Result := fDaemons.Count;
end;
function TDaemonScheduler.GetDaemon(i : integer) : IDaemon;
begin
Result := IDaemon(fDaemons[i]);
end;
procedure TDaemonScheduler.SchedulerTimer(Sender : TObject);
var
i : integer;
elapsedticks : integer;
Daemon : IDaemon;
begin
if fDaemons <> nil
then
for i := 0 to pred(fDaemons.Count) do
begin
Daemon := IDaemon(fDaemons[i]);
elapsedticks := longint(GetTickCount) - Daemon.LastRun;
if elapsedticks >= Daemon.GetPeriod
then Schedule(Daemon);
end;
end;
procedure TDaemonScheduler.OnIdle(Sender: TObject; var Done: Boolean);
var
i : integer;
Daemon : IDaemon;
begin
for i := 0 to pred(fDaemons.Count) do
begin
Daemon := IDaemon(fDaemons[i]);
if not Daemon.IsRunning
then Daemon.SynchronizedRun;
end;
Done := true;
end;
end.
|
unit HmrcRestSupport;
(*****************************************************************************
* HMRC API REST Support Unit *
******************************************************************************
* Support types and values for the HMRC REST Client components *
* *
* created 24/11/18. *
* updated 12/01/19. *
* version 1.0.0 *
* *
* original copyright Ian Hamilton 2018/19. *
*****************************************************************************)
interface
(****************************************************************************)
uses
System.Classes, System.SysUtils, System.UITypes, System.Variants,
IPPeerClient, REST.Types, REST.Client, REST.Authenticator.OAuth,
System.JSON;
(****************************************************************************)
const
REST_ = 'REST';
csAccessToken = 'access_token';
csApJson = 'application/json';
csApVnd = 'application/vnd.hmrc.';
csAuthorization = 'Authorization';
csAuthorize = 'oauth/authorize';
csAuthToken = 'oauth/token';
csAuthCode = 'authorization_code';
csChargeRefNumber = 'chargeRefNumber';
csClientId = 'client_id';
csClientSecret = 'client_secret';
csCode = 'code';
csError = 'Error : ';
csExpiresIn = 'expires_in';
csFormBundleNumber = 'formBundleNumber';
csFrom = 'from';
csGrantType = 'grant_type';
csHello = 'hello';
csHmrcLogin = 'HMRC Service Login';
csIsoDate = 'YYYYMMDD';
csLBearer = 'bearer';
csLiabilities = 'liabilities';
csMessage = 'message';
csObligations = 'obligations';
csOrgsVat = 'organisations/vat/';
csPaymentIndicator = 'paymentIndicator';
csPayments = 'payments';
csProcessingDate = 'processingDate';
csReadVat = 'read:vat';
csReceiptId = 'Receipt-Id';
csRedirectUri = 'redirect_uri';
csRefreshToken = 'refresh_token';
csResponseType = 'response_type';
csReturns = 'returns';
csRiteVat = 'write:vat';
csScope = 'scope';
csStatus = 'status';
csTo = 'to';
csTokenType = 'token_type';
csUBearer = 'Bearer';
csWithJson = '+json';
csXCorrelationid = 'X-Correlationid';
csMsgBadData = 'The data is either invalid or incomplete';
csMsgBadPeriod = 'The VAT Period is invalid';
csMsgBadResponse = 'HTTP Reponse error.';
csMsgBadTarget = 'The target name is invalid.';
csMsgBadUserId = 'Invalid User ID found.';
csMsgDateError = 'Search date error - the start date must be before the end date.';
csMsgDateHigh = 'The start date is too late.';
csMsgDateLow = 'The start date is too early.';
csMsgDateRange = 'The search date range is too great.';
csMsgNewToken = 'Please get a new token.';
csMsgNoClient = 'A client id and secret must be supplied.';
csMsgNoData = 'No data was supplied for submission.';
csMsgNoPort = 'A valid callback port must be supplied.';
csMsgNoSvrToken = 'No server token found.';
csMsgNoTokenFnd = 'No access token found. PLease get an access token and try again.';
csMsgNoTokenRtn = 'No access token returned.';
csMsgNoUri = 'Base and callback URLs must be supplied.';
csMsgNoUserId = 'No User ID found.';
csMsgNoAcsToken = 'There is no access token for this user and scope. ';
csMsgNoRefresh = 'Unable to refresh the access token.';
csMsgNoRfsToken = 'There is no refresh token for this user and scope.';
csMsgRefreshErr = 'Error trying to refresh the access token : ';
csMsgTestUsrErr = 'Hello user test error : ';
csMsgTokenErr = 'Unknown token error - unable to continue.';
csMsgTokenExp = 'The access token for this user and scope has expired.';
HmrcProdUrl = 'https://api.service.hmrc.gov.uk';
HmrcTestUrl = 'https://test-api.service.hmrc.gov.uk';
ERR_NO_ACCESS_TOKEN = 1101;
ERR_NO_CALLBACK_PORT = 1102;
ERR_NO_CALLBACK_URL = 1103;
ERR_NO_CLIENT_ID = 1104;
ERR_NO_CLIENT_SECRET = 1105;
ERR_NO_DATA = 1106;
ERR_NO_REFRESH_TOKEN = 1107;
ERR_NO_SERVER_TOKEN = 1108;
ERR_NO_TARGET_URL = 1109;
ERR_NO_USER_ID = 1110;
ERR_TOKEN_EXPIRED = 1115;
ERR_DATE_ERROR = 1121;
ERR_DATE_LOW = 1122;
ERR_DATE_HIGH = 1123;
ERR_DATE_RANGE = 1124;
ERR_INVALID_USER_ID = 1131;
ERR_INVALID_PERIOD = 1132;
ERR_INVALID_TARGET = 1133;
ERR_INVALID_DATA = 1134;
RESULT_NONE = 0;
RESULT_OK = 1;
RESULT_FAIL = -1;
RESULT_ERROR = -3;
(****************************************************************************)
type
(***************************************************************************
** HMRC REST API service authentication modes **
***************************************************************************)
THmrcAuthMode = (amNone, amApplication, amUser);
(***************************************************************************
** HMRC REST API service current token status modes **
***************************************************************************)
THmrcTokenState = (tsNone, tsOK, tsRefresh, tsExpired, tsUpdated);
(***************************************************************************
** HMRC REST API token saving signature **
***************************************************************************)
THmrcTokenEvent = procedure(Sender: TObject; const uid, scp, atn, rtn: string; const exp, tmo: TDateTime) of object;
(***************************************************************************
** Relevant scopes as an array of string **
***************************************************************************)
TScopeArray = Array of string;
(***************************************************************************
** HMRC REST API user access tokens **
****************************************************************************
** A simple object to hold an access token. **
***************************************************************************)
THmrcAccessToken = class
public
UID : string; // User/ company/ Agent ID
Scope : string; // Authorisation scope
Access : string; // access token
Refresh : string; // refresh token
Expires : TDateTime; // when it can no longer be refreshed (18 months) // DateToStr
TimeOut : TDateTime; // When the current access token times out (4 hours) // Format[DD-MM-YYYY HH:NN:SS] DateTimeToStr
Status : THmrcTokenState; // current token state
end;
(***************************************************************************
** A list to hold access tokens. **
***************************************************************************)
THmrcAccessTokens = class (TList)
public
Destructor Destroy; override;
procedure AddToken(const aUID, aScope, aToken, aRefresh: string; const anExpiry, aTimeOut: TDateTime);
function FindToken(const aUID, aScope: string): THmrcAccessToken;
function GetAccessToken(const aUID, aScope: string): THmrcAccessToken;
end;
(***************************************************************************
** HMRC REST API Client Details **
****************************************************************************
** A simple object to hold the list of application/client details. **
***************************************************************************)
THmrcClientDetails = class
private
FClientId : string;
FClientSecret : string;
FCallbackPort : string;
FCallbackUrl : string;
FServerToken : string;
FBaseUrl : string;
public
property ClientId : string read FClientId write FClientId;
property ClientSecret : string read FClientSecret write FClientSecret;
property CallbackPort : string read FCallbackPort write FCallbackPort;
property CallbackUrl : string read FCallbackUrl write FCallbackUrl;
property ServerToken : string read FServerToken write FServerToken;
property BaseUrl : string read FBaseUrl write FBaseUrl;
end;
(****************************************************************************)
implementation
(****************************************************************************)
{ THmrcAccessTokens }
(*****************************************************************************
* HMRC REST API user access tokens *
******************************************************************************
* Clear up. *
*****************************************************************************)
destructor THmrcAccessTokens.Destroy;
var
idx: integer;
obj: THmrcAccessToken;
begin
if Count > 0 then
for idx := Count - 1 downto 0 do
begin
obj := THmrcAccessToken(Items[idx]);
Remove(obj);
obj.Free;
end;
inherited;
end;
(*****************************************************************************
* Add a new token to the list. *
*****************************************************************************)
procedure THmrcAccessTokens.AddToken(const aUID, aScope, aToken, aRefresh: string; const anExpiry, aTimeOut: TDateTime);
var
idx: integer;
dun: boolean;
obj: THmrcAccessToken;
begin
dun := false;
// check whether this combination already exists
if Count > 0 then
begin
for idx := 0 to Count - 1 do
begin
obj := THmrcAccessToken(Items[idx]);
if (AnsiSameText(obj.UID, aUID)) and (AnsiSameText(obj.Scope, aScope)) then
begin
dun := true;
Break;
end;
end;
end;
// need to add it to the list
if (not dun) then
begin
obj := THmrcAccessToken.Create;
obj.UID := aUID;
obj.Scope := aScope;
Self.Add(obj);
end;
obj.Access := aToken;
obj.Refresh := aRefresh;
obj.Expires := anExpiry;
obj.TimeOut := aTimeOut;
// chack status
if (anExpiry < Date) then
obj.Status := tsExpired
else if (aTimeOut < Now) then
obj.Status := tsRefresh
else
obj.Status := tsOK;
end;
(*****************************************************************************
* Add a new token to the list. *
*****************************************************************************)
function THmrcAccessTokens.FindToken(const aUID, aScope: string): THmrcAccessToken;
var
idx: integer;
dun: boolean;
obj: THmrcAccessToken;
begin
Result := nil;
dun := false;
// check whether this combination already exists
if Count > 0 then
begin
for idx := 0 to Count - 1 do
begin
obj := THmrcAccessToken(Items[idx]);
if (AnsiSameText(obj.UID, aUID)) and (AnsiSameText(obj.Scope, aScope)) then
begin
dun := true;
Result := obj;
Break;
end;
end;
end;
// need to add it to the list
if (not dun) then
begin
obj := THmrcAccessToken.Create;
obj.UID := aUID;
obj.Scope := aScope;
obj.Status := tsUpdated;
Self.Add(obj);
Result := obj;
end;
end;
(*****************************************************************************
* Find a token in the list. *
*****************************************************************************)
function THmrcAccessTokens.GetAccessToken(const aUID, aScope: string): THmrcAccessToken;
var
idx: integer;
obj: THmrcAccessToken;
begin
Result := nil;
if Count > 0 then
begin
for idx := 0 to Count - 1 do
begin
obj := THmrcAccessToken(Items[idx]);
if (AnsiSameText(obj.UID, aUID)) and (AnsiSameText(obj.Scope, aScope)) then
begin
Result := obj;
Break;
end;
end;
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
// FFormConfig.pas
// MTB communication library
// Main config form
// (c) Petr Travnik (petr.travnik@kmz-brno.cz),
// Jan Horacek (jan.horacek@kmz-brno.cz),
// Michal Petrilak (engineercz@gmail.com)
////////////////////////////////////////////////////////////////////////////////
{
LICENSE:
Copyright 2015 Petr Travnik, Michal Petrilak, Jan Horacek
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.
}
{
DESCRIPTION:
TFormConfig is a class representing main configuration form.
}
unit FFormConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Menus, StrUtils, FFormModule, ExtCtrls, MTBusb,
Version;
type
TFormConfig = class(TForm)
pm_mod: TPopupMenu;
pm_mod_nastaveni: TMenuItem;
PC_Main: TPageControl;
TS_Stav: TTabSheet;
TS_Device: TTabSheet;
TS_Modules: TTabSheet;
TS_Log: TTabSheet;
l_3: TLabel;
l_modcount: TLabel;
Label1: TLabel;
Label2: TLabel;
L_Openned: TLabel;
L_Started: TLabel;
cb_mtbName: TComboBox;
cb_speed: TComboBox;
b_ScanBrd: TButton;
l_2: TLabel;
RG_TimerInterval: TRadioGroup;
LV_Log: TListView;
Label3: TLabel;
Label4: TLabel;
B_DeleteNonExist: TButton;
L_LogLevel: TLabel;
CB_LogLevel: TComboBox;
lv_modules: TListView;
B_ClearLog: TButton;
CHB_ShowAllModules: TCheckBox;
procedure b_ScanBrdClick(Sender: TObject);
procedure lv_modulesDblClick(Sender: TObject);
procedure cb_mtbNameChange(Sender: TObject);
procedure pm_mod_nastaveniClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure RG_TimerIntervalClick(Sender: TObject);
procedure pm_modPopup(Sender: TObject);
procedure cb_speedChange(Sender: TObject);//cteni verze z nastaveni
procedure OnError(Sender: TObject; errValue: word; errAddr: byte);
procedure BeforeOpen(Sender:TObject);
procedure AfterOpen(Sender:TObject);
procedure BeforeClose(Sender:TObject);
procedure AfterClose(Sender:TObject);
procedure BeforeStart(Sender:TObject);
procedure AfterStart(Sender:TObject);
procedure BeforeStop(Sender:TObject);
procedure AfterStop(Sender:TObject);
procedure OnLog(Sender: TObject; logLevel:TLogLevel; logValue: string);
procedure LV_LogCustomDrawItem(Sender: TCustomListView; Item: TListItem;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure B_DeleteNonExistClick(Sender: TObject);
procedure CB_LogLevelChange(Sender: TObject);
procedure B_ClearLogClick(Sender: TObject);
procedure CHB_ShowAllModulesClick(Sender: TObject);
private
public
procedure UpdateModulesList();
procedure OnConfigLoad();
end;
var
FormConfig: TFormConfig;
implementation
{$R *.dfm}
uses LibraryEvents, LibCML, Errors;
////////////////////////////////////////////////////////////////////////////////
procedure TFormConfig.b_ScanBrdClick(Sender: TObject);
var
i,cnt: Integer;
begin
b_ScanBrd.Enabled := false;
cb_mtbName.Enabled := false;
cb_mtbName.Clear;
cnt := MTBdrv.GetDeviceCount();
if (cnt > 0) then
begin
for i := 0 to cnt-1 do
begin
cb_mtbName.Items.Add(MTBdrv.GetDeviceSerial(i));
if (MTBdrv.GetDeviceSerial(i) = MTBdrv.UsbSerial) then
cb_mtbName.ItemIndex := i;
end;
end;
cb_mtbName.Enabled := true;
b_ScanBrd.Enabled := true;
end;
procedure TFormConfig.CB_LogLevelChange(Sender: TObject);
begin
MTBdrv.LogLevel := TLogLevel(Self.CB_LogLevel.ItemIndex);
end;
procedure TFormConfig.lv_modulesDblClick(Sender: TObject);
begin
if (lv_modules.Selected <> nil) then
FormModule.OpenForm(StrToInt(lv_modules.Items.Item[lv_modules.ItemIndex].SubItems.Strings[0]));
end;
procedure TFormConfig.cb_speedChange(Sender: TObject);
begin
MTBdrv.MtbSpeed := TMtbSpeed(Self.cb_speed.ItemIndex+2);
end;
procedure TFormConfig.CHB_ShowAllModulesClick(Sender: TObject);
begin
Self.UpdateModulesList();
end;
procedure TFormConfig.cb_mtbNameChange(Sender: TObject);
begin
MTBdrv.UsbSerial := cb_mtbName.text;
end;
procedure TFormConfig.pm_mod_nastaveniClick(Sender: TObject);
begin
FormModule.OpenForm(StrToInt(lv_modules.Items.Item[lv_modules.ItemIndex].SubItems.Strings[0]));
end;
procedure TFormConfig.FormCreate(Sender: TObject);
begin
Self.Caption := Self.Caption+' v'+Version.GetLibVersion();
Self.PC_Main.ActivePageIndex := 0;
Self.OnConfigLoad();
end;
procedure TFormConfig.OnConfigLoad();
var
i: integer;
begin
Self.cb_speed.ItemIndex := Integer(MTBdrv.MtbSpeed)-2;
case (Mtbdrv.ScanInterval) of
ti50 :Self.RG_TimerInterval.ItemIndex := 0;
ti100:Self.RG_TimerInterval.ItemIndex := 1;
ti200:Self.RG_TimerInterval.ItemIndex := 2;
ti250:Self.RG_TimerInterval.ItemIndex := 3;
end;
//zjisteni pripojenych MTB zarizeni
b_ScanBrdClick(self);
for i := 0 to cb_mtbName.Items.Count-1 do
begin
if (cb_mtbName.Items.Strings[i] = MTBdrv.UsbSerial) then
begin
cb_mtbName.ItemIndex := i;
Break;
end;
end;
Self.CB_LogLevel.ItemIndex := Integer(MTBdrv.LogLevel);
end;
procedure TFormConfig.LV_LogCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
var logLevel:TLogLevel;
begin
(Sender as TCustomListView).Canvas.Brush.Color := clWhite;
if (Item.SubItems.Count > 0) then
begin
try
logLevel := TLogLevel(ord(Item.SubItems.Strings[0][1]) - ord('0'));
if (logLevel = MTBusb.llError) then (Sender as TCustomListView).Canvas.Brush.Color := $E0E0FF
else if (logLevel = MTBusb.llWarning) then (Sender as TCustomListView).Canvas.Brush.Color := $A0FFFF
else if (logLevel = MTBusb.llInfo) then (Sender as TCustomListView).Canvas.Brush.Color := $FFEEEE
else if (logLevel = MTBusb.llCmd) then (Sender as TCustomListView).Canvas.Brush.Color := $EEFFEE;
except
end;
end;
end;
procedure TFormConfig.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := false;
Hide;
end;
procedure TFormConfig.RG_TimerIntervalClick(Sender: TObject);
begin
MTBdrv.ScanInterval := TTimerInterval(StrToIntDef(RG_TimerInterval.Items.Strings[RG_TimerInterval.ItemIndex],50));
end;
procedure TFormConfig.pm_modPopup(Sender: TObject);
var cyklus:Integer;
begin
if (lv_modules.Selected <> nil) then
begin
for cyklus := 0 to pm_mod.Items.Count-1 do pm_mod.Items.Items[cyklus].Enabled := true;
end else begin
for cyklus := 0 to pm_mod.Items.Count-1 do pm_mod.Items.Items[cyklus].Enabled := false;
end;//else LV_HV.Selected <> nil
end;
procedure TFormConfig.BeforeOpen(Sender:TObject);
var i:Integer;
begin
Self.l_modcount.Caption := 'hledám...';
Self.L_Openned.Caption := 'otevírám...';
Self.L_Openned.Font.Color := clSilver;
// set MTB board to ComboBox
cb_mtbName.ItemIndex := -1;
for i := 0 to cb_mtbName.Items.Count-1 do
begin
if (cb_mtbName.Items.Strings[i] = MTBdrv.UsbSerial) then
begin
cb_mtbName.ItemIndex := i;
Break;
end;
end;
if (cb_mtbName.ItemIndex = -1) then
begin
// new device -> add to list
cb_mtbName.Items.Add(MTBdrv.UsbSerial);
cb_mtbName.ItemIndex := 0;
end;
Self.cb_speed.Enabled := false;
Self.cb_mtbName.Enabled := false;
Self.b_ScanBrd.Enabled := false;
end;
procedure TFormConfig.AfterOpen(Sender:TObject);
begin
Self.L_Openned.Caption := 'otevřeno';
Self.L_Openned.Font.Color := clGreen;
Self.UpdateModulesList();
end;
procedure TFormConfig.BeforeClose(Sender:TObject);
begin
Self.L_Openned.Caption := 'zavírám...';
Self.L_Openned.Font.Color := clSilver;
end;
procedure TFormConfig.AfterClose(Sender:TObject);
begin
Self.UpdateModulesList();
Self.L_Openned.Caption := 'uzavřeno';
Self.L_Openned.Font.Color := clRed;
Self.cb_speed.Enabled := true;
Self.cb_mtbName.Enabled := true;
Self.b_ScanBrd.Enabled := true
end;
procedure TFormConfig.BeforeStart(Sender:TObject);
begin
Self.L_Started.Caption := 'spouštím...';
Self.L_Started.Font.Color := clSilver;
end;
procedure TFormConfig.AfterStart(Sender:TObject);
begin
Self.L_Started.Caption := 'spuštěna';
Self.L_Started.Font.Color := clGreen;
end;
procedure TFormConfig.BeforeStop(Sender:TObject);
begin
Self.L_Started.Caption := 'zastavuji...';
Self.L_Started.Font.Color := clSilver;
end;
// vyresetovat konfiguraci vsech modulu, ktere nebyly nalezeny
// to je dobre napriklad pri prechodu na jine kolejiste
procedure TFormConfig.B_ClearLogClick(Sender: TObject);
begin
Self.LV_Log.Clear();
end;
procedure TFormConfig.B_DeleteNonExistClick(Sender: TObject);
var i, j:Integer;
begin
if (Application.MessageBox('Opravdu vyresetovat konfiguraci všech MTB modulů, které se nenachází v tabulce níže?', 'Opravdu', MB_YESNO OR MB_ICONQUESTION) <> mrYes) then Exit();
for i := 1 to _ADDR_MAX_NUM do
begin
if (not MTBdrv.IsModule(i)) then
begin
for j := 0 to 3 do
MTBdrv.WrCfgData.CFGdata[j] := 0;
MTBdrv.WrCfgData.CFGpopis := '';
MTBdrv.SetModuleCfg(i);
end;
end;//for i
Application.MessageBox('Konfigurace příslušných MTB modulů smazána', 'Hotovo', MB_OK OR MB_ICONINFORMATION);
end;//procedure
procedure TFormConfig.AfterStop(Sender:TObject);
begin
Self.L_Started.Caption := 'zastavena';
Self.L_Started.Font.Color := clRed;
end;
procedure TFormConfig.OnLog(Sender: TObject; logLevel:TLogLevel; logValue: string);
var LI:TListItem;
timeStr:string;
begin
if (Self.LV_Log.Items.Count > 1000) then
Self.LV_Log.Clear();
DateTimeToString(timeStr, 'hh:mm:ss', time);
LI := Self.LV_Log.Items.Insert(0);
LI.Caption := timeStr;
case (logLevel) of
llError : LI.SubItems.Add('1: Error');
llWarning : LI.SubItems.Add('2: Varování');
llInfo : LI.SubItems.Add('3: Info');
llCmd : LI.SubItems.Add('4: Příkaz');
llRawCmd : LI.SubItems.Add('5: RAW');
llDebug : LI.SubItems.Add('6: Debug');
else
LI.SubItems.Add('');
end;
LI.SubItems.Add(logValue);
end;
procedure TFormConfig.OnError(Sender: TObject; errValue: word; errAddr: byte);
begin
if (errAddr = 255) then
begin
//errors on main board (MTB-USB)
case (errValue) of
MTB_FT_EXCEPTION: Self.AfterClose(Self);
end;//case
end;//if errAddr = 255
end;//procedure
procedure TFormConfig.UpdateModulesList();
var
i: Integer;
LI: TListItem;
cfg:TModulConfigGet;
begin
if (MTBdrv.Openned) then
l_modcount.Caption := IntToStr(MTBdrv.ModuleCount)
else
l_modcount.Caption := '?';
lv_modules.Clear();
if ((not MTBdrv.Openned) and (not CHB_ShowAllModules.Checked)) then
begin
lv_modules.Color := $EDEDED;
Exit();
end;
// show modules
lv_modules.Color := clWindow;
for i := 0 to _ADDR_MAX_NUM do
begin
if ((not MTBdrv.IsModule(i)) and (not CHB_ShowAllModules.Checked)) then continue;
LI := lv_modules.Items.Add;
cfg := MTBdrv.GetModuleCfg(i);
LI.Caption := cfg.CFGpopis;
LI.SubItems.Add(IntToStr(i));
LI.SubItems.Add(MTBdrv.GetModuleTypeName(i));
LI.SubItems.Add(IntToHex(MTBdrv.GetCfg(i), 8));
end;
end;
initialization
finalization
FreeAndNil(FormConfig);
end.//unit
|
program TicketTranslation;
uses
Classes,
RegExpr,
SysUtils;
type
TicketRule = record
r_name: string;
r_rule: string;
end;
Ticket = record
t_values: array of integer;
end;
var
NewTicketRule: TicketRule;
TicketRules: array of TicketRule;
NewTicket: Ticket;
YourTicket: Ticket;
NearbyTickets: array of Ticket;
RuleRanges: array of array[0..3] of integer;
InvalidFields: array of integer;
(* Read file *)
procedure ReadFile(filename: string);
var
re_rules: TRegExpr;
re_ticket: TRegExpr;
re_yourticket: TRegExpr;
re_nearbyticket: TRegExpr;
fh: text;
line: string;
ir: integer;
it: integer;
isYourTicket: boolean;
splitLine: TStringArray;
i: integer;
begin
re_rules := TRegExpr.Create('^([a-z\s]+):\s([0-9\-\sor]+)$');
re_ticket := TRegExpr.Create('^([\d,]+)$');
re_yourticket := TRegExpr.Create('^your ticket:$');
re_nearbyticket := TRegExpr.Create('^nearby tickets:$');
ir := 0; // Index for rules
it := 0; // Index for tickets
isYourTicket := false;
assign(fh, filename);
reset(fh);
while not eof(fh) do
begin
readln(fh, line);
if line <> '' then
begin
if re_rules.Exec(line) then
begin
NewTicketRule.r_name := re_rules.Match[1];
NewTicketRule.r_rule := re_rules.Match[2];
SetLength(TicketRules, Length(TicketRules) + 1);
TicketRules[ir] := NewTicketRule;
inc(ir);
end
else if re_yourticket.Exec(line) then
begin
isYourTicket := true;
end
else if re_nearbyticket.Exec(line) then
begin
isYourTicket := false;
end
else if re_ticket.Exec(line) then
begin
splitLine := re_ticket.Match[1].Split(',');
SetLength(NewTicket.t_values, Length(splitLine));
for i := 0 to Length(splitLine) - 1 do
begin
if splitLine[i] <> '' then
begin
NewTicket.t_values[i] := StrToInt(splitLine[i]);
end;
end;
if isYourTicket then
begin
YourTicket := NewTicket;
end
else
begin
SetLength(NearbyTickets, Length(NearbyTickets) + 1);
NearbyTickets[it] := NewTicket;
inc(it);
end;
end;
end;
end;
re_rules.Free();
re_ticket.Free();
close(fh);
end;
(* Parse ticket rules *)
procedure ParseRules();
var
i: integer;
j: integer;
re_ranges: TRegExpr;
begin
re_ranges := TRegExpr.Create('([0-9]+)');
for i := 0 to Length(TicketRules) - 1 do
begin
if re_ranges.Exec(TicketRules[i].r_rule) then
begin
j := 0;
SetLength(RuleRanges, Length(RuleRanges) + 1);
RuleRanges[i][j] := StrToInt(re_ranges.Match[1]);
while re_ranges.ExecNext do
begin
j := j + 1;
RuleRanges[i][j] := StrToInt(re_ranges.Match[1]);
end;
end;
end;
re_ranges.Free();
end;
(* Check if ticket matches rules *)
procedure CheckTickets();
var
i: integer; // NearbyTickets index
j: integer; // NearbyTickets t_values index
k: integer; // RuleRanges index
validFieldFound: boolean;
begin
for i := 0 to Length(NearbyTickets) - 1 do
begin
for j := 0 to Length(NearbyTickets[i].t_values) - 1 do
begin
validFieldFound := false;
for k := 0 to Length(RuleRanges) - 1 do
begin
if ((NearbyTickets[i].t_values[j] >= RuleRanges[k][0]) and (NearbyTickets[i].t_values[j] <= RuleRanges[k][1])) or ((NearbyTickets[i].t_values[j] >= RuleRanges[k][2]) and (NearbyTickets[i].t_values[j] <= RuleRanges[k][3])) then
begin
validFieldFound := true;
end;
end;
if validFieldFound <> true then
begin
SetLength(InvalidFields, Length(InvalidFields) + 1);
InvalidFields[Length(InvalidFields) - 1] := NearbyTickets[i].t_values[j];
end;
end;
end;
end;
(* Calculate sum of invalid fields *)
procedure CalculateSum();
var
i, sum: integer;
begin
sum := 0;
for i := Low(invalidFields) to High(invalidFields) do sum := sum + invalidFields[i];
writeln('Sum: ', sum);
end;
(* Main *)
begin
ReadFile('./day16/day16.txt');
ParseRules();
CheckTickets();
CalculateSum();
end.
|
unit RecorderControl;
// Recorder's gui. separates gui from logic, the logic is in the Recorder class (Recorder.pas)
interface
uses Chart, Controls, Classes, Series, Graphics, Menus, SetNewValForm, SysUtils, TeeProcs;
type
IRecorderControlCallback = interface
procedure SetRelativeMeasure;
procedure SetAbsoluteMeasure;
procedure AddChannel;
procedure RemoveChannel;
procedure DeleteRecorder;
end;
TRecorderControl = class(TChart)
public
constructor Create(AOwner: TComponent); override;
procedure AddPointToGraphLine(inputLineNumber : integer; x : double; y : double);
procedure RenameGraphLine(inputLineNumber : integer; name : string);
procedure SetGraphWidth(inputLineNumber : integer; newWidth : integer);
procedure SetGraphColor(inputLineNumber : integer; newColor : TColor);
function AddGraphLine(inputLineNumber : integer; graphName : string; graphColor : TColor) : integer;
procedure DeleteGraphLine(inputLineNumber : integer);
function GetDisplayInterval() : double;
procedure SetDisplayInterval(interval : double);
procedure ChangeInterval(Sender: TObject);
procedure RelativeMeasure(Sender: TObject);
procedure AbsoluteMeasure(Sender: TObject);
procedure AddChannel(Sender: TObject);
procedure RemoveChannel(Sender: TObject);
procedure DeleteThisRecorder(Sender: TObject);
procedure SetGuiCallback(callback : IRecorderControlCallback);
function HasInputLineGraph(inputLineNumber : integer) : boolean;
private
displayInterval : double;
controlSeriesNumbers : Array of integer;
guiCallback : IRecorderControlCallback;
procedure MaintainControlSeriesNumbers;
end;
implementation
{ TRecorderControl }
procedure TRecorderControl.AbsoluteMeasure(Sender: TObject);
begin
self.guiCallback.SetAbsoluteMeasure;
end;
procedure TRecorderControl.AddChannel(Sender: TObject);
begin
self.guiCallback.AddChannel;
end;
function TRecorderControl.AddGraphLine(inputLineNumber : integer; graphName: string; graphColor : TColor): integer;
var series : TLineSeries;
begin
Result := 0;
if HasInputLineGraph(inputLineNumber) then
exit;
Result := self.SeriesCount;
series := TLineSeries.Create(self);
series.Title := graphName;
series.Color := graphColor;
series.Tag := inputLineNumber;
AddSeries(series);
self.MaintainControlSeriesNumbers;
end;
procedure TRecorderControl.AddPointToGraphLine(inputLineNumber: integer; x,
y: double);
var seriesNum : integer;
begin
seriesNum := controlSeriesNumbers[inputLineNumber];
if (seriesNum >= self.SeriesCount) then
exit;
Series[seriesNum].AddXY(x, y);
while ((Series[seriesNum].ValuesList[0].Count > 0) and
((x - Series[seriesNum].ValuesList[0].Value[0]) > self.displayInterval)) do
begin
Series[seriesNum].Delete(0);
end;
end;
procedure TRecorderControl.ChangeInterval(Sender: TObject);
var setIntervalForm : TNewValForm;
begin
try
setIntervalForm := TNewValForm.Create(self);
setIntervalForm.Caption := 'Set interval';
setIntervalForm.SetPreviousVal(FloatToStr(displayInterval));
setIntervalForm.ShowModal;
if (setIntervalForm.GetNewVal <> '') then
begin
displayInterval := StrToFloat(setIntervalForm.GetNewVal);
end;
except
on Exception : EConvertError do
exit
end;
end;
constructor TRecorderControl.Create(AOwner: TComponent);
var
popupMenu : TPopupMenu;
menuItem: TMenuItem;
begin
inherited;
View3D := false;
Legend.LegendStyle := lsSeries;
Legend.Visible := true;
self.displayInterval := 10;
self.AllowZoom := false;
self.AllowPanning := pmNone;
popupMenu := TPopupMenu.Create(self);
menuItem := TMenuItem.Create(self);
menuItem.Caption := 'Change view interval';
menuItem.OnClick := ChangeInterval;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(self);
menuItem.Caption := 'View relatively to a channel';
menuItem.OnClick := self.RelativeMeasure;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(self);
menuItem.Caption := 'Absolute values';
menuItem.OnClick := self.AbsoluteMeasure;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(self);
menuItem.Caption := 'Add a channel';
menuItem.OnClick := self.AddChannel;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(self);
menuItem.Caption := 'Remove a channel';
menuItem.OnClick := self.RemoveChannel;
popupMenu.Items.Add(menuItem);
menuItem := TMenuItem.Create(self);
menuItem.Caption := 'Remove the recorder';
menuItem.OnClick := self.DeleteThisRecorder;
popupMenu.Items.Add(menuItem);
self.PopupMenu := popupMenu;
end;
procedure TRecorderControl.DeleteGraphLine(inputLineNumber: integer);
var serNum : integer;
begin
if not HasInputLineGraph(inputLineNumber) then
exit;
serNum := self.controlSeriesNumbers[inputLineNumber];
self.RemoveSeries(serNum);
self.MaintainControlSeriesNumbers;
end;
procedure TRecorderControl.DeleteThisRecorder(Sender: TObject);
begin
self.guiCallback.DeleteRecorder;
end;
function TRecorderControl.GetDisplayInterval: double;
begin
Result := self.displayInterval;
end;
function TRecorderControl.HasInputLineGraph(
inputLineNumber: integer): boolean;
var i : integer;
begin
Result := false;
for i := 0 to self.SeriesCount -1 do
begin
if Series[i].Tag = inputLineNumber then
begin
Result := true;
exit;
end;
end;
end;
procedure TRecorderControl.MaintainControlSeriesNumbers;
var i : integer;
begin
SetLength(self.controlSeriesNumbers, 0);
for i := 0 to self.SeriesCount -1 do
begin
if (Length(self.controlSeriesNumbers) <= self.Series[i].Tag) then
SetLength(self.controlSeriesNumbers, self.Series[i].Tag + 1);
self.controlSeriesNumbers[self.Series[i].Tag] := i;
end;
end;
procedure TRecorderControl.RelativeMeasure(Sender: TObject);
begin
self.guiCallback.SetRelativeMeasure;
end;
procedure TRecorderControl.RemoveChannel(Sender: TObject);
begin
self.guiCallback.RemoveChannel;
end;
procedure TRecorderControl.RenameGraphLine(inputLineNumber: integer;
name: string);
var serNum : integer;
begin
if not HasInputLineGraph(inputLineNumber) then
exit;
serNum := self.controlSeriesNumbers[inputLineNumber];
self.Series[serNum].Title := name;
end;
procedure TRecorderControl.SetDisplayInterval(interval: double);
begin
self.displayInterval := interval;
end;
procedure TRecorderControl.SetGraphColor(inputLineNumber: integer;
newColor: TColor);
var serNum : integer;
begin
if not HasInputLineGraph(inputLineNumber) then
exit;
serNum := self.controlSeriesNumbers[inputLineNumber];
(TLineSeries(Series[serNum])).Color := newColor;
end;
procedure TRecorderControl.SetGraphWidth(inputLineNumber: integer;
newWidth: integer);
var serNum : integer;
begin
if not HasInputLineGraph(inputLineNumber) then
exit;
serNum := self.controlSeriesNumbers[inputLineNumber];
(TLineSeries(Series[serNum])).LinePen.Width := newWidth;
end;
procedure TRecorderControl.SetGuiCallback(
callback: IRecorderControlCallback);
begin
self.guiCallback := callback;
end;
end.
|
unit MMO.PacketWriter;
interface
uses MMO.Packet;
type
TPacketWriter = class(TPacket)
private
public
function WriteUInt8(const src: UInt8): Boolean;
function WriteUInt16(const src: UInt16): Boolean;
function WriteUInt32(const src: UInt32): Boolean;
function WriteInt32(const src: Int32): Boolean;
function WriteUInt64(const src: UInt64): Boolean;
function WriteInt64(const src: Int64): Boolean;
function Write(const src; const count: UInt32): Boolean;
function WriteDouble(const src: Double): boolean;
function WriteStr(const src: AnsiString): Boolean; overload;
function WriteStr(const src: AnsiString; const count: UInt32): Boolean; overload;
function WriteStr(const src: AnsiString; const count: UInt32; const overflow: AnsiChar): Boolean; overload;
end;
implementation
function TPacketWriter.WriteUInt8(const src: UInt8): Boolean;
begin
Exit(Write(src, 1));
end;
function TPacketWriter.WriteUInt16(const src: UInt16): Boolean;
begin
Exit(Write(src, 2));
end;
function TPacketWriter.WriteUInt32(const src: UInt32): Boolean;
begin
Exit(Write(src, 4));
end;
function TPacketWriter.WriteInt32(const src: Int32): Boolean;
begin
Exit(Write(src, 4));
end;
function TPacketWriter.WriteUInt64(const src: UInt64): Boolean;
begin
Exit(Write(src, 8));
end;
function TPacketWriter.WriteInt64(const src: Int64): Boolean;
begin
Exit(Write(src, 8));
end;
function TPacketWriter.Write(const src; const count: Cardinal): Boolean;
begin
Result := m_data.Write(src, count) = count;
end;
function TPacketWriter.WriteDouble(const src: Double): boolean;
begin
Exit(Write(src, 4));
end;
function TPacketWriter.WriteStr(const src: AnsiString; const count: UInt32): Boolean;
begin
Exit(WriteStr(src, count, #$00));
end;
function TPacketWriter.WriteStr(const src: AnsiString; const count: UInt32; const overflow: AnsiChar): Boolean;
var
dataSize: UInt32;
remainingDataSize: integer;
remainningData: AnsiString;
begin
dataSize := Length(src);
if dataSize < count then
begin
Result := Write(src[1], dataSize);
remainingDataSize := count - dataSize;
remainningData := StringOfChar(overflow, remainingDataSize);
Result := Result and Write(remainningData[1], remainingDataSize);
end else begin
Exit(Write(src[1], count));
end;
end;
function TPacketWriter.WriteStr(const src: AnsiString): Boolean;
var
size: UInt16;
begin
size := Length(src);
WriteUInt16(size);
Write(src[1], size);
end;
end.
|
program Ch1;
{$mode objfpc}
uses
SysUtils, Math, GVector;
type
TVec = specialize TVector<Integer>;
var
I:Integer;
Vec:TVec;
function IsPrime(N:Integer):Boolean;
var
I:Integer;
begin
if(N <= 1) then Exit(False);
for I := 2 to Trunc(Sqrt(N)) do
if(N mod I = 0) then Exit(False);
Result := True;
end;
function SumDigits(N:Integer):Integer;
var
Sum:Integer;
begin
Sum := 0;
while N <> 0 do
begin
Sum := Sum + N mod 10;
N := N div 10;
end;
Result := Sum;
end;
function AdditivePrimes:TVec;
var
I:Integer;
Vec:TVec;
begin
Vec := TVec.Create;
for I := 0 to 100 do
if((IsPrime(I)) and (IsPrime(SumDigits(I)))) then
Vec.PushBack(I);
Result := Vec;
end;
begin
Vec := AdditivePrimes;
for I := 0 to Vec.Size-1 do Write(Vec[I], ' ');
FreeAndNil(Vec);
end.
|
unit UDMTabImposto;
interface
uses
SysUtils, Classes, DB, DBTables, DBIProcs;
type
TDMTabImposto = class(TDataModule)
tTabPis: TTable;
tTabPisCodigo: TStringField;
tTabPisNome: TStringField;
dsTabPis: TDataSource;
tTabCofins: TTable;
dsTabCofins: TDataSource;
tTabCofinsCodigo: TStringField;
tTabCofinsNome: TStringField;
tRegimeTrib: TTable;
tRegimeTribCodigo: TIntegerField;
tRegimeTribNome: TStringField;
dsRegimeTrib: TDataSource;
tOrigemProd: TTable;
dsOrigemProd: TDataSource;
tOrigemProdOrigem: TStringField;
tOrigemProdNome: TStringField;
procedure tTabPisAfterPost(DataSet: TDataSet);
procedure tTabCofinsAfterPost(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure tRegimeTribAfterPost(DataSet: TDataSet);
procedure tOrigemProdAfterPost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DMTabImposto: TDMTabImposto;
implementation
{$R *.dfm}
procedure TDMTabImposto.tTabPisAfterPost(DataSet: TDataSet);
begin
DBISaveChanges(tTabPis.Handle);
end;
procedure TDMTabImposto.tTabCofinsAfterPost(DataSet: TDataSet);
begin
DBISaveChanges(tTabCofins.Handle);
end;
procedure TDMTabImposto.DataModuleCreate(Sender: TObject);
begin
tTabCofins.Open;
tTabPis.Open;
tRegimeTrib.Open;
tOrigemProd.Open;
end;
procedure TDMTabImposto.tRegimeTribAfterPost(DataSet: TDataSet);
begin
DBISaveChanges(tRegimeTrib.Handle);
end;
procedure TDMTabImposto.tOrigemProdAfterPost(DataSet: TDataSet);
begin
DBISaveChanges(tOrigemProd.Handle);
end;
end.
|
unit FileScanner;
{
für Delphi-Praxis by shmia
}
interface
uses Windows, SysUtils;
type
// Info über einzelne Datei oder Verzeichnis
TFileInformation = record
Name : string;
Path : string;
IsDir : boolean;
ArchiveFlag, ReadOnlyFlag, HiddenFlag, SystemFlag : boolean;
// Owner : TOwner; // TODO
Size : Int64;
Depth : Integer; // Tiefe: 0=Startverz, 1= erstes Unterverz.
Created,LastWrite, LastAccess : TDateTime;
end;
TFileFindEvent = procedure(Sender:TObject; const FileInformation:TFileInformation) of object;
// Klasse um Verzeichnisse aufzulisten
//
TFileScanner = class(Tobject)
private
FOnFound: TFileFindEvent;
FRecursive: Boolean;
FStopped : Boolean;
FStopDir : Boolean;
FStartDepth : Integer;
procedure DoFound(const FileInformation:TFileInformation);virtual;
class procedure CopyFileInfo(const SR : TSearchRec; var FI : TFileInformation);
procedure ScanDirInternal(const Directory:string; depth:Integer);
procedure ScanDirInternal2(const Directory:string; depth:Integer);
public
procedure ScanDir(const Directory:string; DirsAtTheEnd:Boolean); // Verzeichnis scannen
procedure Stop; // Scanvorgang anhalten
procedure StopDirectory; // nur Scanvorgang im aktuellen Verzeichnis unterbrechen
property Recursive:Boolean read FRecursive write FRecursive;
property OnFound:TFileFindEvent read FOnFound write FOnFound;
property Stopped:Boolean read FStopped;
end;
implementation
uses Classes;
const
FileTimeBase = -109205.0;
FileTimeStep: Extended = 24.0 * 60.0 * 60.0 * 1000.0 * 1000.0 * 10.0; // 100 nSek per Day
function FileTimeToDateTime(const FileTime: TFileTime): TDateTime;
begin
Result := Int64(FileTime) / FileTimeStep;
Result := Result + FileTimeBase;
end;
function FileTimeToLocalDateTime(const FileTime: TFileTime): TDateTime;
var
LocalFileTime: TFileTime;
begin
if FileTimeToLocalFileTime(FileTime, LocalFileTime) then
Result := FileTimeToDateTime(LocalFileTime)
{ TODO : daylight saving time }
else
Result := 0.0;
end;
function FileTimeToSystemDateTime(const FileTime: TFileTime): TDateTime;
begin
Result := FileTimeToDateTime(FileTime)
end;
{ TFileScanner }
procedure TFileScanner.DoFound(const FileInformation: TFileInformation);
begin
if Assigned(onFound) then
OnFound(Self, FileInformation)
else
Stop; // ohne Eventhandler macht es keinen Sinn
end;
procedure TFileScanner.ScanDir(const Directory: string; DirsAtTheEnd:Boolean);
begin
if Recursive then
FStartDepth := 255
else
FStartDepth := 0;
FStopped := False;
if DirsAtTheEnd then
ScanDirInternal2(IncludeTrailingBackslash(Directory), FStartDepth)
else
ScanDirInternal(IncludeTrailingBackslash(Directory), FStartDepth);
end;
class procedure TFileScanner.CopyFileInfo(const SR: TSearchRec; var FI: TFileInformation);
begin
FI.Name := SR.Name;
FI.Size := SR.Size;
FI.IsDir := False;
FI.Created := FileTimeToSystemDateTime(SR.FindData.ftCreationTime);
FI.LastWrite := FileTimeToSystemDateTime(SR.FindData.ftLastWriteTime);
FI.LastAccess := FileTimeToSystemDateTime(SR.FindData.ftLastAccessTime);
{
FI.Created := FileTimeToLocalDateTime(SR.FindData.ftCreationTime);
FI.LastWrite := FileTimeToLocalDateTime(SR.FindData.ftLastWriteTime);
FI.LastAccess := FileTimeToLocalDateTime(SR.FindData.ftLastAccessTime);
}
FI.ReadOnlyFlag := (SR.FindData.dwFileAttributes and faReadOnly) <> 0;
FI.HiddenFlag := (SR.FindData.dwFileAttributes and faHidden) <> 0;
FI.SystemFlag := (SR.FindData.dwFileAttributes and faSysFile) <> 0;
FI.ArchiveFlag := (SR.FindData.dwFileAttributes and faArchive) <> 0;
(*
TODO:
Size mit 64-Bit Dateigrösse füllen
*)
end;
procedure TFileScanner.ScanDirInternal(const Directory: string; depth:Integer);
var
SR : TSearchRec;
FI : TFileInformation;
begin
FStopDir := False;
FI.Path := Directory;
FI.Depth := FStartDepth-depth;
FI.IsDir := True;
if FindFirst(Directory+'*.*',faAnyFile,SR) = 0 then
begin
try
DoFound(FI);
if FStopDir then
Exit;
repeat
if (SR.Attr and faDirectory) = faDirectory then
begin
if (depth > 0) and (SR.Name <> '.') and (SR.Name <> '..') then
ScanDirInternal(IncludeTrailingBackSlash(Directory+SR.Name), depth-1);
end
else
begin
CopyFileInfo(SR, FI);
DoFound(FI);
end;
until FStopped or (FindNext(SR) <> 0);
finally
FindClose(SR);
end;
end;
end;
procedure TFileScanner.ScanDirInternal2(const Directory: string; depth: Integer);
var
SR : TSearchRec;
FI : TFileInformation;
dlist : TStringList;
begin
dlist := TStringList.Create;
FStopDir := False;
FI.Path := Directory;
FI.Depth := FStartDepth-depth;
FI.IsDir := True;
if FindFirst(Directory+'*.*',faAnyFile,SR) = 0 then
begin
try
DoFound(FI);
if FStopDir then
Exit;
repeat
if (SR.Attr and faDirectory) = faDirectory then
begin
if (depth > 0) and (SR.Name <> '.') and (SR.Name <> '..') then
dlist.Add(IncludeTrailingBackSlash(Directory+SR.Name));
end
else
begin
CopyFileInfo(SR, FI);
DoFound(FI);
end;
until FStopped or (FindNext(SR) <> 0);
while dlist.Count > 0 do
begin
ScanDirInternal2(dlist[0], depth-1);
dlist.Delete(0);
end;
finally
FindClose(SR);
dlist.Free;
end;
end;
end;
procedure TFileScanner.Stop;
begin
FStopped := True;
end;
procedure TFileScanner.StopDirectory;
begin
FStopDir := True;
end;
end.
|
unit m_stringgrid;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Grids;
type
{ TMariaeStringGrid }
TMariaeStringGrid = class(TStringGrid)
private
FChanged: Boolean;
procedure SetChanged(AValue: Boolean);
protected
public
constructor Create(MOwner: TComponent); override;
procedure EditingDone; override;
procedure ResetChanged;
published
property Changed: Boolean read FChanged write SetChanged;
end;
procedure Register;
implementation
procedure Register;
begin
{$I m_stringgrid_icon.lrs}
RegisterComponents('Mariae Controls',[TMariaeStringGrid]);
end;
{ TMariaeStringGrid }
procedure TMariaeStringGrid.SetChanged(AValue: Boolean);
begin
if FChanged = AValue then Exit;
FChanged := AValue;
end;
constructor TMariaeStringGrid.Create(MOwner: TComponent);
begin
inherited Create(MOwner);
Self.FixedCols := 0;
Self.DefaultRowHeight := 20;
end;
procedure TMariaeStringGrid.EditingDone;
begin
inherited EditingDone;
Self.SetChanged(True);
end;
procedure TMariaeStringGrid.ResetChanged;
begin
Self.SetChanged(False);
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSErrors.pas }
{ File version: 5.03 }
{ Description: TLS Errors }
{ }
{ Copyright: Copyright (c) 2008-2020, David J Butler }
{ 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. }
{ 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. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/09 5.02 Create flcTLSErrors unit from flcTLSUtils unit. }
{ 2020/05/11 5.03 ETLSError CreateAlert constructor. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSErrors;
interface
uses
{ System }
SysUtils,
{ TLS }
flcTLSAlert;
{ }
{ Errors }
{ }
const
TLSError_None = 0;
TLSError_InvalidBuffer = 1;
TLSError_InvalidParameter = 2;
TLSError_InvalidCertificate = 3;
TLSError_InvalidState = 4;
TLSError_DecodeError = 5;
TLSError_BadProtocol = 6;
function TLSErrorMessage(const TLSError: Integer): String;
type
ETLSError = class(Exception)
private
FTLSError : Integer;
FAlertDescription : TTLSAlertDescription;
function InitAlert(
const ATLSError: Integer;
const AAlertDescription: TTLSAlertDescription;
const AMsg: String = ''): String;
public
constructor Create(
const ATLSError: Integer;
const AMsg: String = '');
constructor CreateAlert(
const ATLSError: Integer;
const AAlertDescription: TTLSAlertDescription;
const AMsg: String = '');
constructor CreateAlertBufferDecode;
constructor CreateAlertBufferEncode;
constructor CreateAlertUnexpectedMessage;
constructor CreateAlertBadProtocolVersion;
property TLSError: Integer read FTLSError;
property AlertDescription: TTLSAlertDescription read FAlertDescription;
end;
implementation
{ }
{ Errors }
{ }
const
SErr_InvalidBuffer = 'Invalid buffer';
SErr_InvalidCertificate = 'Invalid certificate';
SErr_InvalidParameter = 'Invalid parameter';
SErr_InvalidState = 'Invalid state';
SErr_DecodeError = 'Decode error';
SErr_BadProtocol = 'Bad protocol';
function TLSErrorMessage(const TLSError: Integer): String;
begin
case TLSError of
TLSError_None : Result := '';
TLSError_InvalidBuffer : Result := SErr_InvalidBuffer;
TLSError_InvalidParameter : Result := SErr_InvalidParameter;
TLSError_InvalidCertificate : Result := SErr_InvalidCertificate;
TLSError_InvalidState : Result := SErr_InvalidState;
TLSError_DecodeError : Result := SErr_DecodeError;
TLSError_BadProtocol : Result := SErr_BadProtocol;
else
Result := '[TLSError#' + IntToStr(TLSError) + ']';
end;
end;
constructor ETLSError.Create(
const ATLSError: Integer;
const AMsg: String);
var S : String;
begin
FTLSError := ATLSError;
if AMsg = '' then
S := TLSErrorMessage(ATLSError)
else
S := AMsg;
FAlertDescription := tlsadMax;
inherited Create(S);
end;
constructor ETLSError.CreateAlert(
const ATLSError: Integer;
const AAlertDescription: TTLSAlertDescription;
const AMsg: String);
begin
inherited Create(InitAlert(ATLSError, AAlertDescription, AMsg));
end;
function ETLSError.InitAlert(
const ATLSError: Integer;
const AAlertDescription: TTLSAlertDescription;
const AMsg: String): String;
var
S : String;
begin
FTLSError := ATLSError;
FAlertDescription := AAlertDescription;
if AMsg = '' then
S := TLSErrorMessage(ATLSError) + ':' + TLSAlertDescriptionToStr(AAlertDescription)
else
S := AMsg;
Result := S;
end;
constructor ETLSError.CreateAlertBufferDecode;
begin
inherited Create(InitAlert(TLSError_InvalidBuffer, tlsadDecode_error));
end;
constructor ETLSError.CreateAlertBufferEncode;
begin
inherited Create(InitAlert(TLSError_InvalidBuffer, tlsadInternal_error));
end;
constructor ETLSError.CreateAlertUnexpectedMessage;
begin
inherited Create(InitAlert(TLSError_BadProtocol, tlsadUnexpected_message));
end;
constructor ETLSError.CreateAlertBadProtocolVersion;
begin
inherited Create(InitAlert(TLSError_BadProtocol, tlsadProtocol_version));
end;
end.
|
{ Subroutine SST_OPCODE_NEW
*
* Create a new opcode descriptor at the current end of chain.
}
module sst_OPCODE_NEW;
define sst_opcode_new;
%include 'sst2.ins.pas';
procedure sst_opcode_new; {create new empty opcode, make current}
begin
util_mem_grab ( {allocate memory for new opcode descriptor}
sizeof(sst_opc_p^), {amount of memory to allocate}
sst_scope_p^.mem_p^, {parent memory context}
false, {won't need to separately deallocate this}
sst_opc_p); {returned pointer to new memory}
sst_opc_next_pp^ := sst_opc_p; {link new opcode to end of chain}
sst_opc_next_pp := addr(sst_opc_p^.next_p); {update end of chain pointer}
sst_opc_p^.next_p := nil; {init to new opcode is last in chain}
sst_opc_p^.str_h.first_char.crange_p := nil;
sst_opc_p^.str_h.first_char.ofs := 0;
sst_opc_p^.str_h.last_char.crange_p := nil;
sst_opc_p^.str_h.last_char.ofs := 0;
end;
|
unit ExtIDEM_frm_sub_COMMENTs;
{$mode objfpc}{$H+}
interface
uses extIDEM_frm_sub,
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, ExtCtrls;
type
{ TextIDEM_sub_COMMENTs_frm }
TextIDEM_sub_COMMENTs_frm = class(tExtIDEM_sub_frm)
chb_Enabled: TCheckBox;
edt_CmntSMB: TEdit;
procedure chb_EnabledChange(Sender: TObject);
protected
procedure _CmntSMB_set_(const value:string);
function _CmntSMB_get_:string;
procedure _CmntUSE_set_(const value:boolean);
function _CmntUSE_get_:boolean;
protected
function getFRM_caption:string; override;
public
constructor Create(AOwner:TComponent); override;
public
property CmntUsed:boolean read _CmntUSE_get_ write _CmntUSE_set_;
property CmntSMBs:string read _CmntSMB_get_ write _CmntSMB_set_;
end;
implementation
const _cTXT_frmCaption_='Комментарии';
{$R *.lfm}
constructor TextIDEM_sub_COMMENTs_frm.Create(AOwner:TComponent);
begin
inherited;
chb_Enabled.Checked:=false;
chb_EnabledChange(chb_Enabled);
end;
//------------------------------------------------------------------------------
procedure TextIDEM_sub_COMMENTs_frm._CmntSMB_set_(const value:string);
begin
edt_CmntSMB.Text:=value;
end;
function TextIDEM_sub_COMMENTs_frm._CmntSMB_get_:string;
begin
result:=edt_CmntSMB.Text;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TextIDEM_sub_COMMENTs_frm._CmntUSE_set_(const value:boolean);
begin
chb_Enabled.Checked:=value;
end;
function TextIDEM_sub_COMMENTs_frm._CmntUSE_get_:boolean;
begin
result:=chb_Enabled.Checked;
end;
//------------------------------------------------------------------------------
procedure TextIDEM_sub_COMMENTs_frm.chb_EnabledChange(Sender: TObject);
begin
edt_CmntSMB.Enabled:=TCheckBox(sender).Checked;
end;
function TextIDEM_sub_COMMENTs_frm.getFRM_caption:string;
begin
result:=_cTXT_frmCaption_;
end;
end.
|
{***************************************************************
* Unit Name: GX_SampleExpert
* Purpose : Template for creation of new GExperts experts
* : Customize this when creating new experts
* : Add this unit to the GExperts .dpr and compile
* Authors : Stefan Hoffmeister, Scott Mattes, Erik Berry
****************************************************************}
unit GX_SampleExpert;
{$I GX_CondDefine.inc}
interface
uses
GX_Experts, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, GX_BaseForm;
type
TfmGxSampleExpertForm = class(TfmBaseForm)
btnOK: TButton;
lblNote: TLabel;
lblData: TLabel;
edtData: TEdit;
btnCancel: TButton;
end;
implementation
{$R *.dfm}
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
Registry, Menus, GX_GExperts, GX_ConfigurationInfo;
type
///<summary>
/// Use this sample expert as a starting point for your own expert.
/// Do not forget to rename the unit and the class(es).
/// Many of the methods are optional and you can omit them if the default
/// behaviour is suitable for your expert. </summary>
TGxSampleExpert = class(TGX_Expert)
private
FSomeData: string;
protected
procedure SetActive(New: Boolean); override;
public
// optional, defaults to ClassName
class function GetName: string; override;
// optional, defauls to true
function CanHaveShortCut: boolean; override;
constructor Create; override;
destructor Destroy; override;
function GetActionCaption: string; override;
// optional, defaults to no shortcut
function GetDefaultShortCut: TShortCut; override;
// optional, but recommended
function GetHelpString: string; override;
// optional, defaults to true
function HasConfigOptions: Boolean; override;
// optional, defaults to true
function HasMenuItem: Boolean; override;
// optional if HasConfigOptions returns false
procedure Configure; override;
// Overrride to load any configuration settings
procedure InternalLoadSettings(Settings: TExpertSettings); override;
// Overrride to save any configuration settings
procedure InternalSaveSettings(Settings: TExpertSettings); override;
procedure Execute(Sender: TObject); override;
end;
{ TGxSampleExpert }
//*********************************************************
// Name: TGxSampleExpert.Execute
// Purpose: The action taken when the menu item is clicked
//*********************************************************
procedure TGxSampleExpert.Execute(Sender: TObject);
begin
with TfmGxSampleExpertForm.Create(nil) do
try
edtData.Text := FSomeData;
if ShowModal = mrOk then
begin
FSomeData := edtData.Text;
SaveSettings;
end;
finally
Free;
end;
end;
//*********************************************************
// Name: TGxSampleExpert.CanHaveShortCut
// Purpose: Determines whether this expert can have a
// hotkey assigned to it
// Note: If it returns false, no hotkey configuration
// control is shown in the configuratoin dialog.
// If your expert can have a hotkey, you can
// simply delete this function, since the
// inherited funtion already returns true.
//*********************************************************
function TGxSampleExpert.CanHaveShortCut: boolean;
begin
Result := True;
end;
//*********************************************************
// Name: TGxSampleExpert.Configure
// Purpose: Action taken when user clicks the Configure
// button on the Experts tab of menu item GExperts/
// GExperts Configuration...
//*********************************************************
procedure TGxSampleExpert.Configure;
resourcestring
SYouClickedConfigure = 'You clicked the Configuration button!';
begin
MessageDlg(SYouClickedConfigure, mtInformation, [mbOK], 0);
end;
constructor TGxSampleExpert.Create;
begin
inherited Create;
// Assign a default value to your data
FSomeData := 'Sample Data';
// Saved settings are loaded automatically for you by the ancestor
// via the virtual LoadSettings method
end;
destructor TGxSampleExpert.Destroy;
begin
// Free any created objects here
inherited Destroy;
end;
//*********************************************************
// Name: TGxSampleExpert.GetActionCaption
// Purpose: Returns the string displayed on the GExperts
// menu item
//*********************************************************
function TGxSampleExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Sample E&xpert...';
begin
Result := SMenuCaption;
end;
//*********************************************************
// Name: TGxSampleExpert.GetDefaultShortCut
// Purpose: The default shortcut to call your expert.
// Notes: It is perfectly fine not to assign a default
// shortcut and let the expert be called via
// the menu only. The user can always assign
// a shortcut to it in the configuration dialog.
// Available shortcuts have become a very rare
// resource in the Delphi IDE.
// The value of ShortCut is touchy, use the ShortCut
// button on the Editor Experts tab of menu item
// GExperts/GExperts Configuration... on an existing
// editor expert to see if you can use a specific
// combination for your expert.
//*********************************************************
function TGxSampleExpert.GetDefaultShortCut: TShortCut;
begin
// If desired, assign a default menu item shortcut
Result := Menus.ShortCut(Word('Z'), [ssCtrl, ssShift, ssAlt]);
end;
//*********************************************************
// Name: TGxSampleExpert.GetHelpString
// Purpose: To provide your text on what this expert
// does to the expert description hint that is shown
// when the user puts the mouse over the expert's icon
// in the configuration dialog.
//*********************************************************
function TGxSampleExpert.GetHelpString: string;
resourcestring
SSampleExpertHelp =
'This is the text that will appear in the explanation hint on the ' +
'Editor tab of menu item GExperts/GExperts Configuration...' + sLineBreak +
sLineBreak +
'You can allow the text to wrap automatically, or you can force your ' +
'own line breaks, or both.';
begin
Result := SSampleExpertHelp;
end;
//*********************************************************
// Name: TGxSampleExpert.GetName
// Purpose: Used to determine the unique keyword used to
// save the active state and shortcut into the registry
// Note: The inherited implementation returns the
// expert's class name. This is usually fine
// as long as it is unique within GExperts.
// Feel free to omit this method from your expert.
//*********************************************************
class function TGxSampleExpert.GetName: string;
begin
Result := 'SampleExpert';
end;
//*********************************************************
// Name: TGxSampleExpert.HasConfigOptions
// Purpose: This expert should have a configure button in
// the configuration dialog
//*********************************************************
function TGxSampleExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
//*********************************************************
// Name: TGxSampleExpert.HasMenuItem
// Purpose: This expert has a visible menu item
// in the GExperts top level menu
//*********************************************************
function TGxSampleExpert.HasMenuItem: Boolean;
begin
Result := True;
end;
//*********************************************************
// Name: TGxSampleExpert.LoadSettings
// Purpose: Gets the expert settings from the registry
//*********************************************************
procedure TGxSampleExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited;
FSomeData := Settings.ReadString('TestSetting', FSomeData);
end;
//*********************************************************
// Name: TGxSampleExpert.SaveSettings
// Purpose: Saves the expert settings to the registry
// You must call this manually in the destructor
//*********************************************************
procedure TGxSampleExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited;
Settings.WriteString('TestSetting', FSomeData);
end;
//********************************************************************
// Name: TGxSampleExpert.SetActive
// Purpose: Called to clean up the expert when it is disabled at runtime
// or destroyed on shutdown. Free any forms and objects here.
// The ancestor removes the menu item for you.
//********************************************************************
procedure TGxSampleExpert.SetActive(New: Boolean);
begin
if New <> Active then
begin
inherited SetActive(New);
if New then
// Initialize anything necessary here (generally empty for modal experts)
else
begin
// If we had a non-modal form, it would be destroyed here
//FreeAndNil(FSampleForm);
end;
end;
end;
//*********************************************************
// Purpose: Lets GExperts know about this new expert
//*********************************************************
initialization
RegisterGX_Expert(TGxSampleExpert);
end.
|
program oddNumbers(input, output);
var
i, number : integer;
begin
write('n: ');
read(number);
for i := 0 to number do
if (i mod 2 <> 0) then
write(i, ' ');
writeln();
end.
|
unit FFSMemo2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TFFSMemo2 = class(TMemo)
private
FMaxLines: integer;
procedure SetMaxLines(const Value: integer);
{ Private declarations }
protected
{ Protected declarations }
procedure KeyPress(var Key: Char); override;
public
{ Public declarations }
constructor create(AOwner:TComponent);override;
published
{ Published declarations }
property MaxLines:integer read FMaxLines write SetMaxLines default 2;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TFFSMemo2]);
end;
{ TFFSMemo2 }
constructor TFFSMemo2.create(AOwner: TComponent);
begin
inherited;
MaxLines := 2;
end;
procedure TFFSMemo2.KeyPress(var Key: Char);
var oldx : integer;
begin
inherited;
if lines.Count > MaxLines then
begin
oldx := caretpos.x;
while caretpos.y >= MaxLines do selstart := selstart - 1;
while caretpos.x > oldx do selstart := selstart - 1;
sellength := 0;
while lines.count > MaxLines do lines.delete(maxlines);
end;
end;
procedure TFFSMemo2.SetMaxLines(const Value: integer);
begin
if Value >= 2 then FMaxLines := Value;
end;
end.
|
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, DB, ADODB, uADStanIntf, uADStanOption,
uADStanError, uADGUIxIntf, uADPhysIntf, uADStanDef, uADStanPool, uADStanAsync,
uADPhysManager, uADGUIxFormsWait, uADStanParam, uADDatSManager, uADDAptIntf,
uADDAptManager, uADPhysODBCBase, uADPhysMSSQL, uADCompDataSet, uADCompClient,
uADCompGUIx, Inifiles, Generics.Collections;
type
TfrmMain = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
prgForLoop2: TProgressBar;
btnForLoop: TButton;
btnForLoopProgress: TButton;
lblForLoop: TLabel;
lblForLoop2: TLabel;
ADOConnection1: TADOConnection;
ADOQuery1: TADOQuery;
mmoQuery: TMemo;
btnExecuteQuery: TButton;
lblExecuteQuery: TLabel;
Label1: TLabel;
lblExecuteQuery2: TLabel;
btnExecuteLowlevel: TButton;
lblExecuteQueryLow: TLabel;
btnExecuteQuery2: TButton;
bntOpenOffice: TButton;
TabSheet4: TTabSheet;
Button1: TButton;
Button2: TButton;
Button3: TButton;
dbMain: TADConnection;
ADGUIxWaitCursor1: TADGUIxWaitCursor;
qryFire: TADQuery;
ADPhysMSSQLDriverLink1: TADPhysMSSQLDriverLink;
TabSheet5: TTabSheet;
Button4: TButton;
TabSheet6: TTabSheet;
Button5: TButton;
TabSheet7: TTabSheet;
Button6: TButton;
TabSheet8: TTabSheet;
Button7: TButton;
Memo1: TMemo;
Button8: TButton;
Button9: TButton;
procedure btnForLoopClick(Sender: TObject);
procedure btnForLoopProgressClick(Sender: TObject);
procedure btnExecuteQueryClick(Sender: TObject);
procedure btnExecuteQuery2Click(Sender: TObject);
procedure btnExecuteLowlevelClick(Sender: TObject);
procedure bntOpenOfficeClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure Button9Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses
DateUtils, UHojaCalc, _uAsmProfDllLoader;
//StringConcatBench;
{$R *.dfm}
procedure TfrmMain.bntOpenOfficeClick(Sender: TObject);
var hcalc: THojaCalc;
i: Integer;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
HCalc:= THojaCalc.create(thcOpenOffice, false); //OpenOffice doc if possible, please
HCalc.FileName := ExtractFilePath(Application.ExeName) + 'testdoc'; //Needs a file name before you SaveDoc!
//Change a cell value.
for i := 1 to 1 * 1000 do
begin
IF HCalc.CellText[i,2] = '' THEN
HCalc.CellText[i,2] := 'Hello world!';
end;
HCalc.Free;
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
bntOpenOfficeClick(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.btnExecuteLowlevelClick(Sender: TObject);
var
i: Integer;
tstart: TDateTime;
data: _Recordset;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
ADOConnection1.Connected := True;
tstart := Now;
for i := 0 to 1000 do
begin
data := ADOConnection1.Execute(ADOQuery1.SQL.Text);
if (data.RecordCount > 0) then
data.Fields.Item[0].Value;
end;
lblExecuteQueryLow.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
btnExecuteLowlevelClick(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.btnExecuteQuery2Click(Sender: TObject);
var
i: Integer;
tstart: TDateTime;
data: _Recordset;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
ADOConnection1.Connected := True;
tstart := Now;
// mmoQuery.Lines.BeginUpdate;
try
for i := 0 to 1000 do
begin
mmoQuery.Lines.Add(ADOQuery1.SQL.Text);
data := ADOConnection1.Execute(ADOQuery1.SQL.Text);
if (data.RecordCount > 0) then
data.Fields.Item[0].Value;
end;
finally
// mmoQuery.Lines.EndUpdate;
end;
lblExecuteQuery2.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
btnExecuteQuery2Click(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.btnExecuteQueryClick(Sender: TObject);
var
i: Integer;
tstart: TDateTime;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
ADOConnection1.Connected := True;
tstart := Now;
for i := 0 to 100 do
begin
ADOQuery1.Active := True;
ADOQuery1.Active := False;
end;
lblExecuteQuery.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
btnExecuteQueryClick(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.btnForLoopClick(Sender: TObject);
var
i,j: Integer;
tstart: TDateTime;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
tstart := Now;
for i := 0 to 10 * 1000 * 1000 do
begin
j := i*2;
end;
if j > 0 then ;
lblForLoop.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
btnForLoopClick(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.btnForLoopProgressClick(Sender: TObject);
var
i,j: Integer;
tstart: TDateTime;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
tstart := Now;
prgForLoop2.Max := 10 * 1000 * 1000;
for i := 0 to 10 * 1000 * 1000 do
begin
j := i*2;
//if i mod 1000 = 0 then //update each 1000 items (e.g. remainder of 2000 / 1000 = 0)
if i mod 100 = 0 then //update each 100 items (e.g. remainder of 2000 / 100 = 0)
begin
prgForLoop2.Position := i;
prgForLoop2.Update;
end;
end;
if j > 0 then ;
lblForLoop2.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
btnForLoopProgressClick(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.Button1Click(Sender: TObject);
procedure Sleep100;
begin
Sleep(100);
end;
procedure Sleep1000;
var
i: Integer;
begin
for i := 1 to 10 do
Sleep100;
end;
var
i: Integer;
begin
//trick to get Button1Click in profiler
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
for i := 1 to 10 do
Sleep1000;
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
Button1Click(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.Button2Click(Sender: TObject);
var
i: Integer;
tstart: TDateTime;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
dbMain.Connected := True;
qryFire.SQL.Text := ADOQuery1.SQL.Text;
tstart := Now;
for i := 0 to 1000 do
begin
qryFire.Active := True;
qryFire.Active := False;
end;
lblExecuteQueryLow.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
Button2Click(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.Button3Click(Sender: TObject);
var
i: Integer;
tstart: TDateTime;
data: variant;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
dbMain.Connected := True;
tstart := Now;
for i := 0 to 1000 do
begin
data := dbMain.ExecSQLScalar(ADOQuery1.SQL.Text);
end;
lblExecuteQueryLow.Caption := Format('Duration: %dms',[MilliSecondsBetween(Now, tStart)]);
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
Button3Click(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
function MiniDumpWriteDump(hProcess: THANDLE; ProcessId: DWORD; hFile: THANDLE; DumpType: DWORD; ExceptionParam: pointer; UserStreamParam: pointer; CallbackParam: pointer): BOOL; stdcall;
external 'dbghelp.dll' name 'MiniDumpWriteDump';
const
SE_DEBUG_NAME = 'SeDebugPrivilege' ;
procedure GetDebugPrivileges;
var
hToken: THandle;
tkp: TTokenPrivileges;
retval: cardinal;
begin
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken)) then
begin
LookupPrivilegeValue(nil, SE_DEBUG_NAME , tkp.Privileges[0].Luid);
tkp.PrivilegeCount := 1;
tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, false, tkp, 0, nil, retval);
end;
end;
const
MiniDumpNormal = $0000;
MiniDumpWithDataSegs = $0001;
MiniDumpWithFullMemory = $0002;
MiniDumpWithHandleData = $0004;
MiniDumpFilterMemory = $0008;
MiniDumpScanMemory = $0010;
MiniDumpWithUnloadedModules = $0020;
MiniDumpWithIndirectlyReferencedMemory = $0040;
MiniDumpFilterModulePaths = $0080;
MiniDumpWithProcessThreadData = $0100;
MiniDumpWithPrivateReadWriteMemory = $0200;
MiniDumpWithThreadInfo = $1000;
procedure MakeMinidump(aPID:integer; const aOutputFile: string = '');
var
hProc,
hFile: THandle;
sFile: string;
begin
GetDebugPrivileges;
if aOutputFile = '' then
sFile := ExtractFileName(Application.ExeName) + '.dmp'
else
sFile := aOutputFile;
hProc := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, aPID);
hFile := CreateFile(PChar(sFile),
GENERIC_WRITE,FILE_SHARE_WRITE,nil,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
try
if not MiniDumpWriteDump(
hProc,
aPID,
hFile,
MiniDumpNormal or MiniDumpWithHandleData or
MiniDumpWithProcessThreadData or MiniDumpWithThreadInfo,
nil, nil ,nil) then
begin
if not MiniDumpWriteDump(
hProc, aPID, hFile,
MiniDumpNormal,
nil, nil ,nil)
then
RaiseLastOSError;
end;
finally
FileClose(hfile);
end;
end;
procedure TfrmMain.Button4Click(Sender: TObject);
const
C_GUI_TIME_OUT_SECONDS: Integer = 5;
begin
//start watchdog thread
TThread.CreateAnonymousThread(
procedure
var
iRes : DWORD_PTR;
begin
repeat
if SendMessageTimeOut(Application.MainForm.Handle,
WM_NULL, 0, 0,
SMTO_NORMAL, // or SMTO_NOTIMEOUTIFNOTHUNG or SMTO_ERRORONEXIT, // or SMTO_ABORTIFHUNG otherwise always after 5s?
//wait number of seconds...
C_GUI_TIME_OUT_SECONDS * 1000, @iRes) = 0 then
begin
if Application.Terminated then Exit;
if (GetLastError = ERROR_TIMEOUT) then
begin
MakeMinidump(GetCurrentProcessId);
Windows.MessageBox(0, 'Minidump made', 'Application hangs', MB_OK);
Exit;
end;
end;
until 1 = 2;
end).Start;
//let mainthread hang...
Sleep(C_GUI_TIME_OUT_SECONDS * 1000 * 2);
end;
procedure TfrmMain.Button5Click(Sender: TObject);
begin
//load dll + show GUI
if _uAsmProfDllLoader.LoadProfilerDll then
_uAsmProfDllLoader.ShowProfileForm;
end;
procedure TfrmMain.Button6Click(Sender: TObject);
var
str: TStringList;
dict: TDictionary<string,Integer>;
procedure _HashTest1;
var
i: Integer;
begin
str := THashedStringList.Create;
try
//str.Sorted := True;
for i := 0 to 10 * 1000 do
begin
str.AddObject(IntToStr(i), TObject(i));
//search 1 per 1000
if (i mod 1000) = 0 then
str.IndexOf(IntToStr(i-1));
end;
finally
str.Free;
end;
end;
procedure _HashTest2;
var
i: Integer;
begin
dict := TDictionary<string,Integer>.Create;
try
for i := 0 to 10 * 1000 do
begin
dict.Add(IntToStr(i), i);
//search 1 per 1000
if (i mod 1000) = 0 then
dict.ContainsKey(IntToStr(i-1));
end;
finally
dict.Free;
end;
end;
begin
if (Sender = nil) or not _uAsmProfDllLoader.IsProfilerDllLoaded then
begin
_HashTest1;
_HashTest2;
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
Button6Click(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end;
end;
procedure TfrmMain.Button7Click(Sender: TObject);
begin
(* StringConcatBench.NB_THREADS := 2;
Windows.SetPriorityClass(GetCurrentProcess, HIGH_PRIORITY_CLASS); //high prio for fair results
Memo1.Lines.Add( 'UseStringBuilder: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseStringBuilder ) );
Sleep(1000); //insert pause in proces explorer cpu graph
Memo1.Lines.Add( 'UseStringBuilderPreallocated: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseStringBuilderPreallocated ) );
Sleep(1000);
Memo1.Lines.Add( 'UseStringStream: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseStringStream ) );
Sleep(1000);
Memo1.Lines.Add( 'UseStringStream2: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseStringStream2 ) );
Sleep(1000);
Memo1.Lines.Add( 'UseConcatTrivial: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseConcatTrivial ) );
Sleep(1000);
Memo1.Lines.Add( 'UseConcatPreAllocated: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseConcatPreAllocated ) );
Sleep(1000);
Memo1.Lines.Add( 'UseConcatFormat: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseConcatFormat ) );
Sleep(1000);
Memo1.Lines.Add( 'UseWOBS: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseWOBS ) );
Sleep(1000);
Memo1.Lines.Add( 'UseTextWriter: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseTextWriter ) );
Sleep(1000);
Memo1.Lines.Add( 'UseStringData: ' + StringConcatBench.MeasureThreaded( StringConcatBench.UseStringData ) );
Sleep(1000);
Windows.SetPriorityClass(GetCurrentProcess, NORMAL_PRIORITY_CLASS); *)
end;
procedure TfrmMain.Button8Click(Sender: TObject);
begin
(* if Sender = nil then
begin
StringConcatBench.Measure( StringConcatBench.UseStringBuilder );
StringConcatBench.Measure( StringConcatBench.UseStringBuilderPreallocated );
StringConcatBench.Measure( StringConcatBench.UseStringStream );
StringConcatBench.Measure( StringConcatBench.UseStringStream2 );
StringConcatBench.Measure( StringConcatBench.UseConcatTrivial );
StringConcatBench.Measure( StringConcatBench.UseConcatPreAllocated );
StringConcatBench.Measure( StringConcatBench.UseConcatFormat );
StringConcatBench.Measure( StringConcatBench.UseWOBS );
StringConcatBench.Measure( StringConcatBench.UseTextWriter );
StringConcatBench.Measure( StringConcatBench.UseStringData );
end
else
begin
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StartProfiler(True);
Button8Click(nil);
if _uAsmProfDllLoader.IsProfilerDllLoaded then
_uAsmProfDllLoader.StopProfiler;
end; *)
end;
procedure TfrmMain.Button9Click(Sender: TObject);
begin
(* //run for long time, so we can start/stop sampling profiler
//StringConcatBench.NB := 1000;
StringConcatBench.MEASURE_ITER := 10 * 1000 * 1000;
//normal strings
Memo1.Lines.Add( 'UseConcatTrivial: ' + StringConcatBench.Measure( StringConcatBench.UseConcatTrivial ) );
Application.ProcessMessages;
//dws
Memo1.Lines.Add( 'UseWOBS: ' + StringConcatBench.Measure( StringConcatBench.UseWOBS ) );
Application.ProcessMessages;
//mormot
Memo1.Lines.Add( 'UseTextWriter: ' + StringConcatBench.Measure( StringConcatBench.UseTextWriter ) );
Application.ProcessMessages; *)
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
PageControl1.ActivePageIndex := 0;
end;
end.
|
unit DataContainers.TRecord;
interface
uses
System.SysUtils, System.Variants,
Utils.TArrayUtil,
Framework.Interfaces,
Exceptions.EFieldNameMustBeUniqueException;
type
TRecord = class(TInterfacedObject, IRecord)
strict private
FFields: TArray<IField>;
function FieldNameAlreadyExists(const AFieldName: String): Boolean;
function GetFields: TArray<IField>;
public
constructor Create;
destructor Destroy; override;
function FieldByName(const AFieldName: String): IField;
procedure AddField(const AField: IField);
property Fields: TArray<IField> read GetFields;
end;
implementation
{ TRecord }
procedure TRecord.AddField(const AField: IField);
begin
if FieldNameAlreadyExists(AField.Name) then
raise EFieldNameMustBeUniqueException.Create(EFieldNameMustBeUniqueException.FIELD_NAME_MUST_BE_UNIQUE_MESSAGE);
TArrayUtil<IField>.Append(FFields, AField);
end;
constructor TRecord.Create;
begin
inherited;
end;
destructor TRecord.Destroy;
begin
inherited;
end;
function TRecord.FieldByName(const AFieldName: String): IField;
var
Index: Integer;
begin
Result := Nil;
for Index := 0 to Length(FFields) - 1 do
if (UpperCase(FFields[Index].Name) = UpperCase(Trim(AFieldName))) then
begin
Result := FFields[Index];
Break;
end;
if Result = Nil then
begin
raise Exception.Create('Field not Found. Please, check your File Definition');
Abort;
end;
end;
function TRecord.FieldNameAlreadyExists(const AFieldName: String): Boolean;
var
Index: Integer;
begin
for Index := 0 to Length(FFields) - 1 do
begin
Result := UpperCase(Trim(FFields[Index].Name)) = UpperCase(Trim(AFieldName));
if Result then
Break;
end;
end;
function TRecord.GetFields: TArray<IField>;
begin
Result := FFields;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit OraSysPrivs;
interface
uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable;
type
Priv = record
GRANTEE,
NAME : string;
PROPERTIES: Integer;
GRANTED,
ADMIN_OPTION : boolean;
end;
TPriv = ^Priv;
TPrivList = class(TObject)
private
FPrivList: TList;
FOraSession: TOraSession;
FDSPrivList: TVirtualTable;
FGRANTEE: String;
function GetPriv(Index: Integer): TPriv;
procedure SetPriv(Index: Integer; Priv: TPriv);
function GetPrivCount: Integer;
function GetPrivs: string;
public
procedure PrivAdd(Priv: TPriv);
procedure PrivDelete(Index: Integer);
property PrivCount: Integer read GetPrivCount;
property PrivItems[Index: Integer]: TPriv read GetPriv write SetPriv;
procedure CopyFrom(PrivList: TPrivList);
function FindByPriv(Name: string): integer;
property GRANTEE: String read FGRANTEE write FGRANTEE;
property DSPrivList: TVirtualTable read FDSPrivList;
property OraSession: TOraSession read FOraSession write FOraSession;
constructor Create;
destructor Destroy; override;
procedure SetDDL;
function GetDDL: string;
function GetAlterDDL(APrivList: TPrivList): string;
function Priv(PrivScript: string) : boolean;
end;
function GetSysPrivs: string;
implementation
uses util, frmSchemaBrowser;
{********************** TPriv ***********************************}
function GetSysPrivs: string;
begin
result := 'select * from sys.system_privilege_map ';
end;
constructor TPrivList.Create;
begin
FPrivList := TList.Create;
FDSPrivList := TVirtualTable.Create(nil);
end;
destructor TPrivList.Destroy;
var
i : Integer;
FPriv: TPriv;
begin
try
if FPrivList.Count > 0 then
begin
for i := FPrivList.Count - 1 downto 0 do
begin
FPriv := FPrivList.Items[i];
Dispose(FPriv);
end;
end;
finally
FPrivList.Free;
end;
FDSPrivList.Free;
inherited;
end;
function TPrivList.GetPrivs: string;
begin
result :=
' Select GRANTEE, spm.name, '
+' decode(dsp.GRANTEE,null,''NO'',''YES'') GRANTED, '
+' nvl(dsp.ADMIN_OPTION,''NO'') ADMIN_OPTION, '
+' PROPERTY '
+' from sys.dba_sys_privs dsp, '
+' sys.system_privilege_map spm '
+' where dsp.privilege(+) = spm.name '
+' and dsp.grantee(+)= :pName '
+' and spm.name not in (''DEBUG CONNECT ANY'', ''DEBUG CONNECT USER'') '
+' order by spm.name ';
end;
procedure TPrivList.PrivAdd(Priv: TPriv);
begin
FPrivList.Add(Priv);
end;
procedure TPrivList.PrivDelete(Index: Integer);
begin
TObject(FPrivList.Items[Index]).Free;
FPrivList.Delete(Index);
end;
function TPrivList.GetPriv(Index: Integer): TPriv;
begin
Result := FPrivList.Items[Index];
end;
procedure TPrivList.SetPriv(Index: Integer; Priv: TPriv);
begin
if Assigned(Priv) then
FPrivList.Items[Index] := Priv;
end;
function TPrivList.GetPrivCount: Integer;
begin
Result := FPrivList.Count;
end;
procedure TPrivList.CopyFrom(PrivList: TPrivList);
var
i: integer;
begin
FOraSession := PrivList.OraSession;
FGRANTEE := PrivList.GRANTEE;
for i := 0 to PrivList.PrivCount -1 do
FPrivList.Add(TPriv(PrivList.PrivItems[i]));
end;
function TPrivList.FindByPriv(Name: string): integer;
var
i: integer;
begin
result := -1;
for i := 0 to FPrivList.Count -1 do
begin
if (TPriv(FPrivList[i]).NAME = Name) then
begin
result := i;
exit;
end;
end;
end;
procedure TPrivList.SetDDL;
var
FPriv: TPriv;
q: TOraQuery;
begin
q := TOraQuery.Create(nil);
q.Session := FOraSession;
q.SQL.Text := GetPrivs;
q.ParamByName('pName').AsString := FGRANTEE;
q.Open;
CopyDataSet(q, FDSPrivList);
while not q.Eof do
begin
if q.FieldByName('GRANTEE').AsString = FGRANTEE then
begin
new(FPriv);
FPriv^.GRANTEE := q.FieldByName('GRANTEE').AsString;
FPriv^.PROPERTIES := q.FieldByName('PROPERTY').asInteger;
FPriv^.NAME := q.FieldByName('NAME').AsString;
FPriv^.GRANTED := q.FieldByName('GRANTED').AsString = 'YES';
FPriv^.ADMIN_OPTION := q.FieldByName('ADMIN_OPTION').AsString = 'YES';
PrivAdd(FPriv);
end;
q.Next;
end;
q.close;
end;
function TPrivList.GetDDL: string;
var
i: integer;
FPriv: TPriv;
s: string;
begin
s := '';
with self do
begin
for i := 0 to GetPrivCount -1 do
begin
if FPriv.GRANTEE <> '' then
begin
s := '';
FPriv := PrivItems[i];
if FPriv.GRANTED then
s := ln+ 'GRANT '+FPriv.NAME +' TO '+FPriv.GRANTEE;
if FPriv.ADMIN_OPTION then
s := s + ' WITH ADMIN OPTION ';
if s <> '' then
s := s + ';';
result := result + s;
end;
end;
end; //with self
end;
function TPrivList.GetAlterDDL(APrivList: TPrivList): string;
var
i: integer;
FPriv: TPriv;
s: string;
begin
s := '';
with self do
begin
for i := 0 to GetPrivCount -1 do
begin
FPriv := PrivItems[i];
if FPriv.GRANTEE <> '' then
begin
if APrivList.FindByPriv(FPriv.NAME) >= 0 then
begin
if not FPriv.GRANTED then
result := result + ln+ 'REWORK '+FPriv.NAME +' FROM '+FPriv.GRANTEE +';';
end else
begin
s := '';
if FPriv.GRANTED then
s := ln+ 'GRANT '+FPriv.NAME +' TO '+FPriv.GRANTEE;
if (FPriv.ADMIN_OPTION) and ( s <> '') then
s := s + ' WITH ADMIN OPTION ';
if s <> '' then
s := s + ';';
result := result + s;
end;
end;
end;
end; //with self
end;
function TPrivList.Priv(PrivScript: string) : boolean;
begin
result := ExecSQL(PrivScript, '', FOraSession);
end;
end.
|
unit JunoApi4DelphiManager;
interface
uses
JunoApi4Delphi.Interfaces;
type
TJunoApi4DelphiManager = class(TInterfacedObject, iJunoApi4DelphiManager)
private
FConfig : iJunoApi4DelphiConig;
public
constructor Create;
destructor Destroy; override;
class function New : iJunoApi4DelphiManager;
function ContentTypeHeader : String;
function ContentEncodingHeader : String;
function XResourceToken : String;
function XApiVersion : String;
function Config : iJunoApi4DelphiConig;
function Resources : iJunoApi4DelphiResources;
end;
implementation
uses
JunoApi4Delphi.Config, JunoAi4DelphiResources;
{ TJunoApi4DelphiManager }
function TJunoApi4DelphiManager.Config: iJunoApi4DelphiConig;
begin
FConfig := TJunoApi4DelphiConig.New;
Result := FConfig;
end;
function TJunoApi4DelphiManager.ContentEncodingHeader: String;
begin
Result := 'Content-encoding';
end;
function TJunoApi4DelphiManager.ContentTypeHeader: String;
begin
Result := 'Content-type';
end;
constructor TJunoApi4DelphiManager.Create;
begin
end;
destructor TJunoApi4DelphiManager.Destroy;
begin
inherited;
end;
class function TJunoApi4DelphiManager.New: iJunoApi4DelphiManager;
begin
Result := Self.Create;
end;
function TJunoApi4DelphiManager.Resources: iJunoApi4DelphiResources;
begin
Result := TJunoApi4DelphiResources.New(FConfig);
end;
function TJunoApi4DelphiManager.XApiVersion: String;
begin
Result := 'X-API-Version';
end;
function TJunoApi4DelphiManager.XResourceToken: String;
begin
Result := 'X-Resource-Token';
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2021 Kike Pérez
Unit : Quick.Url.Utils
Description : Common Url utils
Author : Kike Pérez
Version : 2.0
Created : 17/03/2021
Modified : 17/03/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Url.Utils;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
{$IFDEF NOTUSEINDY}
System.NetEncoding,
{$ELSE}
IdURI,
{$ENDIF}
Quick.Commons;
type
TUrlUtils = class
class function GetProtocol(const aUrl : string) : string;
class function GetHost(const aUrl : string) : string;
class function GetPath(const aUrl : string) : string;
class function GetQuery(const aUrl : string) : string;
class function RemoveProtocol(const aUrl : string) : string;
class function RemoveQuery(const aUrl : string) : string;
class function EncodeUrl(const aUrl : string) : string;
end;
implementation
{ TUrlUtils }
class function TUrlUtils.EncodeUrl(const aUrl: string): string;
{$IFDEF NOTUSEINDY}
const
RestUnsafeChars: TURLEncoding.TUnsafeChars = [Ord('"'), Ord(''''), Ord(':'), Ord(';'), Ord('<'), Ord('='), Ord('>'),
Ord('@'), Ord('['), Ord(']'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'), Ord('\'), Ord('?'), Ord('#'),
Ord('&'), Ord('!'), Ord('$'), Ord('('), Ord(')'), Ord(','), Ord('~'), Ord(' '), Ord('*'), Ord('+')];
{$ENDIF}
var
proto : string;
path : string;
query : string;
begin
{$IFDEF NOTUSEINDY}
Result := TNetEncoding.URL.Encode(aUrl);
//Result := StringReplace(aUrl,' ','%20',[rfReplaceAll]);
proto := UrlGetProtocol(aUrl);
if not proto.IsEmpty then proto := proto + '://';
path := UrlGetPath(aUrl);
path := TNetEncoding.Url.EncodePath(path);
query := UrlGetQuery(aUrl);
query := TNetEncoding.Url.EncodeQuery(query);
if not query.IsEmpty then query := '?' + query;
Result := proto + UrlGetHost(aUrl) + path + query;
{$ELSE}
Result := TIdURI.URLEncode(aUrl);
{$ENDIF}
end;
class function TUrlUtils.GetProtocol(const aUrl: string): string;
begin
Result := UrlGetProtocol(aUrl);
end;
class function TUrlUtils.GetHost(const aUrl: string): string;
begin
Result := UrlGetHost(aUrl);
end;
class function TUrlUtils.GetPath(const aUrl: string): string;
begin
Result := UrlGetPath(aUrl);
end;
class function TUrlUtils.GetQuery(const aUrl: string): string;
begin
Result := UrlGetQuery(aUrl);
end;
class function TUrlUtils.RemoveProtocol(const aUrl: string): string;
begin
Result := UrlRemoveProtocol(aUrl);
end;
class function TUrlUtils.RemoveQuery(const aUrl: string): string;
begin
Result := UrlRemoveQuery(aUrl);
end;
end.
|
unit csImportTaskPrim;
// Модуль: "w:\common\components\rtl\Garant\cs\csImportTaskPrim.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TcsImportTaskPrim" MUID: (53ABFE3202CF)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, csProcessTask
, csTasksHelpers
, evdTasksHelpers
, k2Base
;
type
TcsImportTaskPrim = class(TddProcessTask)
protected
function pm_GetDeleteIncluded: Boolean;
procedure pm_SetDeleteIncluded(aValue: Boolean);
function pm_GetIsAnnotation: Boolean;
procedure pm_SetIsAnnotation(aValue: Boolean);
function pm_GetIsRegion: Boolean;
procedure pm_SetIsRegion(aValue: Boolean);
function pm_GetSourceDir: AnsiString;
procedure pm_SetSourceDir(const aValue: AnsiString);
function pm_GetSourceFiles: SourceFilesHelper;
function pm_GetRegionIDList: RegionIDListHelper;
function pm_GetSafeDir: AnsiString;
procedure pm_SetSafeDir(const aValue: AnsiString);
function pm_GetNeedSendMailReport: Boolean;
procedure pm_SetNeedSendMailReport(aValue: Boolean);
public
class function GetTaggedDataType: Tk2Type; override;
public
property DeleteIncluded: Boolean
read pm_GetDeleteIncluded
write pm_SetDeleteIncluded;
property IsAnnotation: Boolean
read pm_GetIsAnnotation
write pm_SetIsAnnotation;
property IsRegion: Boolean
read pm_GetIsRegion
write pm_SetIsRegion;
property SourceDir: AnsiString
read pm_GetSourceDir
write pm_SetSourceDir;
property SourceFiles: SourceFilesHelper
read pm_GetSourceFiles;
property RegionIDList: RegionIDListHelper
read pm_GetRegionIDList;
property SafeDir: AnsiString
read pm_GetSafeDir
write pm_SetSafeDir;
property NeedSendMailReport: Boolean
read pm_GetNeedSendMailReport
write pm_SetNeedSendMailReport;
end;//TcsImportTaskPrim
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, ImportTask_Const
//#UC START# *53ABFE3202CFimpl_uses*
//#UC END# *53ABFE3202CFimpl_uses*
;
function TcsImportTaskPrim.pm_GetDeleteIncluded: Boolean;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.BoolA[k2_attrDeleteIncluded]);
end;//TcsImportTaskPrim.pm_GetDeleteIncluded
procedure TcsImportTaskPrim.pm_SetDeleteIncluded(aValue: Boolean);
begin
TaggedData.BoolW[k2_attrDeleteIncluded, nil] := (aValue);
end;//TcsImportTaskPrim.pm_SetDeleteIncluded
function TcsImportTaskPrim.pm_GetIsAnnotation: Boolean;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.BoolA[k2_attrIsAnnotation]);
end;//TcsImportTaskPrim.pm_GetIsAnnotation
procedure TcsImportTaskPrim.pm_SetIsAnnotation(aValue: Boolean);
begin
TaggedData.BoolW[k2_attrIsAnnotation, nil] := (aValue);
end;//TcsImportTaskPrim.pm_SetIsAnnotation
function TcsImportTaskPrim.pm_GetIsRegion: Boolean;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.BoolA[k2_attrIsRegion]);
end;//TcsImportTaskPrim.pm_GetIsRegion
procedure TcsImportTaskPrim.pm_SetIsRegion(aValue: Boolean);
begin
TaggedData.BoolW[k2_attrIsRegion, nil] := (aValue);
end;//TcsImportTaskPrim.pm_SetIsRegion
function TcsImportTaskPrim.pm_GetSourceDir: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrSourceDir]);
end;//TcsImportTaskPrim.pm_GetSourceDir
procedure TcsImportTaskPrim.pm_SetSourceDir(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrSourceDir, nil] := (aValue);
end;//TcsImportTaskPrim.pm_SetSourceDir
function TcsImportTaskPrim.pm_GetSourceFiles: SourceFilesHelper;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := TSourceFilesHelper.Make(TaggedData.cAtom(k2_attrSourceFiles));
end;//TcsImportTaskPrim.pm_GetSourceFiles
function TcsImportTaskPrim.pm_GetRegionIDList: RegionIDListHelper;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := TRegionIDListHelper.Make(TaggedData.cAtom(k2_attrRegionIDList));
end;//TcsImportTaskPrim.pm_GetRegionIDList
function TcsImportTaskPrim.pm_GetSafeDir: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrSafeDir]);
end;//TcsImportTaskPrim.pm_GetSafeDir
procedure TcsImportTaskPrim.pm_SetSafeDir(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrSafeDir, nil] := (aValue);
end;//TcsImportTaskPrim.pm_SetSafeDir
function TcsImportTaskPrim.pm_GetNeedSendMailReport: Boolean;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.BoolA[k2_attrNeedSendMailReport]);
end;//TcsImportTaskPrim.pm_GetNeedSendMailReport
procedure TcsImportTaskPrim.pm_SetNeedSendMailReport(aValue: Boolean);
begin
TaggedData.BoolW[k2_attrNeedSendMailReport, nil] := (aValue);
end;//TcsImportTaskPrim.pm_SetNeedSendMailReport
class function TcsImportTaskPrim.GetTaggedDataType: Tk2Type;
begin
Result := k2_typImportTask;
end;//TcsImportTaskPrim.GetTaggedDataType
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit UnitCadExperienciaProfissional;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TFormCadExperienciaProfissional = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edEmpresa: TEdit;
edCargo: TEdit;
edInicio: TEdit;
edTermino: TEdit;
Panel2: TPanel;
btOk: TButton;
btNovo: TButton;
procedure btOkClick(Sender: TObject);
procedure btNovoClick(Sender: TObject);
private
procedure SalvarDados();
public
id_curriculo: Integer;
end;
var
id_experiencia_profissional: Integer;
FormCadExperienciaProfissional: TFormCadExperienciaProfissional;
implementation
{$R *.dfm}
uses UDataModule;
procedure TFormCadExperienciaProfissional.btNovoClick(Sender: TObject);
begin
SalvarDados();
edEmpresa.Text := '';
edCargo.Text := '';
edInicio.Text := '';
edTermino.Text := '';
edEmpresa.SetFocus;
end;
procedure TFormCadExperienciaProfissional.btOkClick(Sender: TObject);
begin
SalvarDados();
Close();
end;
procedure TFormCadExperienciaProfissional.SalvarDados();
var
empresa, cargo, ano_inicio, ano_termino: String;
camposPreenchidos: Boolean;
begin
empresa := edEmpresa.Text;
cargo := edCargo.Text;
ano_inicio := edInicio.Text;
ano_termino := edTermino.Text;
camposPreenchidos := (empresa <> '') and (cargo <> '') and (ano_inicio <> '');
if (camposPreenchidos) then
begin
with DM.FDQueryTemp do
begin
Close();
SQL.Clear;
SQL.Add('insert into experiencia_profissional (empresa, cargo, ano_inicio, ano_termino) values (:pEmpresa, :pCargo, :pAno_inicio, :pAno_termino);');
ParamByName('pEmpresa').AsString := empresa;
ParamByName('pCargo').AsString := cargo;
ParamByName('pAno_inicio').AsString := ano_inicio;
ParamByName('pAno_termino').AsString := ano_termino;
ExecSQL();
DM.FDConnection1.Commit();
Close();
end;
with DM.FDQueryTemp do
begin
Close();
SQL.Clear();
SQL.Add('SELECT max(id_experiencia_profissional) FROM experiencia_profissional');
Open();
id_experiencia_profissional := Fields[0].AsInteger;
Close();
end;
with DM.FDQueryTemp do
begin
Close();
SQL.Clear();
SQL.Add('insert into GERAR_EXP_PROFISSIONAL (id_curriculo, id_experiencia_profissional) values (:pId_curriculo, :PId_experiencia_profissional)');
ParamByName('pId_curriculo').AsInteger := id_curriculo;
ParamByName('PId_experiencia_profissional').AsInteger :=
id_experiencia_profissional;
ExecSQL();
DM.FDConnection1.Commit();
Close();
end;
end
else
raise Exception.Create('Preencha todos os campos obrigatórios.');
end;
end.
|
unit SearchAndReplacePrimTest;
{* Тест поиска/замены }
// Модуль: "w:\common\components\gui\Garant\Daily\SearchAndReplacePrimTest.pas"
// Стереотип: "TestCase"
// Элемент модели: "TSearchAndReplacePrimTest" MUID: (4C288B4D012F)
{$Include w:\common\components\gui\sdotDefine.inc}
interface
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3IntfUses
, TextViaEditorProcessor
, nevTools
, evTypes
, PrimTextLoad_Form
;
type
TSearchAndReplacePrimTest = {abstract} class(TTextViaEditorProcessor)
{* Тест поиска/замены }
protected
function Searcher: IevSearcher; virtual; abstract;
function Replacer: IevReplacer; virtual; abstract;
function Options: TevSearchOptionSet; virtual; abstract;
procedure Process(aForm: TPrimTextLoadForm); override;
{* Собственно процесс обработки текста }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TSearchAndReplacePrimTest
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
implementation
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3ImplUses
, TestFrameWork
, vcmBase
, SysUtils
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
, l3Base
//#UC START# *4C288B4D012Fimpl_uses*
//#UC END# *4C288B4D012Fimpl_uses*
;
procedure TSearchAndReplacePrimTest.Process(aForm: TPrimTextLoadForm);
{* Собственно процесс обработки текста }
//#UC START# *4BE13147032C_4C288B4D012F_var*
//#UC END# *4BE13147032C_4C288B4D012F_var*
begin
//#UC START# *4BE13147032C_4C288B4D012F_impl*
aForm.Text.Find(Searcher,
Replacer,
Options);
//#UC END# *4BE13147032C_4C288B4D012F_impl*
end;//TSearchAndReplacePrimTest.Process
function TSearchAndReplacePrimTest.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'Everest';
end;//TSearchAndReplacePrimTest.GetFolder
function TSearchAndReplacePrimTest.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4C288B4D012F';
end;//TSearchAndReplacePrimTest.GetModelElementGUID
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
end.
|
{$include lem_directives.inc}
unit LemTypes;
interface
uses
Classes, SysUtils, Contnrs,
GR32, GR32_LowLevel,
UZip,
//Dialogs,
UTools;
type
TLemDataType = (
ldtNone,
ldtLemmings, // resource 'lemdata'
ldtSound, // resource 'lemsounds'
ldtMusic,
ldtParticles
);
type
TBitmaps = class(TObjectList)
private
function GetItem(Index: Integer): TBitmap32;
protected
public
function Add(Item: TBitmap32): Integer;
procedure Insert(Index: Integer; Item: TBitmap32);
property Items[Index: Integer]: TBitmap32 read GetItem; default;
property List;
published
end;
TBasicWrapper = class(TComponent)
private
fPersistentObject: TPersistent;
protected
public
published
property PersistentObject: TPersistent read fPersistentObject write fPersistentObject;
end;
// lemlowlevel
procedure ReplaceColor(B: TBitmap32; FromColor, ToColor: TColor32);
function CalcFrameRect(Bmp: TBitmap32; FrameCount, FrameIndex: Integer): TRect;
procedure PrepareFramedBitmap(Bmp: TBitmap32; FrameCount, FrameWidth, FrameHeight: Integer);
procedure InsertFrame(Dst, Src: TBitmap32; FrameCount, FrameIndex: Integer);
function AppPath: string;
function LemmingsPath: string;
function MusicsPath: string;
function CreateDataStream(const aFileName: string; aType: TLemDataType): TStream;
implementation
var
_AppPath: string;
function AppPath: string;
begin
if _AppPath = '' then
_AppPath := ExtractFilePath(ParamStr(0));
Result := _AppPath;
end;
function LemmingsPath: string;
begin
// @styledef
Result := AppPath;
end;
function MusicsPath: string;
begin
// @styledef
Result := AppPath;
end;
procedure ReplaceColor(B: TBitmap32; FromColor, ToColor: TColor32);
var
P: PColor32;
i: Integer;
begin
P := B.PixelPtr[0, 0];
for i := 0 to B.Height * B.Width - 1 do
begin
if P^ = FromColor then
P^ := ToColor;
Inc(P);
end;
end;
function CalcFrameRect(Bmp: TBitmap32; FrameCount, FrameIndex: Integer): TRect;
var
Y, H, W: Integer;
begin
W := Bmp.Width;
H := Bmp.Height div FrameCount;
Y := H * FrameIndex;
// Assert(Bmp.Height mod FrameCount = 0)
Result.Left := 0;
Result.Top := Y;
Result.Right := W;
Result.Bottom := Y + H;
end;
procedure PrepareFramedBitmap(Bmp: TBitmap32; FrameCount, FrameWidth, FrameHeight: Integer);
begin
Bmp.SetSize(FrameWidth, FrameCount * FrameHeight);
Bmp.ResetAlpha(0);
end;
procedure InsertFrame(Dst, Src: TBitmap32; FrameCount, FrameIndex: Integer);
var
H, Y: Integer;
W: Integer;
SrcP, DstP: PColor32;
begin
Assert(FrameCount > 0);
Assert(Dst.Height = FrameCount * Src.Height);
Assert(Dst.Width = Src.Width);
H := Dst.Height div FrameCount;
Y := H * FrameIndex;
SrcP := Src.PixelPtr[0, 0];
DstP := Dst.PixelPtr[0, Y];
W := Dst.Width;
for Y := 0 to H - 1 do
begin
MoveLongWord(SrcP^, DstP^, W);
Inc(SrcP, W);
Inc(DstP, W);
end;
end;
function CreateDataStream__(const aFileName: string; aType: TLemDataType): TStream;
{-------------------------------------------------------------------------------
Dependent on the compiled mode we create a filestream or a
decompressed memorystream from resource.
Note the ExtractFileName(): we did *not* include path info in the
archived resource files
-------------------------------------------------------------------------------}
{$ifdef resourcelemmings}
var
Arc: TArchive;
{$endif}
begin
{$ifdef resourcelemmings}
Result := TMemoryStream.Create;
Arc := TArchive.Create;
try
try
case aType of
ldtLemmings: Arc.OpenResource(HINSTANCE, 'lemdata', 'archive');
ldtSound: Arc.OpenResource(HINSTANCE, 'lemsounds', 'archive');
ldtMusic: Arc.OpenResource(HINSTANCE, 'lemmusic', 'archive');
end;
Arc.ExtractFile(ExtractFileName(aFileName), Result);
except
FreeAndNil(Result);
raise;
end;
Result.Seek(0, soFromBeginning);
finally
Arc.Free;
end;
{$else}
Result := TFileStream.Create(aFileName, fmOpenRead);
{$endif}
end;
function CreateDataStream(const aFileName: string; aType: TLemDataType): TStream;
{-------------------------------------------------------------------------------
Dependent on the compiled mode we create a filestream or a
decompressed memorystream from resource.
Note the ExtractFileName(): we did *not* include path info in the
archived resource files
-------------------------------------------------------------------------------}
{$ifdef resourcelemmings}
var
Arc: TArchive;
tk: String;
{$endif}
begin
case aType of
ldtLemmings:
begin
{$ifdef resourcelemdata}
Result := TMemoryStream.Create;
Arc := TArchive.Create;
try
Arc.OpenResource(HINSTANCE, 'lemdata', 'archive');
Arc.ExtractFile(ExtractFileName(aFileName), Result);
finally
Arc.Free;
end;
{$else}
Result := TFileStream.Create(aFileName, fmOpenRead);
{$endif}
end;
ldtSound:
begin
{$ifdef resourcelemsounds}
Result := TMemoryStream.Create;
Arc := TArchive.Create;
try
Arc.OpenResource(HINSTANCE, 'lemsounds', 'archive');
Arc.ExtractFile(ExtractFileName(aFileName), Result);
finally
Arc.Free;
end;
{$else}
Result := TFileStream.Create(aFileName, fmOpenRead);
{$endif}
end;
ldtMusic:
begin
{$ifdef resourcelemmusic}
Result := TMemoryStream.Create;
Arc := TArchive.Create;
try
{$ifdef extmusic}
tk := ChangeFileExt(ParamStr(0), '') + '_MUSIC.DAT';
//MessageDlg(tk, mtcustom, [mbok], 0);
if FileExists(tk) then Arc.OpenArchive(tk, amOpen)
else
{$endif}
Arc.OpenResource(HINSTANCE, 'lemmusic', 'archive');
tk := ChangeFileExt(aFileName, '') + '.ogg';
if Arc.ArchiveList.IndexOf(ExtractFileName(tk)) = -1 then tk := aFileName + '.it';
Arc.ExtractFile(ExtractFileName(tk), Result);
finally
Arc.Free;
end;
{$else}
tk := ChangeFileExt(aFileName, '') + '.ogg';
Result := TFileStream.Create(tk, fmOpenRead);
{$endif}
end;
ldtParticles:
begin
{$ifdef resourceparticles}
Result := TMemoryStream.Create;
Arc := TArchive.Create;
try
Arc.OpenResource(HINSTANCE, 'lemparticles', 'archive');
Arc.ExtractFile(ExtractFileName(aFileName), Result);
finally
Arc.Free;
end;
{$else}
Result := TFileStream.Create(aFileName, fmOpenRead);
{$endif}
end;
else
Result := nil;
end;
Assert(Result <> nil);
Result.Seek(0, soFromBeginning);
end;
{ TBitmaps }
function TBitmaps.Add(Item: TBitmap32): Integer;
begin
Result := inherited Add(Item);
end;
function TBitmaps.GetItem(Index: Integer): TBitmap32;
begin
Result := inherited Get(Index);
end;
procedure TBitmaps.Insert(Index: Integer; Item: TBitmap32);
begin
inherited Insert(Index, Item);
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uMultiCastEventImpl.pas }
{ Описание: Реализация IMultiCastEvent }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uMultiCastEventImpl;
interface
uses
SysUtils, Classes, uMultiCastEvent;
function CreateMultiCastEvent: IMultiCastEvent;
implementation
type
PMethod = ^TMethod;
type
TMultiCastEvent = class(TInterfacedObject, IMultiCastEvent)
private
FList: TList;
public
procedure AfterConstruction(); override;
procedure BeforeDestruction; override;
procedure Broadcast(ASender: TObject); stdcall;
procedure RegisterListener(AListener: TNotifyEvent); stdcall;
procedure UnRegisterListener(AListener: TNotifyEvent); stdcall;
end;
procedure TMultiCastEvent.AfterConstruction;
begin
inherited;
FList := TList.Create;
end;
procedure TMultiCastEvent.BeforeDestruction;
begin
while FList.Count > 0 do
begin
Dispose(FList[0]);
FList.Delete(0);
end;
FList.Free;
inherited;
end;
procedure TMultiCastEvent.Broadcast(ASender: TObject);
var
I: Integer;
P: PMethod;
begin
for I := 0 to FList.Count-1 do
begin
P := PMethod(FList[I]);
TNotifyEvent(P^)(ASender);
end;
end;
procedure TMultiCastEvent.RegisterListener(AListener: TNotifyEvent);
var
P: PMethod;
begin
New(P);
P.Code := TMethod(AListener).Code;
P.Data := TMethod(AListener).Data;
FList.Add(P);
end;
procedure TMultiCastEvent.UnRegisterListener(AListener: TNotifyEvent);
var
P: PMethod;
I: Integer;
Index: Integer;
begin
Index := -1;
for I := 0 to FList.Count-1 do
begin
P := PMethod(FList[I]);
if (P.Data = TMethod(AListener).Data) and (P.Code = TMethod(AListener).Code) then
begin
Index := I;
Break;
end;
end;
if Index > -1 then
begin
Dispose(FList[I]);
FList.Delete(I);
end;
end;
function CreateMultiCastEvent: IMultiCastEvent;
begin
Result := TMultiCastEvent.Create;
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.ProgressDialog.Android;
interface
uses
AndroidApi.ProgressDialog, AndroidApi.JNIBridge, Androidapi.JNI.GraphicsContentViewText,
FGX.ProgressDialog, FGX.ProgressDialog.Types;
type
{ TAndroidProgressDialogService }
TAndroidProgressDialogService = class(TInterfacedObject, IFGXProgressDialogService)
public
{ IFGXProgressDialogService }
function CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog;
function CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog;
end;
TDialogDismissListener = class;
TAndroidNativeActivityDialog = class(TfgNativeActivityDialog)
private
FID: Integer;
FNativeDialog: JProgressDialog;
FDialogListener: TDialogDismissListener;
protected
procedure InitNativeDialog; virtual;
{ inherited }
procedure TitleChanged; override;
procedure MessageChanged; override;
procedure CancellableChanged; override;
function GetIsShown: Boolean; override;
public
constructor Create(const AOwner: TObject); override;
destructor Destroy; override;
procedure Show; override;
procedure Hide; override;
property ID: Integer read FID;
end;
TAndroidNativeProgressDialog = class(TfgNativeProgressDialog)
private
FID: Integer;
FNativeDialog: JProgressDialog;
FDialogListener: TDialogDismissListener;
protected
function IsDialogKindDeterminated(const DialogKind: TfgProgressDialogKind): Boolean;
procedure InitNativeDialog; virtual;
{ inherited }
procedure TitleChanged; override;
procedure KindChanged; override;
procedure MessageChanged; override;
procedure ProgressChanged; override;
procedure CancellableChanged; override;
procedure RangeChanged; override;
function GetIsShown: Boolean; override;
public
constructor Create(const AOwner: TObject); override;
destructor Destroy; override;
procedure ResetProgress; override;
procedure Show; override;
procedure Hide; override;
property ID: Integer read FID;
end;
TDialogDismissListener = class(TJavaLocal, JDialogInterface_OnCancelListener)
private
[Weak] FDialog: TfgNativeDialog;
public
constructor Create(const ADialog: TfgNativeDialog);
{ JDialogInterface_OnCancelListener }
procedure onCancel(dialog: JDialogInterface); cdecl;
end;
procedure RegisterService;
procedure UnregisterService;
implementation
uses
System.SysUtils, System.Classes, Androidapi.Helpers, AndroidApi.JNI.JavaTypes, Androidapi.JNI.App, FMX.Platform,
FMX.Platform.Android, FMX.Helpers.Android, FMX.Types, FGX.Helpers, FGX.Helpers.Android, FGX.Asserts;
procedure RegisterService;
begin
if TOSVersion.Check(2, 0) then
TPlatformServices.Current.AddPlatformService(IFGXProgressDialogService, TAndroidProgressDialogService.Create);
end;
procedure UnregisterService;
begin
TPlatformServices.Current.RemovePlatformService(IFGXProgressDialogService);
end;
{ TAndroidProgressDialogService }
function TAndroidProgressDialogService.CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog;
begin
Result := TAndroidNativeActivityDialog.Create(AOwner);
end;
function TAndroidProgressDialogService.CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog;
begin
Result := TAndroidNativeProgressDialog.Create(AOwner);
end;
{ TAndroidNativeProgressDialog }
procedure TAndroidNativeActivityDialog.CancellableChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setCancelable(Cancellable);
FNativeDialog.setCanceledOnTouchOutside(Cancellable);
end);
end;
constructor TAndroidNativeActivityDialog.Create(const AOwner: TObject);
var
ThemeID: Integer;
begin
inherited Create(AOwner);
FID := TfgGeneratorUniqueID.GenerateID;
FDialogListener := TDialogDismissListener.Create(Self);
ThemeID := GetNativeTheme(AOwner);
CallInUIThreadAndWaitFinishing(procedure begin
FNativeDialog := TJProgressDialog.JavaClass.init(TAndroidHelper.Context, ThemeID);
end);
end;
destructor TAndroidNativeActivityDialog.Destroy;
begin
FNativeDialog := nil;
FreeAndNil(FDialogListener);
inherited Destroy;
end;
function TAndroidNativeActivityDialog.GetIsShown: Boolean;
begin
Result := FNativeDialog.isShowing;
end;
procedure TAndroidNativeActivityDialog.Hide;
begin
AssertIsNotNil(FNativeDialog);
inherited;
DoHide;
CallInUIThread(procedure begin
HideDialog(FNativeDialog, FID);
end);
end;
procedure TAndroidNativeActivityDialog.InitNativeDialog;
begin
AssertIsNotNil(FNativeDialog);
FNativeDialog.setTitle(StrToJCharSequence(Title));
FNativeDialog.setMessage(StrToJCharSequence(Message));
FNativeDialog.setProgressStyle(TJProgressDialog.JavaClass.STYLE_SPINNER);
FNativeDialog.setCanceledOnTouchOutside(Cancellable);
FNativeDialog.setCancelable(Cancellable);
FNativeDialog.setOnCancelListener(FDialogListener);
end;
procedure TAndroidNativeActivityDialog.MessageChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setMessage(StrToJCharSequence(Message));
end);
end;
procedure TAndroidNativeActivityDialog.Show;
begin
AssertIsNotNil(FNativeDialog);
inherited;
CallInUIThread(procedure begin
InitNativeDialog;
ShowDialog(FNativeDialog, FID);
end);
DoShow;
end;
procedure TAndroidNativeActivityDialog.TitleChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setTitle(StrToJCharSequence(Title));
end);
end;
{ TAndroidNativeActivityDialog }
procedure TAndroidNativeProgressDialog.CancellableChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setCancelable(Cancellable);
FNativeDialog.setCanceledOnTouchOutside(Cancellable);
end);
end;
constructor TAndroidNativeProgressDialog.Create(const AOwner: TObject);
var
ThemeID: Integer;
begin
inherited Create(AOwner);
FID := TfgGeneratorUniqueID.GenerateID;
FDialogListener := TDialogDismissListener.Create(Self);
ThemeID := GetNativeTheme(AOwner);
CallInUIThreadAndWaitFinishing(procedure begin
FNativeDialog := TJProgressDialog.JavaClass.init(TAndroidHelper.Context, ThemeID);
end);
end;
destructor TAndroidNativeProgressDialog.Destroy;
begin
FNativeDialog := nil;
FreeAndNil(FDialogListener);
inherited Destroy;
end;
function TAndroidNativeProgressDialog.GetIsShown: Boolean;
begin
Result := FNativeDialog.isShowing;
end;
procedure TAndroidNativeProgressDialog.Hide;
begin
AssertIsNotNil(FNativeDialog);
inherited;
DoHide;
CallInUIThread(procedure begin
HideDialog(FNativeDialog, FID);
end);
end;
procedure TAndroidNativeProgressDialog.InitNativeDialog;
begin
AssertIsNotNil(FNativeDialog);
FNativeDialog.setTitle(StrToJCharSequence(Title));
FNativeDialog.setMessage(StrToJCharSequence(Message));
FNativeDialog.setMax(Round(Max));
FNativeDialog.setProgress(Round(Progress));
FNativeDialog.setProgressStyle(TJProgressDialog.JavaClass.STYLE_HORIZONTAL);
FNativeDialog.setIndeterminate(IsDialogKindDeterminated(Kind));
FNativeDialog.setCanceledOnTouchOutside(Cancellable);
FNativeDialog.setCancelable(Cancellable);
FNativeDialog.setOnCancelListener(FDialogListener);
end;
function TAndroidNativeProgressDialog.IsDialogKindDeterminated(const DialogKind: TfgProgressDialogKind): Boolean;
begin
Result := DialogKind = TfgProgressDialogKind.Undeterminated;
end;
procedure TAndroidNativeProgressDialog.KindChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setIndeterminate(IsDialogKindDeterminated(Kind));
end);
end;
procedure TAndroidNativeProgressDialog.MessageChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setMessage(StrToJCharSequence(Message));
end);
end;
procedure TAndroidNativeProgressDialog.ProgressChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setProgress(Round(Progress));
end);
end;
procedure TAndroidNativeProgressDialog.RangeChanged;
begin
AssertIsNotNil(FNativeDialog);
inherited RangeChanged;
CallInUIThread(procedure begin
FNativeDialog.setMax(Round(Max));
end);
end;
procedure TAndroidNativeProgressDialog.ResetProgress;
begin
AssertIsNotNil(FNativeDialog);
inherited ResetProgress;
CallInUIThread(procedure begin
FNativeDialog.setProgress(0);
end);
end;
procedure TAndroidNativeProgressDialog.Show;
begin
AssertIsNotNil(FNativeDialog);
inherited;
CallInUIThread(procedure begin
InitNativeDialog;
ShowDialog(FNativeDialog, FID);
end);
DoShow;
end;
procedure TAndroidNativeProgressDialog.TitleChanged;
begin
AssertIsNotNil(FNativeDialog);
CallInUIThread(procedure begin
FNativeDialog.setTitle(StrToJCharSequence(Title));
end);
end;
{ TDialogDismissListener }
constructor TDialogDismissListener.Create(const ADialog: TfgNativeDialog);
begin
AssertIsNotNil(ADialog);
inherited Create;
FDialog := ADialog;
end;
procedure TDialogDismissListener.onCancel(dialog: JDialogInterface);
begin
AssertIsNotNil(FDialog);
TThread.Synchronize(nil, procedure
begin
if Assigned(FDialog.OnCancel) then
FDialog.OnCancel(FDialog.Owner);
end);
end;
end.
|
unit DW.UIHelper.Android;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Types,
// FMX
FMX.Types, FMX.Forms;
type
/// <summary>
/// Helper functions specific to UI
/// </summary>
TPlatformUIHelper = record
public
/// <summary>
/// Special function for handling of "notch" based devices
/// </summary>
class function GetOffsetRect: TRectF; overload; static;
class function GetOffsetRect(const AHandle: TWindowHandle): TRectF; overload; static;
class procedure Render(const AForm: TForm); static;
end;
implementation
uses
FMX.Platform.UI.Android;
{ TPlatformUIHelper }
class function TPlatformUIHelper.GetOffsetRect: TRectF;
begin
// Yet to be implemented. Work is in progress
Result := TRectF.Empty;
end;
class function TPlatformUIHelper.GetOffsetRect(const AHandle: TWindowHandle): TRectF;
begin
// Yet to be implemented. Work is in progress
Result := TRectF.Empty;
end;
class procedure TPlatformUIHelper.Render(const AForm: TForm);
begin
TAndroidWindowHandle(AForm.Handle).Render.Render;
end;
end.
|
{-------------------------------------------------- Progressive Path Tracing ---------------------------------------------------
This unit is responsible for reading a scene file, loading all the primitives and materials in memory, and providing methods to
access the scene - in particular a method which takes as a parameter a ray and a wavelength, and returns whether the ray gets
absorbed by a primitive with a light material. This method is probabilistic, and the average of successive samples converge
towards the correct result.
-------------------------------------------------------------------------------------------------------------------------------}
unit SceneManager;
interface
uses Windows, SysUtils, Classes, VectorMath, VectorTypes, MaterialTypes, Utils, Math, PRNG;
const
{ This small number is used to make sure rays collide properly. Floating-point inaccuracies means that when a ray collides with
a surface, the collision point may be right behind the surface, and if the ray is reflected, it will immediately bounce back
into the surface which is incorrect, so we account for this by moving the intersection point slightly forward or backward,
depending on whether reflection or refraction is occuring. }
SELF_INTERSECTION_EPSILON = 1e-7;
type
TSceneManager = class
private
FDepth: Longword;
FPRNG: array of TPRNG;
FPrimitives: array of TPrimitive;
FMaterials: array of TMaterial;
function FirstIntersection(Ray: TRay; var Primitive: Longword): Double;
public
constructor Create(ADepth, AWorkerCount: Longword; Scene: Pointer); reintroduce;
destructor Destroy; override;
function Raytrace(Ray: TRay; Wavelength, Worker: Longword): Boolean;
end;
PSceneManager = ^TSceneManager;
implementation
{ Loads the scene pointed at by Scene. }
constructor TSceneManager.Create(ADepth, AWorkerCount: Longword; Scene: Pointer);
Var
I: Integer;
PrimitiveType, Len: Longword;
begin
{ Set some members. }
FDepth := ADepth;
SetLength(FPRNG, AWorkerCount);
for I := 0 to High(FPRNG) do FPRNG[I] := TPRNG.Create(GetWorkerSeed(I));
{ Read the number of primitives and materials from the scene. }
SetLength(FPrimitives, PLongword(Scene)^); IncPtr(Scene, SizeOf(Longword));
SetLength(FMaterials, PLongword(Scene)^); IncPtr(Scene, SizeOf(Longword));
{ Walk through the stream, loading each primitive. }
for I := 0 to High(FPrimitives) do
begin
{ Read the primitive's data length. }
Len := PLongword(Scene)^;
IncPtr(Scene, SizeOf(Longword));
{ Read the primitive type, and create the primitive accordingly. }
PrimitiveType := PLongword(Scene)^;
IncPtr(Scene, SizeOf(Longword));
case PrimitiveType of
0: FPrimitives[I] := TSphere.Create(Scene);
1: FPrimitives[I] := TPlane.Create(Scene);
2: FPrimitives[I] := TTriangle.Create(Scene);
end;
{ Increment the pointer to the next primitive. }
IncPtr(Scene, Len);
end;
{ Walk through the stream, loading each material. }
for I := 0 to High(FMaterials) do
begin
{ Copy the material from the stream, and increment the pointer. }
CopyMemory(@FMaterials[I], Scene, SizeOf(TMaterial));
IncPtr(Scene, SizeOf(TMaterial));
end;
end;
{ Releases all memory taken up by the primitives and materials. }
destructor TSceneManager.Destroy;
Var
I: Integer;
begin
{ Release all primitives and PRNG classes. }
for I := 0 to High(FPrimitives) do FPrimitives[I].Free;
for I := 0 to High(FPRNG) do FPRNG[I].Free;
inherited;
end;
{ Finds the first intersection of the given ray with the scene. }
function TSceneManager.FirstIntersection(Ray: TRay; var Primitive: Longword): Double;
Var
Distance: Double;
I: Integer;
begin
Result := -1;
{ Iterate over all primitives. }
for I := 0 to High(FPrimitives) do
begin
{ Calculate the distance to this primitive. }
Distance := FPrimitives[I].Intersects(Ray);
{ If it is greater than zero and less than the current closest distance, use it. }
if (Distance < Result) and (Distance > 0) then
begin
Result := Distance;
Primitive := I;
Continue;
end;
{ If the current closest distance is less than zero, use it. }
if (Result < 0) then
begin
Result := Distance;
Primitive := I;
end;
end;
end;
{ Raytrace a ray of a given wavelength, by a given worker. }
function TSceneManager.Raytrace(Ray: TRay; Wavelength, Worker: Longword): Boolean;
Var
Distance: Double;
Primitive: Longword;
R, Ni, CosI, CosT: Double;
Iteration: Integer;
Normal: TVector;
begin
{ Raytracing is done using a modified Russian Roulette algorithm - after an intersection is found, the ray is checked for
absorption - if it is absorbed, the process is stopped here (and it is returned either true or false depending on whether
the ray got absorbed by some ordinary primitive or by a light). If the ray doesn't get absorbed, then it either gets
reflected or refracted, according to the Fresnel Equations (nonrefractive materials are defined as those with a refractive
index of 0. The decision of whether a ray is absorbed, refracted or reflected, is a random choice based on the probabilities
of each event happening - this is why a ray will eventually get absorbed in most cases. For those cases where a ray can get
stuck, we introduce a maximum depth limit, which limits the number of times a ray can be reflected or refracted - if it
exceeds this depth limit, it is automatically discarded and assumed to be "eventually absorbed" (not by a light). }
Result := False;
{ Repeat this operation until the maximum depth is attained. }
for Iteration := 0 to FDepth - 1 do
begin
{ Find the first intersection with the scene. }
Distance := FirstIntersection(Ray, Primitive);
{ If there is no intersection with the scene, return False. }
if (Distance < 0) then Exit;
{ For convenience we reference the primitive's material in a with clause. }
with FMaterials[FPrimitives[Primitive].Material] do
begin
{ Calculate the normal at the intersecting primitive. Note that we cannot reuse the intersection point here because of
the self-intersection problem, we need to be able to offset the point slightly to avoid having the ray immediately
reintersect the same primitive at the next iteration. And this offset can be either backwards or forwards depending
on whether the ray is reflected or refracted. }
Normal := FPrimitives[Primitive].NormalAt(AddVector(MulVector(Ray.Direction, Distance), Ray.Origin));
{ Check whether the intersecting primitive absorbs the ray. }
if (FPRNG[Worker].random >= AbsorptionSpectrum[Wavelength]) then
begin
{ If the primitive is a light, return True, otherwise return False. }
Result := IsLight;
{ If light, check the light's dot product, as area lights don't emit the same amount of light in all directions. }
if Result then Result := (FPRNG[Worker].random < Max(-DotVector(Normal, Ray.Direction), 0));
Exit;
end;
{ The ray didn't get absorbed, we now check for reflection or refraction. The probability of a ray being reflected depends
on the Fresnel equations, which in turn depend on the incident ray, the surface normal and the refraction index. }
R := Fresnel(Ray.Direction, Normal, RefractionIndices[Wavelength], Ni, CosI, CosT);
{ We now perform a random trial to decide whether to reflect or to refract the ray. }
if (FPRNG[Worker].random <= R) then
begin
{ It got reflected, so place the new ray's origin slightly outside the primitive and get the new direction. }
Ray.Origin := AddVector(MulVector(Ray.Direction, Distance - SELF_INTERSECTION_EPSILON), Ray.Origin);
if (FPRNG[Worker].random < Specularity) then Ray.Direction := NormalizeVector(ReflectVector(Ray.Direction, Normal)) else
begin
Ray.Direction := NormalizeVector(Vector(FPRNG[Worker].random - FPRNG[Worker].random, FPRNG[Worker].random - FPRNG[Worker].random, FPRNG[Worker].random - FPRNG[Worker].random));
if DotVector(Ray.Direction, Normal) < 0 then Ray.Direction := MulVector(Ray.Direction, -1);
end;
end
else
begin
{ It got refracted, move the ray's origin slightly inside the primitive and compute the new direction. }
Ray.Origin := AddVector(MulVector(Ray.Direction, Distance + SELF_INTERSECTION_EPSILON), Ray.Origin);
Ray.Direction := RefractVector(Ray.Direction, Normal, Ni, CosI, CosT);
end;
end;
end;
end;
end.
|
program factorial;
var
number : integer;
fact : integer;
i : integer;
begin
writeln('Welcome to factorial');
write('Introduce a positive integer: ');
read(number);
fact := 1;
for i := number downto 1 do
begin
fact := fact * i;
end;
writeln('The factorial of ', number, ' is ', fact)
{}
end.
|
unit DictionInterfaces;
{* Интерфейсы для работы с толковым словарём }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Diction\DictionInterfaces.pas"
// Стереотип: "ControllerInterfaces"
// Элемент модели: "DictionInterfaces" MUID: (491D57C802CD)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, l3TreeInterfaces
, bsTypes
{$If Defined(Nemesis)}
, nscNewInterfaces
{$IfEnd} // Defined(Nemesis)
, DocumentAndListInterfaces
, CommonDictionInterfaces
{$If NOT Defined(NoVCM)}
, vcmControllers
{$IfEnd} // NOT Defined(NoVCM)
, QueryCardInterfaces
, DictionInterfacesPrim
, l3InternalInterfaces
, l3Interfaces
, DynamicTreeUnit
{$If NOT Defined(NoVCM)}
, vcmInterfaces
{$IfEnd} // NOT Defined(NoVCM)
, l3Types
, DocumentInterfaces
, DocumentUnit
, bsTypesNew
, DynamicDocListUnit
, PrimPrimListInterfaces
, nsTypes
, AdapterFacade
;
type
InsLangToContextMap = interface
['{E8C780B1-C226-4065-9287-D4CDC58C6F29}']
function pm_GetByLang(aLang: TbsLanguage): InscContextFilterState;
procedure pm_SetByLang(aLang: TbsLanguage;
const aValue: InscContextFilterState);
procedure Subscribe(const aNotifySource: Il3ContextFilterNotifySource);
procedure Unsubscribe(const aNotifySource: Il3ContextFilterNotifySource);
property ByLang[aLang: TbsLanguage]: InscContextFilterState
read pm_GetByLang
write pm_SetByLang;
end;//InsLangToContextMap
IbsDictionListener = interface(IbsCommonDictionListener)
{* Слушатель событий бизнес объекта формы список толкований }
['{A9A4196C-CD68-47BA-8DED-97CC7084AB53}']
procedure UpdateLanguage(aLanguage: TbsLanguage);
{* обновить язык списка толкований }
end;//IbsDictionListener
IdsDiction = interface(IdsCommonDiction)
{* Список толкований }
['{D97C5B61-097A-4C19-95EF-1C5820AD89EB}']
function pm_GetLanguage: TbsLanguage;
procedure pm_SetLanguage(aValue: TbsLanguage);
function pm_GetContextMap: InsLangToContextMap;
procedure pm_SetContextMap(const aValue: InsLangToContextMap);
property Language: TbsLanguage
read pm_GetLanguage
write pm_SetLanguage;
property ContextMap: InsLangToContextMap
read pm_GetContextMap
write pm_SetContextMap;
end;//IdsDiction
IdDiction = interface(IdCommonDiction)
{* Данные толкового словаря }
['{9BE60C81-85BB-4DBB-AC9A-CA023E09BA3C}']
function pm_GetLanguages: TbsLanguages;
procedure pm_SetLanguages(aValue: TbsLanguages);
function pm_GetRefTranslationCount: Integer;
function pm_GetIsShowLiteratureList: Boolean;
procedure pm_SetIsShowLiteratureList(aValue: Boolean);
function pm_GetContextMap: InsLangToContextMap;
procedure pm_SetContextMap(const aValue: InsLangToContextMap);
function pm_GetCurrentLanguage: TbsLanguage;
procedure pm_SetCurrentLanguage(aValue: TbsLanguage);
function pm_GetRefTranslation(aIndex: Integer): IvcmFormDataSourceRef;
property Languages: TbsLanguages
read pm_GetLanguages
write pm_SetLanguages;
property refTranslationCount: Integer
read pm_GetRefTranslationCount;
property IsShowLiteratureList: Boolean
read pm_GetIsShowLiteratureList
write pm_SetIsShowLiteratureList;
property ContextMap: InsLangToContextMap
read pm_GetContextMap
write pm_SetContextMap;
property CurrentLanguage: TbsLanguage
read pm_GetCurrentLanguage
write pm_SetCurrentLanguage;
property refTranslation[aIndex: Integer]: IvcmFormDataSourceRef
read pm_GetRefTranslation;
end;//IdDiction
IdeDiction = interface(IdeCommonDiction)
{* Данные для сборки Толковый словарь }
['{A16C999F-97F3-416A-A277-572CDB3E8896}']
function pm_GetDictLanguage: TbsLanguage;
procedure pm_SetDictLanguage(aValue: TbsLanguage);
function pm_GetContextMap: InsLangToContextMap;
procedure pm_SetContextMap(const aValue: InsLangToContextMap);
property DictLanguage: TbsLanguage
read pm_GetDictLanguage
write pm_SetDictLanguage;
property ContextMap: InsLangToContextMap
read pm_GetContextMap
write pm_SetContextMap;
end;//IdeDiction
IsdsDiction = interface(IsdsCommonDiction)
{* Толковый словарь }
['{5F50593A-39D2-4EC7-9410-0A4FEE1DB991}']
function pm_GetDsDiction: IdsDiction;
function pm_GetTranslationForms: Integer;
function pm_GetDefaultLanguage: TbsLanguage;
function pm_GetDsTranslate(aLanguageId: Integer): IdsDictionDocument;
function pm_GetContextMap: InsLangToContextMap;
procedure OpenLiteratureList;
{* открыть список литературы для толкового словаря }
function IsShowLiteratureList: Boolean;
property dsDiction: IdsDiction
read pm_GetDsDiction;
property TranslationForms: Integer
read pm_GetTranslationForms;
{* количество форм с переводом (по количеству возможных языков) }
property DefaultLanguage: TbsLanguage
read pm_GetDefaultLanguage;
{* язык по умолчанию, используется для установки фиктивной закладки толкового словаря }
property dsTranslate[aLanguageId: Integer]: IdsDictionDocument
read pm_GetDsTranslate;
{* получить бизнес объект для указанного языка }
property ContextMap: InsLangToContextMap
read pm_GetContextMap;
end;//IsdsDiction
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
(*$d-,c-,v:000001000005b*)
Program Relprt(input,output);
{ program to print relocatable files for debugging
-- Greg Satz }
type
string = packed array [1..10] of char;
var
input: file of integer;
i,count,tmp: integer;
rad50_chars: packed array [1..40] of char;
filename, device: alfa;
word_count: integer;
word: packed record {for word manipulation}
case integer of
1:(full_word: integer);
2:(second_half, first_half: 0..777777b);
3:(code: 0..17b;
rest: 0..37777777777b);
4:(cpu: 0..77b;
compiler: 0..7777b;
blank_common: 0..777777b);
5:(asciz: packed array [1..5] of 0..127;
bit35: 0..1)
end;
procedure from6(i: integer; var a: alfa); extern;
function ipower(a,b:integer):integer; extern;
procedure quit; extern;
procedure rad50(number: integer);
{prints the character value of a radix 50 number}
const
len = 5; {number of characters in rad50 per word}
var
i:integer;
j:integer;
begin {rad50}
for i:=len downto 0 do
begin
j:=number div ipower(40,i);
if j <> 0 then
write(output,rad50_chars[j+1]);
number:=number-(j*ipower(40,i))
end
end; {rad50}
procedure skip(count: integer);
{skips count number of input words}
var
i: integer;
begin {skip}
for i:=1 to count do
begin
get(input);
word_count:=word_count+1
end
end; {skip}
begin {main}
rad50_chars:=' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.$%';
word_count:=0;
reset(input);
rewrite(output);
while not eof(input) do
begin
word.full_word:=input^;
write(output,'Block Type: (',word.first_half:6:o,') ');
case word.first_half of
0b:
begin
writeln(output,' Zero word -- Ignored,,',
word.second_half:6:o);
if word.second_half <> 0 then
skip(word.second_half+1)
end;
1b:
begin
writeln(output,' Code,,',word.second_half:6:o);
skip(word.second_half+1)
end;
2b:
begin
writeln(output,' Symbols,,',word.second_half:6:o);
count:=word.second_half div 2;
get(input); {relocation word}
word_count:=word_count+1;
write(output,'Global symbols: ');
for i:=1 to count do
begin
get(input);
word_count:=word_count+1;
word.full_word:=input^;
tmp:=input^;
if word.code = 14b then {code=60b}
begin {global request}
get(input);
word_count:=word_count+1;
word.full_word:=input^;
if word.code = 00b then
begin {valid name}
word.full_word:=tmp;
rad50(word.rest);
write(output,', ')
end
end
else
begin
get(input);
word_count:=word_count+1
end
end;
writeln(output)
end;
3b:
begin
writeln(output,' HISEG,,',word.second_half:6:o);
count:=word.second_half;
get(input); {relocation word}
word_count:=word_count+1;
get(input);
word_count:=word_count+1;
word.full_word:=input^;
writeln(output,'HISEG break,,origin: ',
word.first_half:6:o,',,',
word.second_half:6:o);
if count = 2 then
begin
get(input);
word_count:=word_count+1;
word.full_word:=input^;
writeln(output,'LOSEG break,,origin: ',
word.first_half:6:o,',,',
word.second_half:6:o)
end
end;
4b:
begin
writeln(output,'Entry,,',word.second_half:6:o);
count:=word.second_half;
get(input); {relocation word}
word_count:=word_count+1;
write(output,'Symbols: ');
while count <> 0 do
begin
get(input);
if input^ <> 0 then
begin
word_count:=word_count+1;
rad50(input^);
write(output,', ');
count:=count-1
end
end;
writeln(output)
end;
5b:
begin
writeln(output,'End,,',word.second_half:6:o);
get(input); {relocation word}
word_count:=word_count+1;
get(input);
word_count:=word_count+1;
i:=input^;
get(input);
word_count:=word_count+1;
writeln(output,'HISEG break: ',i:12:o,
' LOSEG or ABS break: ',input^:12:o)
end;
6b:
begin
writeln(output,'Name,,',word.second_half:6:o);
count:=word.second_half;
get(input); {relocation word}
word_count:=word_count+1;
get(input);
word_count:=word_count+1;
write(output,'Name: ');
rad50(input^);
writeln(output);
if count = 2 then
begin
get(input);
word_count:=word_count+1;
word.full_word:=input^;
write(output,'CPU: ');
case word.cpu of
20b: write(output,' KS10,');
4b: write(output,' KL10,');
2b: write(output,' KI10,');
1b: write(output,' KA10,');
others: write(output,' Unknown,')
end; {case}
write(output,' Compiled by ');
case word.compiler of
0b: writeln(output,'Unknown');
1b: writeln(output,'Not used');
2b: writeln(output,'COBOL-68');
3b: writeln(output,'ALGOL');
4B: writeln(output,'NELIAC');
5b: writeln(output,'PL/I');
6b: writeln(output,'BLISS');
7b: writeln(output,'SAIL');
10b: writeln(output,'FORTRAN');
11b: writeln(output,'MACRO');
12b: writeln(output,'FAIL');
13b: writeln(output,'BCPL');
14b: writeln(output,'MIDAS');
15b: writeln(output,'SIMULA');
16b: writeln(output,'COBOL-74');
17b: writeln(output,'(Reserved)');
20b: writeln(output,'BLISS-36');
21b: writeln(output,'BASIC');
22b: writeln(output,'SITGO');
23b: writeln(output,'G-float FORTRAN');
24b: writeln(output,'PASCAL');
25b: writeln(output,'JOVIAL');
others: writeln(output,' Unknown1')
end;
writeln(output,'Length of blank common: ',
word.blank_common)
end
end;
7b:
begin
writeln(output,'Start,,',word.second_half:6:o);
count:=word.second_half;
get(input); {relocation word}
word_count:=word_count+1;
get(input);
word_count:=word_count+1;
writeln(output,'Start address: ',input^:12:o);
if count = 2 then
begin
get(input);
word_count:=word_count+1;
word.full_word:=input^;
write(output,'Code: ',word.code:3:o,
'Symbol: ');
rad50(word.rest);
writeln(output)
end
end;
10b:
begin
writeln(output,'Internal request,,',
word.second_half:6:o);
skip(word.second_half+1)
end;
11b:
begin
writeln(output,'Polish,,',word.second_half:6:o);
skip(word.second_half+1)
end;
12b:
begin
writeln(output,'Chain,,',word.second_half:6:o);
skip(word.second_half+1)
end;
14b:
begin
writeln(output,'Index,,',word.second_half:6:o);
skip(word.second_half)
end;
15b:
begin
writeln(output,'ALGOL,,',word.second_half:6:o);
skip(word.second_half+1)
end;
16b,17b:
begin
if word.first_half = 16b then
write(output,'Request load')
else
write(output,'Request library');
writeln(output,',,',word.second_half:6:o);
count:=word.second_half;
get(input); {relocation count}
word_count:=word_count+1;
while count <> 0 do
begin
get(input);
word_count:=word_count+1;
from6(input^, filename);
get(input);
word_count:=word_count+1;
word.full_word:=input^;
get(input);
word_count:=word_count+1;
from6(input^, device);
writeln(output, 'Device: ', device,
' Filename: ',filename,' ',
word.first_half:6:o,',,',
word.second_half:6:o);
count:=count-3
end
end;
20b:
begin
writeln(output,'Common,,',word.second_half:6:o);
skip(word.second_half+1)
end;
21b:
begin
writeln(output,'Sparse data,,',word.second_half:6:o);
skip(word.second_half+1)
end;
22b:
begin
writeln(output,'PSECT origin,,',word.second_half:6:o);
skip(word.second_half+1)
end;
23b:
begin
writeln(output,'PSECT End block,,',
word.second_half:6:o);
skip(word.second_half+1)
end;
24b:
begin
writeln(output,'PSECT Header block,,',
word.second_half:6:o);
skip(word.second_half+1)
end;
37b:
begin
writeln(output,'COBOL Symbols,,',word.second_half:6:o);
skip(word.second_half+1)
end;
100b:
begin
writeln(output,'.ASSIGN,,',word.second_half:6:o);
skip(word.second_half+1)
end;
776b:
begin
writeln(output,'Symbol File,,',word.second_half:6:o);
skip(word.second_half)
end;
777b:
begin
writeln(output,'Universal file,,',
word.second_half:6:o);
skip(word.second_half)
end;
1000b:
begin
writeln(output,'1000 -- Ignored,,',
word.second_half:6:o);
skip(word.second_half)
end;
1001b:
begin
writeln(output,'1001 Entry,,',word.second_half:6:o);
skip(word.second_half)
end;
1002b:
begin
writeln(output,'1002 Long entry,,',
word.second_half:6:o);
skip(word.second_half)
end;
1003b:
begin
writeln(output,'Long Title,,',word.second_half:6:o);
skip(word.second_half)
end;
1004b:
begin
writeln(output,'Byte Init.,,',word.second_half:6:o);
skip(word.second_half)
end;
1120b,1121b,1122b,1123b,1124b,1125b,1126b,1127b:
begin
writeln(tty,'Arg. Desc. Block,,',
word.second_half:6:o);
skip(word.second_half)
end;
1130b:
begin
writeln(output,'Coercion Block,,',
word.second_half:6:o);
skip(word.second_half)
end;
others:
begin
if word.first_half > 3777b then {asciz}
begin
write(output,'ASCIZ: ');
i:=1;
while word.asciz[i] <> 0 do
begin
write(output,chr(word.asciz[i]));
i:=i+1;
if i > 5 then
begin
get(input);
word_count:=word_count+1;
word.full_word:=input^;
i:=1
end
end;
writeln(output)
end
else
begin
writeln(output,'?Error -- unexpected word in ',
'relocatable code (',word_count:8:o,'): ',
word.first_half:6:o,',,',
word.second_half:6:o);
quit
end
end
end; {case}
writeln(output);
get(input);
word_count:=word_count+1
end; {while}
writeln(output,'Done.')
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
{ Rev 1.6 2004.02.03 5:45:10 PM czhower
{ Name changes
}
{
{ Rev 1.5 1/21/2004 2:29:38 PM JPMugaas
{ InitComponent
}
{
{ Rev 1.4 2/24/2003 08:41:20 PM JPMugaas
{ Should compile with new code.
}
{
{ Rev 1.3 12/8/2002 07:58:54 PM JPMugaas
{ Now compiles properly.
}
{
{ Rev 1.2 12/8/2002 07:26:38 PM JPMugaas
{ Added published host and port properties.
}
{
{ Rev 1.1 12/6/2002 05:29:34 PM JPMugaas
{ Now decend from TIdTCPClientCustom instead of TIdTCPClient.
}
{
{ Rev 1.0 11/14/2002 02:19:50 PM JPMugaas
}
unit IdFinger;
{*******************************************************}
{ }
{ Indy Finger Client TIdFinger }
{ }
{ Copyright (C) 2000 Winshoes Working Group }
{ Original author J. Peter Mugaas }
{ 2000-April-23 }
{ Based on RFC 1288 }
{ }
{*******************************************************}
{2000-April-30 J. Peter Mugaas
-adjusted CompleteQuery to permit recursive finger queries such
as "test@test.com@example.com". I had mistakenly assumed that
everything after the first @ was the host name.
-Added option for verbose output request from server - note that
many do not support this.}
interface
uses
IdAssignedNumbers,
IdTCPClient;
type
TIdFinger = class(TIdTCPClientCustom)
protected
FQuery: String;
FVerboseOutput: Boolean;
Procedure SetCompleteQuery(AQuery: String);
Function GetCompleteQuery: String;
Procedure InitComponent; override;
public
{This connects to a server, does the finger querry specified in the Query
property and returns the results of the querry}
function Finger: String;
published
property Port default IdPORT_FINGER;
property Host;
{This is the querry to the server which you set with the Host Property}
Property Query: String read FQuery write FQuery;
{This is the complete querry such as "user@host"}
Property CompleteQuery: String read GetCompleteQuery write SetCompleteQuery;
{This indicates that the server should give more detailed information on
some systems. However, this will probably not work on many systems so it is
False by default}
Property VerboseOutput: Boolean read FVerboseOutPut write FVerboseOutPut
default False;
end;
implementation
uses
IdGlobal, IdGlobalProtocols,
IdTCPConnection;
{ TIdFinger }
procedure TIdFinger.InitComponent;
begin
inherited InitComponent;
Port := IdPORT_FINGER;
end;
{This is the method used for retreiving Finger Data which is returned in the
result}
function TIdFinger.Finger: String;
var QStr : String;
begin
QStr := FQuery;
if VerboseOutPut then
begin
QStr := QStr + '/W'; {Do not Localize}
end; //if VerboseOutPut then
Connect;
try
{Write querry}
Result := ''; {Do not Localize}
IOHandler.WriteLn(QStr);
{Read results}
Result := IOHandler.AllData;
finally
Disconnect;
end;
end;
function TIdFinger.GetCompleteQuery: String;
begin
Result := FQuery + '@' + Host; {Do not Localize}
end;
procedure TIdFinger.SetCompleteQuery(AQuery: String);
var p : Integer;
begin
p := RPos('@', AQuery, -1); {Do not Localize}
if (p <> 0) then begin
if ( p < Length ( AQuery ) ) then
begin
Host := Copy(AQuery, p + 1, Length ( AQuery ) );
end; // if ( p < Length ( AQuery ) ) then
FQuery := Copy(AQuery, 1, p - 1);
end //if (p <> 0) then begin
else
begin
FQuery := AQuery;
end; //else..if (p <> 0) then begin
end;
end.
|
unit evDocumentPartHotSpotTester;
{* Реализует интерфейсы IevHotSpotTester и IevHotSpot для части документа. }
// Модуль: "w:\common\components\gui\Garant\Everest\evDocumentPartHotSpotTester.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevDocumentPartHotSpotTester" MUID: (4A27B5510171)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
{$If Defined(evNeedHotSpot)}
uses
l3IntfUses
, evParaListHotSpotTester
, nevGUIInterfaces
, l3Interfaces
, nevTools
, afwInterfaces
, l3Units
, evInternalInterfaces
, l3IID
;
type
TevDocumentPartHotSpotTester = class(TevParaListHotSpotTester, IevAdvancedHotSpot)
{* Реализует интерфейсы IevHotSpotTester и IevHotSpot для части документа. }
private
f_DragArea: TevObjectArea;
f_Name: Il3CString;
f_Sub: IevSub;
f_TopEdge: InevBasePoint;
{* Верхняя граница блока }
f_BottomEdge: InevBasePoint;
{* Нижняя граница блока }
f_Area: TevObjectArea;
protected
thisMap: InevMap;
protected
procedure CheckSub;
function GetName: Il3CString;
function GetHintPrefix(const aState: TafwCursorState): Il3CString; virtual;
function DoDrop(const aView: InevControlView;
const aPt: Tl3Point): Boolean;
{* Обрабатывает перемещение блока на aPt. }
function CanChangeBorder(const aView: InevControlView;
const aPt: Tl3Point): Boolean;
{* Проверяет можно ли изменять границу блока. }
procedure ChangeBorder(const aView: InevControlView;
const aPt: Tl3Point);
{* Изменяет границу блока. }
function GetEdge(const aView: InevView;
aTop: Boolean): InevBasePoint;
function MouseAction(const aView: InevControlView;
aButton: Tl3MouseButton;
anAction: Tl3MouseAction;
const Keys: TevMouseState;
var Effect: TevMouseEffect): Boolean;
{* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false }
function CanDrag: Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure DoHitTest(const aView: InevControlView;
const aState: TafwCursorState;
var theInfo: TafwCursorInfo); override;
function COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult; override;
{* Реализация запроса интерфейса }
function DoGetAdvancedHotSpot(const aView: InevControlView;
const aState: TevCursorState;
const aPt: InevBasePoint;
const aMap: InevMap;
out theSpot: IevHotSpot): Boolean; override;
public
function ShowParts(const aView: InevControlView): Boolean; virtual;
function DoMouseAction(const aView: InevControlView;
aButton: TevMouseButton;
anAction: TevMouseAction;
const Keys: TevMouseState;
var Effect: TevMouseEffect): Boolean; virtual;
protected
property Area: TevObjectArea
read f_Area;
end;//TevDocumentPartHotSpotTester
{$IfEnd} // Defined(evNeedHotSpot)
implementation
{$If Defined(evNeedHotSpot)}
uses
l3ImplUses
{$If Defined(k2ForEditor)}
, evParaTools
{$IfEnd} // Defined(k2ForEditor)
, evParaCollapser
, k2Tags
, l3Base
{$If Defined(k2ForEditor)}
, evDocumentPart
{$IfEnd} // Defined(k2ForEditor)
, nevInterfaces
, Classes
, l3String
, SysUtils
, evOp
, evHotSpotMisc
, l3InterfacesMisc
, Block_Const
, ParaList_Const
, l3Memory
, nevBase
, k2OpMisc
, evMsgCode
{$If Defined(k2ForEditor)}
, evCursorTools
{$IfEnd} // Defined(k2ForEditor)
, TextPara_Const
, evTypes
, evdInterfaces
, TableCell_Const
//#UC START# *4A27B5510171impl_uses*
//#UC END# *4A27B5510171impl_uses*
;
const
cnInitOperation: array [Boolean] of Integer = (ev_ocBottomRight, ev_ocTopLeft);
procedure TevDocumentPartHotSpotTester.CheckSub;
//#UC START# *4F9655E60184_4A27B5510171_var*
var
l_SubList : InevSubList;
//#UC END# *4F9655E60184_4A27B5510171_var*
begin
//#UC START# *4F9655E60184_4A27B5510171_impl*
if (f_Sub = nil) then
begin
l_SubList := ParaX.MainSubList;
if (l_SubList <> nil) then
try
with TagInst.Attr[k2_tiHandle] do
if IsValid then
f_Sub := l_SubList.Sub[AsLong];
finally
l_SubList := nil;
end;//try..finally
end;//f_Sub = nil
//#UC END# *4F9655E60184_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.CheckSub
function TevDocumentPartHotSpotTester.GetName: Il3CString;
//#UC START# *4F96560203C8_4A27B5510171_var*
//#UC END# *4F96560203C8_4A27B5510171_var*
begin
//#UC START# *4F96560203C8_4A27B5510171_impl*
if (f_Name = nil) then
begin
if (f_Sub = nil) then
Result := l3CStr(evGetBlockName(TagInst).AsPCharLen)
else
Result := l3CStr(f_Sub.Name);
f_Name := Result;
end//f_Name = nil
else
Result := f_Name;
//#UC END# *4F96560203C8_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.GetName
function TevDocumentPartHotSpotTester.GetHintPrefix(const aState: TafwCursorState): Il3CString;
//#UC START# *4F96562802A7_4A27B5510171_var*
//#UC END# *4F96562802A7_4A27B5510171_var*
begin
//#UC START# *4F96562802A7_4A27B5510171_impl*
Result := nil;
case f_Area of
ev_oaCollapse :
if TagInst.BoolA[k2_tiCollapsed] then
Result := str_nevdphExpand.AsCStr
else
Result := str_nevdphCollapse.AsCStr;
ev_oaLeftEdge :
Result := str_nevdphSelect.AsCStr;
ev_oaProperties :
begin
if (ssCtrl in aState.rKeys) then
Result := str_nevdphMove.AsCStr
else
if (ssShift in aState.rKeys) then
Result := str_nevdphChangeTopBorder.AsCStr
else
Result := str_nevdphProperties.AsCStr;
end;//ev_oaProperties
ev_oaBottomEdge :
if (ssShift in aState.rKeys) then
Result := str_nevdphChangeBottomBorder.AsCStr
else
Exit;
else
Exit;
end;//case f_Area
//#UC END# *4F96562802A7_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.GetHintPrefix
function TevDocumentPartHotSpotTester.DoDrop(const aView: InevControlView;
const aPt: Tl3Point): Boolean;
{* Обрабатывает перемещение блока на aPt. }
//#UC START# *4F96565C038E_4A27B5510171_var*
//#UC END# *4F96565C038E_4A27B5510171_var*
begin
//#UC START# *4F96565C038E_4A27B5510171_impl*
Result := false;
//#UC END# *4F96565C038E_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.DoDrop
function TevDocumentPartHotSpotTester.CanChangeBorder(const aView: InevControlView;
const aPt: Tl3Point): Boolean;
{* Проверяет можно ли изменять границу блока. }
//#UC START# *4F96578503B9_4A27B5510171_var*
var
l_Result: Boolean absolute Result;
procedure lp_CheckEdge(aTop: Boolean);
var
l_EdgePoint : InevBasePoint;
l_MousePoint: InevBasePoint;
begin
l_MousePoint := aView.PointByPt(aPt, True);
l_Result := l_MousePoint <> nil;
if l_Result then
begin
l_EdgePoint := GetEdge(aView, not aTop);
if aTop then
l_Result := l_MousePoint.Diff(aView, l_EdgePoint, aView.FormatInfoByPoint(l_MousePoint)) <= 0
else
l_Result := l_MousePoint.Diff(aView, l_EdgePoint, aView.FormatInfoByPoint(l_MousePoint)) >= 0;
end; // if l_Result then
end;
//#UC END# *4F96578503B9_4A27B5510171_var*
begin
//#UC START# *4F96578503B9_4A27B5510171_impl*
Result := True;
if (f_DragArea in [ev_oaTopEdge, ev_oaBottomEdge]) then
lp_CheckEdge(f_DragArea = ev_oaTopEdge);
//#UC END# *4F96578503B9_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.CanChangeBorder
procedure TevDocumentPartHotSpotTester.ChangeBorder(const aView: InevControlView;
const aPt: Tl3Point);
{* Изменяет границу блока. }
//#UC START# *4F9657D00104_4A27B5510171_var*
var
l_InsCursor : InevBasePoint; // - Курсор для вставки
procedure CheckInsCursor;
var
l_Cursor : InevBasePoint;
begin//CheckInsCursor
l_Cursor := l_InsCursor.MostInner;
if not l3IEQ(l_Cursor.ParentPoint, l_InsCursor) then
begin
l_Cursor := l_Cursor.ParentPoint;
while True do
begin
if (l_Cursor.ParentPoint = nil) then
Break;
with l_Cursor.Obj^ do
if not IsKindOf(k2_typBlock) OR
// - если это не блок
not IsSame(ParaX.AsObject.Owner) then
// - или блок не наш родитель
l_Cursor := l_Cursor.ParentPoint
// - Понимаемся на уровень выше
else
Break; // - Нашли точку вставки
end;//while true
if l_Cursor.Inner.Obj.AsObject.IsKindOf(k2_typParaList) then
// - Игнорируем текст, картинки etc
l_Cursor.Inner := nil;
// - Вставляем именно в нужную точку вставки
end;//l_Cursor.Parent <> l_InsCursor
end;//CheckInsCursor
var
l_TopBorder : Boolean;
l_TopDiff : Integer;
l_BottomDiff : Integer;
function lp_CheckOutWholeBlock: Boolean;
begin
Result := ParaX.AsObject.ChildrenCount = 1;
if not Result then
Result := l_TopBorder and (l_BottomDiff = 0);
end;
var
l_BPoint : InevBasePoint;
procedure lp_CorrectPoint;
var
l_TablePoint: InevBasePoint;
begin
l_BPoint.MostInner.Move(aView, cnInitOperation[l_TopBorder]); // http://mdp.garant.ru/pages/viewpage.action?pageId=200085942
if l_BPoint.MostInner.ParentPoint.AsObject.IsKindOf(k2_typTableCell) then // http://mdp.garant.ru/pages/viewpage.action?pageId=360024475
begin
l_TablePoint := l_BPoint.MostInner.ParentPoint.ParentPoint.ParentPoint;
if l_TopBorder then
if l_TablePoint.Position >= (l_TablePoint.Obj^.AsObject.ChildrenCount div 2 + 1) then
l_TablePoint.Move(aView, cnInitOperation[not l_TopBorder])
else
l_TablePoint.Move(aView, cnInitOperation[l_TopBorder])
else
if l_TablePoint.Position <= (l_TablePoint.Obj^.AsObject.ChildrenCount div 2 + 1) then
l_TablePoint.Move(aView, cnInitOperation[not l_TopBorder])
else
l_TablePoint.Move(aView, cnInitOperation[l_TopBorder]);
end; // if l_BPoint.MostInner.ParentPoint.IsKindOf(k2_typTableCell) then
end;
function lp_GetParent(const aBorderPoint: InevBasePoint): InevBasePoint;
var
l_CurrentPoint : InevBasePoint;
l_TopBorderPoint: InevBasePoint;
begin
l_TopBorderPoint := aBorderPoint.PointToParentByLevel(MaxInt);
l_CurrentPoint := l_BPoint;
while l_TopBorderPoint.AsObject.IsSame(l_CurrentPoint.AsObject) do
begin
Result := l_TopBorderPoint;
l_TopBorderPoint := l_TopBorderPoint.Inner;
l_CurrentPoint := l_CurrentPoint.Inner;
if (l_TopBorderPoint = nil) or (l_CurrentPoint = nil) then Break;
end; // while l_TopBorderPoint.IsSame(l_CurrentPoint) do
end;
const
ctFlags4Delete: array [Boolean] of TevInsertParaFlags = ([ev_ipfAtEnd], []);
var
l_MoveOp : LongInt;
l_MoveOp1 : LongInt;
l_Border : InevBasePoint; // - старая граница
l_NewBorder : InevBasePoint; // - новая граница
l_DelBlock : InevRange; // - блок для удаления
l_Mem : Tl3MemoryPool;
l_Op : InevOp;
l_OutOfBlock : Boolean;
l_NeedJoin : Boolean;
l_Flags : TevLoadFlags;
l_Pt : Tl3Point;
l_FI : TnevFormatInfoPrim;
l_InsCursorMI : InevBasePoint;
l_NewBorderMI : InevBasePoint;
l_ParentBlock : InevBasePoint;
//#UC END# *4F9657D00104_4A27B5510171_var*
begin
//#UC START# *4F9657D00104_4A27B5510171_impl*
if (aView <> nil) AND CanChangeBorder(aView, aPt) then
begin
l_Op := k2StartOp(Processor, ev_msgDeletePara);
try
if (l_Op <> nil) then l_Op.Lock;
try
with ParaX do
begin
l_TopBorder := f_DragArea = ev_oaTopEdge;
if l_TopBorder then
begin
l_MoveOp := ev_ocPrevParaBottomRight;
l_MoveOp1 := ev_ocParaUp;
end//l_TopBorder
else
begin
l_MoveOp := ev_ocNextParaTopLeft;
l_MoveOp1 := ev_ocParaDown;
end;//l_TopBorder
try
try
try
l_Border := MakePoint;
try
l_Pt := l3Point(l_Pt.X, aPt.Y);
l_BPoint := aView.PointByPt(aPT);
lp_CorrectPoint;
l_Border.Move(aView, cnInitOperation[l_TopBorder]);
// - Инициализируем курсор
l_NeedJoin := False;
l_FI := aView.FormatInfoByPoint(l_BPoint);
l_TopDiff := l_BPoint.Diff(aView, GetEdge(aView, True), l_FI);
l_BottomDiff := l_BPoint.Diff(aView, GetEdge(aView, False), l_FI);
if l_TopBorder then
begin
if l_TopDiff = 0 then Exit;
end
else
if l_BottomDiff = 0 then Exit;
l_OutOfBlock := (l_TopDiff >= 0) and (l_BottomDiff <= 0);
if l_OutOfBlock then // выталкиваем за блок...
begin
if lp_CheckOutWholeBlock then Exit;
// Смотрим родительский. Если попадаем в начало или в конец, то вставляем пустой, с которым потом объединяем...
l_Border := lp_GetParent(l_Border);
with l_Border{, GetRedirect^} do
if IsKindOf(k2_typBlock) then
begin
if (Position = 1) OR
(Position = ChildrenCount) then
begin
evInsertPara(l_Op, l_Border, k2_typTextPara.MakeTag.AsObject, ctFlags4Delete[l_TopBorder]);
l_NeedJoin := True;
end;//l_TopBorder
end;//IsKindOf(k2_typBlock)
end;//l_OutOfBlock
l_Border := l_Border.PointToParentByLevel(MaxInt);
if (l_Border = nil) then
Exit;
l_InsCursor := l_Border.ClonePoint(aView);
l_ParentBlock := l_Border.ClonePoint(aView);
if l_ParentBlock.MostInner.ParentPoint.Move(aView, l_MoveOp) then
begin
if not (l_OutOfBlock and l_InsCursor.MostInner.ParentPoint.AtEnd(aView)) then
l_InsCursor := l_ParentBlock;
end // if l_ParentBlock.MostInner.ParentPoint.Move(aView, l_MoveOp) then
else
begin
l_InsCursor := l_ParentBlock;
if not l_OutOfBlock then
{ TODO -oЛюлин А. В. -cНедоделка :
Пытаемся расширить блок за границы документа.
Сейчас не работает, т.к. некорректно работает l_NewBorder.SetScreen(aPt);
В будущем можно сделать, например установкой:
evMoveCursor(l_NewBorder, l_InitOp); }
Exit
else
if l_InsCursor.MostInner.ParentPoint.Move(aView, l_MoveOp1, l_Op) then
l_NeedJoin := True
else
Exit;
end;//not evMoveCursor(l_InsCursor.BottomChild.Parent As _TevCursor, l_MoveOp)
// - формируем курсор для вставки
if l_OutOfBlock then
begin
// - выталкиваем параграфы из блока
if (l_BPoint = nil) then
Exit
else
l_NewBorder := l_BPoint;
if not l_NeedJoin then
begin
l_InsCursorMI := l_InsCursor.MostInner;
l_NewBorderMI := l_NewBorder.MostInner;
l_NeedJoin := l_NewBorderMI.AtEnd(aView) and l_InsCursorMI.AtStart and (l_NewBorderMI.Compare(l_InsCursorMI) = 1);
end; // if not l_NeedJoin then
end//l_OutOfBlock
else
begin
// - затаскиваем параграфы в блок
l_NewBorder := l_BPoint;
l_NewBorderMI := l_NewBorder.MostInner;
l3Swap(Pointer(l_InsCursor), Pointer(l_Border));
end;//l_OutOfBlock
if (l_NewBorder.Compare(l_Border) <= 0) then
l_DelBlock := l_Border.Obj.Range(l_NewBorder, l_Border)
else
l_DelBlock := l_Border.Obj.Range(l_Border, l_NewBorder);
l_Mem := Tl3MemoryPool.Create;
try
l_DelBlock.Data.Store(cf_EverestBin, l_Mem As IStream, nil, evDefaultStoreFlags + [evd_sfInternal] - [evd_sfStoreParaEnd]);
// - Здесь сохраняем блок
l_DelBlock.Modify.Delete(aView, l_Op, ev_cmEmpty4BlockResize);
// - Удаляем блок
if l_OutOfBlock then
// - Предотвращаем попадание параграфов в другой блок или таблицу
CheckInsCursor
else
evShrinkCursorChildren(l_InsCursor, ParaX.AsObject);
l_Flags := evDefaultLoadFlags + [ev_lfInternal];
if l_NeedJoin then
l_Flags := l_Flags + [ev_lfNeedJoin]
else
l_Flags := l_Flags - [ev_lfNeedJoin];
if not l_NeedJoin AND ((l_TopBorder AND l_OutOfBlock)
OR (not l_TopBorder)) then
l_Flags := l_Flags + [ev_lfAtEnd];
l_InsCursor.Text.Modify.InsertStream(aView, l_Mem As IStream, cf_EverestBin, l_Op, l_Flags);
// - Вставляем блок в другое место
finally
l3Free(l_Mem);
end;//try..finally
finally
l_Border := nil;
end;//try..finally
finally
l_NewBorder := nil;
end;//try..finally
finally
l_InsCursor := nil;
end;//try..finally
finally
l_DelBlock := nil;
end;//try..finally
end;//with ParaX
finally
if (l_Op <> nil) then l_Op.Unlock;
end;//try..finally
finally
l_Op := nil;
end;//try..finally
end;//CanChangeBorder..
//#UC END# *4F9657D00104_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.ChangeBorder
function TevDocumentPartHotSpotTester.ShowParts(const aView: InevControlView): Boolean;
//#UC START# *4F965819031F_4A27B5510171_var*
//#UC END# *4F965819031F_4A27B5510171_var*
begin
//#UC START# *4F965819031F_4A27B5510171_impl*
Result := False;
if (aView <> nil) then
Result := aView.Metrics.ShowDocumentParts;
//#UC END# *4F965819031F_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.ShowParts
function TevDocumentPartHotSpotTester.DoMouseAction(const aView: InevControlView;
aButton: TevMouseButton;
anAction: TevMouseAction;
const Keys: TevMouseState;
var Effect: TevMouseEffect): Boolean;
//#UC START# *4F96584801B7_4A27B5510171_var*
procedure DoDouble;
begin//DoDouble
case f_Area of
ev_oaLeftEdge :
begin
evSelectBlock(aView.Control.Selection, Self.ParaX);
Effect.rNeedAsyncLoop := False;
Result := True;
end;//ev_oaLeftEdge
ev_oaCollapse:
begin
Effect.rNeedAsyncLoop := False;
Result := True;
with TagInst do
BoolW[k2_tiCollapsed, k2StartOp(Processor)] := not BoolA[k2_tiCollapsed];
end;//ev_oaCollapse
ev_oaBottomEdge :
Result := True;
else
Result := False;
end;//Case f_Area
end;//DoDouble
//#UC END# *4F96584801B7_4A27B5510171_var*
begin
//#UC START# *4F96584801B7_4A27B5510171_impl*
CheckSub;
case aButton of
ev_mbLeft :
begin
case anAction of
ev_maDown:
begin
if (f_Area = ev_oaNone) then
Result := False
else
begin
Result := True;
if (ssCtrl in Keys.rKeys) then
begin
if (f_Area = ev_oaProperties) then
f_DragArea := ev_oaDragPoint;
end
else
if (ssShift in Keys.rKeys) then
begin
case f_Area of
ev_oaProperties : f_DragArea := ev_oaTopEdge;
ev_oaBottomEdge : f_DragArea := ev_oaBottomEdge;
end;//case f_Area of
end;//ssCtrl in Keys.rKeys
end;//f_Area = ev_oaNone
{$IfDef Nemesis}
DoDouble;
{$EndIf Nemesis}
if Result then
begin
if (f_DragArea in [ev_oaTopEdge, ev_oaBottomEdge]) then
Effect.rStrob := afw_stHorz;
end;//Result
end;//ev_maDown
ev_maMove:
begin
if (f_DragArea <> ev_oaNone) then
begin
Result := CanChangeBorder(aView, Tl3Point(Keys.rPoint));
case f_DragArea of
ev_oaTopEdge,
ev_oaBottomEdge :
begin
aView.Control.Selection.SelectPt(Keys.rPoint, false);
aView.Control.Selection.Point.MostInner.Move(aView, cnInitOperation[f_DragArea = ev_oaTopEdge]);
// http://mdp.garant.ru/pages/viewpage.action?pageId=200085942
aView.Control.ViewArea.Update;
end;//ev_oaTopEdge
else
aView.Control.Selection.SelectPt(Keys.rPoint, true);
end;//case f_DragArea of
end//f_DragArea <> ev_oaNone
else
Result := False;
end;//ev_maMove
ev_maUp:
begin
case f_DragArea of
ev_oaDragPoint :
begin
if (ssCtrl in Keys.rKeys) then
DoDrop(aView, Tl3Point(Keys.rPoint));
Result := True;
end;//ev_oaDragPoint
ev_oaTopEdge,
ev_oaBottomEdge :
begin
if (ssShift in Keys.rKeys) then
ChangeBorder(aView, Tl3Point(Keys.rPoint));
Result := True;
end;//ev_oaTopEdge..
else
Result := False;
end;//case f_DragAread
f_DragArea := ev_oaNone;
end;//ev_maUp
{$IfNDef Nemesis}
ev_maDouble :
DoDouble;
{$EndIf Nemesis}
else
Result := False;
end;//Case anAction
end;//ev_mbLeft
else
Result := False;
end;//case aButton
//#UC END# *4F96584801B7_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.DoMouseAction
function TevDocumentPartHotSpotTester.GetEdge(const aView: InevView;
aTop: Boolean): InevBasePoint;
//#UC START# *4F969E7001AD_4A27B5510171_var*
//#UC END# *4F969E7001AD_4A27B5510171_var*
begin
//#UC START# *4F969E7001AD_4A27B5510171_impl*
if aTop then
begin
if f_TopEdge = nil then
begin
f_TopEdge := ParaX.Para[0].MakePoint;
f_TopEdge.Move(aView, ev_ocTopLeft);
f_TopEdge := f_TopEdge.PointToParentByLevel(MaxInt);
end; // if f_TopEdge = nil then
Result := f_TopEdge;
end
else
begin
if f_BottomEdge = nil then
begin
f_BottomEdge := ParaX.Para[ParaX.ParaCount - 1].MakePoint;
f_BottomEdge.Move(aView, ev_ocBottomRight);
f_BottomEdge := f_BottomEdge.PointToParentByLevel(MaxInt);
end; // if f_BottomEdge = nil then
Result := f_BottomEdge;
end;
//#UC END# *4F969E7001AD_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.GetEdge
function TevDocumentPartHotSpotTester.MouseAction(const aView: InevControlView;
aButton: Tl3MouseButton;
anAction: Tl3MouseAction;
const Keys: TevMouseState;
var Effect: TevMouseEffect): Boolean;
{* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false }
//#UC START# *48E263CD01BD_4A27B5510171_var*
//#UC END# *48E263CD01BD_4A27B5510171_var*
begin
//#UC START# *48E263CD01BD_4A27B5510171_impl*
Result := DoMouseAction(aView, aButton, anAction, Keys, Effect);
//#UC END# *48E263CD01BD_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.MouseAction
function TevDocumentPartHotSpotTester.CanDrag: Boolean;
//#UC START# *4ECCD6840014_4A27B5510171_var*
//#UC END# *4ECCD6840014_4A27B5510171_var*
begin
//#UC START# *4ECCD6840014_4A27B5510171_impl*
Result := True;
//#UC END# *4ECCD6840014_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.CanDrag
procedure TevDocumentPartHotSpotTester.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4A27B5510171_var*
//#UC END# *479731C50290_4A27B5510171_var*
begin
//#UC START# *479731C50290_4A27B5510171_impl*
thisMap := nil;
f_TopEdge := nil;
f_BottomEdge := nil;
f_Area := ev_oaNone;
f_DragArea := ev_oaNone;
f_Sub := nil;
f_Name := nil;
inherited;
//#UC END# *479731C50290_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.Cleanup
procedure TevDocumentPartHotSpotTester.DoHitTest(const aView: InevControlView;
const aState: TafwCursorState;
var theInfo: TafwCursorInfo);
//#UC START# *4A267FC6016B_4A27B5510171_var*
var
l_Name : Il3CString;
//#UC END# *4A267FC6016B_4A27B5510171_var*
begin
//#UC START# *4A267FC6016B_4A27B5510171_impl*
inherited;
case f_DragArea of
ev_oaDragPoint :
theInfo.rCursor := ev_csDrag;
else
case f_Area of
ev_oaCollapse :
theInfo.rCursor := ev_csHandPoint;
ev_oaLeftEdge :
theInfo.rCursor := ev_csArrow;
ev_oaProperties :
begin
if (ssShift in aState.rKeys) then
theInfo.rCursor := ev_csVSplit
else
theInfo.rCursor := ev_csProperties;
end;//ev_oaProperties
ev_oaBottomEdge :
if (ssShift in aState.rKeys) then
theInfo.rCursor := ev_csVSplit;
end;//case f_Area
end;//case f_DragArea
theInfo.rHint := GetHintPrefix(aState);
if not l3IsNil(theInfo.rHint) then
begin
l_Name := GetName;
if not l3IsNil(l_Name) then
theInfo.rHint := l3Cat([l3Cat(theInfo.rHint, ': '), l_Name]);
with TagInst.Attr[k2_tiHandle] do
if IsValid then
theInfo.rHint := l3Cat(l3Cat(theInfo.rHint, ': '), IntToStr(AsLong));
end;//theInfo.rHint <> ''
//#UC END# *4A267FC6016B_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.DoHitTest
function TevDocumentPartHotSpotTester.COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult;
{* Реализация запроса интерфейса }
//#UC START# *4A60B23E00C3_4A27B5510171_var*
var
l_Sub : IevSub;
//#UC END# *4A60B23E00C3_4A27B5510171_var*
begin
//#UC START# *4A60B23E00C3_4A27B5510171_impl*
if IID.EQ(IevSub) then
begin
if (f_Sub = nil) then
CheckSub; // !!! заглушка !!!
if (f_Sub = nil) then
begin
Result.SetNoInterface;
Pointer(Obj) := nil;
end//f_Sub = nil
else
begin
Result.SetOk;
IevSub(Obj) := f_Sub;
end;//f_Sub = nil
end//IID.EQ(IevSub)
else
if IID.EQ(IevDocumentPart) then
begin
if l3IOk(QueryInterface(IevSub, l_Sub)) then
try
Result := Tl3HResult_C(l_Sub.QueryInterface(IID.IID, Obj));
finally
l_Sub := nil;
end//try..finally
else
Result := inherited COMQueryInterface(IID, Obj);
end//IID.EQ(IevDocumentPart)
else
Result := inherited COMQueryInterface(IID, Obj);
//#UC END# *4A60B23E00C3_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.COMQueryInterface
function TevDocumentPartHotSpotTester.DoGetAdvancedHotSpot(const aView: InevControlView;
const aState: TevCursorState;
const aPt: InevBasePoint;
const aMap: InevMap;
out theSpot: IevHotSpot): Boolean;
//#UC START# *4E6E4F91001A_4A27B5510171_var*
var
l_Pt : TnevPoint;
l_HotSpotSink : IevHotSpotSink;
{$IFNDEF Nemesis}
l_Map : InevMap;
l_ChildPoint : InevBasePoint;
{$ENDIF Nemesis}
//#UC END# *4E6E4F91001A_4A27B5510171_var*
begin
//#UC START# *4E6E4F91001A_4A27B5510171_impl*
thisMap := aMap;
f_Area := ev_oaNone;
if (aMap <> nil) then
begin
l_Pt := Tl3Point(aState.rPoint).Sub(aMap.Bounds.R.TopLeft);
begin
if (l_Pt.X >= 0) AND (l_Pt.Y >= 0) then
begin
if (l_Pt.Y < evDocumentPartMargin * 2) then
begin
if ShowParts(aView) then
begin
{$IfDef evNeedCollapseBlocks}
if (l_Pt.X < evDocumentPartMargin * 2) then
f_Area := ev_oaCollapse
else
{$EndIf evNeedCollapseBlocks}
{$IfNDef Nemesis}
if (l_Pt.Y < evDocumentPartMargin) then
f_Area := ev_oaProperties
else
{$EndIf Nemesis}
f_Area := ev_oaNone;
end//ShowParts..
else
f_Area := ev_oaNone;
end//l_Pt.Y < evDocumentPartMargin
else
if ShowParts(aView) then
begin
if (l_Pt.X < evDocumentPartMargin) then
f_Area := ev_oaLeftEdge
{$IFNDEF Nemesis}
else
if (l_Pt.Y >= aMap.Bounds.Bottom - aMap.Bounds.Top - evDocumentPartMargin) then
begin
l_ChildPoint := aPt.ClonePoint(aView);
l_ChildPoint.SetAtEnd(aView, True);
l_ChildPoint := l_ChildPoint.MostInner;
if not l_ChildPoint.AsObject.IsSame(aPt.Obj^.AsObject) then
begin
l_Map := aView.MapByPoint(l_ChildPoint);
if (l_Map <> nil) then
if (l_Map.Bounds.Bottom <= aMap.Bounds.Bottom) then
f_Area := ev_oaBottomEdge;
end;//if not l_ChildPoint.IsSame(aPt.Obj^) then
end;//if (l_Pt.Y >= aMap.Bounds.Bottom - aMap.Bounds.Top - evDocumentPartMargin) then
{$ENDIF Nemesis}
end;//l_Pt.Y < evDocumentPartMargin
end;//l_Pt.X >= 0
end;//IID.EQ(IevAdvancedHotSpot)
end;//aMap <> nil
if (f_Area = ev_oaNone) then
Result := inherited DoGetAdvancedHotSpot(aView, aState, aPt, aMap, theSpot)
else
begin
aView.Control.QueryInterface(IevHotSpotSink, l_HotSpotSink);
theSpot := TevHotSpotWrap.Make(Self, l_HotSpotSink);
Result := True;
end;//f_Area = ev_oaNone
//#UC END# *4E6E4F91001A_4A27B5510171_impl*
end;//TevDocumentPartHotSpotTester.DoGetAdvancedHotSpot
{$IfEnd} // Defined(evNeedHotSpot)
end.
|
unit Video2Matrix_TLB;
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// $Rev: 52393 $
// File generated on 6/29/2016 9:18:10 AM from Type Library described below.
// ************************************************************************ //
// Type Lib: C:\Users\foo\Desktop\video2matrix\delphi_dll\Video2Matrix (1)
// LIBID: {751FCBF0-DAEA-47CA-BE39-04F06EFBCA92}
// LCID: 0
// Helpfile:
// HelpString:
// DepndLst:
// (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb)
// SYS_KIND: SYS_WIN32
// ************************************************************************ //
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
{$WARN SYMBOL_PLATFORM OFF}
{$WRITEABLECONST ON}
{$VARPROPSETTER ON}
{$ALIGN 4}
interface
uses Winapi.Windows, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleServer, Winapi.ActiveX;
// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:
// Type Libraries : LIBID_xxxx
// CoClasses : CLASS_xxxx
// DISPInterfaces : DIID_xxxx
// Non-DISP interfaces: IID_xxxx
// *********************************************************************//
const
// TypeLibrary Major and minor versions
Video2MatrixMajorVersion = 1;
Video2MatrixMinorVersion = 0;
LIBID_Video2Matrix: TGUID = '{751FCBF0-DAEA-47CA-BE39-04F06EFBCA92}';
IID_IVideoLoader: TGUID = '{38C4F412-A710-4F73-8013-9EE3735A66FB}';
CLASS_VideoLoader: TGUID = '{EC8DAD21-94B2-444D-90B6-452375B937EF}';
IID_IUtilFuncs: TGUID = '{50798219-ACCD-4A91-BD2B-993141954ADB}';
CLASS_UtilFuncs: TGUID = '{6A2CE78E-735B-4DDF-9CA1-893D634B39E6}';
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
IVideoLoader = interface;
IUtilFuncs = interface;
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// (NOTE: Here we map each CoClass to its Default Interface)
// *********************************************************************//
VideoLoader = IVideoLoader;
UtilFuncs = IUtilFuncs;
// *********************************************************************//
// Declaration of structures, unions and aliases.
// *********************************************************************//
PVideoInfo = ^TVideoInfo; {*}
PShortint1 = ^Shortint; {*}
PInteger1 = ^Integer; {*}
PByte1 = ^Byte; {*}
TVideoInfo = record
filename: WideString;
isValid: WordBool;
width: Integer;
height: Integer;
duration: Double;
avgFrameRate: Double;
estNumFrames: Integer;
thumbFilename: WideString;
end;
// *********************************************************************//
// Interface: IVideoLoader
// Flags: (256) OleAutomation
// GUID: {38C4F412-A710-4F73-8013-9EE3735A66FB}
// *********************************************************************//
IVideoLoader = interface(IUnknown)
['{38C4F412-A710-4F73-8013-9EE3735A66FB}']
function Init: HResult; stdcall;
function TryLoad(const videoPath: WideString; const thumbsPath: WideString;
var videoInfo: TVideoInfo; out success: WordBool): HResult; stdcall;
function FitFrame(origW: Integer; origH: Integer; maxW: Integer; maxH: Integer;
out outW: Integer; out outH: Integer): HResult; stdcall;
function OpenVideo(const filename: WideString; var maxW: Integer; var maxH: Integer;
out outHandle: Integer): HResult; stdcall;
function CloseVideo(videoHandle: Integer): HResult; stdcall;
function FreePreviewFrames(videoHandle: Integer): HResult; stdcall;
function SeekVideo(videoHandle: Integer; frame: Integer): HResult; stdcall;
function SetMatrixSize(videoHandle: Integer; width: Integer; height: Integer): HResult; stdcall;
function AllocPreviewFrames(videoHandle: Integer; maxPreviewFrames: Integer): HResult; stdcall;
function RenderPreviewFrame(videoHandle: Integer; out retVal: WordBool): HResult; stdcall;
function TotalFrames(videoHandle: Integer; out numFrames: Integer): HResult; stdcall;
function GetCachedFrame(videoHandle: Integer; frameNum: Integer; var dest: Byte): HResult; stdcall;
function GetCachedMatrix(videoHandle: Integer; frameNum: Integer; cropX: Integer;
cropY: Integer; cropW: Integer; cropH: Integer; var dest: Byte;
blendFrames: WordBool): HResult; stdcall;
function GetFullMatrix(videoHandle: Integer; frameNum: Integer; cropX: Integer; cropY: Integer;
cropW: Integer; cropH: Integer; var dest: Byte): HResult; stdcall;
function CurrentFrame(videoHandle: Integer; out retVal: Integer): HResult; stdcall;
function GetMatrixWH(videoHandle: Integer; out outW: Integer; out outH: Integer): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IUtilFuncs
// Flags: (256) OleAutomation
// GUID: {50798219-ACCD-4A91-BD2B-993141954ADB}
// *********************************************************************//
IUtilFuncs = interface(IUnknown)
['{50798219-ACCD-4A91-BD2B-993141954ADB}']
function TestFunc01(whatever: Integer; out output: Integer): HResult; stdcall;
end;
// *********************************************************************//
// The Class CoVideoLoader provides a Create and CreateRemote method to
// create instances of the default interface IVideoLoader exposed by
// the CoClass VideoLoader. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoVideoLoader = class
class function Create: IVideoLoader;
class function CreateRemote(const MachineName: string): IVideoLoader;
end;
// *********************************************************************//
// The Class CoUtilFuncs provides a Create and CreateRemote method to
// create instances of the default interface IUtilFuncs exposed by
// the CoClass UtilFuncs. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoUtilFuncs = class
class function Create: IUtilFuncs;
class function CreateRemote(const MachineName: string): IUtilFuncs;
end;
implementation
uses System.Win.ComObj;
class function CoVideoLoader.Create: IVideoLoader;
begin
Result := CreateComObject(CLASS_VideoLoader) as IVideoLoader;
end;
class function CoVideoLoader.CreateRemote(const MachineName: string): IVideoLoader;
begin
Result := CreateRemoteComObject(MachineName, CLASS_VideoLoader) as IVideoLoader;
end;
class function CoUtilFuncs.Create: IUtilFuncs;
begin
Result := CreateComObject(CLASS_UtilFuncs) as IUtilFuncs;
end;
class function CoUtilFuncs.CreateRemote(const MachineName: string): IUtilFuncs;
begin
Result := CreateRemoteComObject(MachineName, CLASS_UtilFuncs) as IUtilFuncs;
end;
end.
|
unit cSampleDataset;
interface
uses Generics.Collections, Data.Db;
type
TSampleDataset = class
const
NUM_REC = 20;
private
fDS: TDataset;
fKeys: TList<integer>;
function RandomNum: integer;
function RandomKey: integer;
function RandomHex: string;
procedure RandomMove;
public
constructor Create(aDs: TDataset);
destructor Destroy; override;
procedure ActionClear;
procedure ActionAppend;
procedure ActionInsert;
procedure ActionDelete;
procedure ActionUpdate;
procedure ActionRandom;
function AsDebug: string;
end;
implementation
uses System.Classes, System.Math, System.SysUtils;
function TSampleDataset.RandomNum: integer;
begin
Result := RandomRange(0, 99999999);
end;
function TSampleDataset.RandomKey: integer;
var
i: integer;
begin
for i := 0 to 999 do
begin
Result := RandomRange(1, NUM_REC + 1);
if not fKeys.Contains(Result) then
begin
fKeys.Add(Result);
Exit;
end;
end;
raise Exception.Create('RandomKey : Unable to generate unique key');
end;
function TSampleDataset.RandomHex: string;
begin
Result := IntToHex(RandomNum(), 8);
end;
procedure TSampleDataset.ActionRandom;
begin
case RandomRange(0, 4) of
0:
ActionAppend;
1:
ActionInsert;
2:
ActionDelete;
3:
ActionUpdate;
else
raise Exception.Create('Invalid action');
end;
end;
procedure TSampleDataset.RandomMove;
begin
Exit;
fDS.First;
fDS.MoveBy(RandomRange(0, fKeys.Count) div 3 * 2);
end;
procedure TSampleDataset.ActionAppend;
begin
fDS.Append;
fDS.FieldByName('nn').AsInteger := RandomKey;
fDS.FieldByName('ss').AsString := RandomHex;
fDS.Post;
end;
procedure TSampleDataset.ActionInsert;
begin
RandomMove;
fDS.Insert;
fDS.FieldByName('nn').AsInteger := RandomKey;
fDS.FieldByName('ss').AsString := RandomHex;
fDS.Post;
end;
procedure TSampleDataset.ActionDelete;
begin
if fDS.IsEmpty then
Exit;
RandomMove;
fKeys.Remove(fDS.FieldByName('nn').AsInteger);
fDS.Delete;
end;
procedure TSampleDataset.ActionUpdate;
begin
if fDS.IsEmpty then
Exit;
RandomMove;
fDS.Edit;
fDS.FieldByName('ss').AsString := RandomHex;
fDS.Post;
end;
function TSampleDataset.AsDebug: string;
var
c: string;
r: string;
begin
// if fDS.IsEmpty then
// Exit('0');
//
Exit(IntToStr(fDS.RecNo));
// c := fDS.FieldByName('nn').AsString;
fDS.First;
while not fDS.Eof do
begin
r := r + fDS.FieldByName('nn').AsString + ',';
fDS.Next;
end;
r := '[' + c + ']' + r;
Result := r;
end;
procedure TSampleDataset.ActionClear;
begin
while not fDS.IsEmpty do
fDS.Delete;
fKeys.Clear;
end;
constructor TSampleDataset.Create(aDs: TDataset);
begin
fDS := aDs;
fKeys := TList<integer>.Create;
end;
destructor TSampleDataset.Destroy;
begin
fKeys.Free;
inherited;
end;
end.
|
unit nscCustomReminderModelPart;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Nemesis"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/Nemesis/nscCustomReminderModelPart.pas"
// Начат: 18.04.2011 20:11
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<GuiControl::Class>> Shared Delphi For F1::Nemesis::Reminders::TnscCustomReminderModelPart
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Nemesis\nscDefine.inc}
interface
{$If defined(Nemesis)}
uses
Classes
{$If not defined(NoVCM)}
,
vcmExternalInterfaces
{$IfEnd} //not NoVCM
,
l3ProtoObject
{$If not defined(NoVCM)}
,
vtReminderModelPart
{$IfEnd} //not NoVCM
;
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
type
InscReminderState = interface(IUnknown)
['{5E0FFE44-CACA-4C5C-91A2-F6AE6F764F89}']
function Get_PopupFormVisible: Boolean;
property PopupFormVisible: Boolean
read Get_PopupFormVisible;
end;//InscReminderState
TnscReminderState = class(Tl3ProtoObject {$If not defined(NoVCM)}, IvcmBase{$IfEnd} //not NoVCM
, InscReminderState)
private
// private fields
f_PopupFormVisible : Boolean;
protected
// realized methods
function Get_PopupFormVisible: Boolean;
public
// public methods
constructor Create(aPopupFormVisible: Boolean); reintroduce;
class function Make(aPopupFormVisible: Boolean): InscReminderState; reintroduce;
{* Сигнатура фабрики TnscReminderState.Make }
end;//TnscReminderState
TnscCustomReminderModelPart = class(TvtReminderModelPart {$If not defined(NoVCM)}, IvcmState{$IfEnd} //not NoVCM
)
protected
// realized methods
{$If not defined(NoVCM)}
function SaveState(out theState: IUnknown;
aStateType: TvcmStateType): Boolean;
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
function LoadState(const theState: IUnknown;
aStateType: TvcmStateType): Boolean;
{$IfEnd} //not NoVCM
end;//TnscCustomReminderModelPart
{$IfEnd} //Nemesis
implementation
{$If defined(Nemesis)}
uses
SysUtils
;
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
// start class TnscReminderState
constructor TnscReminderState.Create(aPopupFormVisible: Boolean);
//#UC START# *4DAC655A0360_4DAC647800DC_var*
//#UC END# *4DAC655A0360_4DAC647800DC_var*
begin
//#UC START# *4DAC655A0360_4DAC647800DC_impl*
inherited Create;
f_PopupFormVisible := aPopupFormVisible;
//#UC END# *4DAC655A0360_4DAC647800DC_impl*
end;//TnscReminderState.Create
class function TnscReminderState.Make(aPopupFormVisible: Boolean): InscReminderState;
var
l_Inst : TnscReminderState;
begin
l_Inst := Create(aPopupFormVisible);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TnscReminderState.Get_PopupFormVisible: Boolean;
//#UC START# *4DAC65280226_4DAC647800DCget_var*
//#UC END# *4DAC65280226_4DAC647800DCget_var*
begin
//#UC START# *4DAC65280226_4DAC647800DCget_impl*
Result := f_PopupFormVisible;
//#UC END# *4DAC65280226_4DAC647800DCget_impl*
end;//TnscReminderState.Get_PopupFormVisible
{$If not defined(NoVCM)}
function TnscCustomReminderModelPart.SaveState(out theState: IUnknown;
aStateType: TvcmStateType): Boolean;
//#UC START# *4683E75B01D8_4DAC62900118_var*
//#UC END# *4683E75B01D8_4DAC62900118_var*
begin
//#UC START# *4683E75B01D8_4DAC62900118_impl*
Result := (aStateType = vcm_stContent) AND (PopupForm <> nil);
if Result then
begin
theState := TnscReminderState.Make(PopupForm.Visible);
PopupForm.Visible := false;
end;//Result
//#UC END# *4683E75B01D8_4DAC62900118_impl*
end;//TnscCustomReminderModelPart.SaveState
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
function TnscCustomReminderModelPart.LoadState(const theState: IUnknown;
aStateType: TvcmStateType): Boolean;
//#UC START# *4683E79D0331_4DAC62900118_var*
var
l_St : InscReminderState;
//#UC END# *4683E79D0331_4DAC62900118_var*
begin
//#UC START# *4683E79D0331_4DAC62900118_impl*
Result := (aStateType = vcm_stContent);
if Result then
begin
if Supports(theState, InscReminderState, l_St) then
try
if (PopupForm = nil) then
Self.ShowPopupFormOnDockLocal := l_St.PopupFormVisible
else
begin
Assert(PopupForm <> nil);
PopupForm.Visible := l_St.PopupFormVisible;
end;//PopupForm = nil
finally
l_St := nil;
end;//try..finally
end;//Result
//#UC END# *4683E79D0331_4DAC62900118_impl*
end;//TnscCustomReminderModelPart.LoadState
{$IfEnd} //not NoVCM
{$IfEnd} //Nemesis
end. |
unit vcmBaseEntitiesCollection;
{* Коллекция сущностей. }
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmBaseEntitiesCollection - }
{ Начат: 19.11.2003 10:36 }
{ $Id: vcmBaseEntitiesCollection.pas,v 1.43 2013/07/01 12:28:52 morozov Exp $ }
// $Log: vcmBaseEntitiesCollection.pas,v $
// Revision 1.43 2013/07/01 12:28:52 morozov
// {RequestLink:382416588}
//
// Revision 1.42 2012/08/07 17:07:16 lulin
// {RequestLink:372998156}
//
// Revision 1.41 2012/08/07 15:15:12 lulin
// {RequestLink:358352265}
//
// Revision 1.40 2012/08/07 14:37:42 lulin
// {RequestLink:358352265}
//
// Revision 1.39 2012/04/13 18:22:34 lulin
// {RequestLink:237994598}
//
// Revision 1.38 2011/01/24 16:51:02 lulin
// {RequestLink:236719144}.
// - исправления насчёт отвалившихся GetState.
//
// Revision 1.37 2011/01/24 16:11:50 lulin
// {RequestLink:236719144}.
//
// Revision 1.36 2011/01/19 15:05:10 lulin
// {RequestLink:248195582}.
// - сделано удаление комментариев из списка комментариев.
//
// Revision 1.35 2010/07/16 16:07:06 lulin
// {RequestLink:197496539}.
//
// Revision 1.34 2010/07/15 15:55:05 lulin
// {RequestLink:197496539}.
//
// Revision 1.33 2009/10/23 12:46:05 lulin
// {RequestLink:167353056}. Пляски с бубном вокруг тулбаров.
//
// Revision 1.32 2009/10/12 11:27:15 lulin
// - коммитим после падения CVS.
//
// Revision 1.32 2009/10/08 12:46:44 lulin
// - чистка кода.
//
// Revision 1.31 2009/08/28 17:15:47 lulin
// - начинаем публикацию и описание внутренних операций.
//
// Revision 1.30 2009/02/11 15:19:45 lulin
// - чистка кода.
//
// Revision 1.29 2009/02/04 15:33:55 lulin
// - исправляем ошибку ненахождения методов. http://mdp.garant.ru/pages/viewpage.action?pageId=136260278&focusedCommentId=136260289#comment-136260289
//
// Revision 1.28 2008/12/25 13:04:37 lulin
// - <K>: 133891241.
//
// Revision 1.27 2008/03/19 14:23:44 lulin
// - cleanup.
//
// Revision 1.26 2008/01/31 18:53:33 lulin
// - избавляемся от излишней универсальности списков.
//
// Revision 1.25 2007/08/07 17:33:54 lulin
// - публикуем сущность, даже если контрол не задан.
//
// Revision 1.24 2007/02/27 14:14:49 lulin
// - для привязывания сущности к контролу используем ее идентификатор, а не имя.
//
// Revision 1.23 2007/02/27 12:08:52 lulin
// - cleanup.
//
// Revision 1.22 2006/03/16 11:30:21 lulin
// - cleanup.
//
// Revision 1.21 2006/03/16 11:28:51 lulin
// - вычищены имена сущностей и операций - перешли на их идентификаторы.
//
// Revision 1.20 2006/01/20 11:33:06 mmorozov
// 1. Нельзя было на панель инструментов положить неколько операций из разных сущностей с одинаковыми именами;
// 2. Если в панели инструментов встречаются операции с одинаковыми названиями, то им автоматически добавляется суффикс в виде названия сущности;
// 3. Появилась возможность указать, что контекстные операции сущности должны показываться в отдельном пункте меню;
// 3.
//
// Revision 1.19 2005/06/27 07:16:17 mmorozov
// change: сигнатура _LinkControl (TvcmBaseEntitiesCollection);
// change: в методе _LinkControl не происходит работа с интерфейсом IvcmSettingsSource;
//
// Revision 1.18 2005/06/23 16:00:44 mmorozov
// change: сигнатура _LinkControl;
//
// Revision 1.17 2005/01/27 13:43:28 lulin
// - bug fix: не все контролы отвязывались от операций (CQ OIT5-11924).
//
// Revision 1.16 2005/01/27 10:13:04 lulin
// - new behavior: отвязываем от сущностей все вложенные компоненты.
//
// Revision 1.15 2004/12/23 13:45:38 am
// new: _UnlinkControlFromEntity - метод, парный _LinkControlToEntity
//
// Revision 1.14 2004/12/17 12:43:20 mmorozov
// new: в _LinkControl устанавливаем компоненту IvcmSettings, если он поддерживает IvcmSettingsSource;
//
// Revision 1.13 2004/11/25 11:06:02 lulin
// - new method: IvcmOperationsPublisher._PublishEntity.
//
// Revision 1.12 2004/11/25 10:44:11 lulin
// - rename type: _TvcmExecuteEvent -> TvcmControlExecuteEvent.
// - rename type: _TvcmTestEvent -> TvcmControlTestEvent.
// - new type: TvcmControlGetTargetEvent.
//
// Revision 1.11 2004/11/24 12:35:55 lulin
// - new behavior: обработчики операций от контролов теперь привязываются к операциям.
//
// Revision 1.10 2004/11/22 16:23:10 lulin
// - new behavior: вчерне сделал механизм вытаскивания операций из контролов, пока эти операции никуда не попадают.
//
// Revision 1.9 2004/11/17 18:56:05 lulin
// - new method: TvcmBaseEntitiesCollection._UnlinkControl.
//
// Revision 1.8 2004/09/27 16:26:25 lulin
// - new behavior: в редакторе свойств для сущностей и операций показываем дополнительные параметры.
//
// Revision 1.7 2004/09/22 06:12:34 lulin
// - оптимизация - методу TvcmBaseCollection.FindItemByID придана память о последнем найденном элементе.
//
// Revision 1.6 2004/09/22 05:41:24 lulin
// - оптимизация - убраны код и данные, не используемые в Run-Time.
//
// Revision 1.5 2004/06/02 10:20:43 law
// - удален конструктор Tl3VList.MakeIUnknown - пользуйтесь _Tl3InterfaceList.Make.
//
// Revision 1.4 2004/05/18 14:50:58 law
// - new method: TvcmBaseEntitiesCollection.GetOp.
//
// Revision 1.3 2004/02/26 12:09:24 nikitin75
// + присваиваем shortcut'ы в runtime;
//
// Revision 1.2 2003/11/24 17:35:21 law
// - new method: TvcmCustomEntities._RegisterInRep.
//
// Revision 1.1 2003/11/19 11:38:24 law
// - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано.
//
{$Include vcmDefine.inc }
interface
uses
Classes,
vcmBase,
vcmInterfaces,
vcmExternalInterfaces,
vcmBaseCollection,
vcmBaseCollectionItem,
vcmBaseEntitiesCollectionItem,
vcmBaseOperationsCollectionItem
;
type
TvcmBaseEntitiesCollection = class(TvcmBaseCollection, IvcmOperationsPublisher)
{* Коллекция сущностей. }
public
// interface methods
// IvcmOperationsPublisher
procedure PublishEntity(const anEntity : TvcmString;
aGetTarget : TvcmControlGetTargetEvent);
{* - опубликовать сущность. }
function PublishFormEntity(const anEntity : TvcmString;
aGetTarget : TvcmGetTargetEvent): TvcmBaseEntitiesCollectionItem;
{* - опубликовать сущность. }
procedure GroupItemsInContextMenu(const anEntity : TvcmString);
{-}
procedure ToolbarAtBottom(const anEntity : TvcmString);
{-}
procedure ContextMenuWeight(const anEntity : TvcmString;
aWeight : Integer); overload;
{* - установить вес сущности в контекстном меню }
procedure ContextMenuWeight(const anEntity : TvcmString;
const anOperation : TvcmString;
aWeight : Integer;
aNoPrefix : Boolean = False); overload;
{* - установить вес операции в контекстном меню }
procedure PublishOp(const anEntity : TvcmString;
const anOperation : TvcmString;
anExecute : TvcmControlExecuteEvent = nil;
aTest : TvcmControlTestEvent = nil;
aGetState : TvcmControlGetStateEvent = nil;
aNoPrefix : Boolean = false);
{* - опубликовать операцию. }
procedure PublishOpWithResult(const anEntity : TvcmString;
const anOperation : TvcmString;
anExecute : TvcmExecuteEvent;
aTest : TvcmControlTestEvent;
aGetState : TvcmControlGetStateEvent;
aNoPrefix : Boolean = false);
{* - опубликовать операцию. }
function GetOperationByName(const anEntity : TvcmString;
const anOperation : TvcmString;
aNoPrefix : Boolean = false): TvcmBaseOperationsCollectionItem;
{-}
procedure ShowInContextMenu(const anEntity : TvcmString;
const anOperation : TvcmString;
aValue : Boolean;
aNoPrefix : Boolean = false);
{-}
procedure ShowInToolbar(const anEntity : TvcmString;
const anOperation : TvcmString;
aValue : Boolean;
aNoPrefix : Boolean = false);
{-}
public
// internal methods
function CheckEntityForControl(const anEntity : TvcmString): TvcmBaseEntitiesCollectionItem;
{-}
protected
// internal methods
function GetAttrCount: Integer;
override;
{-}
function GetAttr(Index: Integer): string;
override;
{-}
function GetItemAttr(Index, ItemIndex: Integer): string;
override;
{-}
public
// public methods
class function GetItemClass: TCollectionItemClass;
override;
{-}
procedure GetEntitiesDef(aList : TvcmInterfaceList);
{* - возвращает список описателей сущностей. }
procedure LinkControl(aControl : TComponent);
{-}
procedure UnlinkControl(aControl: TComponent);
{-}
procedure RegisterInRep;
{-}
function IsItemCaptionUnique(const aItem: TvcmBaseCollectionItem): Boolean;
{* - поиск операции по названию. }
end;//TvcmBaseEntitiesCollection
implementation
uses
SysUtils,
vcmEntities,
vcmUserControls
;
// start class TvcmBaseEntitiesCollection
procedure TvcmBaseEntitiesCollection.PublishEntity(const anEntity : TvcmString;
aGetTarget : TvcmControlGetTargetEvent);
{* - опубликовать сущность. }
var
l_M : TMethod absolute aGetTarget;
l_Control : TComponent;
l_En : TvcmBaseEntitiesCollectionItem;
begin
l_En := CheckEntityForControl(anEntity);
l_Control := TComponent(l_M.Data);
if (l_Control <> nil) then
l_En.PublishEntity(l_Control, aGetTarget);
end;
function TvcmBaseEntitiesCollection.PublishFormEntity(const anEntity : TvcmString;
aGetTarget : TvcmGetTargetEvent): TvcmBaseEntitiesCollectionItem;
{* - опубликовать сущность. }
begin
Result := CheckEntityForControl(anEntity);
if Assigned(aGetTarget) then
Result.PublishFormEntity(aGetTarget);
end;
procedure TvcmBaseEntitiesCollection.GroupItemsInContextMenu(const anEntity : TvcmString);
{-}
begin
with CheckEntityForControl(anEntity) do
Options := Options + [vcm_enoGroupItemsInContextMenu];
end;
procedure TvcmBaseEntitiesCollection.ToolbarAtBottom(const anEntity : TvcmString);
{-}
begin
CheckEntityForControl(anEntity).ToolbarPos := vcm_tbpBottom;
end;
procedure TvcmBaseEntitiesCollection.PublishOp(const anEntity : TvcmString;
const anOperation : TvcmString;
anExecute : TvcmControlExecuteEvent = nil;
aTest : TvcmControlTestEvent = nil;
aGetState : TvcmControlGetStateEvent = nil;
aNoPrefix : Boolean = false);
{* - опубликовать операцию. }
var
l_Execute : TMethod absolute anExecute;
l_Test : TMethod absolute aTest;
l_GetState : TMethod absolute aGetState;
l_Control : TComponent;
l_Op : String;
l_En : TvcmBaseEntitiesCollectionItem;
begin
l_Control := TComponent(l_Execute.Data);
if (l_Control = nil) then
l_Control := TComponent(l_Test.Data);
if (l_Control = nil) then
l_Control := TComponent(l_GetState.Data);
l_En := CheckEntityForControl(anEntity);
(* if (l_Control <> nil) then
begin*)
if aNoPrefix then
l_Op := anOperation
else
l_Op := 'op' + anOperation;
l_En.PublishOp(l_Control, l_Op, anExecute, aTest, aGetState);
(* end;//l_Control <> nil*)
end;
procedure TvcmBaseEntitiesCollection.PublishOpWithResult(const anEntity : TvcmString;
const anOperation : TvcmString;
anExecute : TvcmExecuteEvent;
aTest : TvcmControlTestEvent;
aGetState : TvcmControlGetStateEvent;
aNoPrefix : Boolean = false);
//overload;
{* - опубликовать операцию. }
var
l_Execute : TMethod absolute anExecute;
l_Test : TMethod absolute aTest;
l_Control : TComponent;
l_Op : String;
l_En : TvcmBaseEntitiesCollectionItem;
begin
l_Control := TComponent(l_Execute.Data);
if (l_Control = nil) then
l_Control := TComponent(l_Test.Data);
l_En := CheckEntityForControl(anEntity);
if (l_Control <> nil) then
begin
if aNoPrefix then
l_Op := anOperation
else
l_Op := 'op' + anOperation;
l_En.PublishOp(l_Control, l_Op, anExecute, aTest, aGetState);
end;//l_Control <> nil
end;
function TvcmBaseEntitiesCollection.CheckEntityForControl(const anEntity : TvcmString): TvcmBaseEntitiesCollectionItem;
{-}
var
l_En : String;
begin
l_En := 'en' + anEntity;
Result := FindItemByName(l_En) As TvcmBaseEntitiesCollectionItem;
if (Result = nil) then
begin
Result := Add As TvcmBaseEntitiesCollectionItem;
Result.Name := l_En;
end;//l_EnI = nil
end;
function TvcmBaseEntitiesCollection.GetOperationByName(const anEntity : TvcmString;
const anOperation : TvcmString;
aNoPrefix : Boolean = false): TvcmBaseOperationsCollectionItem;
{-}
var
l_Op : String;
begin
if aNoPrefix then
l_Op := anOperation
else
l_Op := 'op' + anOperation;
Result := CheckEntityForControl(anEntity).Operations.FindItemByName(l_Op) As TvcmBaseOperationsCollectionItem;
end;
procedure TvcmBaseEntitiesCollection.ShowInContextMenu(const anEntity : TvcmString;
const anOperation : TvcmString;
aValue : Boolean;
aNoPrefix : Boolean = false);
{-}
var
l_Op : TvcmOperationOptions;
begin
with GetOperationByName(anEntity, anOperation, aNoPrefix) do
begin
l_Op := Options;
if aValue then
Include(l_Op, vcm_ooShowInContextMenu)
else
begin
Exclude(l_Op, vcm_ooShowInContextMenu);
if (l_Op = []) then
Include(l_Op, vcm_ooShowInChildMenu);
end;//aValue
Options := l_Op;
end;//GetOperationByName(anEntity, anOperation, aNoPrefix)
end;
procedure TvcmBaseEntitiesCollection.ShowInToolbar(const anEntity : TvcmString;
const anOperation : TvcmString;
aValue : Boolean;
aNoPrefix : Boolean = false);
{-}
var
l_Op : TvcmOperationOptions;
begin
with GetOperationByName(anEntity, anOperation, aNoPrefix) do
begin
l_Op := Options;
if aValue then
Include(l_Op, vcm_ooShowInChildToolbar)
else
begin
Exclude(l_Op, vcm_ooShowInChildToolbar);
if (l_Op = []) then
Include(l_Op, vcm_ooShowInChildMenu);
end;//aValue
Options := l_Op;
end;//GetOperationByName(anEntity, anOperation, aNoPrefix)
end;
function TvcmBaseEntitiesCollection.GetAttrCount: Integer;
//override;
{-}
begin
Result := inherited GetAttrCount + 2;
end;
function TvcmBaseEntitiesCollection.GetAttr(Index: Integer): string;
//override;
{-}
var
l_C : Integer;
begin
l_C := inherited GetAttrCount;
if (Index >= l_C) then
begin
Case Index - l_C of
0 : Result := 'Caption';
1 : Result := 'Name';
end;//Case Index - l_C
end//Index >= l_C
else
Result := inherited GetAttr(Index);
end;
function TvcmBaseEntitiesCollection.GetItemAttr(Index, ItemIndex: Integer): string;
//override;
{-}
var
l_C : Integer;
begin
l_C := inherited GetAttrCount;
if (Index > l_C) then
begin
Case Index - l_C of
1 : Result := TvcmBaseEntitiesCollectionItem(Items[ItemIndex]).Name;
end;//Case Index - l_C
end//Index > l_C
else
Result := inherited GetItemAttr(Index, ItemIndex);
end;
class function TvcmBaseEntitiesCollection.GetItemClass: TCollectionItemClass;
//override;
{-}
begin
Result := TvcmBaseEntitiesCollectionItem;
end;
procedure TvcmBaseEntitiesCollection.GetEntitiesDef(aList : TvcmInterfaceList);
{* - возвращает список описателей сущностей. }
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(Count) do
aList.Add(TvcmBaseEntitiesCollectionItem(Items[l_Index]).EntityDef);
end;
procedure TvcmBaseEntitiesCollection.LinkControl(aControl : TComponent);
{-}
var
l_Provider : IvcmOperationsProvider;
begin
if (aControl <> nil) then
begin
// Зарегистрируем операции
if Supports(aControl, IvcmOperationsProvider, l_Provider) then
try
l_Provider.ProvideOps(Self);
finally
l_Provider := nil;
end;//try..finally
end;//aControl <> nil
end;
procedure TvcmBaseEntitiesCollection.UnlinkControl(aControl: TComponent);
{-}
var
l_Index : Integer;
l_Item : TvcmBaseEntitiesCollectionItem;
begin
if (aControl <> nil) then
begin
for l_Index := 0 to Pred(Count) do
begin
l_Item := TvcmBaseEntitiesCollectionItem(Items[l_Index]);
l_Item.SupportedBy[aControl] := false;
end;//for l_Index
end;//aControl <> nil
end;
procedure TvcmBaseEntitiesCollection.RegisterInRep;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(Count) do
TvcmBaseEntitiesCollectionItem(Items[l_Index]).RegisterInRep;
end;
function TvcmBaseEntitiesCollection.IsItemCaptionUnique(const aItem: TvcmBaseCollectionItem): Boolean;
{* - поиск операции по названию. }
var
l_Index: Integer;
begin
Result := True;
// Только для сущностей форм
if Owner is TvcmEntities then
for l_Index := 0 to Pred(Count) do
with TvcmBaseEntitiesCollectionItem(Items[l_Index]) do
if not IsItemCaptionUnique(aItem) then
begin
Result := False;
Break;
end;//if IsItemCaptionUnique(aCaption) then
end;//IsItemCaptionUnique
procedure TvcmBaseEntitiesCollection.ContextMenuWeight(
const anEntity: TvcmString; aWeight: Integer);
{* - установить вес в контекстном меню}
var
l_EntitiesCollectionItem: TvcmBaseEntitiesCollectionItem;
begin
l_EntitiesCollectionItem := CheckEntityForControl(anEntity);
if (l_EntitiesCollectionItem <> nil) then
l_EntitiesCollectionItem.ContextMenuWeight := aWeight;
end;
procedure TvcmBaseEntitiesCollection.ContextMenuWeight(const anEntity : TvcmString;
const anOperation : TvcmString;
aWeight : Integer;
aNoPrefix : Boolean = False);
var
l_EntitiesCollectionItem: TvcmBaseEntitiesCollectionItem;
l_OperationsCollectionItem: TvcmBaseOperationsCollectionItem;
begin
l_EntitiesCollectionItem := CheckEntityForControl(anEntity);
if (l_EntitiesCollectionItem <> nil) then
begin
l_OperationsCollectionItem := GetOperationByName(anEntity, anOperation, aNoPrefix);
if (l_OperationsCollectionItem <> nil) then
l_OperationsCollectionItem.ContextMenuWeight := aWeight;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.