text stringlengths 14 6.51M |
|---|
// dws2HelperFunc
{: Helper functions for creating class, properties and
method symbols in DelphiWebScriptII.<p>
<b>History : </b><font size=-1><ul>
<li>27/04/2004 - SG - Creation
</ul></font>
}
unit dws2HelperFunc;
interface
uses
Classes, SysUtils, dws2Symbols, dws2CompStrings;
procedure AddForwardDeclaration(ClassName: String; SymbolTable : TSymbolTable);
function AddClassSymbol(SymbolTable : TSymbolTable; Name, Ancestor : String) : TSymbol;
procedure AddPropertyToClass(Name, DataType, ReadAccess,
WriteAccess, IndexDataType: String; IsDefault : Boolean;
ClassSym: TClassSymbol; Table: TSymbolTable);
procedure ValidateExternalObject(ExtObject : TObject; ObjClass : TClass);
implementation
// AddForwardDeclaration
//
procedure AddForwardDeclaration(ClassName: String; SymbolTable : TSymbolTable);
var
Sym : TSymbol;
begin
Sym:=SymbolTable.FindSymbol(ClassName);
if Assigned(Sym) then exit;
Sym:=TClassSymbol.Create(ClassName);
TClassSymbol(Sym).IsForward:=True;
SymbolTable.AddSymbol(Sym);
end;
// AddClassSymbol
//
function AddClassSymbol(SymbolTable : TSymbolTable; Name, Ancestor : String) : TSymbol;
var
ancestorSym : TClassSymbol;
begin
Result := SymbolTable.FindSymbol(Name);
try
if Assigned(Result) then begin
if Result is TClassSymbol then begin
if not (TClassSymbol(Result).IsForward) then begin
exit;
end;
end else begin
Result:=nil;
exit;
end;
end;
try
if not Assigned(Result) then
Result := TClassSymbol.Create(Name);
ancestorSym := TClassSymbol(SymbolTable.FindSymbol(Ancestor));
if ancestorSym = nil then
raise Exception.CreateFmt(UNT_SuperClassUnknwon, [Ancestor]);
TClassSymbol(Result).InheritFrom(ancestorSym);
except
if not TClassSymbol(Result).IsForward then
FreeAndNil(Result);
raise;
end;
if TClassSymbol(Result).IsForward then
TClassSymbol(Result).IsForward:=False
else
SymbolTable.AddSymbol(Result);
finally
if not Assigned(Result) then
raise Exception.CreateFmt('Unable to add %s to the symbol table', [Name]);
end;
end;
// AddPropertyToClass
//
procedure AddPropertyToClass(Name, DataType, ReadAccess,
WriteAccess, IndexDataType: String; IsDefault : Boolean; ClassSym: TClassSymbol;
Table: TSymbolTable);
var
Sym : TSymbol;
ParamSym : TParamSymbol;
PropertySym: TPropertySymbol;
begin
if Assigned(ClassSym.Members.FindLocal(Name)) then exit;
Sym:=Table.FindSymbol(DataType);
PropertySym:=TPropertySymbol.Create(Name, Sym);
if ReadAccess<>'' then
PropertySym.ReadSym:=ClassSym.Members.FindLocal(ReadAccess);
if WriteAccess<>'' then
PropertySym.WriteSym := ClassSym.Members.FindLocal(WriteAccess);
if IndexDataType<>'' then begin
Sym:=Table.FindSymbol(IndexDataType);
ParamSym:=TParamSymbol.Create('Index', Sym);
PropertySym.ArrayIndices.AddSymbol(ParamSym);
end;
ClassSym.AddProperty(PropertySym);
if IsDefault then
ClassSym.DefaultProperty := PropertySym;
end;
// ValidateExternalObject
//
procedure ValidateExternalObject(ExtObject : TObject; ObjClass : TClass);
var
Valid : Boolean;
begin
if Assigned(ExtObject) then
Valid:=(ExtObject is ObjClass)
else
Valid:=False;
if not Valid then
raise Exception.Create('Invalid external object.');
end;
end. |
namespace Events.EventClasses;
interface
type
OnSetNameDelegate = delegate(SimpleClassWithEvents: SimpleClassWithEvents; var aNewName: String);
SimpleClassWithEvents = class
private
fOnSetName : OnSetNameDelegate;
fName : String := 'NoName';
protected
procedure SetName(Value : String);
public
property Name: String read fName write SetName;
event OnSetName: OnSetNameDelegate delegate fOnSetName;
end;
implementation
procedure SimpleClassWithEvents.SetName(Value : string);
begin
if Value = fName then Exit;
if assigned(OnSetName) then
OnSetName(self, var Value); // Triggers the event
fName := Value;
end;
end. |
unit BCEditor.Editor.LeftMargin.LineState;
interface
uses
Classes;
type
TBCEditorLeftMarginLineState = class(TPersistent)
strict private
FEnabled: Boolean;
FOnChange: TNotifyEvent;
FWidth: Integer;
procedure DoChange;
procedure SetEnabled(const Value: Boolean);
procedure SetOnChange(Value: TNotifyEvent);
procedure SetWidth(const Value: Integer);
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property Enabled: Boolean read FEnabled write SetEnabled default True;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Width: Integer read FWidth write SetWidth default 2;
end;
implementation
{ TBCEditorLeftMarginLineState }
constructor TBCEditorLeftMarginLineState.Create;
begin
inherited;
FEnabled := True;
FWidth := 2;
end;
procedure TBCEditorLeftMarginLineState.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorLeftMarginLineState) then
with Source as TBCEditorLeftMarginLineState do
begin
Self.FEnabled := FEnabled;
Self.FWidth := FWidth;
Self.DoChange;
end
else
inherited;
end;
procedure TBCEditorLeftMarginLineState.SetOnChange(Value: TNotifyEvent);
begin
FOnChange := Value;
end;
procedure TBCEditorLeftMarginLineState.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorLeftMarginLineState.SetEnabled(const Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
DoChange
end;
end;
procedure TBCEditorLeftMarginLineState.SetWidth(const Value: Integer);
begin
if FWidth <> Value then
begin
FWidth := Value;
DoChange
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DBActRes;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ImgList, StdActns, ActnList, DBActns;
type
TStandardDatasetActions = class(TDataModule)
ActionList1: TActionList;
ImageList1: TImageList;
DataSetCancel1: TDataSetCancel;
DataSetDelete1: TDataSetDelete;
DataSetEdit1: TDataSetEdit;
DataSetFirst1: TDataSetFirst;
DataSetInsert1: TDataSetInsert;
DataSetLast1: TDataSetLast;
DataSetNext1: TDataSetNext;
DataSetPost1: TDataSetPost;
DataSetPrior1: TDataSetPrior;
DataSetRefresh1: TDataSetRefresh;
private
{ Private declarations }
public
{ Public declarations }
end;
var
StandardDatasetActions: TStandardDatasetActions;
implementation
{$IFDEF MSWINDOWS}
{$R *.dfm}
{$ENDIF}
end.
|
PROGRAM Fibo;
(* Print a table of Fibonacci numbers using (slow) recursive definition
P.D. Terry, Rhodes University, 2016 *)
FUNCTION Fib (m : LONGINT) : LONGINT;
(* Compute m-th term in Fibonacci series 0,1,1,2 ... *)
BEGIN
IF m = 0 THEN Fib := 0
ELSE IF m = 1 THEN Fib := 1
ELSE Fib := Fib(m-1) + Fib(m-2);
END;
VAR
i, limit : LONGINT;
BEGIN
Write('Supply upper limit ');
Read(limit);
i := 0;
WHILE (i < limit) DO BEGIN
WriteLn(i:5 , Fib(i) : 15);
i := i + 1;
END
END.
|
program GameMain;
uses SwinGame, sgTypes, Sysutils;
type
Track = record
trackID: Integer;
trackTitle: String;
trackLocation: String;
end;
TrackArray = array [0..14] of Track;
Album = record
albumID: Integer;
albumTitle: String;
artistName: String;
artwork: String;
numberOfTracks: Integer;
albumTracks: TrackArray;
end;
AlbumArray = array [0..3] of Album;
var
numberOfAlbums : Integer = 0;
allAlbumsArray : AlbumArray;
buttonStopX, buttonPlayX, buttonForwardX, buttonDimension, artworkDimX, artworkDimY : Single;
artwork1X, artwork1Y : Single;
artwork2X, artwork2Y : Single;
artwork3X, artwork3Y : Single;
artwork4X, artwork4Y : Single;
widthArea, heightArea: Single;
buttonControlY : Single;
titleClickOrder: Integer;
playlistAlbum: Album;
// Set Stop Button position
procedure SetPosition();
begin
buttonStopX:= 398;
buttonControlY:= 480;
buttonPlayX := buttonStopX + 100;
buttonForwardX := buttonStopX + 200;
buttonDimension := 64;
artworkDimX := 250;
artworkDimY := 200;
artwork1X := 20;
artwork1Y := 20;
artwork2X := 290;
artwork2Y := 20;
artwork3X := 20;
artwork3Y := 240;
artwork4X := 290;
artwork4Y := 240;
end;
// Set area for clickable
procedure SetArea(xPos, yPos, widthDim, heightDim: Single);
begin
widthArea := xPos + widthDim;
heightArea := yPos + heightDim;
end;
// Readl lines by lines from file
procedure ReadLinesFromFile(myFileName: String);
var i: Integer = 0;
j: Integer = 0;
myFile: TextFile;
begin
AssignFile(myFile, myFileName);
{$I-} //disable i/o error checking
Reset(myFile);
{$I+} //enable i/o error checking again
if (IOResult <> 0) then
begin
WriteLn('File ',myFileName,' is not found...');
end else
begin
ReadLn(myFile, numberOfAlbums);
repeat // Repeating reading albums
allAlbumsArray[i].albumID := i + 1;
ReadLn(myFile, allAlbumsArray[i].albumTitle);
ReadLn(myFile, allAlbumsArray[i].artistName);
ReadLn(myFile, allAlbumsArray[i].artwork);
ReadLn(myFile, allAlbumsArray[i].numberOfTracks);
repeat // Repeating reading tracks name and tracks locations
allAlbumsArray[i].albumTracks[j].trackID := allAlbumsArray[i].albumID * 100 + j;
ReadLn(myFile, allAlbumsArray[i].albumTracks[j].trackTitle);
ReadLn(myFile, allAlbumsArray[i].albumTracks[j].trackLocation);
LoadMusic(allAlbumsArray[i].albumTracks[j].trackLocation);
WriteLn('Track title: ', allAlbumsArray[i].albumTracks[j].trackTitle);
WriteLn('Track ID: ', allAlbumsArray[i].albumTracks[j].trackID);
j := j + 1;
until j = allAlbumsArray[i].numberOfTracks;
j := 0;
i := i + 1;
until i = numberOfAlbums;
Close(myFile);
end;
end;
// ButtonClicked will get mouse position and return true if mouse clicked inside button's area
function ButtonClicked(buttonName:String): Boolean;
var
buttonX: Single = -10;
buttonY: Single = -10;
mousePositionX, mousePositionY: Single;
begin
mousePositionX := MouseX();
mousePositionY := MouseY();
case buttonName of
'stop' :
begin
buttonX := buttonStopX;
buttonY := buttonControlY;
SetArea(buttonX, buttonY, buttonDimension, buttonDimension);
end;
'play' :
begin
buttonX := buttonPlayX;
buttonY := buttonControlY;
SetArea(buttonX, buttonY, buttonDimension, buttonDimension);
end;
'forward' :
begin
buttonX := buttonForwardX;
buttonY := buttonControlY;
SetArea(buttonX, buttonY, buttonDimension, buttonDimension);
end;
'artwork1' :
begin
buttonX := artwork1X;
buttonY := artwork1Y;
SetArea(buttonX, buttonY, artworkDimX, artworkDimY);
end;
'artwork2' :
begin
buttonX := artwork2X;
buttonY := artwork2Y;
SetArea(buttonX, buttonY, artworkDimX, artworkDimY);
end;
'artwork3' :
begin
buttonX := artwork3X;
buttonY := artwork3Y;
SetArea(buttonX, buttonY, artworkDimX, artworkDimY);
end;
'artwork4' :
begin
buttonX := artwork4X;
buttonY := artwork4Y;
SetArea(buttonX, buttonY, artworkDimX, artworkDimY);
end;
else buttonX := -10;
end;
result := false;
if MouseClicked(LeftButton) then
begin
if (mousePositionX >= buttonX) and (mousePositionX <= widthArea) then
begin
if (mousePositionY >= buttonY) and (mousePositionY <= heightArea) then
begin
result := true;
end;
end;
end;
widthArea := 0;
heightArea := 0;
end;
// Click Track Title --> Click to trackTitle then return trackID
function trackTitleClicked(playingAlbumInput: Album; titlePosition: String): Integer;
var
mousePositionX, mousePositionY: Single;
widthAreaTest, heightAreaTest: Single;
buttonX, buttonY: Single;
i: Integer;
begin
case titlePosition of
'Album':
begin
buttonX := 580;
end;
'Playlist':
begin
buttonX := 820;
end;
end;
buttonY := 38;
widthAreaTest := buttonX + 130;
mousePositionX := MouseX();
mousePositionY := MouseY();
result := -1;
for i:= 0 to (playingAlbumInput.numberOfTracks - 1) do
begin
heightAreaTest := buttonY + 14;
if MouseClicked(LeftButton) then
begin
if (mousePositionX >= buttonX) and (mousePositionX <= widthAreaTest) then
begin
if (mousePositionY >= buttonY) and (mousePositionY <= heightAreaTest) then
begin
result := playingAlbumInput.albumTracks[i].trackID;
end;
buttonY := buttonY + 28;
end;
end;
end;
heightAreaTest := buttonY + 14;
end;
// Check if trackId exist in playlistAlbum.albumTracks
function TrackOrderInPlaylist(trackIdInput: Integer): Integer;
var i: Integer;
begin
result := -1;
if (playlistAlbum.numberOfTracks >= 0) and (playlistAlbum.numberOfTracks <= 15) then
begin
for i := 0 to (playlistAlbum.numberOfTracks - 1) do
begin
if (trackIdInput = playlistAlbum.albumTracks[i].trackId) then
result := i;
end;
end;
end;
// Click Add arrow --> return trackID
function AddToPlaylist(playingAlbumInput: Album): Integer;
var
mousePositionX, mousePositionY: Single;
widthAreaTest, heightAreaTest: Single;
buttonX, buttonY: Single;
i: Integer;
begin
buttonX := 780;
buttonY := 38;
widthAreaTest := buttonX + 20;
mousePositionX := MouseX();
mousePositionY := MouseY();
result := -1;
if (playlistAlbum.numberOfTracks < 15) then
begin
for i:= 0 to (playingAlbumInput.numberOfTracks - 1) do
begin
heightAreaTest := buttonY + 14;
if MouseClicked(LeftButton) then
begin
if (mousePositionX >= buttonX) and (mousePositionX <= widthAreaTest) then
begin
if (mousePositionY >= buttonY) and (mousePositionY <= heightAreaTest) then
begin
result := playingAlbumInput.albumTracks[i].trackID;
end;
buttonY := buttonY + 28;
end;
end;
end;
end;
heightAreaTest := buttonY + 14;
end;
// Click remove --> Click to remove then return trackID to be removed
function RemoveFromPlaylist(): Integer;
var
mousePositionX, mousePositionY: Single;
widthAreaTest, heightAreaTest: Single;
buttonX, buttonY: Single;
i: Integer;
begin
buttonX := 1000;
buttonY := 42;
widthAreaTest := buttonX + 10;
mousePositionX := MouseX();
mousePositionY := MouseY();
result := -1;
for i:= 0 to (playlistAlbum.numberOfTracks - 1) do
begin
heightAreaTest := buttonY + 10;
if MouseClicked(LeftButton) then
begin
if (mousePositionX >= buttonX) and (mousePositionX <= widthAreaTest) then
begin
if (mousePositionY >= buttonY) and (mousePositionY <= heightAreaTest) then
begin
result := playlistAlbum.albumTracks[i].trackID;
end;
buttonY := buttonY + 28;
end;
end;
end;
heightAreaTest := buttonY + 10;
end;
// Find Album by trackID
function GetAlbumByTrackId(trackIdInput: Integer): Album;
var i,j: Integer;
countSearch: Integer = 0;
albumReturn: Album;
begin
for i:=0 to High(allAlbumsArray) do
begin
for j:=0 to allAlbumsArray[i].numberOfTracks do
begin
if allAlbumsArray[i].albumTracks[j].trackID = trackIdInput then
begin
albumReturn := allAlbumsArray[i];
countSearch := countSearch + 1;
end
end;
end;
if countSearch = 0 then
begin
albumReturn.albumID:= -1;
WriteLn('Sorry not found');
end;
result:= albumReturn;
end;
// Find track by trackID
function GetTrackById(trackIdInput: Integer): Track;
var i: Integer;
countSearch: Integer = 0;
trackReturn: Track;
albumHelper: Album;
begin
albumHelper := GetAlbumByTrackId(trackIdInput);
for i:=0 to albumHelper.numberOfTracks do
begin
if albumHelper.albumTracks[i].trackID = trackIdInput then
begin
trackReturn := albumHelper.albumTracks[i];
countSearch := countSearch + 1;
end
end;
if countSearch = 0 then
begin
trackReturn.trackID:= -1;
WriteLn('Sorry no track found');
end;
result:= trackReturn;
end;
// Playing Music by trackID
procedure PlayMusicByTrackID(trackIdInput: Integer);
begin
PlayMusic(GetTrackById(trackIdInput).trackLocation);
end;
// Draw Playing text
procedure DrawPlayingText(text: String);
var stringDisplay: String;
begin
if MusicPlaying() then
begin
stringDisplay := 'Now playing ' + text;
DrawText(stringDisplay, ColorBlack, 'montserrat.ttf', 14, 425, 555);
end else
begin
stringDisplay := 'Please choose music to play';
DrawText(stringDisplay, ColorBlack, 'montserrat.ttf', 14, 425, 555);
end;
end;
// Draw Album name
procedure DrawalbumTitle(text: String);
begin
DrawText(text, ColorBlack, 'montserrat.ttf', 20, 580, 5);
DrawText('Playlist', ColorBlack, 'montserrat.ttf', 20, 820, 5);
end;
// Draw Tracks title
procedure DrawtrackTitle(playingAlbumInput: Album; trackPlayingIDInput: Integer);
var
i: Integer;
space: Integer = 28;
begin
for i:=0 to (playingAlbumInput.numberOfTracks - 1) do
begin
DrawText(playingAlbumInput.albumTracks[i].trackTitle, ColorBlack, 'montserrat.ttf', 14, 580, (10 + space));
DrawText('->', ColorBlack, 'montserrat.ttf', 14, 780, (10 + space));
space := space + 28;
end;
space := 28;
end;
// Draw Playlist title
procedure DrawPlaylistTitle();
var
i: Integer;
space: Integer = 28;
begin
for i:=0 to (playlistAlbum.numberOfTracks - 1) do
begin
DrawText(playlistAlbum.albumTracks[i].trackTitle, ColorBlack, 'montserrat.ttf', 14, 820, (10 + space));
LoadBitmapNamed('remove' ,'remove.png' );
DrawBitmap( 'remove', 1000, (14 + space) );
space := space + 28;
end;
space := 28;
end;
// Draw screen
procedure DrawScreen();
begin
SetPosition();
// Draw button
LoadBitmapNamed('stop' ,'stop.png' );
DrawBitmap( 'stop', buttonStopX, buttonControlY );
LoadBitmapNamed('play' ,'play.png' );
DrawBitmap( 'play', buttonPlayX, buttonControlY );
LoadBitmapNamed('forward' ,'forward.png' );
DrawBitmap( 'forward', buttonForwardX, buttonControlY );
//Draw artwork
LoadBitmapNamed('album1' ,allAlbumsArray[0].artwork );
DrawBitmap('album1', artwork1X, artwork1Y );
LoadBitmapNamed('album2' ,allAlbumsArray[1].artwork );
DrawBitmap('album2', artwork2X, artwork2Y );
LoadBitmapNamed('album3' ,allAlbumsArray[2].artwork );
DrawBitmap('album3', artwork3X, artwork3Y );
LoadBitmapNamed('album4' ,allAlbumsArray[3].artwork );
DrawBitmap('album4', artwork4X, artwork4Y );
// Draw horizontal line
DrawLine(ColorBlack, 0, 460, 1020, 460);
// Draw first vertical line
DrawLine(ColorBlack, 560, 0, 560, 460);
// Draw second vertical line
DrawLine(ColorBlack, 800, 0, 800, 460);
end;
procedure ResetPlaylistAlbum();
var i: Integer;
begin
playlistAlbum.albumID := 5000;
playlistAlbum.albumTitle := 'Playlist';
playlistAlbum.artistName := 'Customize';
playlistAlbum.artwork := 'customize.png';
playlistAlbum.numberOfTracks := 0;
for i := 0 to 14 do
playlistAlbum.albumTracks[i].trackID := playlistAlbum.albumTracks[i+1].trackID;
playlistAlbum.albumTracks[14].trackID := 0;
end;
procedure DeleteInPlaylistArray(position: Integer);
var
i, max: Integer;
begin
if (playlistAlbum.numberOfTracks = 15) then max := 14 else max := playlistAlbum.numberOfTracks;
for i := position to (max - 1) do
playlistAlbum.albumTracks[i] := playlistAlbum.albumTracks[i+1];
playlistAlbum.albumTracks[14].trackID := 0;
playlistAlbum.numberOfTracks:= playlistAlbum.numberOfTracks - 1;
end;
procedure Main();
var
screenColor: Color;
albumTitleDisplay: String;
trackTitleDisplay: TrackArray;
fileName: String;
trackPlayingID: Integer = 0;
playingText: String;
playingAlbum: Album;
numberOfForward: Integer = 0;
loopInAlbum: Integer = 0;
begin
OpenAudio();
OpenGraphicsWindow('Music Player', 1020, 600);
ReadLinesFromFile('album.dat');
trackPlayingID := allAlbumsArray[0].albumTracks[0].trackID;
albumTitleDisplay := allAlbumsArray[0].albumTitle;
playingText := GetTrackById(trackPlayingID).trackTitle;
playingAlbum := allAlbumsArray[0];
ResetPlaylistAlbum();
repeat
ClearScreen(ColorWhite);
DrawScreen();
ProcessEvents();
//Clicked Control Button
if ButtonClicked('stop') then
begin
WriteLn('Clicked Stop');
StopMusic();
end;
if ButtonClicked('play') then
begin
PlayMusicByTrackID(trackPlayingID);
playingText := GetTrackById(trackPlayingID).trackTitle;
WriteLn('Clicked Play, trackTitle: ', GetTrackById(trackPlayingID).trackTitle);
end;
if ButtonClicked('forward') then
begin
trackPlayingID := trackPlayingID + 1;
if trackPlayingID <= playingAlbum.albumTracks[(playingAlbum.numberOfTracks - 1)].trackID then
begin
PlayMusicByTrackID(trackPlayingID);
playingText := GetTrackById(trackPlayingID).trackTitle;
end else
begin
trackPlayingID := trackPlayingID - 1;
PlayMusicByTrackID(trackPlayingID);
playingText := GetTrackById(trackPlayingID).trackTitle;
end;
WriteLn('Clicked Forward, trackTitle: ', GetTrackById(trackPlayingID).trackTitle);
end;
// Clicked artwork
if ButtonClicked('artwork1') then
begin
WriteLn('Clicked artwork1');
trackPlayingID := allAlbumsArray[0].albumTracks[0].trackID;
albumTitleDisplay := allAlbumsArray[0].albumTitle;
playingAlbum := allAlbumsArray[0];
end;
if ButtonClicked('artwork2') then
begin
WriteLn('Clicked artwork2');
trackPlayingID := allAlbumsArray[1].albumTracks[0].trackID;
albumTitleDisplay := allAlbumsArray[1].albumTitle;
playingAlbum := allAlbumsArray[1];
end;
if ButtonClicked('artwork3') then
begin
WriteLn('Clicked artwork3');
trackPlayingID := allAlbumsArray[2].albumTracks[0].trackID;
albumTitleDisplay := allAlbumsArray[2].albumTitle;
playingAlbum := allAlbumsArray[2];
end;
if ButtonClicked('artwork4') then
begin
WriteLn('Clicked artwork4');
trackPlayingID := allAlbumsArray[3].albumTracks[0].trackID;
albumTitleDisplay := allAlbumsArray[3].albumTitle;
playingAlbum := allAlbumsArray[3];
end;
if trackTitleClicked(playingAlbum, 'Album') > 0 then
begin
trackPlayingID := trackTitleClicked(playingAlbum, 'Album');
PlayMusicByTrackID(trackPlayingID);
playingText := GetTrackById(trackPlayingID).trackTitle;
WriteLn('Clicked on Title, trackTitle: ', GetTrackById(trackPlayingID).trackTitle);
end;
if (AddToPlaylist(playingAlbum) > 0) and (TrackOrderInPlaylist(AddToPlaylist(playingAlbum)) < 0) then
begin
playlistAlbum.albumTracks[playlistAlbum.numberOfTracks] := GetTrackById(AddToPlaylist(playingAlbum));
WriteLn('Clicked on playlist arrow, trackTitle: ', GetTrackById(AddToPlaylist(playingAlbum)).trackTitle);
playlistAlbum.numberOfTracks := playlistAlbum.numberOfTracks + 1;
end;
if (RemoveFromPlaylist() > 0) then
begin
WriteLn('Clicked on remove, with trackID: ', RemoveFromPlaylist());
WriteLn('Track order ', TrackOrderInPlaylist(RemoveFromPlaylist()));
DeleteInPlaylistArray(TrackOrderInPlaylist(RemoveFromPlaylist()));
end;
if trackTitleClicked(playlistAlbum, 'Playlist') > 0 then
begin
loopInAlbum := TrackOrderInPlaylist(trackTitleClicked(playlistAlbum, 'Playlist'));
trackPlayingID := playlistAlbum.albumTracks[loopInAlbum].trackID;
PlayMusicByTrackID(trackPlayingID);
playingText := GetTrackById(trackPlayingID).trackTitle;
WriteLn('Clicked on Playlist Title, trackTitle: ', GetTrackById(trackPlayingID).trackTitle);
WriteLn('loopInAlbum: ', loopInAlbum);
end;
DrawalbumTitle(albumTitleDisplay);
DrawtrackTitle(playingAlbum, trackPlayingID);
DrawPlayingText(playingText);
DrawPlaylistTitle();
RefreshScreen( 60 );
until WindowCloseRequested();
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end.
|
unit Semaphor;
interface
procedure sInit; {$IFNDEF SOLID}export;{$ENDIF}
procedure sDone; {$IFNDEF SOLID}export;{$ENDIF}
procedure sSetSemaphore(Name, Value: String); {$IFNDEF SOLID}export;{$ENDIF}
function sGetSemaphore(Name: String): String; {$IFNDEF SOLID}export;{$ENDIF}
function sGetBoolSemaphore(Name: String): Boolean; {$IFNDEF SOLID}export;{$ENDIF}
function sGetNumSemaphore(Name: String): Longint; {$IFNDEF SOLID}export;{$ENDIF}
function sGetPtrSemaphore(Name: String): Pointer; {$IFNDEF SOLID}export;{$ENDIF}
function sExitNow: Boolean; {$IFNDEF SOLID}export;{$ENDIF}
procedure sSetExitNow; {$IFNDEF SOLID}export;{$ENDIF}
implementation
uses Types, Log, Config, Wizard;
{$I fastuue.inc}
var
Semaphores: PCollection;
ExitNow: Boolean;
DebugSemaphores: Boolean;
type
PSemaphore = ^TSemaphore;
TSemaphore = object(TObject)
Name: PString;
Value: PString;
constructor Init(const AName, AValue: String);
destructor Done; virtual;
end;
constructor TSemaphore.Init;
begin
inherited Init;
Name:=NewStr(AName);
Value:=NewStr(AValue);
end;
destructor TSemaphore.Done;
begin
DisposeStr(Name);
DisposeStr(Value);
inherited Done;
end;
procedure sDebug(S: String);
begin
logWrite('Main', 'sDebug: ' + S);
end;
procedure sInit;
begin
Semaphores:=New(PCollection, Init);
ExitNow:=False;
DebugSemaphores:=cGetBoolParam('Debug.Semaphores');
end;
function SeekSemaphore(var Name: String): PSemaphore;
var
K: Longint;
S: PSemaphore;
begin
for K:=1 to Semaphores^.Count do
begin
S:=Semaphores^.At(K);
if S^.Name^ = Name then
begin
SeekSemaphore:=S;
Exit;
end;
end;
SeekSemaphore:=Nil;
end;
procedure sSetSemaphore(Name, Value: String);
var
S: PSemaphore;
var
K: Longint;
begin
StUpcaseEx(Name);
S:=SeekSemaphore(Name);
if S = Nil then
begin
S:=New(PSemaphore, Init(Name, Value));
Semaphores^.Insert(S);
if DebugSemaphores then
sDebug('Created ''' + Name + ''', value ''' + Value + '''');
end
else
begin
if DebugSemaphores then
sDebug('Changed ''' + Name + ''', value ''' + Value + '''');
DisposeStr(S^.Value);
S^.Value:=NewStr(Value);
end;
end;
function sGetSemaphore(Name: String): String;
var
S: PSemaphore;
begin
if Semaphores = Nil then
begin
sGetSemaphore:='';
Exit;
end;
StUpcaseEx(Name);
S:=SeekSemaphore(Name);
if S = Nil then
begin
sGetSemaphore:='';
if DebugSemaphores then
sDebug('NULL ''' + Name + '''');
end
else
begin
if S^.Value = Nil then
sGetSemaphore:=''
else
sGetSemaphore:=S^.Value^;
if DebugSemaphores then
sDebug('Get ''' + Name + ''', value ''' + GetPString(S^.Value) + '''');
end;
end;
function sGetBoolSemaphore(Name: String): Boolean;
begin
Name:=sGetSemaphore(Name);
TrimEx(Name);
StUpcaseEx(Name);
sGetBoolSemaphore:=(Name[0] <> #0) and (Name[1] in ['1','Y']);
end;
function sGetNumSemaphore(Name: String): Longint;
var
A: Longint;
begin
Name:=sGetSemaphore(Name);
TrimEx(Name);
StUpcaseEx(Name);
Str2Longint(Name, A);
sGetNumSemaphore:=A;
end;
function sGetPtrSemaphore(Name: String): Pointer;
var
P: Pointer;
D: record s, o: word; end absolute P;
begin
Name:=sGetSemaphore(Name);
Str2Word('$'+Copy(Name,1,4), D.S);
Str2Word('$'+Copy(Name,6,4), D.O);
sGetPtrSemaphore:=P;
end;
procedure sDone;
begin
if Semaphores <> nil then
Dispose(Semaphores, Done);
end;
function sExitNow: boolean;
begin
sExitNow:=ExitNow;
end;
procedure sSetExitNow;
begin
if DebugSemaphores then sDebug('ExitNow ON');
ExitNow:=True;
end;
end.
|
unit uFactoryConversao;
interface
uses
uConversao;
type
TTipoConversao = (enInvertido = 0, enMaiusculo = 1, enAlfabetica = 2);
IFactoryConversao = interface
['{9D22BC99-D81A-4D79-960E-278849318302}']
function GetConversao(AnTipo: Integer): IConversao;
end;
TConverteFactory = class(TInterfacedObject, IFactoryConversao)
private
public
function GetConversao(AnTipo: Integer): IConversao;
class function New: IFactoryConversao;
end;
implementation
{ TConverteFactory }
function TConverteFactory.GetConversao(
AnTipo: Integer): IConversao;
begin
case AnTipo of
Ord(enInvertido) : Result := TConverteInvertido.Create;
Ord(enMaiusculo) : Result := TConvertePrimeiraMaiuscula.Create;
Ord(enAlfabetica): Result := TConverteOrdenado.Create
else
Result := Nil;
end;
end;
class function TConverteFactory.New: IFactoryConversao;
begin
Result := TConverteFactory.Create;
end;
end.
|
unit fibAthlInstanceCounter;
interface
uses
Windows,
Messages,
SysUtils,
Classes;
// Graphics,
// Controls,
// Forms,
// Dialogs;
const
CNLEN = 15; // Computer name length
EventSignature = $EAB6F31C;
type
TAthlInstanceEventType =
(
ieGlobalCreated, // Global notiifcation about instance creation
ieGlobalDeleted, // Global notiifcation about instance deletion
ieLocalRequest, // Local request for immeidate update
ieLocalStatus, // "I'm still alive" local notification
ieGlobalRequest, // Global request for immeidate update
ieGlobalStatus // "I'm still alive" global notification
);
TAthlInstanceEvent = record
Signature: DWORD; // $EAB6F31C
Id: DWORD; // Unique (per-process) ID to suppress duplicates
Event: TAthlInstanceEventType; // TYpe of event
Computer: string[CNLEN + 1]; // Name of computer
LocalIndex: Integer; // Used to form slot name
InstanceCount: Integer; // The number of instances on computer
PID: DWORD; // Process ID
end;
PAthlInstanceEvent = ^TAthlInstanceEvent;
TAthlInstanceGlobalInfo = record
Computer: string[CNLEN + 1]; // Name of computer
LocalCount: Integer; // Count of instances on the computer
LastRefresh: TDateTime; // Last time the activity of computer detected
end;
PAthlInstanceGlobalInfo = ^TAthlInstanceGlobalInfo;
TAthlInstanceLocalInfo = record
PID: DWORD; // Process ID
LastRefresh: TDateTime; // Last time the activity of process detected
end;
PAthlInstanceLocalInfo = ^TAthlInstanceLocalInfo;
TAthlInstanceCounterThread = class;
TAthlInstanceCounter = class{(TComponent)}
private
{ Private declarations }
_Active: Boolean;
_UpdateCount: Integer;
_Interval: Integer;
_InstanceName: string;
_OnChange: TNotifyEvent;
procedure RemoveExpiredInfo;
procedure SetInterval(const Value: Integer);
procedure SetInstanceName(const Value: string);
// delete items older then Now-Interval*3
private
_ReceivedEvents: TStringList;
_ThreadLocalInfo: TThreadList;
_ThreadGlobalInfo: TThreadList;
_LocalInfo: TList;
_GlobalInfo: TList;
_LockCount: Integer;
procedure Lock;
procedure Unlock;
private
_ThreadStop: THANDLE;
_ThreadStopped: THANDLE;
_Thread: TAthlInstanceCounterThread;
protected
{ Protected declarations }
procedure SetActive(Value: Boolean);
procedure ApplyUpdates;
// procedure Loaded; override;
public
{ Public declarations }
function CountComputers: Integer;
function CountInstances: Integer;
procedure RequestUpdate;
published
{ Published declarations }
constructor Create{(AComponent: TComponent)}; //override;
destructor Destroy; override;
property Active: Boolean read _Active write SetActive;
procedure BeginUpdates;
procedure EndUpdates;
property InstanceName: string read _InstanceName write SetInstanceName;
property Interval: Integer read _Interval write SetInterval default 10000;
property OnChange: TNotifyEvent read _OnChange write _OnChange;
end;
TAthlInstanceCounterThread = class(TThread)
private
_Owner: TAthlInstanceCounter;
_LocalInfo: TList;
_GlobalInfo: TList;
_IntervalTime: TDateTIme;
_LocalIndex: Integer;
_Slot: THANDLE;
_SlotName: string;
_Changed: Boolean;
_LockCount: Integer;
procedure Changed;
procedure Lock;
procedure Unlock;
procedure InitSlot;
procedure DoneSlot;
procedure UpdateSlot;
function GetInstanceEvent(var Event: TAthlInstanceEvent): Boolean;
procedure ProcessInstanceEvent(const Event: TAthlInstanceEvent);
function FindLocal(const Event: TAthlInstanceEvent): PAthlInstanceLocalInfo;
procedure PostLocal(const Event: TAthlInstanceEvent; LocalIndex: Integer);
procedure PostLocalStatus(LocalIndex: Integer);
procedure PostLocalRequest;
function FindGlobal(const Event: TAthlInstanceEvent):
PAthlInstanceGlobalInfo;
procedure PostGlobal(const Event: TAthlInstanceEvent; Computer: string;
LocalIndex: Integer);
procedure PostGlobalStatus(Computer: string; LocalIndex: Integer);
procedure PostGlobalRequest;
procedure InitEvent(var Event: TAthlInstanceEvent);
procedure DoPostEvent(const Event: TAthlInstanceEvent; SlotName: string);
procedure ProcessLocalCreated(const Event: TAthlInstanceEvent);
procedure ProcessLocalDeleted(const Event: TAthlInstanceEvent);
procedure ProcessGlobalCreated(const Event: TAthlInstanceEvent);
procedure ProcessGlobalDeleted(const Event: TAthlInstanceEvent);
procedure ProcessLocalRequest(const Event: TAthlInstanceEvent);
procedure ProcessLocalStatus(const Event: TAthlInstanceEvent);
procedure ProcessGlobalRequest(const Event: TAthlInstanceEvent);
procedure ProcessGlobalStatus(const Event: TAthlInstanceEvent);
protected
procedure Execute; override;
public
constructor Create(Owner: TAthlInstanceCounter);
end;
implementation
var
_LastEventId: Integer;
function LastEventId: Integer;
begin
result := _LastEventId;
INC(_LastEventId);
end;
function ComputerName: string;
var
Buf: array[0..CNLEN] of Char;
BufSize: DWORD;
begin
BufSize := CNLEN + 1;
GetComputerName(Buf, BufSize);
result := Buf;
end;
//------------------------------------------------------------TAthlInstanceCounter
constructor TAthlInstanceCounter.Create{(AComponent: TComponent)};
begin
inherited;
_ReceivedEvents := TStringList.Create;
_ThreadGlobalInfo := TThreadList.Create;
_ThreadLocalInfo := TThreadList.Create;
_Interval := 10000;
_ThreadStop := CreateEvent(nil, True, False, nil);
_ThreadStopped := CreateEvent(nil, True, False, nil);
end;
destructor TAthlInstanceCounter.Destroy;
begin
_UpdateCount := 0;
Active := False;
RemoveExpiredInfo;
_LocalInfo.Free;
_GlobalInfo.Free;
_ReceivedEvents.Free;
CloseHandle(_ThreadStop);
CloseHandle(_ThreadStopped);
inherited;
end;
{procedure TAthlInstanceCounter.Loaded;
begin
inherited;
ApplyUpdates;
end;
}
procedure TAthlInstanceCounter.Lock;
begin
_GlobalInfo := _ThreadGlobalInfo.LockList;
_LocalInfo := _ThreadLocalInfo.LockList;
INC(_LockCount);
end;
procedure TAthlInstanceCounter.Unlock;
begin
DEC(_LockCount);
if _LockCount = 0 then
begin
_LocalInfo := nil;
_GlobalInfo := nil;
end;
_ThreadLocalInfo.UnLockList;
_ThreadGlobalInfo.UnLockList;
end;
procedure TAthlInstanceCounter.RemoveExpiredInfo;
var
i: Integer;
Expiration: TDateTime;
PLI: PAthlInstanceLocalInfo;
PGI: PAthlInstanceGlobalInfo;
begin
Lock;
try
Expiration := Now - 3 * Interval / 24 / 3600 / 1000;
for i := _LocalInfo.Count - 1 downto 0 do
begin
PLI := _LocalInfo[i];
if Active and (PLI.LastRefresh > Expiration) then
continue;
FreeMem(PLI);
_LocalInfo.Remove(PLI);
end;
for i := _GlobalInfo.Count - 1 downto 0 do
begin
PGI := _GlobalInfo[i];
if Active and (PGI.LastRefresh > Expiration) then
continue;
FreeMem(PGI);
_GlobalInfo.Remove(PGI);
end;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounter.SetActive(Value: Boolean);
begin
_Active := Value;
{ if csLoading in ComponentState then
exit;
if csDesigning in ComponentState then exit;
} if _UpdateCount > 0 then
exit;
if not Active then
begin
if _Thread = nil then
exit;
_Thread.Terminate;
SetEvent(_ThreadStop);
WaitForSingleObject(_ThreadStopped, INFINITE);
_Thread := nil;
end
else
begin
if _Thread <> nil then
exit;
ResetEvent(_ThreadStop);
ResetEvent(_ThreadStopped);
_Thread := TAthlInstanceCounterThread.Create(Self);
end;
end;
procedure TAthlInstanceCounter.SetInterval(const Value: Integer);
begin
if Value < 1000 then
raise Exception.Create('Interval can''t be smaller then 1000');
_Interval := Value;
end;
function TAthlInstanceCounter.CountComputers: Integer;
begin
Lock;
try
RemoveExpiredInfo;
result := _GlobalInfo.Count;
finally
Unlock;
end;
end;
function TAthlInstanceCounter.CountInstances: Integer;
var
i: Integer;
begin
result := 0;
Lock;
try
RemoveExpiredInfo;
for i := _GlobalInfo.Count - 1 downto 0 do
result := result + PAthlInstanceGlobalInfo(_GlobalInfo[i]).LocalCount;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounter.SetInstanceName(const Value: string);
var
i: Integer;
begin
if Length(Value) > 8 then
raise
Exception.Create('Instance name is too long (max length is 8 symbols)');
for i := 1 to Length(Value) do
if not (Value[i] in ['a'..'z', 'A'..'Z', '0'..'9', '-', '_']) then
raise Exception.Create('Invalid symbol in InstanceName');
_InstanceName := Value;
{ if csLoading in ComponentState then
exit;
if csDesigning in ComponentState then
exit;
} ApplyUpdates;
end;
procedure TAthlInstanceCounter.ApplyUpdates;
begin
{ if csLoading in ComponentState then
exit;
if csDesigning in ComponentState then
exit;
} if _UpdateCount > 0 then
exit;
if not Active then
exit;
Active := False;
Active := True;
end;
procedure TAthlInstanceCounter.BeginUpdates;
begin
INC(_UpdateCount);
end;
procedure TAthlInstanceCounter.EndUpdates;
begin
DEC(_UpdateCount);
if _UpdateCount = 0 then
ApplyUpdates;
end;
procedure TAthlInstanceCounter.RequestUpdate;
begin
if not Active then
exit;
if _UpdateCount > 0 then
exit;
if _Thread = nil then
exit;
_Thread.PostGlobalRequest;
end;
//------------------------------------------------------TAthlInstanceCounterThread
constructor TAthlInstanceCounterThread.Create(Owner: TAthlInstanceCounter);
begin
inherited Create(True);
_Owner := Owner;
_IntervalTime := _Owner._Interval / 1000 / 3600 / 24;
FreeOnTerminate := True;
Resume;
end;
procedure TAthlInstanceCounterThread.Execute;
var
Event: TAthlInstanceEvent;
NextBroadcast: TDateTime;
NextSlotUpdate: TDateTime;
begin
InitSlot;
NextBroadcast := Now + _IntervalTime;
NextSlotUpdate := Now + 0.5 / 3600 / 24;
while not Terminated do
begin
if Now > NextBroadcast then
begin
PostLocalStatus(-1);
if _LocalIndex < 2 then
PostGlobalStatus('', -1);
NextBroadcast := Now + _IntervalTime;
_Owner.RemoveExpiredInfo;
end;
if GetInstanceEvent(Event) then
ProcessInstanceEvent(Event)
else
WaitForSingleObject(_Owner._ThreadStop, 100);
if Now > NextSlotUpdate then // Attemp to decrease LocalIndex
begin
UpdateSlot;
NextSlotUpdate := Now + 0.5 / 3600 / 24;
end;
end;
DoneSlot;
SetEvent(_Owner._ThreadStopped);
end;
function TAthlInstanceCounterThread.GetInstanceEvent(var Event:
TAthlInstanceEvent): Boolean;
var
Size: DWORD;
Buf: PAthlInstanceEvent;
Count: DWORD;
S: string;
begin
result := False;
Lock;
try
// Slot is not active
if _Slot = INVALID_HANDLE_VALUE then
exit;
while True do
begin
// Check for new messages
if not GetMailslotInfo(_Slot, nil, Size, nil, nil) then
exit;
if Size = MAILSLOT_NO_MESSAGE then
exit;
GetMem(Buf, Size);
try
if not ReadFile(_Slot, Buf^, Size, Count, nil) then
exit;
if Buf.Signature <> EventSignature then
continue;
if Count < SizeOf(Event) then
continue;
Event := Buf^;
S := Event.Computer + IntToHex(Event.PID, 8) + IntToHex(Event.Id, 8);
// Mailslot can get duplicated messages
// Do not process duplicates twice
with _Owner._ReceivedEvents do
begin
if IndexOf(S) >= 0 then
continue;
Add(S);
while Count > 100 do
Delete(0);
end;
Event := Buf^;
result := True;
exit;
finally
FreeMem(Buf);
end;
end;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessInstanceEvent(const Event:
TAthlInstanceEvent);
begin
case Event.Event of
ieGlobalCreated: ProcessGlobalCreated(Event);
ieGlobalDeleted: ProcessGlobalDeleted(Event);
ieLocalRequest: ProcessLocalRequest(Event);
ieLocalStatus: ProcessLocalStatus(Event);
ieGlobalRequest: ProcessGlobalRequest(Event);
ieGlobalStatus: ProcessGlobalStatus(Event);
end;
end;
procedure TAthlInstanceCounterThread.Lock;
begin
_Owner.Lock;
INC(_LockCount);
_LocalInfo := _Owner._LocalInfo;
_GlobalInfo := _Owner._GlobalInfo;
end;
procedure TAthlInstanceCounterThread.Unlock;
begin
DEC(_LockCount);
if _LockCount = 0 then
begin
_LocalInfo := nil;
_GlobalInfo := nil;
end;
_Owner.Unlock;
if _Changed and (_LockCount = 0) then
begin
Synchronize(Changed);
_Changed := False;
end;
end;
procedure TAthlInstanceCounterThread.ProcessGlobalCreated(const Event:
TAthlInstanceEvent);
var
PIGI: PAthlInstanceGLobalInfo;
SameComputer: Boolean;
SameProcess: Boolean;
StatusEvent: TAthlInstanceEvent;
i: Integer;
begin
Lock;
try
ProcessLocalCreated(Event);
PIGI := FindGlobal(Event);
if PIGI = nil then
begin
GetMem(PIGI, SizeOF(PIGI^));
PIGI.Computer := Event.Computer;
PIGI.LocalCount := 0;
_GlobalInfo.Add(PIGI);
end;
INC(PIGI.LocalCount);
_Changed := True;
PIGI.LastRefresh := Now;
if _LocalIndex > 1 then
exit;
SameComputer := Event.Computer = ComputerName;
SameProcess := SameComputer and (Event.PID = GetCurrentProcessId);
if SameProcess then
exit;
PostLocal(Event, -1);
if not SameComputer then
begin
PostGlobalStatus(Event.Computer, Event.LocalIndex);
end
else
begin
StatusEvent.Signature := EventSignature;
StatusEvent.Computer := ComputerName;
StatusEvent.Id := LastEventId;
StatusEvent.Event := ieGlobalStatus;
StatusEvent.LocalIndex := Event.LocalIndex;
StatusEvent.PID := Event.PID;
for i := 0 to _GlobalInfo.Count - 1 do
begin
PIGI := _GlobalInfo[i];
StatusEvent.InstanceCount := PIGI.LocalCount;
PostLocal(StatusEvent, Event.LocalIndex);
end;
end;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessGlobalDeleted(const Event:
TAthlInstanceEvent);
var
PIGI: PAthlInstanceGLobalInfo;
begin
Lock;
try
PIGI := FindGlobal(Event);
if PIGI = nil then
exit;
DEC(PIGI.LocalCount);
_Changed := True;
PIGI.LastRefresh := Now;
if PIGI.LocalCount <= 0 then
begin
_GlobalInfo.Remove(PIGI);
FreeMem(PIGI);
end;
if _LocalIndex < 2 then
PostLocal(Event, -1);
ProcessLocalDeleted(Event);
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessGlobalRequest(const Event:
TAthlInstanceEvent);
begin
Lock;
try
if _LocalIndex > 2 then
exit;
PostGlobalStatus(Event.Computer, Event.LocalIndex);
PostLocalRequest;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessGlobalStatus(
const Event: TAthlInstanceEvent);
var
PIGI: PAthlInstanceGlobalInfo;
begin
Lock;
try
PIGI := FindGlobal(Event);
if PIGI <> nil then
begin
PIGI.LastRefresh := Now;
_Changed := _Changed or (PIGI.LocalCount <> Event.InstanceCount);
PIGI.LocalCount := Event.InstanceCount;
end
else
ProcessGlobalCreated(Event);
if _LocalIndex < 2 then
PostLocal(Event, -1);
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessLocalCreated(
const Event: TAthlInstanceEvent);
var
PILI: PAthlInstanceLocalInfo;
begin
if Event.Computer <> ComputerName then
exit;
Lock;
try
PILI := FindLocal(Event);
if PILI <> nil then
exit;
GetMem(PILI, SizeOf(PILI^));
PILI.PID := Event.PID;
PILI.LastRefresh := Now;
_LocalInfo.Add(PILI);
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessLocalDeleted(const Event:
TAthlInstanceEvent);
var
PILI: PAthlInstanceLocalInfo;
begin
if Event.Computer <> ComputerName then
exit;
Lock;
try
PILI := FindLocal(Event);
if PILI <> nil then
begin
_LocalInfo.Remove(PILI);
FreeMem(PILI);
end;
if Event.LocalIndex < _LocalIndex then
UpdateSlot;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessLocalRequest(const Event:
TAthlInstanceEvent);
begin
if Event.PID = GetCurrentProcessId then
exit;
Lock;
try
PostLocalStatus(Event.LocalIndex);
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.ProcessLocalStatus(const Event:
TAthlInstanceEvent);
var
PILI: PAthlInstanceLocalInfo;
begin
Lock;
try
PILI := FindLocal(Event);
if PILI <> nil then
PILI.LastRefresh := Now
else
ProcessLocalCreated(Event);
finally
Unlock;
end;
end;
function TAthlInstanceCounterThread.FindLocal(const Event: TAthlInstanceEvent):
PAthlInstanceLocalInfo;
var
i: Integer;
begin
if _LocalInfo = nil then
raise Exception.Create('Internal error: no lock');
for i := 0 to _LocalInfo.Count - 1 do
begin
result := _LocalInfo[i];
if Event.PID <> Result.PID then
continue;
exit;
end;
result := nil;
end;
function TAthlInstanceCounterThread.FindGlobal(const Event: TAthlInstanceEvent):
PAthlInstanceGlobalInfo;
var
i: Integer;
begin
if _GlobalInfo = nil then
raise Exception.Create('Internal error: no lock');
for i := 0 to _GlobalInfo.Count - 1 do
begin
result := _GlobalInfo[i];
if Event.Computer <> result.Computer then
continue;
exit;
end;
result := nil;
end;
procedure TAthlInstanceCounterThread.DoPostEvent(const Event:
TAthlInstanceEvent; SlotName: string);
var
Slot: THANDLE;
Count: DWORD;
begin
Slot := CreateFile
(
PChar(SlotName),
GENERIC_WRITE,
FILE_SHARE_READ,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0
);
if Slot = INVALID_HANDLE_VALUE then
exit;
WriteFile(Slot, Event, SizeOf(Event), Count, nil);
CloseHandle(Slot);
end;
procedure TAthlInstanceCounterThread.PostGlobalStatus(Computer: string;
LocalIndex: Integer);
var
Event: TAthlInstanceEvent;
begin
InitEvent(Event);
Event.Event := ieGlobalStatus;
PostGlobal(Event, Computer, LocalIndex);
end;
procedure TAthlInstanceCounterThread.PostLocalStatus(LocalIndex: Integer);
var
Event: TAthlInstanceEvent;
begin
InitEvent(Event);
Event.Event := ieLocalStatus;
PostLocal(Event, LocalIndex);
ProcessLocalStatus(Event);
end;
procedure TAthlInstanceCounterThread.PostGlobalRequest;
var
Event: TAthlInstanceEvent;
begin
InitEvent(Event);
Event.Event := ieGlobalRequest;
PostGlobal(Event, '', -1);
end;
procedure TAthlInstanceCounterThread.PostLocalRequest;
var
Event: TAthlInstanceEvent;
begin
InitEvent(Event);
Event.Event := ieLocalRequest;
PostLocal(Event, -1);
ProcessLocalStatus(Event);
end;
procedure TAthlInstanceCounterThread.InitEvent(var Event: TAthlInstanceEvent);
begin
Lock;
try
Event.Signature := EventSignature;
Event.Computer := ComputerName;
Event.Id := LastEventId;
Event.LocalIndex := _LocalIndex;
Event.InstanceCount := _LocalInfo.Count;
Event.PID := GetCurrentProcessId;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.PostLocal(const Event: TAthlInstanceEvent;
LocalIndex: Integer);
var
i: Integer;
SlotName: string;
begin
if LocalIndex >= 0 then
begin
SlotName := '\\' + ComputerName + '\mailslot\' + _Owner.InstanceName + '.';
DoPostEvent(Event, SlotName + IntToHex(LocalIndex, 3));
end
else
begin
SlotName := '\\' + ComputerName + '\mailslot\' + _Owner.InstanceName + '.';
Lock;
try
for i := 0 to _LocalInfo.Count + 4 do
begin
if i <> _LocalIndex then
DoPostEvent(Event, SlotName + IntToHex(i, 3));
end;
finally
Unlock;
end;
end;
end;
procedure TAthlInstanceCounterThread.PostGlobal(const Event: TAthlInstanceEvent;
Computer: string; LocalIndex: Integer);
var
i: Integer;
SlotName: string;
begin
if Computer = '' then // Broadcast
begin
for i := 0 to 1 do
begin
SlotName := '\\*\mailslot\' + _Owner.InstanceName + '.' + IntToHex(i, 3);
DoPostEvent(Event, SlotName);
end;
end
else
begin
SlotName := '\\' + Computer + '\mailslot\' + _Owner.InstanceName + '.' +
IntToHex(LocalIndex, 3);
DoPostEvent(Event, SlotName);
end;
end;
procedure TAthlInstanceCounterThread.InitSlot;
var
i: Integer;
Event: TAthlInstanceEvent;
begin
Lock;
try
_LocalIndex := -1;
for i := 0 to 100 do
// Unlikely that more then 100 instances run on the same computer
begin
_SlotName := '\\.\mailslot\' + _Owner.InstanceName + '.' + IntToHex(i, 3);
_Slot := CreateMailslot(PChar(_SlotName), 400, 0, nil);
if _Slot = INVALID_HANDLE_VALUE then
continue;
// Successful initiation
_LocalIndex := i;
PostLocalRequest;
InitEvent(Event);
Event.Event := ieGlobalCreated;
PostGlobal(Event, '', -1);
break;
end;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.DoneSlot;
var
Event: TAthlInstanceEvent;
begin
Lock;
try
if _Slot = INVALID_HANDLE_VALUE then
exit;
InitEvent(Event);
Event.Event := ieGlobalDeleted;
PostGlobal(Event, '', -1);
CloseHandle(_Slot);
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.UpdateSlot;
var
i: Integer;
Slot: THandle;
S: string;
begin
Lock;
try
for i := 0 to _LocalIndex - 1 do
begin
S := '\\.\mailslot\' + _Owner.InstanceName + '.' + IntToHex(i, 3);
Slot := CreateMailslot(PChar(S), 400, 0, nil);
if Slot = INVALID_HANDLE_VALUE then
continue;
CloseHandle(_Slot);
_SlotName := S;
_Slot := Slot;
_LocalIndex := i;
break;
end;
finally
Unlock;
end;
end;
procedure TAthlInstanceCounterThread.Changed;
begin
if Assigned(_Owner._OnChange) then
_Owner._OnChange(_Owner);
end;
end.
|
{
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.net/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HproseIdHttpClient.pas *
* *
* hprose indy http client unit for delphi. *
* *
* LastModified: Jun 10, 2010 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
}
unit HproseIdHttpClient;
{$I Hprose.inc}
interface
uses Classes, HproseCommon, HproseClient;
type
THproseIdHttpClient = class(THproseClient)
private
FHttpPool: IList;
FHeaders: TStringList;
FProxyHost: string;
FProxyPort: Integer;
FProxyUser: string;
FProxyPass: string;
FUserAgent: string;
FTimeout: Integer;
protected
function GetInvokeContext: TObject; override;
function GetOutputStream(var Context: TObject): TStream; override;
procedure SendData(var Context: TObject); override;
function GetInputStream(var Context: TObject): TStream; override;
procedure EndInvoke(var Context: TObject); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{:Before HTTP operation you may define any non-standard headers for HTTP
request, except of: 'Expect: 100-continue', 'Content-Length', 'Content-Type',
'Connection', 'Authorization', 'Proxy-Authorization' and 'Host' headers.}
property Headers: TStringList read FHeaders;
{:Address of proxy server (IP address or domain name).}
property ProxyHost: string read FProxyHost Write FProxyHost;
{:Port number for proxy connection. Default value is 8080.}
property ProxyPort: Integer read FProxyPort Write FProxyPort;
{:Username for connect to proxy server.}
property ProxyUser: string read FProxyUser Write FProxyUser;
{:Password for connect to proxy server.}
property ProxyPass: string read FProxyPass Write FProxyPass;
{:Here you can specify custom User-Agent indentification. By default is
used: 'Hprose Http Client for Delphi (Indy10)'}
property UserAgent: string read FUserAgent Write FUserAgent;
property Timeout: Integer read FTimeout Write FTimeout;
end;
procedure Register;
implementation
uses IdHttp, IdHeaderList, IdHTTPHeaderInfo, IdGlobalProtocols, IdCookieManager, SysUtils;
type
THproseIdHttpInvokeContext = class
IdHttp: TIdHttp;
OutStream: TStream;
InStream: TStream;
end;
var
CookieManager: TIdCookieManager = nil;
{ THproseIdHttpClient }
constructor THproseIdHttpClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHttpPool := TArrayList.Create(10);
FHeaders := TIdHeaderList.Create(TIdHeaderQuotingType.QuotePlain);
FProxyHost := '';
FProxyPort := 8080;
FProxyUser := '';
FProxyPass := '';
FUserAgent := 'Hprose Http Client for Delphi (Indy10)';
FTimeout := 30000;
end;
destructor THproseIdHttpClient.Destroy;
var
I: Integer;
begin
FHttpPool.Lock;
try
for I := FHttpPool.Count - 1 downto 0 do
TIdHttp(VarToObj(FHttpPool.Delete(I))).Free;
finally
FHttpPool.Unlock;
end;
FreeAndNil(FHeaders);
inherited;
end;
procedure THproseIdHttpClient.EndInvoke(var Context: TObject);
begin
if Context <> nil then
with THproseIdHttpInvokeContext(Context) do begin
IdHttp.Request.Clear;
IdHttp.Request.CustomHeaders.Clear;
IdHttp.Response.Clear;
FHttpPool.Lock;
try
FHttpPool.Add(ObjToVar(IdHttp));
finally
FHttpPool.Unlock;
end;
FreeAndNil(OutStream);
FreeAndNil(InStream);
FreeAndNil(Context);
end;
end;
function THproseIdHttpClient.GetInputStream(var Context: TObject): TStream;
begin
if Context <> nil then
Result := THproseIdHttpInvokeContext(Context).InStream
else
raise EHproseException.Create('Can''t get input stream.');
end;
function THproseIdHttpClient.GetInvokeContext: TObject;
begin
Result := THproseIdHttpInvokeContext.Create;
with THproseIdHttpInvokeContext(Result) do begin
FHttpPool.Lock;
try
if FHttpPool.Count > 0 then
IdHttp := TIdHttp(VarToObj(FHttpPool.Delete(FHttpPool.Count - 1)))
else
IdHttp := TIdHttp.Create(nil);
finally
FHttpPool.Unlock;
end;
OutStream := TMemoryStream.Create;
InStream := TMemoryStream.Create;
end;
end;
function THproseIdHttpClient.GetOutputStream(var Context: TObject): TStream;
begin
if Context <> nil then
Result := THproseIdHttpInvokeContext(Context).OutStream
else
raise EHproseException.Create('Can''t get output stream.');
end;
procedure THproseIdHttpClient.SendData(var Context: TObject);
begin
if Context <> nil then
with THproseIdHttpInvokeContext(Context) do begin
OutStream.Position := 0;
IdHttp.ReadTimeout := FTimeout;
IdHttp.Request.CustomHeaders.Assign(FHeaders);
IdHttp.Request.UserAgent := FUserAgent;
if FProxyHost <> '' then begin
IdHttp.ProxyParams.ProxyServer := FProxyHost;
IdHttp.ProxyParams.ProxyPort := FProxyPort;
IdHttp.ProxyParams.ProxyUsername := FProxyUser;
IdHttp.ProxyParams.ProxyPassword := FProxyPass;
end;
IdHttp.Request.Connection := 'close';
IdHttp.Request.ContentType := 'application/hprose';
IdHttp.AllowCookies := True;
IdHttp.CookieManager := CookieManager;
IdHTTP.HTTPOptions := IdHTTP.HTTPOptions + [hoKeepOrigProtocol];
IdHttp.ProtocolVersion := pv1_1;
IdHttp.Post(FUri, OutStream, InStream);
InStream.Position := 0;
end
else
raise EHproseException.Create('Can''t send data.');
end;
procedure Register;
begin
RegisterComponents('Hprose', [THproseIdHttpClient]);
end;
initialization
CookieManager := TIdCookieManager.Create(nil);
finalization
FreeAndNil(CookieManager);
end.
|
unit u_xpl_triggers;
{$mode objfpc}{$H+}
interface
uses Classes
, SysUtils
, u_xpl_globals
, u_xpl_collection
;
type
{ TxPLtrigger }
TxPLTriggerType = (trgTimers,trgSingle,trgRecurring,trgGlobalChange,trgCondition,trgMessage);
TxPLtrigger = class(TxPLGlobalValue)
private
fTrigType : TxPLTriggerType;
public
published
property TrigType : TxPLTriggerType read fTrigType write fTrigType;
property DisplayName;
property Comment;
end;
{ TxPLtriggers }
TxPLTriggers = specialize TxPLCollection<TxPLtrigger>;
(*
TxPLtriggers = class(TCollection)
private
FOnGlobalChange: TxPLGlobalChangedEvent;
fOwner: TPersistent;
FOntriggerChange: TxPLGlobalChangedEvent;
procedure SetItems(Index: integer; const AValue: TxPLtrigger);
function GetItems(index: integer): TxPLtrigger;
protected
function GetOwner: TPersistent; override;
public
constructor Create(aOwner: TPersistent);
function Add(const aName : string) : TxPLtrigger;
function FindItemName(const aName: string): TxPLtrigger;
function GetItemId(const aName: string): integer;
property Items[Index: integer]: TxPLtrigger Read GetItems Write SetItems; default;
published
property OnGlobalChange : TxPLGlobalChangedEvent read FOnGlobalChange write fOnGlobalChange;
end;*)
implementation
{ TxPLtriggers }
{ TxPLtriggers =============================================================}
{ TxPLtrigger }
end.
|
{
ID: a2peter1
PROG: holstein
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'holstein';
MaxN = 1000;
MaxM = 15;
var
N,M,i,j,k,t,sol : longint;
target,now,tup : array[0..MaxN] of longint;
vit : array[0..MaxM,0..MaxN] of longint;
procedure comb(i,j: longint);
var k : longint;
begin
if j >= sol then exit;
if i > M then
begin
for i := 1 to N do
begin
t := 0;
for k := 1 to j
do inc(t,vit[now[k],i]);
if t < target[i] then exit;
end;{for}
sol := j;
tup := now;
end;{then}
for k := i to M do
begin
now[j + 1] := k;
comb(i + 1,j + 1);
end;{for}
comb(i + 1,j);
end;{comb}
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(N);
for i := 1 to N do read(target[i]);
readln;
readln(M);
for i := 1 to M do
for j := 1 to N do read(vit[i,j]);
sol := M + 2;
comb(1,0);
write(sol);
for i := 1 to sol
do write(' ',tup[i]);
writeln;
close(output);
end.{main}
|
unit NtUtils.WinSafer;
interface
uses
Winapi.WinSafer, NtUtils.Exceptions, NtUtils.Objects;
// Open a Safer level
function SafexOpenLevel(out hLevel: TSaferHandle; ScopeId: TSaferScopeId;
LevelId: TSaferLevelId): TNtxStatus;
// Close a Safer level
procedure SafexCloseLevel(var hLevel: TSaferHandle);
// Query Safer level information
function SafexQueryInformationLevel(hLevel: TSaferHandle;
InfoClass: TSaferObjectInfoClass; out Status: TNtxStatus;
Returned: PCardinal = nil): Pointer;
// Query Safer level name
function SafexQueryNameLevel(hLevel: TSaferHandle; out Name: String)
: TNtxStatus;
// Query Safer level description
function SafexQueryDescriptionLevel(hLevel: TSaferHandle;
out Description: String): TNtxStatus;
// Restrict a token unsing Safer Api. Supports pseudo-handles
function SafexComputeSaferToken(out hxNewToken: IHandle; hExistingToken: THandle;
hLevel: TSaferHandle; MakeSanboxInert: Boolean = False): TNtxStatus;
function SafexComputeSaferTokenById(out hxNewToken: IHandle;
hExistingToken: THandle; ScopeId: TSaferScopeId;
LevelId: TSaferLevelId; MakeSanboxInert: Boolean = False): TNtxStatus;
implementation
uses
Ntapi.ntseapi, NtUtils.Tokens;
function SafexOpenLevel(out hLevel: TSaferHandle; ScopeId: TSaferScopeId;
LevelId: TSaferLevelId): TNtxStatus;
begin
Result.Location := 'SaferCreateLevel';
Result.Win32Result := SaferCreateLevel(ScopeId, LevelId, SAFER_LEVEL_OPEN,
hLevel);
end;
procedure SafexCloseLevel(var hLevel: TSaferHandle);
begin
SaferCloseLevel(hLevel);
hLevel := 0;
end;
function SafexQueryInformationLevel(hLevel: TSaferHandle;
InfoClass: TSaferObjectInfoClass; out Status: TNtxStatus;
Returned: PCardinal): Pointer;
var
BufferSize, Required: Cardinal;
begin
Status.Location := 'SaferGetLevelInformation';
Status.LastCall.CallType := lcQuerySetCall;
Status.LastCall.InfoClass := Cardinal(InfoClass);
Status.LastCall.InfoClassType := TypeInfo(TSaferObjectInfoClass);
BufferSize := 0;
repeat
Result := AllocMem(BufferSize);
Required := 0;
Status.Win32Result := SaferGetLevelInformation(hLevel, InfoClass, Result,
BufferSize, Required);
if not Status.IsSuccess then
begin
FreeMem(Result);
Result := nil;
end;
until not NtxExpandBuffer(Status, BufferSize, Required);
if Status.IsSuccess and Assigned(Returned) then
Returned^ := BufferSize;
end;
function SafexQueryNameLevel(hLevel: TSaferHandle; out Name: String)
: TNtxStatus;
var
Buffer: PWideChar;
Returned: Cardinal;
begin
Buffer := SafexQueryInformationLevel(hLevel, SaferObjectFriendlyName, Result,
@Returned);
if Result.IsSuccess then
begin
// Exclude the ending #0
if Returned > SizeOf(WideChar) then
SetString(Name, Buffer, Returned div SizeOf(WideChar) - 1)
else
Name := '';
FreeMem(Buffer);
end;
end;
function SafexQueryDescriptionLevel(hLevel: TSaferHandle;
out Description: String): TNtxStatus;
var
Buffer: PWideChar;
Returned: Cardinal;
begin
Buffer := SafexQueryInformationLevel(hLevel, SaferObjectDescription, Result,
@Returned);
if Result.IsSuccess then
begin
// Exclude the ending #0
if Returned > SizeOf(WideChar) then
SetString(Description, Buffer, Returned div SizeOf(WideChar) - 1)
else
Description := '';
FreeMem(Buffer);
end;
end;
function SafexComputeSaferToken(out hxNewToken: IHandle; hExistingToken: THandle;
hLevel: TSaferHandle; MakeSanboxInert: Boolean): TNtxStatus;
var
hxExistingToken: IHandle;
hNewToken: THandle;
Flags: Cardinal;
begin
// Manage pseudo-handles for input
Result := NtxExpandPseudoToken(hxExistingToken, hExistingToken,
TOKEN_DUPLICATE or TOKEN_QUERY);
if not Result.IsSuccess then
Exit;
Flags := 0;
if MakeSanboxInert then
Flags := Flags or SAFER_TOKEN_MAKE_INERT;
Result.Location := 'SaferComputeTokenFromLevel';
Result.LastCall.Expects(TOKEN_DUPLICATE or TOKEN_QUERY, @TokenAccessType);
Result.Win32Result := SaferComputeTokenFromLevel(hLevel, hExistingToken,
hNewToken, Flags, nil);
if Result.IsSuccess then
hxNewToken := TAutoHandle.Capture(hNewToken);
SaferCloseLevel(hLevel);
end;
function SafexComputeSaferTokenById(out hxNewToken: IHandle;
hExistingToken: THandle; ScopeId: TSaferScopeId;
LevelId: TSaferLevelId; MakeSanboxInert: Boolean = False): TNtxStatus;
var
hLevel: TSaferHandle;
begin
Result := SafexOpenLevel(hLevel, ScopeId, LevelId);
if Result.IsSuccess then
begin
Result := SafexComputeSaferToken(hxNewToken, hExistingToken, hLevel,
MakeSanboxInert);
SafexCloseLevel(hLevel);
end;
end;
end.
|
unit BI.Tools;
interface
// Divide a TDataItem into 2 parts using different methods.
uses
BI.Arrays, BI.DataItem;
type
{
TDataSplit returns two Indices arrays (A and B) with the row numbers for
both parts of the split
}
TSplitBy=(Percent,Count);
TSplitMode=(Random,Start);
TSplitOptions=record
public
By : TSplitBy;
Count : Integer;
Mode : TSplitMode;
Percent : Single;
procedure Initialize;
end;
// Fills A and B arrays either using random values or sequential
TDataSplit=record
A,
B : TNativeIntArray;
procedure From(const ATotal:TInteger; const AOptions:TSplitOptions);
procedure Random(const CountA, CountB:TInteger);
procedure Sequence(const CountA, CountB:TInteger);
end;
// Converts Data into float values from 0 to 1
TDataNormalize=record
private
class procedure NormalizeInt32(const AData:TDataItem); static;
class procedure NormalizeInt64(const AData:TDataItem); static;
class procedure NormalizeSingle(const AData:TDataItem); static;
class procedure NormalizeDouble(const AData:TDataItem); static;
class procedure NormalizeExtended(const AData:TDataItem); static;
class procedure NormalizeDateTime(const AData:TDataItem); static;
class procedure NormalizeBoolean(const AData:TDataItem); static;
class procedure NormalizeText(const AData:TDataItem); static;
class procedure Recalculate(const AData: TDataItem;
const AKind: TDataKind); static;
public
class procedure Normalize(const AData:TDataItem); overload; static;
class procedure Normalize(const AData:TDataArray); overload; static;
end;
implementation
|
const MAX_IN_BUF = 4096 * 4;
var
total_bytes_read, bytes_read : int64;
input_buffer : array[0..MAX_IN_BUF-1] of char;
idx_input_buffer : longint;
input_stream : TFileStream;
function fast_read_next_char(): Char;
begin
(* Take one char out of the buffer *)
fast_read_next_char := input_buffer[idx_input_buffer];
inc(idx_input_buffer);
if idx_input_buffer = MAX_IN_BUF then (* I'm at the end of the buffer, read another buffer *)
begin
if total_bytes_read <= input_stream.Size then (* We haven't reached EOF *)
begin
bytes_read := input_stream.Read(input_buffer, sizeof(input_buffer));
inc(total_bytes_read, bytes_read);
end;
idx_input_buffer := 0;
end;
end;
(* Returns first non whitespace character *)
function fast_read_char() : char;
var c: Char;
begin
c := fast_read_next_char();
while (ord(c) = $0020) or (ord(c) = $0009) or
(ord(c) = $000a) or (ord(c) = $000b) or
(ord(c) = $000c) or (ord(c) = $000d) do
c := fast_read_next_char();
fast_read_char := c;
end;
function fast_read_int() : longint;
var res : longint;
c : char;
negative : boolean;
begin
res := 0;
negative := False;
repeat
c := fast_read_next_char();
until (c = '-') or (('0' <= c) and (c <= '9'));
if c = '-' then
begin
negative := True;
c := fast_read_next_char();
end;
repeat
res := res * 10 + ord(c) - ord('0');
c := fast_read_next_char();
until not (('0' <= c) and (c <= '9'));
if negative then
fast_read_int := -res
else
fast_read_int := res;
end;
function fast_read_longint() : int64;
var res : int64;
c : char;
negative : boolean;
begin
res := 0;
negative := False;
repeat
c := fast_read_next_char();
until (c = '-') or (('0' <= c) and (c <= '9'));
if c = '-' then
begin
negative := True;
c := fast_read_next_char();
end;
repeat
res := res * 10 + ord(c) - ord('0');
c := fast_read_next_char();
until not (('0' <= c) and (c <= '9'));
if negative then
fast_read_longint := -res
else
fast_read_longint := res;
end;
function fast_read_real() : double;
begin
(* TODO *)
fast_read_real := 42.0;
end;
procedure init_fast_input(file_name : string);
begin
input_stream := TFileStream.Create(file_name, fmOpenRead);
input_stream.Position := 0;
bytes_read := input_stream.Read(input_buffer, sizeof(input_buffer));
inc(total_bytes_read, bytes_read);
idx_input_buffer := 0;
end;
procedure close_fast_input;
begin
input_stream.Free;
end;
|
unit SettingsView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.Samples.Spin, System.Actions, Vcl.ActnList, Settings, Vcl.ComCtrls;
type
ISettingsView = interface
procedure ShowSettings(const Settings: ISettingsReader);
function GetDotMarkerColor: TColor;
function GetDotMarkerStrokeWidth: integer;
function GetDotMarkerStrokeLength: integer;
function GetSavePathMarkers: string;
function GetSavePathMasks: string;
function GetSavePathRelativeTo: integer;
procedure SetOnCloseQueryEvent(Event: TCloseQueryEvent);
function ShowModal: integer;
end;
TFormSettings = class(TForm, ISettingsView)
LabelDotMarkerColor: TLabel;
LabelDotMarkerStrokeWidth: TLabel;
LabelDotMarkerStrokeLength: TLabel;
EditDotMarkerColor: TColorBox;
EditDotMarkerStrokeWidth: TSpinEdit;
EditDotMarkerStrokeLength: TSpinEdit;
PanelDotMarker: TPanel;
ActionList: TActionList;
ActionShowSettings: TAction;
ImageDotMarker: TImage;
ActionDrawDotMarker: TAction;
PageControl: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
LabelMarkers: TLabel;
EditSavePathMasks: TEdit;
Masks: TLabel;
RadioGroupRelativeTo: TRadioGroup;
EditSavePathMarkers: TEdit;
procedure ActionShowSettingsExecute(Sender: TObject);
procedure ActionDrawDotMarkerExecute(Sender: TObject);
procedure EditSavePathMarkersKeyPress(Sender: TObject; var Key: Char);
procedure EditSavePathMasksKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FSavePathsAllowedChar: TArray<char>;
public
{ Public declarations }
procedure ShowSettings(const Settings: ISettingsReader);
function GetDotMarkerColor: TColor;
function GetDotMarkerStrokeWidth: integer;
function GetDotMarkerStrokeLength: integer;
procedure SetOnCloseQueryEvent(Event: TCloseQueryEvent);
function GetSavePathMarkers: string;
function GetSavePathMasks: string;
function GetSavePathRelativeTo: integer;
end;
var
FormSettings: TFormSettings;
implementation
{$R *.dfm}
{ TFormSettings }
procedure TFormSettings.ActionDrawDotMarkerExecute(Sender: TObject);
var
X, Y: integer;
StrokeLength: integer;
begin
ImageDotMarker.Canvas.Pen.Color:= clWhite;
ImageDotMarker.Canvas.Rectangle(0, 0, ImageDotMarker.Picture.Bitmap.Width, ImageDotMarker.Picture.Bitmap.Height);
ImageDotMarker.Canvas.Pen.Color:= EditDotMarkerColor.Selected;
ImageDotMarker.Canvas.Pen.Width:= EditDotMarkerStrokeWidth.Value;
X:= Trunc(ImageDotMarker.Picture.Bitmap.Width / 2);
Y:= Trunc(ImageDotMarker.Picture.Bitmap.Height / 2);
StrokeLength:= EditDotMarkerStrokeLength.Value;
ImageDotMarker.Canvas.MoveTo(X, Y - StrokeLength);
ImageDotMarker.Canvas.LineTo(X, Y + StrokeLength);
ImageDotMarker.Canvas.MoveTo(X - StrokeLength, Y);
ImageDotMarker.Canvas.LineTo(X + StrokeLength, Y);
end;
procedure TFormSettings.ActionShowSettingsExecute(Sender: TObject);
begin
//
end;
procedure TFormSettings.EditSavePathMarkersKeyPress(Sender: TObject;
var Key: Char);
begin
if not (Key in [#8, #46, '\', '_', '-', '0'..'9', 'a'..'z', 'A'..'Z']) then
Key := #0;
end;
procedure TFormSettings.EditSavePathMasksKeyPress(Sender: TObject;
var Key: Char);
begin
if not (Key in [#8, #46, '\', '_', '-', '0'..'9', 'a'..'z', 'A'..'Z']) then
Key := #0;
end;
function TFormSettings.GetDotMarkerColor: TColor;
begin
Result:= EditDotMarkerColor.Selected;
end;
function TFormSettings.GetDotMarkerStrokeLength: integer;
begin
Result:= EditDotMarkerStrokeLength.Value;
end;
function TFormSettings.GetDotMarkerStrokeWidth: integer;
begin
Result:= EditDotMarkerStrokeWidth.Value;
end;
function TFormSettings.GetSavePathMarkers: string;
begin
Result:= EditSavePathMarkers.Text;
end;
function TFormSettings.GetSavePathMasks: string;
begin
Result:= EditSavePathMasks.Text;
end;
function TFormSettings.GetSavePathRelativeTo: integer;
begin
Result:= RadioGroupRelativeTo.ItemIndex;
end;
procedure TFormSettings.SetOnCloseQueryEvent(Event: TCloseQueryEvent);
begin
Self.OnCloseQuery:= Event;
end;
procedure TFormSettings.ShowSettings(const Settings: ISettingsReader);
begin
EditDotMarkerColor.Selected:= Settings.GetDotMarkerColor;
EditDotMarkerStrokeWidth.Value:= Settings.GetDotMarkerStrokeWidth;
EditDotMarkerStrokeLength.Value:= Settings.GetDotMarkerStrokeLength;
EditSavePathMarkers.Text:= Settings.GetSavePathForMarkers;
EditSavePathMasks.Text:= Settings.GetSavePathForMasks;
try
RadioGroupRelativeTo.ItemIndex:= integer(Settings.GetSavepathRelativeTo);
except
RadioGroupRelativeTo.ItemIndex:= 0;
end;
end;
end.
|
unit uToHik86;
interface
uses
System.SysUtils, System.Classes, IniFiles, uLogger, SyncObjs, IOUtils,
IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer,
IdHTTPServer, IdContext, Types, uHik86Sender, Generics.Collections, uGlobal,
uTypes;
type
TToHik86 = class
private
IdHTTPServerIn: TIdHTTPServer;
ipList: string;
procedure IdHTTPServerInCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
function CheckIP(ip: string): boolean;
procedure LoadHikKKMY;
procedure LoadIPMap;
public
constructor Create;
destructor Destroy; override;
end;
var
toHik86: TToHik86;
implementation
constructor TToHik86.Create;
var
ini: TIniFile;
port: integer;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
ipList := ini.ReadString('sys', 'ip', '');
Hik86Url := ini.ReadString('sys', 'Hik86Url', '');
port := ini.ReadInteger('sys', 'PORT', 18008);
ini.Free;
LoadHikKKMY;
LoadIPMap;
IdHTTPServerIn := TIdHTTPServer.Create(nil);
IdHTTPServerIn.Bindings.Clear;
IdHTTPServerIn.DefaultPort := port;
IdHTTPServerIn.OnCommandGet := self.IdHTTPServerInCommandGet;
try
IdHTTPServerIn.Active := True;
logger.logging('Hik86 start', 2);
except
on e: Exception do
begin
logger.logging(e.Message, 4);
end;
end;
end;
procedure TToHik86.IdHTTPServerInCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
action, ip, s: string;
b, b1: boolean;
ss: TStringList;
pass: TPass;
arr: TArray<string>;
begin
action := ARequestInfo.Document.Substring(1);
ip := AContext.Connection.Socket.Binding.PeerIP;
logger.logging('[' + ip + ']' + action, 2);
b := CheckIP(ip);
if b then
begin
try
ss := TStringList.Create;
ss.LoadFromStream(ARequestInfo.PostStream);
logger.Info('RecordCount:' + ss.Count.ToString);
for s in ss do
begin
arr := s.Split([#9]);
if Length(arr) > 8 then
begin
pass.kdbh := arr[0];
pass.gcsj := arr[1];
pass.cdbh := arr[2];
pass.HPHM := arr[3];
pass.HPZL := arr[4];
pass.hpys := arr[5];
pass.clsd := arr[6];
pass.FWQDZ := arr[7];
pass.tp1 := arr[8];
if Length(arr) > 9 then
pass.tp2 := arr[9];
if Length(arr) > 10 then
pass.tp3 := arr[10];
if Length(arr) > 11 then
pass.WFXW := arr[11];
b1 := false;
for ip in IpMapDic.Keys do
begin
if pass.FWQDZ.Contains(ip) then
begin
b1 := true;
pass.FWQDZ := pass.FWQDZ.Replace(ip, IpMapDic[ip]);
THik86Sender.SendPass(pass);
if pass.WFXW.Length >= 4 then
THik86Sender.SendAlarmPass(pass);
break;
end;
end;
if not b1 then
logger.Debug('Invalid FWQDZ: ' + pass.FWQDZ);
end;
end;
ss.Free;
logger.Info('Send OK');
AResponseInfo.ContentText := 'OK';
except
on e: Exception do
begin
logger.Error(e.Message);
end;
end;
end
else begin
logger.Warn('Invalid IP Or Action!');
end;
end;
procedure TToHik86.LoadHikKKMY;
var
ss: TStringDynArray;
s, key, value: string;
i: integer;
begin
HikKKMYDic := TDictionary<string, string>.Create;
s := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'KKMY.ini');
if TFile.Exists(s) then
begin
ss := TFile.ReadAllLines(s);
for s in ss do
begin
i := s.IndexOf(#9);
if i>0 then
begin
key := s.Substring(0, i);
value := s.Substring(i + 1, 100);
if not HikKKMYDic.ContainsKey(key) then
HikKKMYDic.Add(key, value);
end;
end;
end;
end;
procedure TToHik86.LoadIPMap;
var
ss: TStringDynArray;
s, key, value: string;
i: integer;
begin
IpMapDic := TDictionary<string, string>.Create;
s := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'IpMap.ini');
if TFile.Exists(s) then
begin
ss := TFile.ReadAllLines(s);
for s in ss do
begin
i := s.IndexOf(#9);
if i>0 then
begin
key := s.Substring(0, i);
value := s.Substring(i + 1, 100);
if not IpMapDic.ContainsKey(key) then
IpMapDic.Add(key, value);
end;
end;
end;
end;
function TToHik86.CheckIP(ip: string): boolean;
begin
result := (ipList = '') or ipList.Contains(ip);
end;
destructor TToHik86.Destroy;
begin
idHttpServerIn.Active := false;
idHttpServerIn.Free;
HikKKMYDic.Free;
logger.Info('Hik86 stoped');
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_NavMeshTesterTool;
interface
uses
Classes, Controls, StdCtrls, ExtCtrls, Unit_FrameTesterTool,
RN_DetourNavMesh, RN_DetourNavMeshHelper, RN_DetourNavMeshQuery, RN_DetourStatus, RN_Sample;
type
TToolMode =
(
TOOLMODE_PATHFIND_FOLLOW,
TOOLMODE_PATHFIND_STRAIGHT,
TOOLMODE_PATHFIND_SLICED,
TOOLMODE_RAYCAST,
TOOLMODE_DISTANCE_TO_WALL,
TOOLMODE_FIND_POLYS_IN_CIRCLE,
TOOLMODE_FIND_POLYS_IN_SHAPE,
TOOLMODE_FIND_LOCAL_NEIGHBOURHOOD
);
const MAX_POLYS = 256;
const MAX_SMOOTH = 2048;
const MAX_RAND_POINTS = 64;
const MAX_STEER_POINTS = 10;
type
TNavMeshTesterTool = class (TSampleTool)
private
fFrame: TFrameTesterTool;
fUpdateUI: Boolean;
m_sample: TSample;
m_navMesh: TdtNavMesh;
m_navQuery: TdtNavMeshQuery;
m_filter: TdtQueryFilter;
m_pathFindStatus: TdtStatus;
m_toolMode: TToolMode;
m_straightPathOptions: TdtStraightPathOptions;
m_startRef: TdtPolyRef;
m_endRef: TdtPolyRef;
m_polys: array [0..MAX_POLYS-1] of TdtPolyRef;
m_parent: array [0..MAX_POLYS-1] of TdtPolyRef;
m_npolys: Integer;
m_straightPath: array [0..MAX_POLYS*3-1] of Single;
m_straightPathFlags: array [0..MAX_POLYS-1] of Byte;
m_straightPathPolys: array [0..MAX_POLYS-1] of TdtPolyRef;
m_nstraightPath: Integer;
m_polyPickExt: array [0..2] of Single;
m_smoothPath: array [0..MAX_SMOOTH*3-1] of Single;
m_nsmoothPath: Integer;
m_queryPoly: array [0..4*3-1] of Single;
m_randPoints: array [0..MAX_RAND_POINTS*3-1] of Single;
m_nrandPoints: Integer;
m_randPointsInCircle: Boolean;
m_spos: array [0..2] of Single;
m_epos: array [0..2] of Single;
m_hitPos: array [0..2] of Single;
m_hitNormal: array [0..2] of Single;
m_hitResult: Boolean;
m_distanceToWall: Single;
m_neighbourhoodRadius: Single;
m_randomRadius: Single;
m_sposSet: Boolean;
m_eposSet: Boolean;
m_pathIterNum: Integer;
m_pathIterPolys: array [0..MAX_POLYS-1] of TdtPolyRef;
m_pathIterPolyCount: Integer;
m_prevIterPos, m_iterPos, m_steerPos, m_targetPos: array [0..2] of Single;
m_steerPoints: array [0..MAX_STEER_POINTS*3] of Single;
m_steerPointCount: Integer;
public
constructor Create(aOwner: TWinControl);
destructor Destroy; override;
procedure init(sample: TSample); override;
procedure reset(); override;
procedure handleMenu(Sender: TObject); override;
procedure handleClick(s,p: PSingle; shift: Boolean); override;
procedure handleToggle(); override;
procedure handleStep(); override;
procedure handleUpdate(dt: Single); override;
procedure handleRender(); override;
procedure handleRenderOverlay(proj, model: PDouble; view: PInteger); override;
procedure recalc();
procedure drawAgent(pos: PSingle; r, h, c: Single; col: Cardinal);
end;
implementation
uses Math,
RN_Recast, RN_RecastHelper, RN_DebugDraw, RN_RecastDebugDraw, RN_SampleInterfaces,
RN_DetourNavMeshBuilder, RN_DetourDebugDraw, RN_DetourCommon;
// Uncomment this to dump all the requests in stdout.
//#define DUMP_REQS
// Returns a random number [0..1)
//static float frand()
{
// return ((float)(rand() & 0xffff)/(float)0xffff);
return (float)rand()/(float)RAND_MAX;
}
function inRange(v1,v2: PSingle; r,h: Single): Boolean;
var dx,dy,dz: Single;
begin
dx := v2[0] - v1[0];
dy := v2[1] - v1[1];
dz := v2[2] - v1[2];
Result := ((dx*dx + dz*dz) < r*r) and (abs(dy) < h);
end;
function fixupCorridor(path: PdtPolyRef; npath, maxPath: Integer; visited: PdtPolyRef; nvisited: Integer): Integer;
var furthestPath, furthestVisited, i, j: Integer; found: Boolean; req, orig, size: Integer;
begin
furthestPath := -1;
furthestVisited := -1;
// Find furthest common polygon.
for i := npath-1 downto 0 do
begin
found := false;
for j := nvisited-1 downto 0 do
begin
if (path[i] = visited[j]) then
begin
furthestPath := i;
furthestVisited := j;
found := true;
end;
end;
if (found) then
break;
end;
// If no intersection found just return current path.
if (furthestPath = -1) or (furthestVisited = -1) then
Exit(npath);
// Concatenate paths.
// Adjust beginning of the buffer to include the visited.
req := nvisited - furthestVisited;
orig := rcMin(furthestPath+1, npath);
size := rcMax(0, npath-orig);
if (req+size > maxPath) then
size := maxPath-req;
if (size <> 0) then
Move((path+orig)^, (path+req)^, size*sizeof(TdtPolyRef));
// Store visited
for i := 0 to req - 1 do
path[i] := visited[(nvisited-1)-i];
Result := req+size;
end;
// This function checks if the path has a small U-turn, that is,
// a polygon further in the path is adjacent to the first polygon
// in the path. If that happens, a shortcut is taken.
// This can happen if the target (T) location is at tile boundary,
// and we're (S) approaching it parallel to the tile edge.
// The choice at the vertex can be arbitrary,
// +---+---+
// |:::|:::|
// +-S-+-T-+
// |:::| | <-- the step can end up in here, resulting U-turn path.
// +---+---+
function fixupShortcuts(path: PdtPolyRef; npath: Integer; navQuery: TdtNavMeshQuery): Integer;
const maxNeis = 16; maxLookAhead = 6;
var neis: array [0..maxNeis-1] of TdtPolyRef; nneis: Integer; tile: PdtMeshTile; poly: PdtPoly; k: Cardinal; link: PdtLink;
cut,i,j,offset: Integer;
begin
if (npath < 3) then
Exit(npath);
// Get connected polygons
nneis := 0;
tile := nil;
poly := nil;
if (dtStatusFailed(navQuery.getAttachedNavMesh.getTileAndPolyByRef(path[0], @tile, @poly))) then
Exit(npath);
k := poly.firstLink;
while (k <> DT_NULL_LINK) do
begin
link := @tile.links[k];
if (link.ref <> 0) then
begin
if (nneis < maxNeis) then
begin
neis[nneis] := link.ref;
Inc(nneis);
end;
end;
k := tile.links[k].next;
end;
// If any of the neighbour polygons is within the next few polygons
// in the path, short cut to that polygon directly.
cut := 0;
i := dtMin(maxLookAhead, npath) - 1;
while (i > 1) and (cut = 0) do
begin
for j := 0 to nneis - 1 do
begin
if (path[i] = neis[j]) then
begin
cut := i;
break;
end;
end;
Dec(i);
end;
if (cut > 1) then
begin
offset := cut-1;
Dec(npath, offset);
for i := 1 to npath - 1 do
path[i] := path[i+offset];
end;
Result := npath;
end;
function getSteerTarget(navQuery: TdtNavMeshQuery; startPos, endPos: PSingle;
minTargetDist: Single;
path: PdtPolyRef; pathSize: Integer;
steerPos: PSingle; steerPosFlag: PByte; steerPosRef: PdtPolyRef;
outPoints: PSingle = nil; outPointCount: PInteger = nil): Boolean;
const MAX_STEER_POINTS = 3;
var steerPath: array [0..MAX_STEER_POINTS*3-1] of Single; steerPathFlags: array [0..MAX_STEER_POINTS-1] of Byte;
steerPathPolys: array [0..MAX_STEER_POINTS-1] of TdtPolyRef; nsteerPath,i,ns: Integer;
begin
// Find steer target.
nsteerPath := 0;
navQuery.findStraightPath(startPos, endPos, path, pathSize,
@steerPath[0], @steerPathFlags[0], @steerPathPolys[0], @nsteerPath, MAX_STEER_POINTS);
if (nsteerPath = 0) then
Exit(false);
if (outPoints <> nil) and (outPointCount <> nil) then
begin
outPointCount^ := nsteerPath;
for i := 0 to nsteerPath - 1 do
dtVcopy(@outPoints[i*3], @steerPath[i*3]);
end;
// Find vertex far enough to steer to.
ns := 0;
while (ns < nsteerPath) do
begin
// Stop at Off-Mesh link or when point is further than slop away.
if ((steerPathFlags[ns] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION) <> 0) or
not inRange(@steerPath[ns*3], startPos, minTargetDist, 1000.0)) then
break;
Inc(ns);
end;
// Failed to find good point to steer to.
if (ns >= nsteerPath) then
Exit(false);
dtVcopy(steerPos, @steerPath[ns*3]);
steerPos[1] := startPos[1];
steerPosFlag^ := steerPathFlags[ns];
steerPosRef^ := steerPathPolys[ns];
Result := true;
end;
constructor TNavMeshTesterTool.Create(aOwner: TWinControl);
begin
inherited Create;
&type := TOOL_NAVMESH_TESTER;
fFrame := TFrameTesterTool.Create(aOwner);
fFrame.Align := alClient;
fFrame.Parent := aOwner;
fFrame.Visible := True;
fFrame.rgToolMode.OnClick := handleMenu;
fFrame.rgVerticesAtCrossings.OnClick := handleMenu;
fFrame.btnSetRandomStart.OnClick := handleMenu;
fFrame.btnSetRandomEnd.OnClick := handleMenu;
fFrame.btnMakeRandomPoints.OnClick := handleMenu;
fFrame.btnMakeRandomPointsAround.OnClick := handleMenu;
fFrame.cbInclWalk.OnClick := handleMenu;
fFrame.cbInclSwim.OnClick := handleMenu;
fFrame.cbInclDoor.OnClick := handleMenu;
fFrame.cbInclJump.OnClick := handleMenu;
fFrame.cbExclWalk.OnClick := handleMenu;
fFrame.cbExclSwim.OnClick := handleMenu;
fFrame.cbExclDoor.OnClick := handleMenu;
fFrame.cbExclJump.OnClick := handleMenu;
// Delphi: Assume C++ invokes constructor
m_filter := TdtQueryFilter.Create;
m_pathFindStatus := DT_FAILURE;
m_toolMode := TOOLMODE_PATHFIND_FOLLOW;
m_filter.setIncludeFlags(SAMPLE_POLYFLAGS_ALL xor SAMPLE_POLYFLAGS_DISABLED);
m_filter.setExcludeFlags(0);
m_polyPickExt[0] := 2;
m_polyPickExt[1] := 4;
m_polyPickExt[2] := 2;
m_neighbourhoodRadius := 2.5;
m_randomRadius := 5.0;
end;
destructor TNavMeshTesterTool.Destroy;
begin
// Delphi: Assume C++ does the same when var goes out of scope
m_filter.Free;
fFrame.Free;
inherited;
end;
procedure TNavMeshTesterTool.init(sample: TSample);
begin
m_sample := sample;
m_navMesh := sample.getNavMesh;
m_navQuery := sample.getNavMeshQuery;
recalc();
if (m_navQuery <> nil) then
begin
// Change costs.
m_filter.setAreaCost(Byte(SAMPLE_POLYAREA_GROUND), 1.0);
m_filter.setAreaCost(Byte(SAMPLE_POLYAREA_WATER), 10.0);
m_filter.setAreaCost(Byte(SAMPLE_POLYAREA_ROAD), 1.0);
m_filter.setAreaCost(Byte(SAMPLE_POLYAREA_DOOR), 1.0);
m_filter.setAreaCost(Byte(SAMPLE_POLYAREA_GRASS), 2.0);
m_filter.setAreaCost(Byte(SAMPLE_POLYAREA_JUMP), 1.5);
end;
m_neighbourhoodRadius := sample.getAgentRadius * 20.0;
m_randomRadius := sample.getAgentRadius * 30.0;
end;
procedure TNavMeshTesterTool.handleMenu(Sender: TObject);
var status: TdtStatus; i: Integer; pt: array[0..2] of Single; ref: TdtPolyRef;
begin
if fUpdateUI then Exit;
// Delphi: When the Sender is NIL, we fill the controls with current state values
if Sender = nil then
begin
fUpdateUI := True;
fFrame.rgToolMode.ItemIndex := Byte(m_toolMode);
fFrame.rgVerticesAtCrossings.Enabled := m_toolMode = TOOLMODE_PATHFIND_STRAIGHT;
fFrame.rgVerticesAtCrossings.ItemIndex := Byte(m_straightPathOptions);
fFrame.btnSetRandomEnd.Enabled := m_sposSet;
fFrame.btnMakeRandomPointsAround.Enabled := m_sposSet;
fFrame.cbInclWalk.Checked := (m_filter.getIncludeFlags() and SAMPLE_POLYFLAGS_WALK) <> 0;
fFrame.cbInclSwim.Checked := (m_filter.getIncludeFlags() and SAMPLE_POLYFLAGS_SWIM) <> 0;
fFrame.cbInclDoor.Checked := (m_filter.getIncludeFlags() and SAMPLE_POLYFLAGS_DOOR) <> 0;
fFrame.cbInclJump.Checked := (m_filter.getIncludeFlags() and SAMPLE_POLYFLAGS_JUMP) <> 0;
fFrame.cbExclWalk.Checked := (m_filter.getExcludeFlags() and SAMPLE_POLYFLAGS_WALK) <> 0;
fFrame.cbExclSwim.Checked := (m_filter.getExcludeFlags() and SAMPLE_POLYFLAGS_SWIM) <> 0;
fFrame.cbExclDoor.Checked := (m_filter.getExcludeFlags() and SAMPLE_POLYFLAGS_DOOR) <> 0;
fFrame.cbExclJump.Checked := (m_filter.getExcludeFlags() and SAMPLE_POLYFLAGS_JUMP) <> 0;
fUpdateUI := False;
end;
if Sender = fFrame.rgToolMode then
begin
m_toolMode := TToolMode(fFrame.rgToolMode.ItemIndex);
recalc();
end;
fFrame.rgVerticesAtCrossings.Visible := (m_toolMode = TOOLMODE_PATHFIND_STRAIGHT);
if (m_toolMode = TOOLMODE_PATHFIND_STRAIGHT) then
begin
m_straightPathOptions := TdtStraightPathOptions(fFrame.rgVerticesAtCrossings.ItemIndex);
recalc();
end;
if Sender = fFrame.btnSetRandomStart then
begin
status := m_navQuery.findRandomPoint(m_filter, {frand,} @m_startRef, @m_spos[0]);
if (dtStatusSucceed(status)) then
begin
m_sposSet := true;
recalc();
end;
end;
if Sender = fFrame.btnSetRandomEnd then
begin
if (m_sposSet) then
begin
status := m_navQuery.findRandomPointAroundCircle(m_startRef, @m_spos[0], m_randomRadius, m_filter, {frand,} @m_endRef, @m_epos[0]);
if (dtStatusSucceed(status)) then
begin
m_eposSet := true;
recalc();
end;
end;
end;
if Sender = fFrame.btnMakeRandomPoints then
begin
m_randPointsInCircle := false;
m_nrandPoints := 0;
for i := 0 to MAX_RAND_POINTS - 1 do
begin
status := m_navQuery.findRandomPoint(m_filter, {frand,} @ref, @pt[0]);
if (dtStatusSucceed(status)) then
begin
dtVcopy(@m_randPoints[m_nrandPoints*3], @pt[0]);
Inc(m_nrandPoints);
end;
end;
end;
if Sender = fFrame.btnMakeRandomPointsAround then
begin
if (m_sposSet) then
begin
m_nrandPoints := 0;
m_randPointsInCircle := true;
for i := 0 to MAX_RAND_POINTS - 1 do
begin
status := m_navQuery.findRandomPointAroundCircle(m_startRef, @m_spos[0], m_randomRadius, m_filter, {frand,} @ref, @pt[0]);
if (dtStatusSucceed(status)) then
begin
dtVcopy(@m_randPoints[m_nrandPoints*3], @pt[0]);
Inc(m_nrandPoints);
end;
end;
end;
end;
m_filter.setIncludeFlags(Byte(fFrame.cbInclWalk.Checked) * SAMPLE_POLYFLAGS_WALK +
Byte(fFrame.cbInclSwim.Checked) * SAMPLE_POLYFLAGS_SWIM +
Byte(fFrame.cbInclDoor.Checked) * SAMPLE_POLYFLAGS_DOOR +
Byte(fFrame.cbInclJump.Checked) * SAMPLE_POLYFLAGS_JUMP);
recalc();
m_filter.setExcludeFlags(Byte(fFrame.cbExclWalk.Checked) * SAMPLE_POLYFLAGS_WALK +
Byte(fFrame.cbExclSwim.Checked) * SAMPLE_POLYFLAGS_SWIM +
Byte(fFrame.cbExclDoor.Checked) * SAMPLE_POLYFLAGS_DOOR +
Byte(fFrame.cbExclJump.Checked) * SAMPLE_POLYFLAGS_JUMP);
recalc();
end;
procedure TNavMeshTesterTool.handleClick(s,p: PSingle; shift: Boolean);
begin
if (shift) then
begin
m_sposSet := true;
dtVcopy(@m_spos[0], p);
end
else
begin
m_eposSet := true;
dtVcopy(@m_epos[0], p);
end;
recalc();
end;
procedure TNavMeshTesterTool.handleStep();
begin
end;
procedure TNavMeshTesterTool.handleToggle();
const STEP_SIZE = 0.5;
const SLOP = 0.01;
var steerPos,delta,moveTgt,reslt,startPos,endPos: array [0..2] of Single; steerPosFlag: Byte; steerPosRef,prevRef,polyRef: TdtPolyRef;
endOfPath, offMeshConnection: Boolean; len: Single; visited: array [0..15] of TdtPolyRef; nvisited,npos,i: Integer; h,eh: Single;
status: TdtStatus;
begin
// TODO: merge separate to a path iterator. Use same code in recalc() too.
if (m_toolMode <> TOOLMODE_PATHFIND_FOLLOW) then
Exit;
if (not m_sposSet or not m_eposSet or (m_startRef = 0) or (m_endRef = 0)) then
Exit;
if (m_pathIterNum = 0) then
begin
m_navQuery.findPath(m_startRef, m_endRef, @m_spos[0], @m_epos[0], m_filter, @m_polys[0], @m_npolys, MAX_POLYS);
m_nsmoothPath := 0;
m_pathIterPolyCount := m_npolys;
if (m_pathIterPolyCount <> 0) then
Move(m_polys[0], m_pathIterPolys[0], sizeof(TdtPolyRef)*m_pathIterPolyCount);
if (m_pathIterPolyCount <> 0) then
begin
// Iterate over the path to find smooth path on the detail mesh surface.
m_navQuery.closestPointOnPoly(m_startRef, @m_spos[0], @m_iterPos[0], nil);
m_navQuery.closestPointOnPoly(m_pathIterPolys[m_pathIterPolyCount-1], @m_epos[0], @m_targetPos[0], nil);
m_nsmoothPath := 0;
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @m_iterPos[0]);
Inc(m_nsmoothPath);
end;
end;
dtVcopy(@m_prevIterPos[0], @m_iterPos[0]);
Inc(m_pathIterNum);
if (m_pathIterPolyCount = 0) then
Exit;
if (m_nsmoothPath >= MAX_SMOOTH) then
Exit;
// Move towards target a small advancement at a time until target reached or
// when ran out of memory to store the path.
// Find location to steer towards.
if (not getSteerTarget(m_navQuery, @m_iterPos[0], @m_targetPos[0], SLOP,
@m_pathIterPolys[0], m_pathIterPolyCount, @steerPos[0], @steerPosFlag, @steerPosRef,
@m_steerPoints[0], @m_steerPointCount)) then
Exit;
dtVcopy(@m_steerPos[0], @steerPos[0]);
endOfPath := (steerPosFlag and Byte(DT_STRAIGHTPATH_END)) <> 0;
offMeshConnection := (steerPosFlag and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0;
// Find movement delta.
dtVsub(@delta[0], @steerPos[0], @m_iterPos[0]);
len := sqrt(dtVdot(@delta[0],@delta[0]));
// If the steer target is end of path or off-mesh link, do not move past the location.
if (endOfPath or offMeshConnection) and (len < STEP_SIZE) then
len := 1
else
len := STEP_SIZE / len;
dtVmad(@moveTgt[0], @m_iterPos[0], @delta[0], len);
// Move
nvisited := 0;
m_navQuery.moveAlongSurface(m_pathIterPolys[0], @m_iterPos[0], @moveTgt[0], m_filter,
@reslt[0], @visited[0], @nvisited, 16);
m_pathIterPolyCount := fixupCorridor(@m_pathIterPolys[0], m_pathIterPolyCount, MAX_POLYS, @visited[0], nvisited);
m_pathIterPolyCount := fixupShortcuts(@m_pathIterPolys[0], m_pathIterPolyCount, m_navQuery);
h := 0;
m_navQuery.getPolyHeight(m_pathIterPolys[0], @reslt[0], @h);
reslt[1] := h;
dtVcopy(@m_iterPos[0], @reslt[0]);
// Handle end of path and off-mesh links when close enough.
if (endOfPath and inRange(@m_iterPos[0], @steerPos[0], SLOP, 1.0)) then
begin
// Reached end of path.
dtVcopy(@m_iterPos[0], @m_targetPos[0]);
if (m_nsmoothPath < MAX_SMOOTH) then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @m_iterPos[0]);
Inc(m_nsmoothPath);
end;
Exit;
end
else if (offMeshConnection and inRange(@m_iterPos[0], @steerPos[0], SLOP, 1.0)) then
begin
// Reached off-mesh connection.
// Advance the path up to and over the off-mesh connection.
prevRef := 0; polyRef := m_pathIterPolys[0];
npos := 0;
while (npos < m_pathIterPolyCount) and (polyRef <> steerPosRef) do
begin
prevRef := polyRef;
polyRef := m_pathIterPolys[npos];
Inc(npos);
end;
for i := npos to m_pathIterPolyCount - 1 do
m_pathIterPolys[i-npos] := m_pathIterPolys[i];
Dec(m_pathIterPolyCount, npos);
// Handle the connection.
status := m_navMesh.getOffMeshConnectionPolyEndPoints(prevRef, polyRef, @startPos[0], @endPos[0]);
if (dtStatusSucceed(status)) then
begin
if (m_nsmoothPath < MAX_SMOOTH) then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @startPos[0]);
Inc(m_nsmoothPath);
// Hack to make the dotted path not visible during off-mesh connection.
if (m_nsmoothPath and 1) <> 0 then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @startPos[0]);
Inc(m_nsmoothPath);
end;
end;
// Move position at the other side of the off-mesh link.
dtVcopy(@m_iterPos[0], @endPos[0]);
eh := 0.0;
m_navQuery.getPolyHeight(m_pathIterPolys[0], @m_iterPos[0], @eh);
m_iterPos[1] := eh;
end;
end;
// Store results.
if (m_nsmoothPath < MAX_SMOOTH) then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @m_iterPos[0]);
Inc(m_nsmoothPath);
end;
end;
procedure TNavMeshTesterTool.handleUpdate(dt: Single);
var epos: array [0..2] of Single;
begin
if (m_toolMode = TOOLMODE_PATHFIND_SLICED) then
begin
if (dtStatusInProgress(m_pathFindStatus)) then
begin
m_pathFindStatus := m_navQuery.updateSlicedFindPath(1, nil);
end;
if (dtStatusSucceed(m_pathFindStatus)) then
begin
m_navQuery.finalizeSlicedFindPath(@m_polys[0], @m_npolys, MAX_POLYS);
m_nstraightPath := 0;
if (m_npolys <> 0) then
begin
// In case of partial path, make sure the end point is clamped to the last polygon.
dtVcopy(@epos[0], @m_epos[0]);
if (m_polys[m_npolys-1] <> m_endRef) then
m_navQuery.closestPointOnPoly(m_polys[m_npolys-1], @m_epos[0], @epos[0], nil);
m_navQuery.findStraightPath(@m_spos[0], @epos[0], @m_polys[0], m_npolys,
@m_straightPath[0], @m_straightPathFlags[0],
@m_straightPathPolys[0], @m_nstraightPath, MAX_POLYS, Byte(DT_STRAIGHTPATH_ALL_CROSSINGS));
end;
m_pathFindStatus := DT_FAILURE;
end;
end;
end;
procedure TNavMeshTesterTool.reset();
begin
m_startRef := 0;
m_endRef := 0;
m_npolys := 0;
m_nstraightPath := 0;
m_nsmoothPath := 0;
FillChar(m_hitPos[0], sizeof(m_hitPos), 0);
FillChar(m_hitNormal[0], sizeof(m_hitNormal), 0);
m_distanceToWall := 0;
end;
procedure TNavMeshTesterTool.recalc();
const STEP_SIZE = 0.5;
const SLOP = 0.01;
var polys: array [0..MAX_POLYS-1] of TdtPolyRef; npolys: Integer; iterPos,targetPos,steerPos,delta,moveTgt,reslt,startPos,endPos,epos: array [0..2] of Single;
steerPosFlag: Byte; steerPosRef,prevRef,polyRef: TdtPolyRef; endOfPath,offMeshConnection: Boolean; len: Single;
visited: array [0..15] of TdtPolyRef; nvisited,npos,i: Integer; h,eh,t: Single; status: TdtStatus; dx,dz,dist: Single;
nx,nz,agentHeight: Single;
begin
if (m_navMesh = nil) then
Exit;
if (m_sposSet) then
m_navQuery.findNearestPoly(@m_spos[0], @m_polyPickExt[0], m_filter, @m_startRef, nil)
else
m_startRef := 0;
if (m_eposSet) then
m_navQuery.findNearestPoly(@m_epos[0], @m_polyPickExt[0], m_filter, @m_endRef, nil)
else
m_endRef := 0;
m_pathFindStatus := DT_FAILURE;
if (m_toolMode = TOOLMODE_PATHFIND_FOLLOW) then
begin
m_pathIterNum := 0;
if (m_sposSet and m_eposSet and (m_startRef <> 0) and (m_endRef <> 0)) then
begin
{$ifdef DUMP_REQS}
printf("pi %f %f %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], m_epos[0],m_epos[1],m_epos[2],
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
m_navQuery.findPath(m_startRef, m_endRef, @m_spos[0], @m_epos[0], m_filter, @m_polys[0], @m_npolys, MAX_POLYS);
m_nsmoothPath := 0;
if (m_npolys <> 0) then
begin
// Iterate over the path to find smooth path on the detail mesh surface.
Move(m_polys[0], polys[0], sizeof(TdtPolyRef)*m_npolys);
npolys := m_npolys;
m_navQuery.closestPointOnPoly(m_startRef, @m_spos[0], @iterPos[0], nil);
m_navQuery.closestPointOnPoly(polys[npolys-1], @m_epos[0], @targetPos[0], nil);
m_nsmoothPath := 0;
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @iterPos[0]);
Inc(m_nsmoothPath);
// Move towards target a small advancement at a time until target reached or
// when ran out of memory to store the path.
while (npolys <> 0) and (m_nsmoothPath < MAX_SMOOTH) do
begin
// Find location to steer towards.
if (not getSteerTarget(m_navQuery, @iterPos[0], @targetPos[0], SLOP,
@polys[0], npolys, @steerPos[0], @steerPosFlag, @steerPosRef)) then
break;
endOfPath := (steerPosFlag and Byte(DT_STRAIGHTPATH_END)) <> 0;
offMeshConnection := (steerPosFlag and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0;
// Find movement delta.
dtVsub(@delta[0], @steerPos[0], @iterPos[0]);
len := Sqrt(dtVdot(@delta[0],@delta[0]));
// If the steer target is end of path or off-mesh link, do not move past the location.
if (endOfPath or offMeshConnection) and (len < STEP_SIZE) then
len := 1
else
len := STEP_SIZE / len;
dtVmad(@moveTgt[0], @iterPos[0], @delta[0], len);
// Move
nvisited := 0;
m_navQuery.moveAlongSurface(polys[0], @iterPos[0], @moveTgt[0], m_filter,
@reslt[0], @visited[0], @nvisited, 16);
npolys := fixupCorridor(@polys[0], npolys, MAX_POLYS, @visited[0], nvisited);
npolys := fixupShortcuts(@polys[0], npolys, m_navQuery);
h := 0;
m_navQuery.getPolyHeight(polys[0], @reslt[0], @h);
reslt[1] := h;
dtVcopy(@iterPos[0], @reslt[0]);
// Handle end of path and off-mesh links when close enough.
if (endOfPath and inRange(@iterPos[0], @steerPos[0], SLOP, 1.0)) then
begin
// Reached end of path.
dtVcopy(@iterPos[0], @targetPos[0]);
if (m_nsmoothPath < MAX_SMOOTH) then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @iterPos[0]);
Inc(m_nsmoothPath);
end;
break;
end
else if (offMeshConnection and inRange(@iterPos[0], @steerPos[0], SLOP, 1.0)) then
begin
// Reached off-mesh connection.
// Advance the path up to and over the off-mesh connection.
prevRef := 0; polyRef := polys[0];
npos := 0;
while (npos < npolys) and (polyRef <> steerPosRef) do
begin
prevRef := polyRef;
polyRef := polys[npos];
Inc(npos);
end;
for i := npos to npolys - 1 do
polys[i-npos] := polys[i];
Dec(npolys, npos);
// Handle the connection.
status := m_navMesh.getOffMeshConnectionPolyEndPoints(prevRef, polyRef, @startPos[0], @endPos[0]);
if (dtStatusSucceed(status)) then
begin
if (m_nsmoothPath < MAX_SMOOTH) then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @startPos[0]);
Inc(m_nsmoothPath);
// Hack to make the dotted path not visible during off-mesh connection.
if (m_nsmoothPath and 1) <> 0 then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @startPos[0]);
Inc(m_nsmoothPath);
end;
end;
// Move position at the other side of the off-mesh link.
dtVcopy(@iterPos[0], @endPos[0]);
eh := 0.0;
m_navQuery.getPolyHeight(polys[0], @iterPos[0], @eh);
iterPos[1] := eh;
end;
end;
// Store results.
if (m_nsmoothPath < MAX_SMOOTH) then
begin
dtVcopy(@m_smoothPath[m_nsmoothPath*3], @iterPos[0]);
Inc(m_nsmoothPath);
end;
end;
end;
end
else
begin
m_npolys := 0;
m_nsmoothPath := 0;
end;
end
else if (m_toolMode = TOOLMODE_PATHFIND_STRAIGHT) then
begin
if (m_sposSet and m_eposSet and (m_startRef <> 0) and (m_endRef <> 0)) then
begin
{$ifdef DUMP_REQS}
printf("ps %f %f %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], m_epos[0],m_epos[1],m_epos[2],
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
m_navQuery.findPath(m_startRef, m_endRef, @m_spos[0], @m_epos[0], m_filter, @m_polys[0], @m_npolys, MAX_POLYS);
m_nstraightPath := 0;
if (m_npolys <> 0) then
begin
// In case of partial path, make sure the end point is clamped to the last polygon.
dtVcopy(@epos[0], @m_epos[0]);
if (m_polys[m_npolys-1] <> m_endRef) then
m_navQuery.closestPointOnPoly(m_polys[m_npolys-1], @m_epos[0], @epos[0], nil);
m_navQuery.findStraightPath(@m_spos[0], @epos[0], @m_polys[0], m_npolys,
@m_straightPath[0], @m_straightPathFlags[0],
@m_straightPathPolys[0], @m_nstraightPath, MAX_POLYS, Byte(m_straightPathOptions));
end;
end
else
begin
m_npolys := 0;
m_nstraightPath := 0;
end;
end
else if (m_toolMode = TOOLMODE_PATHFIND_SLICED) then
begin
if (m_sposSet and m_eposSet and (m_startRef <> 0) and (m_endRef <> 0)) then
begin
{$ifdef DUMP_REQS}
printf("ps %f %f %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], m_epos[0],m_epos[1],m_epos[2],
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
m_npolys := 0;
m_nstraightPath := 0;
m_pathFindStatus := m_navQuery.initSlicedFindPath(m_startRef, m_endRef, @m_spos[0], @m_epos[0], m_filter, Byte(DT_FINDPATH_ANY_ANGLE));
end
else
begin
m_npolys := 0;
m_nstraightPath := 0;
end;
end
else if (m_toolMode = TOOLMODE_RAYCAST) then
begin
m_nstraightPath := 0;
if (m_sposSet and m_eposSet and (m_startRef <> 0)) then
begin
{$ifdef DUMP_REQS}
printf("rc %f %f %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], m_epos[0],m_epos[1],m_epos[2],
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
t := 0;
m_npolys := 0;
m_nstraightPath := 2;
m_straightPath[0] := m_spos[0];
m_straightPath[1] := m_spos[1];
m_straightPath[2] := m_spos[2];
m_navQuery.raycast(m_startRef, @m_spos[0], @m_epos[0], m_filter, @t, @m_hitNormal[0], @m_polys[0], @m_npolys, MAX_POLYS);
if (t > 1) then
begin
// No hit
dtVcopy(@m_hitPos[0], @m_epos[0]);
m_hitResult := false;
end
else
begin
// Hit
dtVlerp(@m_hitPos[0], @m_spos[0], @m_epos[0], t);
m_hitResult := true;
end;
// Adjust height.
if (m_npolys > 0) then
begin
h := 0;
m_navQuery.getPolyHeight(m_polys[m_npolys-1], @m_hitPos[0], @h);
m_hitPos[1] := h;
end;
dtVcopy(@m_straightPath[3], @m_hitPos[0]);
end;
end
else if (m_toolMode = TOOLMODE_DISTANCE_TO_WALL) then
begin
m_distanceToWall := 0;
if (m_sposSet and (m_startRef <> 0)) then
begin
{$ifdef DUMP_REQS}
printf("dw %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], 100.0f,
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
m_distanceToWall := 0.0;
m_navQuery.findDistanceToWall(m_startRef, @m_spos[0], 100.0, m_filter, @m_distanceToWall, @m_hitPos[0], @m_hitNormal[0]);
end;
end
else if (m_toolMode = TOOLMODE_FIND_POLYS_IN_CIRCLE) then
begin
if (m_sposSet and m_eposSet and (m_startRef <> 0)) then
begin
dx := m_epos[0] - m_spos[0];
dz := m_epos[2] - m_spos[2];
dist := sqrt(dx*dx + dz*dz);
{$ifdef DUMP_REQS}
printf("fpc %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], dist,
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
m_navQuery.findPolysAroundCircle(m_startRef, @m_spos[0], dist, m_filter,
@m_polys[0], @m_parent[0], nil, @m_npolys, MAX_POLYS);
end;
end
else if (m_toolMode = TOOLMODE_FIND_POLYS_IN_SHAPE) then
begin
if (m_sposSet and m_eposSet and (m_startRef <> 0)) then
begin
nx := (m_epos[2] - m_spos[2])*0.25;
nz := -(m_epos[0] - m_spos[0])*0.25;
if m_sample <> nil then agentHeight := m_sample.getAgentHeight else agentHeight := 0;
m_queryPoly[0] := m_spos[0] + nx*1.2;
m_queryPoly[1] := m_spos[1] + agentHeight/2;
m_queryPoly[2] := m_spos[2] + nz*1.2;
m_queryPoly[3] := m_spos[0] - nx*1.3;
m_queryPoly[4] := m_spos[1] + agentHeight/2;
m_queryPoly[5] := m_spos[2] - nz*1.3;
m_queryPoly[6] := m_epos[0] - nx*0.8;
m_queryPoly[7] := m_epos[1] + agentHeight/2;
m_queryPoly[8] := m_epos[2] - nz*0.8;
m_queryPoly[9] := m_epos[0] + nx;
m_queryPoly[10] := m_epos[1] + agentHeight/2;
m_queryPoly[11] := m_epos[2] + nz;
{$ifdef DUMP_REQS}
printf("fpp %f %f %f %f %f %f %f %f %f %f %f %f 0x%x 0x%x\n",
m_queryPoly[0],m_queryPoly[1],m_queryPoly[2],
m_queryPoly[3],m_queryPoly[4],m_queryPoly[5],
m_queryPoly[6],m_queryPoly[7],m_queryPoly[8],
m_queryPoly[9],m_queryPoly[10],m_queryPoly[11],
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
m_navQuery.findPolysAroundShape(m_startRef, @m_queryPoly[0], 4, m_filter,
@m_polys[0], @m_parent[0], nil, @m_npolys, MAX_POLYS);
end;
end
else if (m_toolMode = TOOLMODE_FIND_LOCAL_NEIGHBOURHOOD) then
begin
if (m_sposSet and (m_startRef <> 0)) then
begin
{$ifdef DUMP_REQS}
printf("fln %f %f %f %f 0x%x 0x%x\n",
m_spos[0],m_spos[1],m_spos[2], m_neighbourhoodRadius,
m_filter.getIncludeFlags(), m_filter.getExcludeFlags());
{$endif}
//todo: m_navQuery.findLocalNeighbourhood(m_startRef, m_spos, m_neighbourhoodRadius, m_filter, m_polys, m_parent, &m_npolys, MAX_POLYS);
end;
end;
end;
procedure getPolyCenter(navMesh: TdtNavMesh; ref: TdtPolyRef; center: PSingle);
var tile: PdtMeshTile; poly: PdtPoly; status: TdtStatus; i: Integer; v: PSingle; s: Single;
begin
center[0] := 0;
center[1] := 0;
center[2] := 0;
tile := nil;
poly := nil;
status := navMesh.getTileAndPolyByRef(ref, @tile, @poly);
if (dtStatusFailed(status)) then
Exit;
for i := 0 to poly.vertCount - 1 do
begin
v := @tile.verts[poly.verts[i]*3];
center[0] := center[0] + v[0];
center[1] := center[1] + v[1];
center[2] := center[2] + v[2];
end;
s := 1.0 / poly.vertCount;
center[0] := center[0] * s;
center[1] := center[1] * s;
center[2] := center[2] * s;
end;
procedure TNavMeshTesterTool.handleRender();
const MAX_SEGS = DT_VERTS_PER_POLYGON*4;
var dd: TDebugDrawGL;
startCol, endCol, pathCol, spathCol, prevCol, curCol, steerCol, offMeshCol, col, hitCol: Cardinal;
agentRadius, agentHeight, agentClimb: Single; i,j: Integer;
p0,p1,delta,norm: array [0..2] of Single; pp0,pp1,s,p: PSingle; dx,dz,dist,tseg,distSqr: Single;
segs: array [0..MAX_SEGS*6-1] of Single;
refs: array [0..MAX_SEGS-1] of TdtPolyRef;
nsegs: Integer;
begin
dd := TDebugDrawGL.Create;
startCol := duRGBA(128,25,0,192);
endCol := duRGBA(51,102,0,129);
pathCol := duRGBA(0,0,0,64);
agentRadius := m_sample.getAgentRadius;
agentHeight := m_sample.getAgentHeight;
agentClimb := m_sample.getAgentClimb;
dd.depthMask(false);
if (m_sposSet) then
drawAgent(@m_spos[0], agentRadius, agentHeight, agentClimb, startCol);
if (m_eposSet) then
drawAgent(@m_epos[0], agentRadius, agentHeight, agentClimb, endCol);
dd.depthMask(true);
if (m_navMesh = nil) then
begin
Exit;
end;
if (m_toolMode = TOOLMODE_PATHFIND_FOLLOW) then
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_startRef, startCol);
duDebugDrawNavMeshPoly(dd, m_navMesh, m_endRef, endCol);
if (m_npolys <> 0) then
begin
for i := 0 to m_npolys - 1 do
begin
if (m_polys[i] = m_startRef) or (m_polys[i] = m_endRef) then
continue;
duDebugDrawNavMeshPoly(dd, m_navMesh, m_polys[i], pathCol);
end;
end;
if (m_nsmoothPath <> 0) then
begin
dd.depthMask(false);
spathCol := duRGBA(0,0,0,220);
dd.&begin(DU_DRAW_LINES, 3.0);
for i := 0 to m_nsmoothPath - 1 do
dd.vertex(m_smoothPath[i*3], m_smoothPath[i*3+1]+0.1, m_smoothPath[i*3+2], spathCol);
dd.&end();
dd.depthMask(true);
end;
if (m_pathIterNum <> 0) then
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_pathIterPolys[0], duRGBA(255,255,255,128));
dd.depthMask(false);
dd.&begin(DU_DRAW_LINES, 1.0);
prevCol := duRGBA(255,192,0,220);
curCol := duRGBA(255,255,255,220);
steerCol := duRGBA(0,192,255,220);
dd.vertex(m_prevIterPos[0],m_prevIterPos[1]-0.3,m_prevIterPos[2], prevCol);
dd.vertex(m_prevIterPos[0],m_prevIterPos[1]+0.3,m_prevIterPos[2], prevCol);
dd.vertex(m_iterPos[0],m_iterPos[1]-0.3,m_iterPos[2], curCol);
dd.vertex(m_iterPos[0],m_iterPos[1]+0.3,m_iterPos[2], curCol);
dd.vertex(m_prevIterPos[0],m_prevIterPos[1]+0.3,m_prevIterPos[2], prevCol);
dd.vertex(m_iterPos[0],m_iterPos[1]+0.3,m_iterPos[2], prevCol);
dd.vertex(m_prevIterPos[0],m_prevIterPos[1]+0.3,m_prevIterPos[2], steerCol);
dd.vertex(m_steerPos[0],m_steerPos[1]+0.3,m_steerPos[2], steerCol);
for i := 0 to m_steerPointCount-1 - 1 do
begin
dd.vertex(m_steerPoints[i*3+0],m_steerPoints[i*3+1]+0.2,m_steerPoints[i*3+2], duDarkenCol(steerCol));
dd.vertex(m_steerPoints[(i+1)*3+0],m_steerPoints[(i+1)*3+1]+0.2,m_steerPoints[(i+1)*3+2], duDarkenCol(steerCol));
end;
dd.&end();
dd.depthMask(true);
end;
end
else if (m_toolMode = TOOLMODE_PATHFIND_STRAIGHT) or
(m_toolMode = TOOLMODE_PATHFIND_SLICED) then
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_startRef, startCol);
duDebugDrawNavMeshPoly(dd, m_navMesh, m_endRef, endCol);
if (m_npolys <> 0) then
begin
for i := 0 to m_npolys - 1 do
begin
if (m_polys[i] = m_startRef) or (m_polys[i] = m_endRef) then
continue;
duDebugDrawNavMeshPoly(dd, m_navMesh, m_polys[i], pathCol);
end;
end;
if (m_nstraightPath <> 0) then
begin
dd.depthMask(false);
spathCol := duRGBA(64,16,0,220);
offMeshCol := duRGBA(128,96,0,220);
dd.&begin(DU_DRAW_LINES, 2.0);
for i := 0 to m_nstraightPath-1 - 1 do
begin
if (m_straightPathFlags[i] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0 then
col := offMeshCol
else
col := spathCol;
dd.vertex(m_straightPath[i*3], m_straightPath[i*3+1]+0.4, m_straightPath[i*3+2], col);
dd.vertex(m_straightPath[(i+1)*3], m_straightPath[(i+1)*3+1]+0.4, m_straightPath[(i+1)*3+2], col);
end;
dd.&end();
dd.&begin(DU_DRAW_POINTS, 6.0);
for i := 0 to m_nstraightPath - 1 do
begin
if (m_straightPathFlags[i] and Byte(DT_STRAIGHTPATH_START)) <> 0 then
col := startCol
else if (m_straightPathFlags[i] and Byte(DT_STRAIGHTPATH_END)) <> 0 then
col := endCol
else if (m_straightPathFlags[i] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0 then
col := offMeshCol
else
col := spathCol;
dd.vertex(m_straightPath[i*3], m_straightPath[i*3+1]+0.4, m_straightPath[i*3+2], col);
end;
dd.&end();
dd.depthMask(true);
end;
end
else if (m_toolMode = TOOLMODE_RAYCAST) then
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_startRef, startCol);
if (m_nstraightPath <> 0) then
begin
for i := 1 to m_npolys - 1 do
duDebugDrawNavMeshPoly(dd, m_navMesh, m_polys[i], pathCol);
dd.depthMask(false);
spathCol := IfThen(m_hitResult, duRGBA(64,16,0,220), duRGBA(240,240,240,220));
dd.&begin(DU_DRAW_LINES, 2.0);
for i := 0 to m_nstraightPath-1 - 1 do
begin
dd.vertex(m_straightPath[i*3], m_straightPath[i*3+1]+0.4, m_straightPath[i*3+2], spathCol);
dd.vertex(m_straightPath[(i+1)*3], m_straightPath[(i+1)*3+1]+0.4, m_straightPath[(i+1)*3+2], spathCol);
end;
dd.&end();
dd.&begin(DU_DRAW_POINTS, 4.0);
for i := 0 to m_nstraightPath - 1 do
dd.vertex(m_straightPath[i*3], m_straightPath[i*3+1]+0.4, m_straightPath[i*3+2], spathCol);
dd.&end();
if (m_hitResult) then
begin
hitCol := duRGBA(0,0,0,128);
dd.&begin(DU_DRAW_LINES, 2.0);
dd.vertex(m_hitPos[0], m_hitPos[1] + 0.4, m_hitPos[2], hitCol);
dd.vertex(m_hitPos[0] + m_hitNormal[0]*agentRadius,
m_hitPos[1] + 0.4 + m_hitNormal[1]*agentRadius,
m_hitPos[2] + m_hitNormal[2]*agentRadius, hitCol);
dd.&end();
end;
dd.depthMask(true);
end;
end
else if (m_toolMode = TOOLMODE_DISTANCE_TO_WALL) then
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_startRef, startCol);
dd.depthMask(false);
duDebugDrawCircle(dd, m_spos[0], m_spos[1]+agentHeight/2, m_spos[2], m_distanceToWall, duRGBA(64,16,0,220), 2.0);
dd.&begin(DU_DRAW_LINES, 3.0);
dd.vertex(m_hitPos[0], m_hitPos[1] + 0.02, m_hitPos[2], duRGBA(0,0,0,192));
dd.vertex(m_hitPos[0], m_hitPos[1] + agentHeight, m_hitPos[2], duRGBA(0,0,0,192));
dd.&end();
dd.depthMask(true);
end
else if (m_toolMode = TOOLMODE_FIND_POLYS_IN_CIRCLE) then
begin
for i := 0 to m_npolys - 1 do
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_polys[i], pathCol);
dd.depthMask(false);
if (m_parent[i] <> 0) then
begin
dd.depthMask(false);
getPolyCenter(m_navMesh, m_parent[i], @p0[0]);
getPolyCenter(m_navMesh, m_polys[i], @p1[0]);
duDebugDrawArc(dd, p0[0],p0[1],p0[2], p1[0],p1[1],p1[2], 0.25, 0.0, 0.4, duRGBA(0,0,0,128), 2.0);
dd.depthMask(true);
end;
dd.depthMask(true);
end;
if (m_sposSet and m_eposSet) then
begin
dd.depthMask(false);
dx := m_epos[0] - m_spos[0];
dz := m_epos[2] - m_spos[2];
dist := sqrt(dx*dx + dz*dz);
duDebugDrawCircle(dd, m_spos[0], m_spos[1]+agentHeight/2, m_spos[2], dist, duRGBA(64,16,0,220), 2.0);
dd.depthMask(true);
end;
end
else if (m_toolMode = TOOLMODE_FIND_POLYS_IN_SHAPE) then
begin
for i := 0 to m_npolys - 1 do
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_polys[i], pathCol);
dd.depthMask(false);
if (m_parent[i] <> 0) then
begin
dd.depthMask(false);
getPolyCenter(m_navMesh, m_parent[i], @p0[0]);
getPolyCenter(m_navMesh, m_polys[i], @p1[0]);
duDebugDrawArc(dd, p0[0],p0[1],p0[2], p1[0],p1[1],p1[2], 0.25, 0.0, 0.4, duRGBA(0,0,0,128), 2.0);
dd.depthMask(true);
end;
dd.depthMask(true);
end;
if (m_sposSet and m_eposSet) then
begin
dd.depthMask(false);
col := duRGBA(64,16,0,220);
dd.&begin(DU_DRAW_LINES, 2.0);
for i := 0 to 3 do
begin
j := (i+4-1) mod 4;
pp0 := @m_queryPoly[j*3];
pp1 := @m_queryPoly[i*3];
dd.vertex(pp0, col);
dd.vertex(pp1, col);
end;
dd.&end();
dd.depthMask(true);
end;
end
else if (m_toolMode = TOOLMODE_FIND_LOCAL_NEIGHBOURHOOD) then
begin
for i := 0 to m_npolys - 1 do
begin
duDebugDrawNavMeshPoly(dd, m_navMesh, m_polys[i], pathCol);
dd.depthMask(false);
if (m_parent[i] <> 0) then
begin
dd.depthMask(false);
getPolyCenter(m_navMesh, m_parent[i], @p0[0]);
getPolyCenter(m_navMesh, m_polys[i], @p1[0]);
duDebugDrawArc(dd, p0[0],p0[1],p0[2], p1[0],p1[1],p1[2], 0.25, 0.0, 0.4, duRGBA(0,0,0,128), 2.0);
dd.depthMask(true);
end;
FillChar(refs[0], sizeof(TdtPolyRef)*MAX_SEGS, 0);
nsegs := 0;
m_navQuery.getPolyWallSegments(m_polys[i], m_filter, @segs[0], @refs[0], @nsegs, MAX_SEGS);
dd.&begin(DU_DRAW_LINES, 2.0);
for j := 0 to nsegs - 1 do
begin
s := @segs[j*6];
// Skip too distant segments.
distSqr := dtDistancePtSegSqr2D(@m_spos[0], s, s+3, @tseg);
if (distSqr > Sqr(m_neighbourhoodRadius)) then
continue;
dtVsub(@delta[0], s+3,s);
dtVmad(@p0[0], s, @delta[0], 0.5);
norm[0] := delta[2];
norm[1] := 0;
norm[2] := -delta[0];
dtVnormalize(@norm[0]);
dtVmad(@p1[0], @p0[0], @norm[0], agentRadius*0.5);
// Skip backfacing segments.
if (refs[j] <> 0) then
begin
col := duRGBA(255,255,255,32);
dd.vertex(s[0],s[1]+agentClimb,s[2],col);
dd.vertex(s[3],s[4]+agentClimb,s[5],col);
end
else
begin
col := duRGBA(192,32,16,192);
if (dtTriArea2D(@m_spos[0], s, s+3) < 0.0) then
col := duRGBA(96,32,16,192);
dd.vertex(p0[0],p0[1]+agentClimb,p0[2],col);
dd.vertex(p1[0],p1[1]+agentClimb,p1[2],col);
dd.vertex(s[0],s[1]+agentClimb,s[2],col);
dd.vertex(s[3],s[4]+agentClimb,s[5],col);
end;
end;
dd.&end();
dd.depthMask(true);
end;
if (m_sposSet) then
begin
dd.depthMask(false);
duDebugDrawCircle(dd, m_spos[0], m_spos[1]+agentHeight/2, m_spos[2], m_neighbourhoodRadius, duRGBA(64,16,0,220), 2.0);
dd.depthMask(true);
end;
end;
if (m_nrandPoints > 0) then
begin
dd.&begin(DU_DRAW_POINTS, 6.0);
for i := 0 to m_nrandPoints - 1 do
begin
p := @m_randPoints[i*3];
dd.vertex(p[0],p[1]+0.1,p[2], duRGBA(220,32,16,192));
end;
dd.&end();
if (m_randPointsInCircle and m_sposSet) then
begin
duDebugDrawCircle(dd, m_spos[0], m_spos[1]+agentHeight/2, m_spos[2], m_randomRadius, duRGBA(64,16,0,220), 2.0);
end;
end;
dd.Free;
end;
procedure TNavMeshTesterTool.handleRenderOverlay(proj, model: PDouble; view: PInteger);
//var x,y,z: GLDouble; h: Integer;
begin
{ // Draw start and end point labels
if (m_sposSet and (gluProject(m_spos[0], m_spos[1], m_spos[2],
PGLMatrixd4(model)^, PGLMatrixd4(proj)^, PVector4i(view)^, @x, @y, @z) <> 0)) then
begin
//todo: imguiDrawText((int)x, (int)(y-25), IMGUI_ALIGN_CENTER, "Start", imguiRGBA(0,0,0,220));
end;
if (m_eposSet and (gluProject(m_epos[0], m_epos[1], m_epos[2],
PGLMatrixd4(model)^, PGLMatrixd4(proj)^, PVector4i(view)^, @x, @y, @z) <> 0)) then
begin
//todo: imguiDrawText((int)x, (int)(y-25), IMGUI_ALIGN_CENTER, "End", imguiRGBA(0,0,0,220));
end;
// Tool help
h := view[3];
//todo: imguiDrawText(280, h-40, IMGUI_ALIGN_LEFT, "LMB+SHIFT: Set start location LMB: Set end location", imguiRGBA(255,255,255,192));}
end;
procedure TNavMeshTesterTool.drawAgent(pos: PSingle; r, h, c: Single; col: Cardinal);
var dd: TDebugDrawGL; colb: Cardinal;
begin
dd := TDebugDrawGL.Create;
dd.depthMask(false);
// Agent dimensions.
duDebugDrawCylinderWire(dd, pos[0]-r, pos[1]+0.02, pos[2]-r, pos[0]+r, pos[1]+h, pos[2]+r, col, 2.0);
duDebugDrawCircle(dd, pos[0],pos[1]+c,pos[2],r,duRGBA(0,0,0,64),1.0);
colb := duRGBA(0,0,0,196);
dd.&begin(DU_DRAW_LINES);
dd.vertex(pos[0], pos[1]-c, pos[2], colb);
dd.vertex(pos[0], pos[1]+c, pos[2], colb);
dd.vertex(pos[0]-r/2, pos[1]+0.02, pos[2], colb);
dd.vertex(pos[0]+r/2, pos[1]+0.02, pos[2], colb);
dd.vertex(pos[0], pos[1]+0.02, pos[2]-r/2, colb);
dd.vertex(pos[0], pos[1]+0.02, pos[2]+r/2, colb);
dd.&end();
dd.depthMask(true);
dd.Free;
end;
end. |
unit RPrintParcelSummaryWithSketch;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, (*Progress,*)
RPFiler, RPDefine, RPBase, RPCanvas, RPrinter, PASTypes, Types, UPRNTPRC,
TMultiP, Printers;
type
TParcelInformationWithSketchPrintForm = class(TForm)
Panel2: TPanel;
ParcelTable: TTable;
SwisCodeTable: TTable;
PrintDialog: TPrintDialog;
ReportPrinter: TReportPrinter;
ReportFiler: TReportFiler;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
GroupBox1: TGroupBox;
ResidentialInventoryCheckBox: TCheckBox;
CommercialInventoryCheckBox: TCheckBox;
SalesCheckBox: TCheckBox;
ExemptionCheckBox: TCheckBox;
SpecialDistrictCheckBox: TCheckBox;
BaseInformationCheckBox: TCheckBox;
AssessmentsCheckBox: TCheckBox;
CheckAllButton: TBitBtn;
UncheckAllButton: TBitBtn;
PictureCheckBox: TCheckBox;
TaxableValuesGroupBox2: TGroupBox;
SchoolTaxableCheckBox: TCheckBox;
TownTaxableCheckBox: TCheckBox;
CountyTaxableCheckBox: TCheckBox;
NotesCheckBox: TCheckBox;
AssessmentYearRadioGroup: TRadioGroup;
SBLGroupBox: TGroupBox;
Label11: TLabel;
Label12: TLabel;
StartSBLEdit: TEdit;
EndSBLEdit: TEdit;
AllSBLCheckBox: TCheckBox;
ToEndOfSBLCheckBox: TCheckBox;
LoadFromParcelListCheckBox: TCheckBox;
CreateParcelListCheckBox: TCheckBox;
LoadButton: TBitBtn;
SaveButton: TBitBtn;
PrintButton: TBitBtn;
CloseButton: TBitBtn;
cb_Permits: TCheckBox;
cbSketches: TCheckBox;
cbPropertyCards: TCheckBox;
Image: TPMultiImage;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure PrintButtonClick(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure CheckAllButtonClick(Sender: TObject);
procedure UncheckAllButtonClick(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
ReportCancelled : Boolean;
LoadFromParcelList,
CreateParcelList : Boolean;
SwisSBLKey : String;
Options : OptionsSet;
tbPropertyCard : TTable;
ProcessingType : Integer;
Procedure InitializeForm; {Open the tables and setup.}
Procedure PrintPropertyCard(tbPropertyCard : TTable;
sSwisSBLKey : String);
Procedure PrintParcels;
end;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils,
Preview, Prog, RPTDialg, DataAccessUnit,
PRCLLIST; {Print parcel information}
{$R *.DFM}
{========================================================}
Procedure TParcelInformationWithSketchPrintForm.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TParcelInformationWithSketchPrintForm.InitializeForm;
begin
UnitName := 'RPPRCPRT'; {mmm}
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If _Compare(GlblBuildingSystemLinkType, bldMunicity, coEqual)
then cb_Permits.Visible := True
else cb_Permits.Checked := False;
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If GlblUsesSketches
then cbSketches.Visible := True;
end; {InitializeForm}
{===================================================================}
Procedure TParcelInformationWithSketchPrintForm.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If (Key = #13)
then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end; {FormKeyPress}
{====================================================================}
Procedure TParcelInformationWithSketchPrintForm.CheckAllButtonClick(Sender: TObject);
begin
ResidentialInventoryCheckBox.Checked := True;
CommercialInventoryCheckBox.Checked := True;
SalesCheckBox.Checked := True;
ExemptionCheckBox.Checked := True;
SpecialDistrictCheckBox.Checked := True;
BaseInformationCheckBox.Checked := True;
AssessmentsCheckBox.Checked := True;
CountyTaxableCheckBox.Checked := True;
TownTaxableCheckBox.Checked := True;
SchoolTaxableCheckBox.Checked := True;
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If GlblUsesPASPermits
then cb_Permits.Checked := True;
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If GlblUsesSketches
then cbSketches.Checked := True;
end; {CheckAllButtonClick}
{==============================================================}
Procedure TParcelInformationWithSketchPrintForm.UncheckAllButtonClick(Sender: TObject);
begin
ResidentialInventoryCheckBox.Checked := False;
CommercialInventoryCheckBox.Checked := False;
SalesCheckBox.Checked := False;
ExemptionCheckBox.Checked := False;
SpecialDistrictCheckBox.Checked := False;
BaseInformationCheckBox.Checked := False;
AssessmentsCheckBox.Checked := False;
CountyTaxableCheckBox.Checked := False;
TownTaxableCheckBox.Checked := False;
SchoolTaxableCheckBox.Checked := False;
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If GlblUsesPASPermits
then cb_Permits.Checked := False;
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If GlblUsesSketches
then cbSketches.Visible := False;
end; {UncheckAllButtonClick}
{====================================================================}
Procedure TParcelInformationWithSketchPrintForm.SaveButtonClick(Sender: TObject);
{FXX04091999-8: Add ability to save and load search report options.}
begin
SaveReportOptions(Self, OpenDialog, SaveDialog, 'propinfo.prc', 'Property Cards');
end; {SaveButtonClick}
{====================================================================}
Procedure TParcelInformationWithSketchPrintForm.LoadButtonClick(Sender: TObject);
{FXX04091999-8: Add ability to save and load search report options.}
begin
LoadReportOptions(Self, OpenDialog, 'propinfo.prc', 'Property Cards');
end; {LoadButtonClick}
{===================================================================}
Procedure TParcelInformationWithSketchPrintForm.PrintButtonClick(Sender: TObject);
var
Quit : Boolean;
begin
ReportCancelled := False;
{FXX09301998-1: Disable print button after clicking to avoid clicking twice.}
PrintButton.Enabled := False;
Application.ProcessMessages;
Quit := False;
{CHG10121998-1: Add user options for default destination and show vet max msg.}
SetPrintToScreenDefault(PrintDialog);
If PrintDialog.Execute
then
begin
{FXX04052000-1: Check all if no selection.}
If ((not (AllSBLCheckBox.Checked or
ToEndOfSBLCheckBox.Checked)) and
(Deblank(StartSBLEdit.Text) = '') and
(Deblank(EndSBLEdit.Text) = ''))
then AllSBLCheckBox.Checked := True;
LoadFromParcelList := LoadFromParcelListCheckBox.Checked;
{CHG09071999-2: Add create parcel list.}
CreateParcelList := CreateParcelListCheckBox.Checked;
If CreateParcelList
then ParcelListDialog.ClearParcelGrid(True);
{CHG10131998-1: Set the printer settings based on what printer they selected
only - they no longer need to worry about paper or landscape
mode.}
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit);
PrintParcels();
If CreateParcelList
then ParcelListDialog.Show;
ResetPrinter(ReportPrinter);
end; {If PrintDialog.Execute}
PrintButton.Enabled := True;
end; {PrintButtonClick}
{===========================================================================}
Procedure TParcelInformationWithSketchPrintForm.PrintPropertyCard(tbPropertyCard : TTable;
sSwisSBLKey : String);
begin
If (tbPropertyCard = nil)
then
begin
tbPropertyCard := TTable.Create(nil);
with tbPropertyCard do
try
DatabaseName := 'PASSystem';
TableType := ttDBase;
TableName := PropertyCardTableName;
IndexName := 'BYSWISSBLKEY_DOCUMENTNUMBER';
Open;
except
end;
end;
_SetRange(tbPropertyCard, [sSwisSBLKey, 0], [sSwisSBLKey, 9999], '', []);
If _Compare(tbPropertyCard.RecordCount, 0, coGreaterThan)
then
try
tbPropertyCard.First;
try
Printer.Refresh;
Image.GetInfoAndType(tbPropertyCard.FieldByName('DocumentLocation').Text);
Image.ImageName := tbPropertyCard.FieldByName('DocumentLocation').AsString;
PrintImage(Image, Handle, 0, 0, 6360, 4900,
0, 999, False);
except
end;
except
end;
end; {PrintPropertyCard}
{=======================================================================}
Procedure TParcelInformationWithSketchPrintForm.ReportPrint(Sender: TObject);
begin
PrintAParcel(Sender, SwisSBLKey, ProcessingType, Options);
If (ptPropertyCard in Options)
then PrintPropertyCard(tbPropertyCard, SwisSBLKey);
end;
{=======================================================================}
Procedure TParcelInformationWithSketchPrintForm.PrintParcels;
var
PrintAllParcelIDs,
ValidEntry : Boolean;
StartSwisSBLKey, EndSwisSBLKey : String;
Index : Integer;
SBLRec : SBLRecord;
Quit, Done, FirstTimeThrough : Boolean;
begin
Done := False;
FirstTimeThrough := True;
Index := 1;
If (AssessmentYearRadioGroup.ItemIndex = 0)
then ProcessingType := ThisYear
else ProcessingType := NextYear;
Options := [];
Options := Options + [ptPrintNextYear];
If BaseInformationCheckBox.Checked
then Options := Options + [ptBaseInformation];
If AssessmentsCheckBox.Checked
then Options := Options + [ptAssessments];
If SpecialDistrictCheckBox.Checked
then Options := Options + [ptSpecialDistricts];
If ExemptionCheckBox.Checked
then Options := Options + [ptExemptions];
If SalesCheckBox.Checked
then Options := Options + [ptSales];
If ResidentialInventoryCheckBox.Checked
then Options := Options + [ptResidentialInventory];
If CommercialInventoryCheckBox.Checked
then Options := Options + [ptCommercialInventory];
If PictureCheckBox.Checked
then Options := Options + [ptPictures];
{CHG09192001-2: Allow them to select which taxable values to show.}
If CountyTaxableCheckBox.Checked
then Options := Options + [ptCountyTaxable];
If TownTaxableCheckBox.Checked
then Options := Options + [ptTownTaxable];
If SchoolTaxableCheckBox.Checked
then Options := Options + [ptSchoolTaxable];
{CHG03282002-11: Allow them to print notes.}
If (NotesCheckBox.Checked and
(not GlblUserIsSearcher))
then Options := Options + [ptNotes];
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If (cb_Permits.Checked and
(not GlblUserIsSearcher))
then Options := Options + [ptPermits];
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If GlblUsesSketches
then Options := Options + [ptSketches];
If cbPropertyCards.Checked
then Options := Options + [ptPropertyCard];
OpenTablesForForm(Self, ProcessingType);
PrintAllParcelIDs := False;
If not LoadFromParcelList
then
If AllSBLCheckBox.Checked
then PrintAllParcelIDs := True
else
begin
StartSwisSBLKey := ConvertSwisDashDotToSwisSBL(StartSBLEdit.Text, SwisCodeTable,
ValidEntry);
{FXX12011998-21: Was using StartSBLEdit for end range.}
If not ToEndOfSBLCheckBox.Checked
then EndSwisSBLKey := ConvertSwisDashDotToSwisSBL(EndSBLEdit.Text,
SwisCodeTable,
ValidEntry);
end; {If AllSBLCheckBox.Checked}
{CHG03191999-2: Add option to load from parcel list.}
If LoadFromParcelList
then
begin
ParcelListDialog.GetParcel(ParcelTable, Index);
ProgressDialog.Start(ParcelListDialog.NumItems, True, True);
end
else
begin
ProgressDialog.Start(GetRecordCount(ParcelTable), True, True);
If PrintAllParcelIDs
then ParcelTable.First
else
begin
SBLRec := ExtractSwisSBLFromSwisSBLKey(StartSwisSBLKey);
{FXX12011998-22: Forgot that 1st part of key is tax roll year.}
with SBLRec do
FindNearestOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot',
'Suffix'],
[GetTaxRollYearForProcessingType(ProcessingType),
SwisCode, Section, Subsection, Block, Lot,
Sublot, Suffix]);
end; {else of If PrintAllParcelIDs}
end; {else of If LoadFromParcelList}
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
If LoadFromParcelList
then
begin
Index := Index + 1;
ParcelListDialog.GetParcel(ParcelTable, Index);
end
else ParcelTable.Next;
SwisSBLKey := ExtractSSKey(ParcelTable);
{FXX12011998-23: Check for entered end range.}
{FXX06251999-2: Was not checking the PrintAllParcels and so Print All Parcels was
not working.}
If (ParcelTable.EOF or
((not PrintAllParcelIDs) and
(not LoadFromParcelList) and
(SwisSBLKey > EndSwisSBLKey)) or
(LoadFromParcelList and
(Index > ParcelListDialog.NumItems)))
then Done := True;
If LoadFromParcelList
then ProgressDialog.Update(Self, ParcelListDialog.GetParcelID(Index))
else ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(ExtractSSKey(ParcelTable)));
If not Done
then
begin
Application.ProcessMessages;
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit);
ReportPrinter.Execute;
{CHG09071999-2: Add create parcel list.}
If CreateParcelList
then ParcelListDialog.AddOneParcel(SwisSBLKey);
end; {If not Done}
until (Done or ProgressDialog.Cancelled);
ProgressDialog.Finish;
end; {PrintParcels}
{===================================================================}
Procedure TParcelInformationWithSketchPrintForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
try
tbPropertyCard.Close;
tbPropertyCard.Free;
except
end;
end; {FormClose}
end.
|
unit UExportWindow;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Spin,
StdCtrls, Buttons, math, UShapesList;
type
{ TExportDialog }
TExportDialog = class(TForm)
SaveDialog: TSaveDialog;
ExportSB: TSpeedButton;
CancelSB: TSpeedButton;
WidthLbl: TLabel;
HeightLbl: TLabel;
WidthSE: TSpinEdit;
HeightSE: TSpinEdit;
procedure CancelSBClick(Sender: TObject);
procedure HeightSEChange(Sender: TObject);
procedure ExportSBClick(Sender: TObject);
procedure WidthSEChange(Sender: TObject);
private
{ private declarations }
public
ImgWidth, ImgHeight: Integer;
AspectRatio: Double;
{ public declarations }
end;
var
ExportDialog: TExportDialog;
implementation
{$R *.lfm}
{ TExportDialog }
procedure TExportDialog.ExportSBClick(Sender: TObject);
begin
if SaveDialog.Execute then
begin
case SaveDialog.FilterIndex of
1: Figures.ExportToBMP(SaveDialog.FileName, ImgWidth, ImgHeight);
2: Figures.ExportToPNG(SaveDialog.FileName, ImgWidth, ImgHeight);
3: Figures.ExportToJPG(SaveDialog.FileName, ImgWidth, ImgHeight);
end;
Close;
end;
end;
procedure TExportDialog.WidthSEChange(Sender: TObject);
begin
if WidthSE.Value = ImgWidth then
Exit;
ImgWidth := WidthSE.Value;
ImgHeight := ceil(WidthSE.Value / AspectRatio);
HeightSE.Value := ImgHeight;
end;
procedure TExportDialog.CancelSBClick(Sender: TObject);
begin
Close;
end;
procedure TExportDialog.HeightSEChange(Sender: TObject);
begin
if HeightSE.Value = ImgHeight then
Exit;
ImgHeight := HeightSE.Value;
ImgWidth := ceil(HeightSE.Value * AspectRatio);
WidthSE.Value := ImgWidth;
end;
end.
|
unit Principal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.ExtCtrls, Vcl.StdCtrls, Math,
Vcl.WinXPickers;
type
TPrincipalForm = class(TForm)
MainMenu1: TMainMenu;
Archivo1: TMenuItem;
Salir1: TMenuItem;
a1: TMenuItem;
EjercicioUno1: TMenuItem;
EjercicioDos1: TMenuItem;
EjercicioTres1: TMenuItem;
Cuatro1: TMenuItem;
EjercicioCinco1: TMenuItem;
N11: TMenuItem;
N2: TMenuItem;
EjercicioSeis1: TMenuItem;
EjercicioSiete1: TMenuItem;
EjercicioOcho1: TMenuItem;
EjercicioNueve1: TMenuItem;
Principal1: TMenuItem;
N3: TMenuItem;
Panel1: TPanel;
EjercicioUnoBtn: TButton;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
EjercicioDosBtn: TButton;
EjercicioTresBtn: TButton;
SalirBtn: TButton;
EjercicioCuatroBtn: TButton;
Label2: TLabel;
EjercicioCincoBtn: TButton;
Label5: TLabel;
EjercicioSeisBtn: TButton;
Label6: TLabel;
Label7: TLabel;
EjercicioSieteBtn: TButton;
Label8: TLabel;
EjercicioOchoBtn: TButton;
Label9: TLabel;
EjercicioNueveBtn: TButton;
procedure EjercicioUno1Click(Sender: TObject);
procedure Principal1Click(Sender: TObject);
procedure EjercicioDos1Click(Sender: TObject);
procedure EjercicioTres1Click(Sender: TObject);
procedure Cuatro1Click(Sender: TObject);
procedure EjercicioCinco1Click(Sender: TObject);
procedure EjercicioSeis1Click(Sender: TObject);
procedure EjercicioSiete1Click(Sender: TObject);
procedure EjercicioOcho1Click(Sender: TObject);
procedure EjercicioNueve1Click(Sender: TObject);
procedure Salir1Click(Sender: TObject);
procedure EjercicioUnoBtnClick(Sender: TObject);
procedure EjercicioDosBtnClick(Sender: TObject);
procedure EjercicioTresBtnClick(Sender: TObject);
procedure SalirBtnClick(Sender: TObject);
procedure Ejercicio9Click(Sender: TObject);
procedure EjercicioCuatroBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure hola();
end;
var
PrincipalForm: TPrincipalForm;
implementation
{$R *.dfm}
uses VisualUno, VisualDos, VisualTres, VisualNueve;
Procedure TPrincipalForm.Hola();
begin
//
end;
procedure TPrincipalForm.EjercicioNueve1Click(Sender: TObject);
begin
PrincipalForm.Hide;
VisualNueve.Form9.Show;
end;
procedure TPrincipalForm.Ejercicio9Click(Sender: TObject);
begin
PrincipalForm.Hide;
VisualNueve.Form9.Show;
end;
procedure TPrincipalForm.EjercicioOcho1Click(Sender: TObject);
begin
//
ShowMessage('lkjkljlkjlkjlkj');
end;
procedure TPrincipalForm.EjercicioSeis1Click(Sender: TObject);
begin
//
end;
procedure TPrincipalForm.EjercicioSiete1Click(Sender: TObject);
begin
//
end;
procedure TPrincipalForm.EjercicioCinco1Click(Sender: TObject);
begin
//
end;
procedure TPrincipalForm.EjercicioCuatroBtnClick(Sender: TObject);
begin
Hola();
end;
procedure TPrincipalForm.Cuatro1Click(Sender: TObject);
begin
Hola();
end;
procedure TPrincipalForm.EjercicioTres1Click(Sender: TObject);
begin
PrincipalForm.Hide;
VisualTres.Form3.Show;
end;
procedure TPrincipalForm.EjercicioTresBtnClick(Sender: TObject);
begin
PrincipalForm.Hide;
VisualTres.Form3.Show;
end;
procedure TPrincipalForm.EjercicioDos1Click(Sender: TObject);
begin
PrincipalForm.Hide;
VisualDos.Form2.Show;
end;
procedure TPrincipalForm.EjercicioDosBtnClick(Sender: TObject);
begin
PrincipalForm.Hide;
VisualDos.Form2.Show;
end;
procedure TPrincipalForm.EjercicioUno1Click(Sender: TObject);
begin
PrincipalForm.Hide;
VisualUno.Form1.Show;
end;
procedure TPrincipalForm.EjercicioUnoBtnClick(Sender: TObject);
begin
PrincipalForm.Hide;
VisualUno.Form1.Show;
end;
procedure TPrincipalForm.Principal1Click(Sender: TObject);
begin
PrincipalForm.Show;
end;
procedure TPrincipalForm.Salir1Click(Sender: TObject);
begin
PrincipalForm.Close;
end;
procedure TPrincipalForm.SalirBtnClick(Sender: TObject);
var opcion : Integer;
begin
opcion := 0;
opcion := MessageDlg('¿Desea salir del ejercicio?', mtWarning, mbYesNo, 0);
case opcion of
6 : PrincipalForm.Close;
end;
end;
end.
|
unit Main;
{$mode objfpc}{$H+}{$J-}
interface
uses
Classes,
SysUtils,
Forms,
Controls,
Graphics,
Dialogs,
ExtCtrls,
BGRAVirtualScreen,
BGRABitmap,
BGRABitmapTypes,
Universe;
type
{ TFormGameOfLife }
TFormGameOfLife = class(TForm)
BGRAVirtualScreen: TBGRAVirtualScreen;
TimerRunStep: TTimer;
TimerGarbageCollector: TTimer;
procedure BGRAVirtualScreenMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure BGRAVirtualScreenMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure BGRAVirtualScreenMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure BGRAVirtualScreenMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
procedure BGRAVirtualScreenMouseWheelUp(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
procedure BGRAVirtualScreenRedraw(Sender: TObject; Bitmap: TBGRABitmap);
procedure FormKeyPress(Sender: TObject; var Key: char);
procedure TimerRunStepTimer(Sender: TObject);
procedure TimerGarbageCollectorTimer(Sender: TObject);
private
FUniverse: TUniverse;
FName: String;
FWidth: Integer;
FHeight: Integer;
FDragging: Boolean;
FOrigX: Integer;
FOrigY: Integer;
FPosX: Integer;
FPosY: Integer;
FOffsetX: Integer;
FOffsetY: Integer;
FCellSize: Integer;
procedure OpenRleFile;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
var
FormGameOfLife: TFormGameOfLife;
implementation
uses
Node,
Rle;
{$R *.lfm}
{ TFormGameOfLife }
procedure TFormGameOfLife.FormKeyPress(Sender: TObject; var Key: char);
begin
case Key of
'o', 'O':
begin
TimerRunStep.Enabled := False;
FPosX := 0;
FPosY := 0;
OpenRleFile;
BGRAVirtualScreen.RedrawBitmap;
end;
's', 'S':
begin
TimerRunStep.Enabled := False;
FUniverse.RunStep;
BGRAVirtualScreen.RedrawBitmap;
end;
' ': TimerRunStep.Enabled := not TimerRunStep.Enabled;
#27: Close;
end;
Key := #0;
end;
procedure TFormGameOfLife.TimerRunStepTimer(Sender: TObject);
begin
FUniverse.RunStep;
BGRAVirtualScreen.RedrawBitmap;
end;
procedure TFormGameOfLife.TimerGarbageCollectorTimer(Sender: TObject);
begin
TNode.GarbageCollector;
end;
procedure TFormGameOfLife.OpenRleFile;
var
Stream: TStream;
RleParser: TRleParser;
begin
with TOpenDialog.Create(nil) do
try
Title := 'Select RLE pattern file';
Options := [ofFileMustExist];
Filter := 'RLE pattern file|*.rle';
if not Execute then
Exit;
FUniverse.Clear;
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
RleParser := TRleParser.Create(Stream);
try
FName := RleParser.Name;
FWidth := RleParser.Width;
FHeight := RleParser.Height;
RleParser.LoadInUniverse(FUniverse, -(RleParser.Width div 2), (RleParser.Height div 2));
finally
FreeAndNil(RleParser);
end;
finally
FreeAndNil(Stream);
end;
finally
Free;
end;
end;
constructor TFormGameOfLife.Create(TheOwner: TComponent);
begin
inherited;
FUniverse := TUniverse.Create;
FCellSize := 2;
OpenRleFile;
end;
destructor TFormGameOfLife.Destroy;
begin
FUniverse.Free;
inherited;
end;
procedure TFormGameOfLife.BGRAVirtualScreenRedraw(Sender: TObject; Bitmap: TBGRABitmap);
procedure DrawCells(const Node: INode; x, y: Integer);
var
Offset: Integer;
begin
if Node.Level = 0 then
begin
Bitmap.FillRect(x * FCellSize, y * FCellSize, (x + 1) * FCellSize, (y + 1) * FCellSize, BGRAWhite);
end
else
begin
Offset := 1 shl (Node.Level - 1);
if Node.NW.Population > 0 then
DrawCells(Node.NW, x - Offset, y + Offset);
if Node.NE.Population > 0 then
DrawCells(Node.NE, x + Offset, y + Offset);
if Node.SW.Population > 0 then
DrawCells(Node.SW, x - Offset, y - Offset);
if Node.SE.Population > 0 then
DrawCells(Node.SE, x + Offset, y - Offset);
end;
end;
begin
DrawCells(FUniverse.Root, FPosX + FOffsetX + Bitmap.Width div (2 * FCellSize), FPosY + FOffsetY + Bitmap.Height div (2 * FCellSize));
Bitmap.TextOut(5, 5, Format('Population: %d', [FUniverse.Root.Population]), BGRAWhite);
end;
procedure TFormGameOfLife.BGRAVirtualScreenMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
case Button of
mbLeft:
begin
FDragging := True;
FOrigX := X;
FOrigY := Y;
end;
mbMiddle:
begin
FPosX := 0;
FPosY := 0;
BGRAVirtualScreen.RedrawBitmap;
end;
end;
end;
procedure TFormGameOfLife.BGRAVirtualScreenMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if not FDragging then
Exit;
FOffsetX := (X - FOrigX) div FCellSize;
FOffsetY := (Y - FOrigY) div FCellSize;
BGRAVirtualScreen.RedrawBitmap;
end;
procedure TFormGameOfLife.BGRAVirtualScreenMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
case Button of
mbLeft:
begin
FDragging := False;
FPosX := FPosX + FOffsetX;
FPosY := FPosY + FOffsetY;
FOffsetX := 0;
FOffsetY := 0;
BGRAVirtualScreen.RedrawBitmap;
end;
end;
end;
procedure TFormGameOfLife.BGRAVirtualScreenMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
Dec(FCellSize);
if FCellSize < 1 then
FCellSize := 1;
BGRAVirtualScreen.RedrawBitmap;
end;
procedure TFormGameOfLife.BGRAVirtualScreenMouseWheelUp(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
Inc(FCellSize);
if FCellSize > 16 then
FCellSize := 16;
BGRAVirtualScreen.RedrawBitmap;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSilhouette<p>
Enhanced silhouette classes.<p>
Introduces more evolved/specific silhouette generation and management
classes.<p>
CAUTION : both connectivity classes leak memory.<p>
<b>History : </b><font size=-1><ul>
<li>04/11/10 - DaStr - Restored Delphi5 and Delphi6 compatibility
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>16/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>26/09/03 - EG - Improved performance of TConnectivity data construction
<li>19/06/03 - MF - Split up Connectivity classes
<li>10/06/03 - EG - Creation (based on code from Mattias Fagerlund)
</ul></font>
}
unit GLSilhouette;
interface
{$i GLScene.inc}
uses Classes, GLVectorGeometry, GLVectorLists, GLCrossPlatform;
type
// TGLSilhouetteStyle
//
TGLSilhouetteStyle = (ssOmni, ssParallel);
// TGLSilhouetteParameters
//
{: Silouhette generation parameters.<p>
SeenFrom and LightDirection are expected in local coordinates. }
TGLSilhouetteParameters = packed record
SeenFrom, LightDirection : TAffineVector;
Style : TGLSilhouetteStyle;
CappingRequired : Boolean;
end;
// TGLSilhouette
//
{: Base class storing a volume silhouette.<p>
Made of a set of indexed vertices defining an outline, and another set
of indexed vertices defining a capping volume. Coordinates system
is the object's unscaled local coordinates system.<br>
This is the base class, you can use the TGLSilhouette subclass if you
need some helper methods for generating the indexed sets. }
TGLSilhouette = class
private
{ Private Declarations }
FVertices : TVectorList;
FIndices : TIntegerList;
FCapIndices : TIntegerList;
FParameters : TGLSilhouetteParameters;
protected
{ Protected Declarations }
procedure SetIndices(const value : TIntegerList);
procedure SetCapIndices(const value : TIntegerList);
procedure SetVertices(const value : TVectorList);
public
{ Public Declarations }
constructor Create; virtual;
destructor Destroy; override;
property Parameters : TGLSilhouetteParameters read FParameters write FParameters;
property Vertices : TVectorList read FVertices write SetVertices;
property Indices : TIntegerList read FIndices write SetIndices;
property CapIndices : TIntegerList read FCapIndices write SetCapIndices;
procedure Flush;
procedure Clear;
procedure ExtrudeVerticesToInfinity(const origin : TAffineVector);
{: Adds an edge (two vertices) to the silhouette.<p>
If TightButSlow is true, no vertices will be doubled in the
silhouette list. This should only be used when creating re-usable
silhouettes, because it's much slower. }
procedure AddEdgeToSilhouette(const v0, v1 : TAffineVector;
tightButSlow : Boolean);
procedure AddIndexedEdgeToSilhouette(const Vi0, Vi1 : integer);
{: Adds a capping triangle to the silhouette.<p>
If TightButSlow is true, no vertices will be doubled in the
silhouette list. This should only be used when creating re-usable
silhouettes, because it's much slower. }
procedure AddCapToSilhouette(const v0, v1, v2 : TAffineVector;
tightButSlow : Boolean);
procedure AddIndexedCapToSilhouette(const vi0, vi1, vi2 : Integer);
end;
// TBaseConnectivity
//
TBaseConnectivity = class
protected
FPrecomputeFaceNormal: boolean;
function GetEdgeCount: integer; virtual;
function GetFaceCount: integer; virtual;
public
property EdgeCount : integer read GetEdgeCount;
property FaceCount : integer read GetFaceCount;
property PrecomputeFaceNormal : boolean read FPrecomputeFaceNormal;
procedure CreateSilhouette(const ASilhouetteParameters : TGLSilhouetteParameters; var ASilhouette : TGLSilhouette; AddToSilhouette : boolean); virtual;
constructor Create(APrecomputeFaceNormal : boolean); virtual;
end;
// TConnectivity
//
TConnectivity = class(TBaseConnectivity)
protected
{ All storage of faces and adges are cut up into tiny pieces for a reason,
it'd be nicer with Structs or classes, but it's actually faster this way.
The reason it's faster is because of less cache overwrites when we only
access a tiny bit of a triangle (for instance), not all data.}
FEdgeVertices : TIntegerList;
FEdgeFaces : TIntegerList;
FFaceVisible : TByteList;
FFaceVertexIndex : TIntegerList;
FFaceNormal : TAffineVectorList;
FVertexMemory : TIntegerList;
FVertices : TAffineVectorList;
function GetEdgeCount: integer; override;
function GetFaceCount: integer; override;
function ReuseOrFindVertexID(const seenFrom : TAffineVector;
aSilhouette : TGLSilhouette; index : Integer) : Integer;
public
{: Clears out all connectivity information. }
procedure Clear; virtual;
procedure CreateSilhouette(const silhouetteParameters : TGLSilhouetteParameters; var aSilhouette : TGLSilhouette; AddToSilhouette : boolean); override;
function AddIndexedEdge(vertexIndex0, vertexIndex1 : integer; FaceID: integer) : integer;
function AddIndexedFace(vi0, vi1, vi2 : integer) : integer;
function AddFace(const vertex0, vertex1, vertex2 : TAffineVector) : integer;
function AddQuad(const vertex0, vertex1, vertex2, vertex3 : TAffineVector) : integer;
property EdgeCount : integer read GetEdgeCount;
property FaceCount : integer read GetFaceCount;
constructor Create(APrecomputeFaceNormal : boolean); override;
destructor Destroy; override;
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
implementation
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
uses SysUtils;
// ------------------
// ------------------ TGLSilhouette ------------------
// ------------------
// Create
//
constructor TGLSilhouette.Create;
begin
inherited;
FVertices:=TVectorList.Create;
FIndices:=TIntegerList.Create;
FCapIndices:=TIntegerList.Create;
end;
// Destroy
//
destructor TGLSilhouette.Destroy;
begin
FCapIndices.Free;
FIndices.Free;
FVertices.Free;
inherited;
end;
// SetIndices
//
procedure TGLSilhouette.SetIndices(const value : TIntegerList);
begin
FIndices.Assign(value);
end;
// SetCapIndices
//
procedure TGLSilhouette.SetCapIndices(const value : TIntegerList);
begin
FCapIndices.Assign(value);
end;
// SetVertices
//
procedure TGLSilhouette.SetVertices(const value : TVectorList);
begin
FVertices.Assign(value);
end;
// Flush
//
procedure TGLSilhouette.Flush;
begin
FVertices.Flush;
FIndices.Flush;
FCapIndices.Flush;
end;
// Clear
//
procedure TGLSilhouette.Clear;
begin
FVertices.Clear;
FIndices.Clear;
FCapIndices.Clear;
end;
// ExtrudeVerticesToInfinity
//
procedure TGLSilhouette.ExtrudeVerticesToInfinity(const origin : TAffineVector);
var
i, nv, ni, nc, k : Integer;
vList, vListN : PVectorArray;
iList, iList2 : PIntegerArray;
begin
// extrude vertices
nv:=Vertices.Count;
Vertices.Count:=2*nv;
vList:=Vertices.List;
vListN:=@vList[nv];
for i:=0 to nv-1 do begin
vListN^[i].V[3]:=0;
VectorSubtract(PAffineVector(@vList[i])^, origin, PAffineVector(@vListN[i])^);
end;
// change silhouette indices to quad indices
ni:=Indices.Count;
Indices.Count:=2*ni;
iList:=Indices.List;
i:=ni-2; while i>=0 do begin
iList2:=@iList^[2*i];
iList2^[0]:=iList^[i];
iList2^[1]:=iList^[i+1];
iList2^[2]:=iList^[i+1]+nv;
iList2^[3]:=iList^[i]+nv;
Dec(i, 2);
end;
// add extruded triangles to capIndices
nc:=CapIndices.Count;
CapIndices.Capacity:=2*nc;
iList:=CapIndices.List;
for i:=nc-1 downto 0 do begin
k:=iList^[i];
CapIndices.Add(k);
iList^[i]:=k+nv;
end;
end;
// ------------------
// ------------------ TGLSilhouette ------------------
// ------------------
// AddEdgeToSilhouette
//
procedure TGLSilhouette.AddEdgeToSilhouette(const v0, v1 : TAffineVector;
tightButSlow : Boolean);
begin
if tightButSlow then
Indices.Add(Vertices.FindOrAddPoint(v0),
Vertices.FindOrAddPoint(v1))
else Indices.Add(Vertices.Add(v0, 1),
Vertices.Add(v1, 1));
end;
// AddIndexedEdgeToSilhouette
//
procedure TGLSilhouette.AddIndexedEdgeToSilhouette(const Vi0, Vi1 : integer);
begin
Indices.Add(Vi0, Vi1);
end;
// AddCapToSilhouette
//
procedure TGLSilhouette.AddCapToSilhouette(const v0, v1, v2 : TAffineVector;
tightButSlow : Boolean);
begin
if tightButSlow then
CapIndices.Add(Vertices.FindOrAddPoint(v0),
Vertices.FindOrAddPoint(v1),
Vertices.FindOrAddPoint(v2))
else CapIndices.Add(Vertices.Add(v0, 1),
Vertices.Add(v1, 1),
Vertices.Add(v2, 1));
end;
// AddIndexedCapToSilhouette
//
procedure TGLSilhouette.AddIndexedCapToSilhouette(const vi0, vi1, vi2 : Integer);
begin
CapIndices.Add(vi0, vi1, vi2);
end;
// ------------------
// ------------------ TBaseConnectivity ------------------
// ------------------
{ TBaseConnectivity }
constructor TBaseConnectivity.Create(APrecomputeFaceNormal: boolean);
begin
FPrecomputeFaceNormal := APrecomputeFaceNormal;
end;
procedure TBaseConnectivity.CreateSilhouette(const ASilhouetteParameters : TGLSilhouetteParameters; var ASilhouette : TGLSilhouette; AddToSilhouette : boolean);
begin
// Purely virtual!
end;
// ------------------
// ------------------ TConnectivity ------------------
// ------------------
function TBaseConnectivity.GetEdgeCount: integer;
begin
result := 0;
end;
function TBaseConnectivity.GetFaceCount: integer;
begin
result := 0;
end;
{ TConnectivity }
constructor TConnectivity.Create(APrecomputeFaceNormal : boolean);
begin
FFaceVisible := TByteList.Create;
FFaceVertexIndex := TIntegerList.Create;
FFaceNormal := TAffineVectorList.Create;
FEdgeVertices := TIntegerList.Create;
FEdgeFaces := TIntegerList.Create;
FPrecomputeFaceNormal := APrecomputeFaceNormal;
FVertexMemory := TIntegerList.Create;
FVertices := TAffineVectorList.Create;
end;
destructor TConnectivity.Destroy;
begin
Clear;
FFaceVisible.Free;
FFaceVertexIndex.Free;
FFaceNormal.Free;
FEdgeVertices.Free;
FEdgeFaces.Free;
FVertexMemory.Free;
if Assigned(FVertices) then
FVertices.Free;
inherited;
end;
procedure TConnectivity.Clear;
begin
FEdgeVertices.Clear;
FEdgeFaces.Clear;
FFaceVisible.Clear;
FFaceVertexIndex.Clear;
FFaceNormal.Clear;
FVertexMemory.Clear;
if FVertices<>nil then
FVertices.Clear;
end;
// CreateSilhouette
//
procedure TConnectivity.CreateSilhouette(
const silhouetteParameters : TGLSilhouetteParameters;
var aSilhouette : TGLSilhouette; addToSilhouette : boolean);
var
i : Integer;
vis : PIntegerArray;
tVi0, tVi1 : Integer;
faceNormal : TAffineVector;
face0ID, face1ID : Integer;
faceIsVisible : Boolean;
verticesList : PAffineVectorArray;
begin
if not Assigned(aSilhouette) then
aSilhouette:=TGLSilhouette.Create
else if not AddToSilhouette then
aSilhouette.Flush;
// Clear the vertex memory
FVertexMemory.Flush;
// Update visibility information for all Faces
vis:=FFaceVertexIndex.List;
for i:=0 to FaceCount-1 do begin
if FPrecomputeFaceNormal then
faceIsVisible:=(PointProject(silhouetteParameters.SeenFrom,
FVertices.List^[vis^[0]],
FFaceNormal.List^[i])
>=0)
else begin
verticesList:=FVertices.List;
faceNormal:=CalcPlaneNormal(verticesList^[vis^[0]],
verticesList^[vis^[1]],
verticesList^[vis^[2]]);
faceIsVisible:=(PointProject(silhouetteParameters.SeenFrom,
FVertices.List^[vis^[0]], faceNormal)
>=0);
end;
FFaceVisible[i]:=Byte(faceIsVisible);
if (not faceIsVisible) and silhouetteParameters.CappingRequired then
aSilhouette.CapIndices.Add(ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[0]),
ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[1]),
ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[2]));
vis:=@vis[3];
end;
for i:=0 to EdgeCount-1 do begin
face0ID:=FEdgeFaces[i*2+0];
face1ID:=FEdgeFaces[i*2+1];
if (face1ID=-1) or (FFaceVisible.List^[face0ID]<>FFaceVisible.List^[face1ID]) then begin
// Retrieve the two vertice values add add them to the Silhouette list
vis:=@FEdgeVertices.List[i*2];
// In this moment, we _know_ what vertex id the vertex had in the old
// mesh. We can remember this information and re-use it for a speedup
if FFaceVisible.List^[Face0ID]=0 then begin
tVi0 := ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[0]);
tVi1 := ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[1]);
aSilhouette.Indices.Add(tVi0, tVi1);
end else if Face1ID>-1 then begin
tVi0 := ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[0]);
tVi1 := ReuseOrFindVertexID(silhouetteParameters.SeenFrom, aSilhouette, vis^[1]);
aSilhouette.Indices.Add(tVi1, tVi0);
end;
end;
end;
end;
function TConnectivity.GetEdgeCount: integer;
begin
result := FEdgeVertices.Count div 2;
end;
function TConnectivity.GetFaceCount: integer;
begin
result := FFaceVisible.Count;
end;
// ReuseOrFindVertexID
//
function TConnectivity.ReuseOrFindVertexID(
const seenFrom : TAffineVector; aSilhouette : TGLSilhouette; index : Integer) : Integer;
var
pMemIndex : PInteger;
memIndex, i : Integer;
oldCount : Integer;
list : PIntegerArray;
begin
if index>=FVertexMemory.Count then begin
oldCount:=FVertexMemory.Count;
FVertexMemory.Count:=index+1;
list:=FVertexMemory.List;
for i:=OldCount to FVertexMemory.Count-1 do
list^[i]:=-1;
end;
pMemIndex:=@FVertexMemory.List[index];
if pMemIndex^=-1 then begin
// Add the "near" vertex
memIndex:=aSilhouette.Vertices.Add(FVertices.List^[index], 1);
pMemIndex^:=memIndex;
Result:=memIndex;
end else Result:=pMemIndex^;
end;
// AddIndexedEdge
//
function TConnectivity.AddIndexedEdge(
vertexIndex0, vertexIndex1 : Integer; faceID : Integer) : Integer;
var
i : Integer;
edgesVertices : PIntegerArray;
begin
// Make sure that the edge doesn't already exists
edgesVertices:=FEdgeVertices.List;
for i:=0 to EdgeCount-1 do begin
// Retrieve the two vertices in the edge
if ((edgesVertices^[0]=vertexIndex0) and (edgesVertices^[1]=vertexIndex1))
or ((edgesVertices^[0]=vertexIndex1) and (edgesVertices^[1]=vertexIndex0)) then begin
// Update the second Face of the edge and we're done (this _MAY_
// overwrite a previous Face in a broken mesh)
FEdgeFaces[i*2+1]:=faceID;
Result:=i*2+1;
Exit;
end;
edgesVertices:=@edgesVertices[2];
end;
// No edge was found, create a new one
FEdgeVertices.Add(vertexIndex0, vertexIndex1);
FEdgeFaces.Add(faceID, -1);
Result:=EdgeCount-1;
end;
// AddIndexedFace
//
function TConnectivity.AddIndexedFace(vi0, vi1, vi2 : Integer) : Integer;
var
faceID : integer;
begin
FFaceVertexIndex.Add(vi0, vi1, vi2);
if FPrecomputeFaceNormal then
FFaceNormal.Add(CalcPlaneNormal(FVertices.List^[Vi0],
FVertices.List^[Vi1],
FVertices.List^[Vi2]));
faceID:=FFaceVisible.Add(0);
AddIndexedEdge(vi0, vi1, faceID);
AddIndexedEdge(vi1, vi2, faceID);
AddIndexedEdge(vi2, vi0, faceID);
result:=faceID;
end;
function TConnectivity.AddFace(const Vertex0, Vertex1, Vertex2: TAffineVector) : integer;
var
Vi0, Vi1, Vi2 : integer;
begin
Vi0 := FVertices.FindOrAdd(Vertex0);
Vi1 := FVertices.FindOrAdd(Vertex1);
Vi2 := FVertices.FindOrAdd(Vertex2);
result := AddIndexedFace(Vi0, Vi1, Vi2);
end;
function TConnectivity.AddQuad(const Vertex0, Vertex1, Vertex2,
Vertex3: TAffineVector): integer;
var
Vi0, Vi1, Vi2, Vi3 : integer;
begin
Vi0 := FVertices.FindOrAdd(Vertex0);
Vi1 := FVertices.FindOrAdd(Vertex1);
Vi2 := FVertices.FindOrAdd(Vertex2);
Vi3 := FVertices.FindOrAdd(Vertex3);
// First face
result := AddIndexedFace(Vi0, Vi1, Vi2);
// Second face
AddIndexedFace(Vi2, Vi3, Vi0);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzDlgBlock;
interface
uses Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.StdCtrls, System.SysUtils;
type
TAzBlock = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
lblBlockId: TLabeledEdit;
lblMD5: TLabeledEdit;
lblLeaseId: TLabeledEdit;
lblLocation: TLabeledEdit;
btnFile: TButton;
procedure btnFileClick(Sender: TObject);
private
{ Private declarations }
function GetBlockId: String;
procedure SetBlockId(const Data: String);
function GetLeaseId: String;
procedure SetLeaseId(const Id: String);
function GetMD5: String;
procedure SetMD5(const Val: String);
function GetLocation: String;
procedure SetLocation(const Data: String);
public
{ Public declarations }
function Content: TBytes;
property BlockId: String read GetBlockId write SetBlockId;
property Location: String read GetLocation write SetLocation;
property MD5: String read GetMD5 write SetMD5;
property LeaseId: String read GetLeaseId write SetLeaseId;
end;
implementation
uses Data.DBXClientResStrs, Vcl.Dialogs, DSAzure;
{$R *.dfm}
procedure TAzBlock.btnFileClick(Sender: TObject);
var
foDlg: TOpenDialog;
fs: TFileStream;
begin
foDlg := TOpenDialog.Create(self);
if foDlg.Execute(Handle) then
begin
fs := TFileStream.Create(foDlg.FileName, fmOpenRead);
try
if fs.Size >= 4*1024*1024 then
MessageDlg(SMaxSizeBlock, mtError, [mbOK], 0)
else
lblLocation.Text := foDlg.FileName;
finally
fs.Free;
end;
end;
foDlg.Free;
end;
function TAzBlock.Content: TBytes;
var
fs: TFileStream;
begin
if Length(lblLocation.Text) > 0 then
begin
fs := TFileStream.Create(lblLocation.Text, fmOpenRead);
try
SetLength(Result, fs.Size);
fs.ReadBuffer(Result[0], fs.Size);
finally
fs.Free;
end
end;
end;
function TAzBlock.GetBlockId: String;
begin
Result := TAzureService.Encode(lblBlockId.Text);
end;
function TAzBlock.GetLeaseId: String;
begin
Result := lblLeaseId.Text;
end;
function TAzBlock.GetLocation: String;
begin
Result := lblLocation.Text;
end;
function TAzBlock.GetMD5: String;
begin
Result := lblMD5.Text;
end;
procedure TAzBlock.SetBlockId(const Data: String);
begin
lblBlockId.Text := TAzureService.Decode(Data);
end;
procedure TAzBlock.SetLeaseId(const Id: String);
begin
lblLeaseId.Text := Id;
end;
procedure TAzBlock.SetLocation(const Data: String);
begin
lblLocation.Text := Data;
end;
procedure TAzBlock.SetMD5(const Val: String);
begin
lblMD5.Text := Val;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ColorBox,
Spin, ExtCtrls, switches, indSliders;
type
{ TForm1 }
TForm1 = class(TForm)
cbSliderColor: TColorButton;
cbVertical: TCheckBox;
cbAutoRotate: TCheckBox;
cbColorBelow: TColorButton;
cbColorBetween: TColorButton;
cbColorAbove: TColorButton;
cbFlat: TCheckBox;
cbEnabled: TCheckBox;
cbTransparent: TCheckBox;
cbFormColor: TColorButton;
cmbThumbStyle: TComboBox;
cbColorThumb: TColorButton;
cmbSliderMode: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
seTrackThickness: TSpinEdit;
seDefaultSize: TSpinEdit;
procedure cbAutoRotateChange(Sender: TObject);
procedure cbColorAboveColorChanged(Sender: TObject);
procedure cbColorBelowColorChanged(Sender: TObject);
procedure cbColorBetweenColorChanged(Sender: TObject);
procedure cbColorThumbColorChanged(Sender: TObject);
procedure cbEnabledChange(Sender: TObject);
procedure cbFlatChange(Sender: TObject);
procedure cbSliderColorColorChanged(Sender: TObject);
procedure cmbSliderModeChange(Sender: TObject);
procedure cmbThumbStyleChange(Sender: TObject);
procedure cbTransparentChange(Sender: TObject);
procedure cbVerticalChange(Sender: TObject);
procedure cbFormColorColorChanged(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure seDefaultSizeChange(Sender: TObject);
procedure seTrackThicknessChange(Sender: TObject);
private
slider: TMultiSlider;
procedure PositionChangeHandler(Sender: TObject; AKind: TThumbKind; AValue: Integer);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
slider := TMultiSlider.Create(self);
slider.Parent := self;
slider.Align := alTop;
slider.BorderSpacing.Around := 8;
// slider.Left := 8;
// slider.Top := 8;
slider.Vertical := false;
slider.OnPositionChange := @PositionChangeHandler;
cbColorBelow.ButtonColor := slider.ColorBelow;
cbColorAbove.ButtonColor := slider.ColorAbove;
cbColorBetween.ButtonColor := slider.ColorBetween;
cbColorThumb.ButtonColor := slider.ColorThumb;
cbSliderColor.ButtonColor := slider.Color;
cbFormColor.ButtonColor := Color;
cbTransparent.Checked := slider.Color = clNone;
seTrackThickness.Value := slider.TrackThickness;
seDefaultSize.Value := slider.DefaultSize;
cmbSliderMode.ItemIndex := ord(slider.SliderMode);
end;
procedure TForm1.seDefaultSizeChange(Sender: TObject);
begin
slider.DefaultSize := seDefaultSize.Value;
end;
procedure TForm1.seTrackThicknessChange(Sender: TObject);
begin
slider.TrackThickness := seTrackThickness.Value;
end;
procedure TForm1.cbVerticalChange(Sender: TObject);
begin
slider.Vertical := cbVertical.Checked;
if slider.Vertical then slider.Align := alLeft else slider.Align := alTop;
end;
procedure TForm1.cbFormColorColorChanged(Sender: TObject);
begin
Color := cbFormColor.ButtonColor;
end;
procedure TForm1.cbColorThumbColorChanged(Sender: TObject);
begin
slider.ColorThumb := cbColorThumb.ButtonColor;
end;
procedure TForm1.cbAutoRotateChange(Sender: TObject);
begin
slider.AutoRotate := cbAutoRotate.Checked;
end;
procedure TForm1.cbColorAboveColorChanged(Sender: TObject);
begin
slider.ColorAbove := cbColorAbove.ButtonColor;
end;
procedure TForm1.cbColorBelowColorChanged(Sender: TObject);
begin
slider.ColorBelow := cbColorBelow.ButtonColor;
end;
procedure TForm1.cbColorBetweenColorChanged(Sender: TObject);
begin
slider.ColorBetween := cbColorBetween.ButtonColor;
end;
procedure TForm1.cbSliderColorColorChanged(Sender: TObject);
begin
slider.Color := cbSliderColor.ButtonColor;
end;
procedure TForm1.cmbSliderModeChange(Sender: TObject);
begin
slider.SliderMode := TSliderMode(cmbSliderMode.ItemIndex);
end;
procedure TForm1.cbEnabledChange(Sender: TObject);
begin
slider.Enabled := cbEnabled.Checked;
end;
procedure TForm1.cbFlatChange(Sender: TObject);
begin
slider.Flat := cbFlat.Checked;
end;
procedure TForm1.cmbThumbStyleChange(Sender: TObject);
begin
slider.ThumbStyle := TThumbStyle(cmbThumbStyle.ItemIndex);
end;
procedure TForm1.cbTransparentChange(Sender: TObject);
begin
if cbTransparent.Checked then
slider.Color := clNone;
end;
procedure TForm1.PositionChangeHandler(Sender: TObject; AKind: TThumbKind;
AValue: Integer);
begin
case AKind of
tkMin: Label1.Caption := 'Min = ' + intToStr(AValue);
tkValue: Label2.Caption := 'Value = ' + IntToStr(AValue);
tkMax: Label3.Caption := 'Max = ' + IntToStr(AValue);
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTree<p>
Dynamic tree generation in GLScene<p>
This code was adapted from the nVidia Tree Demo:
http://developer.nvidia.com/object/Procedural_Tree.html<p>
History:<ul>
<li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>13/01/07 - DaStr - Added changes proposed by Tim "Sivael" Kapuściński [sivael@gensys.pl]
Modified the code to create much more realistic trees -
added third branch for every node and modified constants
to make the tree look more "alive".
Also removed the "fractal effect" that ocurred, when
rendering with the older engine - the leaves and
branches were much more "in order".
Added Center* declarations, CenterBranchConstant,
Added AutoRebuild flag.
<li>02/08/04 - LR, YHC - BCB corrections: use record instead array
<li>14/04/04 - SG - Added AutoCenter property.
<li>03/03/04 - SG - Added GetExtents and AxisAlignedDimensionsUnscaled.
<li>24/11/03 - SG - Creation.
</ul>
Some info:
<ul>CenterBranchConstant</ul> -
Defines, how big the central branch is. When around 50%
it makes a small branch inside the tree, for higher values
much more branches and leaves are created, so either use it
with low depth, or set it to zero, and have two-branched tree.
Default : 0.5
<ul>"AutoRebuild" flag</ul> -
Rebuild tree after property change.
Default: True
}
unit GLTree;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils, System.Math,
//GLS
GLScene, GLMaterial, GLVectorGeometry, GLVectorLists,
OpenGLTokens, GLVectorFileObjects, GLApplicationFileIO, GLRenderContextInfo,
XOpenGL, GLContext, GLVectorTypes;
type
TGLTree = class;
TGLTreeBranches = class;
TGLTreeBranchNoise = class;
// TGLTreeLeaves
//
TGLTreeLeaves = class
private
{ Private Declarations }
FOwner : TGLTree;
FCount : Integer;
FVertices : TAffineVectorList;
FNormals : TAffineVectorList;
FTexCoords : TAffineVectorList;
public
{ Public Declarations }
constructor Create(AOwner : TGLTree);
destructor Destroy; override;
procedure BuildList(var rci : TRenderContextInfo);
procedure AddNew(matrix : TMatrix);
procedure Clear;
property Owner : TGLTree read FOwner;
property Count : Integer read FCount;
property Vertices : TAffineVectorList read FVertices;
property Normals : TAffineVectorList read FNormals;
property TexCoords : TAffineVectorList read FTexCoords;
end;
// TGLTreeBranch
//
TGLTreeBranch = class
private
{ Private Declarations }
FOwner : TGLTreeBranches;
FLeft : TGLTreeBranch;
FCenter : TGLTreeBranch;
FRight : TGLTreeBranch;
FParent : TGLTreeBranch;
FBranchID : Integer;
FParentID : Integer;
FMatrix : TMatrix;
FLower : TIntegerList;
FUpper : TIntegerList;
FCentralLeader : Boolean;
procedure BuildBranch(branchNoise : TGLTreeBranchNoise; const Matrix : TMatrix;
TexCoordY, Twist : Single; Level : Integer);
public
{ Public Declarations }
constructor Create(AOwner : TGLTreeBranches; AParent : TGLTreeBranch);
destructor Destroy; override;
property Owner : TGLTreeBranches read FOwner;
property Left : TGLTreeBranch read FLeft;
property Center : TGLTreeBranch read FCenter;
property Right : TGLTreeBranch read FRight;
property Parent : TGLTreeBranch read FParent;
property Matrix : TMatrix read FMatrix;
property Lower : TIntegerList read FLower;
property Upper : TIntegerList read FUpper;
end;
// TGLTreeBranches
//
TGLTreeBranches = class
private
{ Private Declarations }
FOwner : TGLTree;
FSinList : TSingleList;
FCosList : TSingleList;
FVertices : TAffineVectorList;
FNormals : TAffineVectorList;
FTexCoords : TAffineVectorList;
FIndices : TIntegerList;
FRoot : TGLTreeBranch;
FCount : Integer;
FBranchCache : TList;
FBranchIndices : TIntegerList;
procedure BuildBranches;
public
{ Public Declarations }
constructor Create(AOwner : TGLTree);
destructor Destroy; override;
procedure BuildList(var rci : TRenderContextInfo);
procedure Clear;
property Owner : TGLTree read FOwner;
property SinList : TSingleList read FSinList;
property CosList : TSingleList read FCosList;
property Vertices : TAffineVectorList read FVertices;
property Normals : TAffineVectorList read FNormals;
property TexCoords : TAffineVectorList read FTexCoords;
property Count : Integer read FCount;
end;
// TGLTreeBranchNoise
//
TGLTreeBranchNoise = class
private
{ Private Declarations }
FBranchNoise : Single;
FLeft, FRight, FCenter : TGLTreeBranchNoise;
function GetLeft : TGLTreeBranchNoise;
function GetCenter : TGLTreeBranchNoise;
function GetRight : TGLTreeBranchNoise;
public
{ Public Declarations }
constructor Create;
destructor Destroy; override;
property Left : TGLTreeBranchNoise read GetLeft;
property Center : TGLTreeBranchNoise read GetCenter;
property Right : TGLTreeBranchNoise read GetRight;
property BranchNoise : Single read FBranchNoise;
end;
// TGLTree
//
TGLTree = class (TGLImmaterialSceneObject)
private
{ Private Declarations }
FDepth : Integer;
FBranchFacets : Integer;
FLeafSize : Single;
FBranchSize : Single;
FBranchNoise : Single;
FBranchAngleBias : Single;
FBranchAngle : Single;
FBranchTwist : Single;
FBranchRadius : Single;
FLeafThreshold : Single;
FCentralLeaderBias : Single;
FCentralLeader : Boolean;
FSeed : Integer;
FAutoCenter : Boolean;
FAutoRebuild : Boolean;
FCenterBranchConstant : Single;
FLeaves : TGLTreeLeaves;
FBranches : TGLTreeBranches;
FNoise : TGLTreeBranchNoise;
FMaterialLibrary : TGLMaterialLibrary;
FLeafMaterialName : TGLLibMaterialName;
FLeafBackMaterialName : TGLLibMaterialName;
FBranchMaterialName : TGLLibMaterialName;
FRebuildTree : Boolean;
FAxisAlignedDimensionsCache : TVector;
protected
{ Protected Declarations }
procedure SetDepth(const Value : Integer);
procedure SetBranchFacets(const Value : Integer);
procedure SetLeafSize(const Value : Single);
procedure SetBranchSize(const Value : Single);
procedure SetBranchNoise(const Value : Single);
procedure SetBranchAngleBias(const Value : Single);
procedure SetBranchAngle(const Value : Single);
procedure SetBranchTwist(const Value : Single);
procedure SetBranchRadius(const Value : Single);
procedure SetLeafThreshold(const Value : Single);
procedure SetCentralLeaderBias(const Value : Single);
procedure SetCentralLeader(const Value : Boolean);
procedure SetSeed(const Value : Integer);
procedure SetAutoCenter(const Value : Boolean);
procedure SetAutoRebuild(const Value : Boolean);
procedure SetCenterBranchConstant(const Value : Single);
procedure SetMaterialLibrary(const Value : TGLMaterialLibrary);
procedure SetLeafMaterialName(const Value : TGLLibMaterialName);
procedure SetLeafBackMaterialName(const Value : TGLLibMaterialName);
procedure SetBranchMaterialName(const Value : TGLLibMaterialName);
procedure Loaded; override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoRender(var ARci : TRenderContextInfo;
ARenderSelf, ARenderChildren : Boolean); override;
procedure BuildList(var rci : TRenderContextInfo); override;
procedure StructureChanged; override;
procedure BuildMesh(GLBaseMesh : TGLBaseMesh);
procedure RebuildTree;
procedure ForceTotalRebuild;
procedure Clear;
procedure GetExtents(var min, max : TAffineVector);
function AxisAlignedDimensionsUnscaled : TVector; override;
procedure LoadFromStream(aStream : TStream);
procedure SaveToStream(aStream : TStream);
procedure LoadFromFile(aFileName : String);
procedure SaveToFile(aFileName : String);
property Leaves : TGLTreeLeaves read FLeaves;
property Branches : TGLTreeBranches read FBranches;
property Noise : TGLTreeBranchNoise read FNoise;
published
{ Published Declarations }
{: The depth of tree branch recursion. }
property Depth : Integer read FDepth write SetDepth;
{: The number of facets for each branch in the tree. }
property BranchFacets : Integer read FBranchFacets write SetBranchFacets;
{: Leaf size modifier. Leaf size is also influenced by branch recursion
scale. }
property LeafSize : Single read FLeafSize write SetLeafSize;
{: Branch length modifier. }
property BranchSize : Single read FBranchSize write SetBranchSize;
{: Overall branch noise influence. Relates to the 'fullness' of the tree. }
property BranchNoise : Single read FBranchNoise write SetBranchNoise;
{: Effects the habit of the tree. Values from 0 to 1 refer to Upright to
Spreading respectively. }
property BranchAngleBias : Single read FBranchAngleBias write SetBranchAngleBias;
{: Effects the balance of the tree. }
property BranchAngle : Single read FBranchAngle write SetBranchAngle;
{: Effects the rotation of each sub branch in recursion. }
property BranchTwist : Single read FBranchTwist write SetBranchTwist;
{: Effects the thickness of the branches. }
property BranchRadius : Single read FBranchRadius write SetBranchRadius;
{: Determines how thin a branch can get before a leaf is substituted. }
property LeafThreshold : Single read FLeafThreshold write SetLeafThreshold;
{: Determines how BranchAngle effects the central leader (CentralLeader must = True). }
property CentralLeaderBias : Single read FCentralLeaderBias write SetCentralLeaderBias;
{: Does this tree have a central leader? }
property CentralLeader : Boolean read FCentralLeader write SetCentralLeader;
property Seed : Integer read FSeed write SetSeed;
{: Automatically center the tree's vertices after building them. }
property AutoCenter : Boolean read FAutoCenter write SetAutoCenter;
{: Automatically rebuild the tree after changing the settings }
property AutoRebuild : Boolean read FAutoRebuild write SetAutoRebuild;
{: Central branch can be thinner(lower values)/thicker(->1) depending on this constant.
The effect also depends on the BranchAngle variable. }
property CenterBranchConstant : Single read FCenterBranchConstant write SetCenterBranchConstant;
property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
property LeafMaterialName : TGLLibMaterialName read FLeafMaterialName write SetLeafMaterialName;
property LeafBackMaterialName : TGLLibMaterialName read FLeafBackMaterialName write SetLeafBackMaterialName;
property BranchMaterialName : TGLLibMaterialName read FBranchMaterialName write SetBranchMaterialName;
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
implementation
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// TGLTreeLeaves
// -----------------------------------------------------------------------------
// Create
//
constructor TGLTreeLeaves.Create(AOwner: TGLTree);
begin
FOwner:=AOwner;
FCount:=0;
FVertices:=TAffineVectorList.Create;
FNormals:=TAffineVectorList.Create;
FTexCoords:=TAffineVectorList.Create;
end;
// Destroy
//
destructor TGLTreeLeaves.Destroy;
begin
FVertices.Free;
FNormals.Free;
FTexCoords.Free;
inherited;
end;
// AddNew
//
procedure TGLTreeLeaves.AddNew(matrix : TMatrix);
var
radius : Single;
pos : TVector;
begin
radius:=Owner.LeafSize;
Inc(FCount);
pos:=matrix.V[3];
Matrix.V[3]:=NullHMGPoint;
Matrix:=Roll(matrix, FCount/10);
NormalizeMatrix(matrix);
Matrix.V[3]:=pos;
FVertices.Add(VectorTransform(PointMake(0, -radius, 0), matrix));
FVertices.Add(VectorTransform(PointMake(0, radius, 0), matrix));
FVertices.Add(VectorTransform(PointMake(0, radius, 2*radius), matrix));
FVertices.Add(VectorTransform(PointMake(0, -radius, 2*radius), matrix));
FNormals.Add(VectorTransform(XHmgVector, matrix));
FTexCoords.Add(XVector, NullVector);
FTexCoords.Add(YVector, XYVector);
end;
// BuildList
//
procedure TGLTreeLeaves.BuildList(var rci: TRenderContextInfo);
var
i : integer;
n : TAffineVector;
libMat : TGLLibMaterial;
begin
libMat:=Owner.MaterialLibrary.LibMaterialByName(Owner.LeafMaterialName);
if Assigned(libMat) then
libMat.Apply(rci);
GL.EnableClientState(GL_VERTEX_ARRAY);
xgl.EnableClientState(GL_TEXTURE_COORD_ARRAY);
GL.VertexPointer(3, GL_FLOAT, 0, @FVertices.List[0]);
xgl.TexCoordPointer(3, GL_FLOAT, 0, @FTexCoords.List[0]);
for i:=0 to (FVertices.Count div 4)-1 do begin
GL.Normal3fv(@FNormals.List[i]);
GL.DrawArrays(GL_QUADS, 4*i, 4);
end;
with Owner do if LeafMaterialName<>LeafBackMaterialName then begin
if Assigned(libMat) then
libMat.UnApply(rci);
libMat:=MaterialLibrary.LibMaterialByName(LeafBackMaterialName);
if Assigned(libMat) then
libMat.Apply(rci);
end;
rci.GLStates.InvertGLFrontFace;
for i:=0 to (FVertices.Count div 4)-1 do begin
n:=VectorNegate(FNormals[i]);
GL.Normal3fv(@n);
GL.DrawArrays(GL_QUADS, 4*i, 4);
end;
rci.GLStates.InvertGLFrontFace;
GL.DisableClientState(GL_VERTEX_ARRAY);
xgl.DisableClientState(GL_TEXTURE_COORD_ARRAY);
if Assigned(libMat) then
libMat.UnApply(rci);
end;
// Clear
//
procedure TGLTreeLeaves.Clear;
begin
FVertices.Clear;
FNormals.Clear;
FTexCoords.Clear;
FCount:=0;
end;
// -----------------------------------------------------------------------------
// TGLTreeBranch
// -----------------------------------------------------------------------------
// Create
//
constructor TGLTreeBranch.Create(AOwner : TGLTreeBranches; AParent : TGLTreeBranch);
begin
FOwner:=AOwner;
FParent:=AParent;
FUpper:=TIntegerList.Create;
FLower:=TIntegerList.Create;
FCentralLeader:=False;
// Skeletal construction helpers
if Assigned(FOwner) then begin
FBranchID:=FOwner.Count-1;
FOwner.FBranchCache.Add(Self);
end else FBranchID:=-1;
if Assigned(FParent) then
FParentID:=FParent.FBranchID
else FParentID:=-1;
end;
// Destroy
//
destructor TGLTreeBranch.Destroy;
begin
FUpper.Free;
FLower.Free;
FLeft.Free;
FRight.Free;
inherited;
end;
// BuildBranch
//
procedure TGLTreeBranch.BuildBranch(branchNoise : TGLTreeBranchNoise; const Matrix : TMatrix;
TexCoordY, Twist : Single; Level : Integer);
var
i : Integer;
Tree : TGLTree;
Branches : TGLTreeBranches;
Facets : Integer;
t,c,s : Single;
Radius, LeftRadius, RightRadius, CenterRadius : Single;
BranchAngle, LeftAngle, RightAngle, CenterAngle : Single;
BranchAngleBias, BranchTwist, Taper : Single;
LeftBranchNoiseValue, RightBranchNoiseValue, CenterBranchNoiseValue : Single;
LeftBranchNoise : TGLTreeBranchNoise;
CenterBranchNoise : TGLTreeBranchNoise;
RightBranchNoise : TGLTreeBranchNoise;
LeftMatrix, RightMatrix, CenterMatrix : TMatrix;
central_leader : Boolean;
begin
Assert(Assigned(FOwner),'Incorrect use of TGLTreeBranch');
Assert(Assigned(FOwner.FOwner),'Incorrect use of TGLTreeBranches');
FMatrix:=Matrix;
Branches:=FOwner;
Tree:=FOwner.FOwner;
Facets:=Tree.BranchFacets;
Radius:=Tree.BranchRadius;
FLower.Clear;
FLower.Capacity:=Facets+1;
FUpper.Clear;
FUpper.Capacity:=Facets+1;
BranchAngle:=Tree.BranchAngle;
BranchAngleBias:=Tree.BranchAngleBias;
BranchTwist:=Twist+Tree.BranchTwist;
LeftBranchNoise:=BranchNoise.Left;
CenterBranchNoise:=BranchNoise.Center;
RightBranchNoise:=BranchNoise.Right;
LeftBranchNoiseValue:=((LeftBranchNoise.BranchNoise*0.4)-0.1)*Tree.BranchNoise;
LeftRadius:=Sqrt(1-BranchAngle+LeftBranchNoiseValue);
LeftRadius:=ClampValue(LeftRadius,0,1);
LeftAngle:=BranchAngle*90*BranchAngleBias+10*LeftBranchNoiseValue;
CenterBranchNoiseValue:=((CenterBranchNoise.BranchNoise*0.9)-0.1)*Tree.BranchNoise;
CenterRadius:=Sqrt(Tree.CenterBranchConstant-BranchAngle+CenterBranchNoiseValue);
CenterRadius:=ClampValue(CenterRadius,0,1);
CenterAngle:=(1-BranchAngle)*50*CenterBranchNoiseValue*BranchAngleBias;
RightBranchNoiseValue:=((RightBranchNoise.BranchNoise*0.6)-0.1)*Tree.BranchNoise;
RightRadius:=Sqrt(BranchAngle+RightBranchNoiseValue);
RightRadius:=ClampValue(RightRadius,0,1);
RightAngle:=(1-BranchAngle)*-90*BranchAngleBias+10*RightBranchNoiseValue;
Taper:=MaxFloat(LeftRadius, RightRadius, CenterRadius);
// Build cylinder lower
for i:=0 to Facets do begin
t:=1/Facets*i;
c:=Branches.CosList[i];
s:=Branches.SinList[i];
Branches.Vertices.Add(VectorTransform(PointMake(c*Radius,s*Radius,Radius),Matrix));
Branches.Normals.Add(VectorTransform(VectorMake(c,s,0),Matrix));
Branches.TexCoords.Add(t,TexCoordY);
FLower.Add(Branches.Vertices.Count-1);
Branches.FBranchIndices.Add(FBranchID);
end;
TexCoordY:=TexCoordY+1-2*Radius;
// Build cylinder upper
for i:=0 to Facets do begin
t:=1/Facets*i;
c:=Branches.CosList[i];
s:=Branches.SinList[i];
Branches.Vertices.Add(VectorTransform(PointMake(c*Radius*Taper,s*Radius*Taper,1-Radius),Matrix));
Branches.Normals.Add(VectorTransform(VectorMake(c,s,0),Matrix));
Branches.TexCoords.Add(t,TexCoordY);
FUpper.Add(Branches.Vertices.Count-1);
Branches.FBranchIndices.Add(FBranchID);
end;
TexCoordY:=TexCoordY+2*Radius;
// BuildMatrices
SinCos(DegToRad(BranchTwist),s,c);
if Level=0 then
central_leader:=FCentralLeader
else
central_leader:=FParent.FCentralLeader;
if central_leader then begin
LeftMatrix:=MatrixMultiply(
CreateScaleMatrix(AffineVectorMake(LeftRadius,LeftRadius,LeftRadius)),
CreateRotationMatrix(AffineVectorMake(s,c,0),DegToRad(LeftAngle)*Tree.CentralLeaderBias));
end else begin
LeftMatrix:=MatrixMultiply(
CreateScaleMatrix(AffineVectorMake(LeftRadius,LeftRadius,LeftRadius)),
CreateRotationMatrix(AffineVectorMake(s,c,0),DegToRad(LeftAngle)));
end;
LeftMatrix:=MatrixMultiply(
LeftMatrix,
MatrixMultiply(CreateTranslationMatrix(AffineVectorMake(0,0,Tree.BranchSize*(1-LeftBranchNoiseValue))),Matrix));
CenterMatrix:=MatrixMultiply(
CreateScaleMatrix(AffineVectorMake(CenterRadius,CenterRadius,CenterRadius)),
CreateRotationMatrix(AffineVectorMake(s,c,0),DegToRad(CenterAngle)));
CenterMatrix:=MatrixMultiply(
CenterMatrix,
MatrixMultiply(CreateTranslationMatrix(AffineVectorMake(0,0,Tree.BranchSize*(1-CenterBranchNoiseValue))),Matrix));
RightMatrix:=MatrixMultiply(
CreateScaleMatrix(AffineVectorMake(RightRadius,RightRadius,RightRadius)),
CreateRotationMatrix(AffineVectorMake(s,c,0),DegToRad(RightAngle)));
RightMatrix:=MatrixMultiply(
RightMatrix,
MatrixMultiply(CreateTranslationMatrix(AffineVectorMake(0,0,Tree.BranchSize*(1-RightBranchNoiseValue))),Matrix));
if (((Level+1)>=Tree.Depth) or (LeftRadius<Tree.LeafThreshold)) then begin
Tree.Leaves.AddNew(LeftMatrix);
end else begin
Inc(Branches.FCount);
FLeft:=TGLTreeBranch.Create(Owner,Self);
FLeft.FCentralLeader:=central_leader and (LeftRadius>=RightRadius);
FLeft.BuildBranch(LeftBranchNoise,LeftMatrix,TexCoordY,BranchTwist,Level+1);
end;
if (((Level+1)>=Tree.Depth) or (CenterRadius<Tree.LeafThreshold)) then begin
Tree.Leaves.AddNew(CenterMatrix);
end else begin
Inc(Branches.FCount);
FCenter:=TGLTreeBranch.Create(Owner,Self);
FCenter.BuildBranch(CenterBranchNoise,CenterMatrix,TexCoordY,BranchTwist,Level+1);
end;
if (((Level+1)>=Tree.Depth) or (RightRadius<Tree.LeafThreshold)) then begin
Tree.Leaves.AddNew(RightMatrix);
end else begin
Inc(Branches.FCount);
FRight:=TGLTreeBranch.Create(Owner,Self);
FRight.BuildBranch(RightBranchNoise,RightMatrix,TexCoordY,BranchTwist,Level+1);
end;
for i:=0 to Facets do begin
Branches.FIndices.Add(Upper[i]);
Branches.FIndices.Add(Lower[i]);
end;
if Assigned(FRight) then begin
for i:=0 to Facets do begin
Branches.FIndices.Add(Right.Lower[i]);
Branches.FIndices.Add(Upper[i]);
end;
end;
if Assigned(FCenter) then begin
for i:=0 to Facets do begin
Branches.FIndices.Add(Center.Lower[i]);
Branches.FIndices.Add(Upper[i]);
end;
end;
if Assigned(FLeft) then begin
for i:=0 to Facets do begin
Branches.FIndices.Add(Left.Lower[i]);
Branches.FIndices.Add(Upper[i]);
end;
end;
end;
// -----------------------------------------------------------------------------
// TGLTreeBranches
// -----------------------------------------------------------------------------
// Create
//
constructor TGLTreeBranches.Create(AOwner: TGLTree);
begin
FOwner:=AOwner;
FSinList:=TSingleList.Create;
FCosList:=TSingleList.Create;
FVertices:=TAffineVectorList.Create;
FNormals:=TAffineVectorList.Create;
FTexCoords:=TAffineVectorList.Create;
FIndices:=TIntegerList.Create;
FBranchCache:=TList.Create;
FBranchIndices:=TIntegerList.Create;
FCount:=0;
end;
// Destroy
//
destructor TGLTreeBranches.Destroy;
begin
FSinList.Free;
FCosList.Free;
FVertices.Free;
FNormals.Free;
FTexCoords.Free;
FIndices.Free;
FRoot.Free;
FBranchCache.Free;
FBranchIndices.Free;
inherited;
end;
// BuildBranches
//
procedure TGLTreeBranches.BuildBranches;
var
i : Integer;
u : Single;
delta, min, max : TAffineVector;
begin
RandSeed:=Owner.FSeed;
for i:=0 to Owner.BranchFacets do begin
u:=1/Owner.BranchFacets*i;
SinList.Add(Sin(PI*2*u));
CosList.Add(Cos(PI*2*u));
end;
Inc(FCount);
FRoot:=TGLTreeBranch.Create(Self,nil);
FRoot.FCentralLeader:=Owner.CentralLeader;
FRoot.BuildBranch(Owner.Noise,IdentityHMGMatrix,0,0,0);
delta:=AffineVectorMake(0,0,-Owner.BranchRadius);
Vertices.Translate(delta);
Owner.Leaves.Vertices.Translate(delta);
if Owner.AutoCenter then begin
Owner.GetExtents(min, max);
delta:=VectorCombine(min,max,-0.5,-0.5);
Vertices.Translate(delta);
Owner.Leaves.Vertices.Translate(delta);
end;
Owner.FAxisAlignedDimensionsCache.V[0]:=-1;
end;
// BuildList
//
procedure TGLTreeBranches.BuildList(var rci: TRenderContextInfo);
var
i, stride : Integer;
libMat : TGLLibMaterial;
begin
stride:=(Owner.BranchFacets+1)*2;
libMat:=Owner.MaterialLibrary.LibMaterialByName(Owner.BranchMaterialName);
if Assigned(libMat) then
libMat.Apply(rci);
GL.VertexPointer(3, GL_FLOAT, 0, @FVertices.List[0]);
GL.NormalPointer(GL_FLOAT, 0, @FNormals.List[0]);
xgl.TexCoordPointer(3, GL_FLOAT, 0, @FTexCoords.List[0]);
GL.EnableClientState(GL_VERTEX_ARRAY);
GL.EnableClientState(GL_NORMAL_ARRAY);
xgl.EnableClientState(GL_TEXTURE_COORD_ARRAY);
repeat
for i:=0 to (FIndices.Count div stride)-1 do
GL.DrawElements(GL_TRIANGLE_STRIP, stride, GL_UNSIGNED_INT, @FIndices.List[stride*i]);
until (not Assigned(libMat)) or (not libMat.UnApply(rci));
xgl.DisableClientState(GL_TEXTURE_COORD_ARRAY);
GL.DisableClientState(GL_NORMAL_ARRAY);
GL.DisableClientState(GL_VERTEX_ARRAY);
end;
// Clear
//
procedure TGLTreeBranches.Clear;
begin
FSinList.Clear;
FCosList.Clear;
FVertices.Clear;
FNormals.Clear;
FTexCoords.Clear;
FIndices.Clear;
FBranchCache.Clear;
FBranchIndices.Clear;
FreeAndNil(FRoot);
FCount:=0;
end;
// -----------------------------------------------------------------------------
// TGLTreeBranchNoise
// -----------------------------------------------------------------------------
// Create
//
constructor TGLTreeBranchNoise.Create;
begin
FBranchNoise:=Random;
end;
// Destroy
//
destructor TGLTreeBranchNoise.Destroy;
begin
FLeft.Free;
FRight.Free;
inherited;
end;
// GetLeft
//
function TGLTreeBranchNoise.GetLeft: TGLTreeBranchNoise;
begin
if not Assigned(FLeft) then
FLeft:=TGLTreeBranchNoise.Create;
Result:=FLeft;
end;
// GetRight
//
function TGLTreeBranchNoise.GetRight: TGLTreeBranchNoise;
begin
if not Assigned(FRight) then
FRight:=TGLTreeBranchNoise.Create;
Result:=FRight;
end;
function TGLTreeBranchNoise.GetCenter: TGLTreeBranchNoise;
begin
if not Assigned(FCenter) then
FCenter:=TGLTreeBranchNoise.Create;
Result:=FCenter;
end;
// -----------------------------------------------------------------------------
// TGLTree
// -----------------------------------------------------------------------------
// Create
//
constructor TGLTree.Create(AOwner: TComponent);
begin
inherited;
// Default tree setting
FDepth:=5;
FLeafThreshold:=0.02;
FBranchAngleBias:=0.6;
FBranchAngle:=0.4;
FBranchTwist:=45;
FBranchNoise:=0.7;
FBranchSize:=1.0;
FLeafSize:=0.1;
FBranchRadius:=0.12;
FBranchFacets:=6;
FCentralLeader:=False;
FSeed:=0;
FAutoCenter:=False;
FAutoRebuild:=True;
FCenterBranchConstant:=0.5;
FLeaves:=TGLTreeLeaves.Create(Self);
FBranches:=TGLTreeBranches.Create(Self);
FNoise:=TGLTreeBranchNoise.Create;
end;
// Destroy
//
destructor TGLTree.Destroy;
begin
FLeaves.Free;
FBranches.Free;
FNoise.Free;
inherited;
end;
// Loaded
//
procedure TGLTree.Loaded;
begin
inherited;
FBranches.BuildBranches;
end;
// Notification
//
procedure TGLTree.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation=opRemove) and (AComponent=FMaterialLibrary) then
MaterialLibrary:=nil;
inherited;
end;
// DoRender
//
procedure TGLTree.DoRender(var ARci : TRenderContextInfo;
ARenderSelf, ARenderChildren : Boolean);
begin
MaterialLibrary.LibMaterialByName(BranchMaterialName).PrepareBuildList;
MaterialLibrary.LibMaterialByName(LeafMaterialName).PrepareBuildList;
MaterialLibrary.LibMaterialByName(LeafBackMaterialName).PrepareBuildList;
inherited;
end;
// BuildList
//
procedure TGLTree.BuildList(var rci: TRenderContextInfo);
begin
if FRebuildTree then begin
FBranches.BuildBranches;
FRebuildTree:=False;
end;
Branches.BuildList(rci);
Leaves.BuildList(rci);
end;
// StructureChanged
//
procedure TGLTree.StructureChanged;
begin
FAxisAlignedDimensionsCache.V[0]:=-1;
inherited;
end;
// BuildMesh
//
procedure TGLTree.BuildMesh(GLBaseMesh : TGLBaseMesh);
procedure RecursBranches(Branch : TGLTreeBranch; bone : TSkeletonBone; Frame : TSkeletonFrame);
var
trans : TTransformations;
mat : TMatrix;
rot, pos : TAffineVector;
begin
bone.Name:='Branch'+IntToStr(Branch.FBranchID);
bone.BoneID:=Branch.FBranchID;
// Construct base frame
if Assigned(Branch.FParent) then
mat:=Branch.FParent.FMatrix
else
mat:=IdentityHMGMatrix;
InvertMatrix(mat);
NormalizeMatrix(mat);
if MatrixDecompose(mat,trans) then begin
SetVector(rot,trans[ttRotateX],trans[ttRotateY],trans[ttRotateZ]);
SetVector(pos,mat.V[3]);
end else begin
rot:=NullVector;
pos:=NullVector;
end;
Frame.Rotation.Add(rot);
Frame.Position.Add(pos);
// Recurse with child branches
if Assigned(Branch.Left) then
RecursBranches(Branch.Left, TSkeletonBone.CreateOwned(bone), Frame);
if Assigned(Branch.Right) then
RecursBranches(Branch.Right, TSkeletonBone.CreateOwned(bone), Frame);
end;
var
//SkelMesh : TSkeletonMeshObject;
fg : TFGVertexIndexList;
fg2 : TFGVertexNormalTexIndexList;
i,j,stride : integer;
//parent_id : integer;
//bone : TSkeletonBone;
begin
if not Assigned(GLBaseMesh) then exit;
if FRebuildTree then begin
FBranches.BuildBranches;
FRebuildTree:=False;
end;
GLBaseMesh.MeshObjects.Clear;
GLBaseMesh.Skeleton.Clear;
//if GLBaseMesh is TGLActor then
// TSkeletonMeshObject.CreateOwned(GLBaseMesh.MeshObjects)
//else
TMeshObject.CreateOwned(GLBaseMesh.MeshObjects);
GLBaseMesh.MeshObjects[0].Mode:=momFaceGroups;
// Branches
GLBaseMesh.MeshObjects[0].Vertices.Add(Branches.Vertices);
GLBaseMesh.MeshObjects[0].Normals.Add(Branches.Normals);
GLBaseMesh.MeshObjects[0].TexCoords.Add(Branches.TexCoords);
{if GLBaseMesh is TGLActor then begin
TGLActor(GLBaseMesh).Reference:=aarSkeleton;
RecursBranches(Branches.FRoot,
TSkeletonBone.CreateOwned(GLBaseMesh.Skeleton.RootBones),
TSkeletonFrame.CreateOwned(GLBaseMesh.Skeleton.Frames));
SkelMesh:=TSkeletonMeshObject(GLBaseMesh.MeshObjects[0]);
SkelMesh.BonesPerVertex:=1;
SkelMesh.VerticeBoneWeightCount:=Branches.FBranchIndices.Count;
for i:=0 to Branches.FBranchIndices.Count-1 do
SkelMesh.AddWeightedBone(Branches.FBranchIndices[i],1);
GLBaseMesh.Skeleton.RootBones.PrepareGlobalMatrices;
SkelMesh.PrepareBoneMatrixInvertedMeshes;
SkelMesh.ApplyCurrentSkeletonFrame(True);
end;//}
stride:=(BranchFacets+1)*2;
for i:=0 to (FBranches.FIndices.Count div stride)-1 do begin
fg:=TFGVertexIndexList.CreateOwned(GLBaseMesh.MeshObjects[0].FaceGroups);
fg.MaterialName:=BranchMaterialName;
fg.Mode:=fgmmTriangleStrip;
for j:=0 to stride-1 do
fg.VertexIndices.Add(Branches.FIndices[i*stride+j]);
end;
// Leaves
//if GLBaseMesh is TGLActor then
// TSkeletonMeshObject.CreateOwned(GLBaseMesh.MeshObjects)
//else
TMeshObject.CreateOwned(GLBaseMesh.MeshObjects);
GLBaseMesh.MeshObjects[1].Mode:=momFaceGroups;
GLBaseMesh.MeshObjects[1].Vertices.Add(Leaves.Vertices);
GLBaseMesh.MeshObjects[1].Normals.Add(Leaves.FNormals);
for i:=0 to Leaves.Normals.Count-1 do
GLBaseMesh.MeshObjects[1].Normals.Add(VectorNegate(Leaves.FNormals[i]));
GLBaseMesh.MeshObjects[1].TexCoords.Add(Leaves.TexCoords);
for i:=0 to (Leaves.FVertices.Count div 4)-1 do begin
// Leaf front
fg2:=TFGVertexNormalTexIndexList.CreateOwned(GLBaseMesh.MeshObjects[1].FaceGroups);
fg2.MaterialName:=LeafMaterialName;
fg2.Mode:=fgmmTriangleStrip;
with fg2.VertexIndices do begin
Add(i*4);
Add(i*4+1);
Add(i*4+3);
Add(i*4+2);
end;
for j:=0 to 3 do
fg2.NormalIndices.Add(i);
with fg2.TexCoordIndices do begin
Add(0);
Add(1);
Add(3);
Add(2);
end;
// Leaf back
fg2:=TFGVertexNormalTexIndexList.CreateOwned(GLBaseMesh.MeshObjects[1].FaceGroups);
fg2.MaterialName:=LeafBackMaterialName;
fg2.Mode:=fgmmTriangleStrip;
with fg2.VertexIndices do begin
Add(i*4);
Add(i*4+3);
Add(i*4+1);
Add(i*4+2);
end;
for j:=0 to 3 do
fg2.NormalIndices.Add(i);
with fg2.TexCoordIndices do begin
Add(0);
Add(3);
Add(1);
Add(2);
end;
end;
end;
// Clear
//
procedure TGLTree.Clear;
begin
FLeaves.Clear;
FBranches.Clear;
end;
// SetBranchAngle
//
procedure TGLTree.SetBranchAngle(const Value: Single);
begin
if Value<>FBranchAngle then begin
FBranchAngle:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetBranchAngleBias
//
procedure TGLTree.SetBranchAngleBias(const Value: Single);
begin
if Value<>FBranchAngleBias then begin
FBranchAngleBias:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetBranchNoise
//
procedure TGLTree.SetBranchNoise(const Value: Single);
begin
if Value<>FBranchNoise then begin
FBranchNoise:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetBranchRadius
//
procedure TGLTree.SetBranchRadius(const Value: Single);
begin
if Value<>FBranchRadius then begin
FBranchRadius:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetBranchSize
//
procedure TGLTree.SetBranchSize(const Value: Single);
begin
if Value<>FBranchSize then begin
FBranchSize:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetBranchTwist
//
procedure TGLTree.SetBranchTwist(const Value: Single);
begin
if Value<>FBranchTwist then begin
FBranchTwist:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetDepth
//
procedure TGLTree.SetDepth(const Value: Integer);
begin
if Value<>FDepth then begin
FDepth:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetBranchFacets
//
procedure TGLTree.SetBranchFacets(const Value: Integer);
begin
if Value<>FBranchFacets then begin
FBranchFacets:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetLeafSize
//
procedure TGLTree.SetLeafSize(const Value: Single);
begin
if Value<>FLeafSize then begin
FLeafSize:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetLeafThreshold
//
procedure TGLTree.SetLeafThreshold(const Value: Single);
begin
if Value<>FLeafThreshold then begin
FLeafThreshold:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetCentralLeaderBias
//
procedure TGLTree.SetCentralLeaderBias(const Value: Single);
begin
if Value<>FCentralLeaderBias then begin
FCentralLeaderBias:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetCentralLeader
//
procedure TGLTree.SetCentralLeader(const Value: Boolean);
begin
if Value<>FCentralLeader then begin
FCentralLeader:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetSeed
//
procedure TGLTree.SetSeed(const Value: Integer);
begin
if Value<>FSeed then begin
FSeed:=Value;
if (FAutoRebuild) then ForceTotalRebuild;
end;
end;
// SetCenterBranchConstant
//
procedure TGLTree.SetCenterBranchConstant(const Value : Single);
begin
if Value<>CenterBranchConstant then begin
FCenterBranchConstant:=Value;
if (FAutoRebuild) then ForceTotalRebuild;
end;
end;
// SetBranchMaterialName
//
procedure TGLTree.SetBranchMaterialName(const Value: TGLLibMaterialName);
begin
if Value<>FBranchMaterialName then begin
FBranchMaterialName:=Value;
StructureChanged;
end;
end;
// SetLeafBackMaterialName
//
procedure TGLTree.SetLeafBackMaterialName(const Value: TGLLibMaterialName);
begin
if Value<>FLeafBackMaterialName then begin
FLeafBackMaterialName:=Value;
StructureChanged;
end;
end;
// SetLeafMaterialName
//
procedure TGLTree.SetLeafMaterialName(const Value: TGLLibMaterialName);
begin
if Value<>FLeafMaterialName then begin
FLeafMaterialName:=Value;
StructureChanged;
end;
end;
// SetMaterialLibrary
//
procedure TGLTree.SetMaterialLibrary(const Value: TGLMaterialLibrary);
begin
if Value<>FMaterialLibrary then begin
FMaterialLibrary:=Value;
StructureChanged;
end;
end;
// RebuildTree
//
procedure TGLTree.RebuildTree;
begin
if not FRebuildTree then begin
Clear;
FRebuildTree:=True;
StructureChanged;
end;
end;
// ForceTotalRebuild
//
procedure TGLTree.ForceTotalRebuild;
begin
Clear;
FNoise.Free;
RandSeed:=FSeed;
FNoise:=TGLTreeBranchNoise.Create;
FRebuildTree:=False;
FBranches.BuildBranches;
StructureChanged;
end;
// LoadFromStream
//
procedure TGLTree.LoadFromStream(aStream: TStream);
var
StrList, StrParse : TStringList;
str : String;
i : integer;
begin
StrList:=TStringList.Create;
StrParse:=TStringList.Create;
StrList.LoadFromStream(aStream);
try
for i:=0 to StrList.Count-1 do begin
str:=StrList[i];
if Pos('#',str)>0 then
str:=Copy(str,0,Pos('#',str)-1);
StrParse.CommaText:=str;
if StrParse.Count>=2 then begin
str:=LowerCase(StrParse[0]);
if str = 'depth' then FDepth:=StrToInt(StrParse[1])
else if str = 'branch_facets' then FBranchFacets:=StrToInt(StrParse[1])
else if str = 'leaf_size' then FLeafSize:=StrToFloat(StrParse[1])
else if str = 'branch_size' then FBranchSize:=StrToFloat(StrParse[1])
else if str = 'branch_noise' then FBranchNoise:=StrToFloat(StrParse[1])
else if str = 'branch_angle_bias' then FBranchAngleBias:=StrToFloat(StrParse[1])
else if str = 'branch_angle' then FBranchAngle:=StrToFloat(StrParse[1])
else if str = 'branch_twist' then FBranchTwist:=StrToFloat(StrParse[1])
else if str = 'branch_radius' then FBranchRadius:=StrToFloat(StrParse[1])
else if str = 'leaf_threshold' then FLeafThreshold:=StrToFloat(StrParse[1])
else if str = 'central_leader_bias' then FCentralLeaderBias:=StrToFloat(StrParse[1])
else if str = 'central_leader' then FCentralLeader:=LowerCase(StrParse[1])='true'
else if str = 'seed' then FSeed:=StrToInt(StrParse[1])
else if str = 'leaf_front_material_name' then FLeafMaterialName:=StrParse[1]
else if str = 'leaf_back_material_name' then FLeafBackMaterialName:=StrParse[1]
else if str = 'branch_material_name' then FBranchMaterialName:=StrParse[1];
end;
end;
ForceTotalRebuild;
finally
StrList.Free;
StrParse.Free;
end;
end;
// SaveToStream
procedure TGLTree.SaveToStream(aStream: TStream);
var
StrList : TStringList;
begin
StrList:=TStringList.Create;
StrList.Add(Format('depth, %d',[Depth]));
StrList.Add(Format('branch_facets, %d',[BranchFacets]));
StrList.Add(Format('leaf_size, %f',[LeafSize]));
StrList.Add(Format('branch_size, %f',[BranchSize]));
StrList.Add(Format('branch_noise, %f',[BranchNoise]));
StrList.Add(Format('branch_angle_bias, %f',[BranchAngleBias]));
StrList.Add(Format('branch_angle, %f',[BranchAngle]));
StrList.Add(Format('branch_twist, %f',[BranchTwist]));
StrList.Add(Format('branch_radius, %f',[BranchRadius]));
StrList.Add(Format('leaf_threshold, %f',[LeafThreshold]));
StrList.Add(Format('central_leader_bias, %f',[CentralLeaderBias]));
if CentralLeader then
StrList.Add('central_leader, true')
else
StrList.Add('central_leader, false');
StrList.Add(Format('seed, %d',[Seed]));
StrList.Add('leaf_front_material_name, "'+LeafMaterialName+'"');
StrList.Add('leaf_back_material_name, "'+LeafBackMaterialName+'"');
StrList.Add('branch_material_name, "'+BranchMaterialName+'"');
StrList.SaveToStream(aStream);
StrList.Free;
end;
// LoadFromFile
//
procedure TGLTree.LoadFromFile(aFileName: String);
var
stream : TStream;
begin
stream:=CreateFileStream(aFileName);
try
LoadFromStream(stream);
finally
stream.Free;
end;
end;
// SaveToFile
//
procedure TGLTree.SaveToFile(aFileName: String);
var
stream : TStream;
begin
stream:=CreateFileStream(aFileName,fmCreate);
try
SaveToStream(stream);
finally
stream.Free;
end;
end;
// GetExtents
procedure TGLTree.GetExtents(var min, max : TAffineVector);
var
lmin, lmax,
bmin, bmax : TAffineVector;
begin
if Branches.Vertices.Count = 0 then begin
FBranches.BuildBranches;
FRebuildTree:=False;
end;
if Leaves.Vertices.Count>0 then
Leaves.Vertices.GetExtents(lmin, lmax)
else begin
lmin:=NullVector;
lmax:=NullVector;
end;
if Branches.Vertices.Count>0 then
Branches.Vertices.GetExtents(bmin, bmax)
else begin
bmin:=NullVector;
bmax:=NullVector;
end;
min.V[0]:=MinFloat([lmin.V[0], lmax.V[0], bmin.V[0], bmax.V[0]]);
min.V[1]:=MinFloat([lmin.V[1], lmax.V[1], bmin.V[1], bmax.V[1]]);
min.V[2]:=MinFloat([lmin.V[2], lmax.V[2], bmin.V[2], bmax.V[2]]);
max.V[0]:=MaxFloat([lmin.V[0], lmax.V[0], bmin.V[0], bmax.V[0]]);
max.V[1]:=MaxFloat([lmin.V[1], lmax.V[1], bmin.V[1], bmax.V[1]]);
max.V[2]:=MaxFloat([lmin.V[2], lmax.V[2], bmin.V[2], bmax.V[2]]);
end;
// AxisAlignedDimensionsUnscaled
//
function TGLTree.AxisAlignedDimensionsUnscaled : TVector;
var
dMin, dMax : TAffineVector;
begin
if FAxisAlignedDimensionsCache.V[0]<0 then begin
GetExtents(dMin, dMax);
FAxisAlignedDimensionsCache.V[0]:=MaxFloat(Abs(dMin.V[0]), Abs(dMax.V[0]));
FAxisAlignedDimensionsCache.V[1]:=MaxFloat(Abs(dMin.V[1]), Abs(dMax.V[1]));
FAxisAlignedDimensionsCache.V[2]:=MaxFloat(Abs(dMin.V[2]), Abs(dMax.V[2]));
end;
SetVector(Result, FAxisAlignedDimensionsCache);
end;
// SetAutoCenter
//
procedure TGLTree.SetAutoCenter(const Value: Boolean);
begin
if Value<>FAutoCenter then begin
FAutoCenter:=Value;
if (FAutoRebuild) then RebuildTree;
end;
end;
// SetAutoRebuild
//
procedure TGLTree.SetAutoRebuild(const Value: Boolean);
begin
if Value<>FAutoRebuild then begin
FAutoRebuild:=Value;
end;
end;
initialization
RegisterClasses([TGLTree]);
end.
|
unit Unit3;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Windows;
type
{ TForm3 }
TForm3 = class(TForm)
Img: TImage;
procedure imgPaint(Sender: TObject);
procedure setStartSet;
procedure addPoint(y:integer);
procedure CanvasSetTextAngle(c: TCanvas; d: single);
private
x0,y0,x,y: Integer;
valueY: double;
vertex : TStringList;
procedure printAxis;
procedure paintGraphic;
procedure printGrig;
public
end;
var
Form3: TForm3;
implementation
procedure TForm3.setStartSet;
begin
vertex:=TStringList.Create;
imgPaint(TObject(img));
img.Canvas.MoveTo(x0,y0);
end;
procedure TForm3.imgPaint(Sender: TObject);
begin
img.Canvas.Brush.Color:=ClWhite;
img.Canvas.FillRect(img.Canvas.ClipRect);
printAxis;
paintGraphic;
printGrig;
end;
procedure TForm3.addPoint(y:integer);
begin
vertex.Add(inttostr(y));
imgPaint(TObject(img));
end;
procedure TForm3.CanvasSetTextAngle(c: TCanvas; d: single);
var LogRec: TLOGFONT;
begin
GetObject(c.Font.Handle,SizeOf(LogRec) ,Addr(LogRec) );
LogRec.lfEscapement := round(d*10);
c.Font.Handle := CreateFontIndirect(LogRec);
end;
procedure TForm3.printAxis;
begin
// Рисуем оси
x0:=65;
y0:= img.Height - 40;
x:=x0;
With img.Canvas do
begin
Pen.Color:=clBlack;
Pen.Width:=1;
MoveTo(x0,5);
LineTo(x0,y0);
LineTo(ClientWidth-5,y0);
Brush.Style := bsClear;
Font.Size := 10;
Textout(ClientWidth div 2,ClientHeight - img.Canvas.TextHeight('Время'), 'Время');
CanvasSetTextAngle(img.Canvas,90);
Textout(0,ClientHeight div 2, 'Память');
CanvasSetTextAngle(img.Canvas,0);
end;
end;
procedure TForm3.paintGraphic;
var i,maxY:integer;
begin
// Рисуем график
img.Canvas.MoveTo(x0,y0);
img.Canvas.Pen.Color:=clRed;
y:= img.Height- y0;
if vertex.Count > 0 then maxY:=strtoint(vertex[0]);
for i:=0 to vertex.Count-1 do
begin
if maxY<strtoint(vertex[i]) then maxY:=strtoint(vertex[i]);
end;
if vertex.Count > 0 then valueY:=(ClientHeight-y-5)/maxY
else valueY :=0;
x:=x0;
for i:=0 to vertex.Count-1 do
begin
x:=x+trunc((ClientWidth-x0-15)/vertex.Count);
img.Canvas.LineTo(x,ClientHeight-y-trunc(strtoint(vertex[i])*valueY));
end;
end;
procedure TForm3.printGrig;
var i,maxY,stepY,StepX,row,col:integer;
begin
maxY:=0; y:= img.Height- y0;
for i:=0 to vertex.Count-1 do
begin
if maxY<strtoint(vertex[i]) then maxY:=strtoint(vertex[i]);
end;
With img.Canvas do
begin
Pen.Color:=clBlack;
Font.Color:=clBlack;
Font.Size := 8;
end;
row:=8;
stepY:= round(maxY/row);
for i:=1 to row do
begin
With img.Canvas do
begin
MoveTo(x0-3,ClientHeight-y-trunc(stepY*valueY));
LineTo(x0+3,ClientHeight-y-trunc(stepY*valueY));
Textout(x0-3-TextWidth(inttostr(stepY)),ClientHeight-y-trunc(stepY*valueY)-5,inttostr(stepY));
Pen.Style:=psDot;
MoveTo(x0+3,ClientHeight-y-trunc(stepY*valueY));
LineTo(ClientWidth-5,ClientHeight-y-trunc(stepY*valueY));
Pen.Style:=psSolid;
stepY:=stepY + round(maxY/row);
end;
end;
x:=x0;
col:=10;
stepX:=round(vertex.Count/col);
for i:=0 to col do
begin
With img.Canvas do
begin
x:=x+trunc((ClientWidth-x0-15)/col);
MoveTo(x,y0+3);
LineTo(x,y0-3);
Textout(x,y0+5,inttostr(stepX));
Pen.Style:=psDot;
MoveTo(x,y0+3);
LineTo(x,5);
Pen.Style:=psSolid;
stepX:=stepX+round(vertex.Count/col);
end;
end;
end;
{$R *.lfm}
end.
|
unit ClassZakList;
interface
uses Classes, Graphics, Dbtables, Db;
const PageMargin = 50;
type TZakazList = class
private
Query : TQuery;
procedure PrintAtPos( Canvas : TCanvas; X, Y, Width, Height : integer );
public
ZakListCislo : string;
Odberatel : TStringList;
ObjCislo : string;
DatumPrij : string;
VybDna : string;
Zaruka : boolean;
DruhZar : TStringList;
PopisPor : TStringList;
Prisl : TStringList;
PopisVyk : TStringList;
PrislVyk : TStringList;
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Print( Canvas : TCanvas; Width, Height : integer );
procedure Save( FileName : string );
procedure Open( FileName : string );
function GetAndIncCounter : integer;
end;
implementation
uses Dialogs, SysUtils;
// Constructor
constructor TZakazList.Create;
begin
inherited;
Odberatel := TStringList.Create;
DruhZar := TStringList.Create;
PopisPor := TStringList.Create;
Prisl := TStringList.Create;
PopisVyk := TStringList.Create;
PrislVyk := TStringList.Create;
Query := TQuery.Create( nil );
Clear;
end;
// Destructor
destructor TZakazList.Destroy;
begin
Query.Free;
Odberatel.Free;
DruhZar.Free;
PopisPor.Free;
Prisl.Free;
PopisVyk.Free;
PrislVyk.Free;
inherited;
end;
function TZakazList.GetAndIncCounter : integer;
begin
Query.Active := False;
Query.DatabaseName := 'PcPrompt';
Query.SQL.Clear;
Query.SQL.Add( 'SELECT (counter.number) FROM counter' );
Query.Active := True;
Query.First;
Result := Query.Fields[0].AsInteger;
Query.Close;
Query.SQL.Clear;
Query.SQL.Add( 'DELETE FROM counter WHERE number = ' + IntToStr( Result ) );
Query.ExecSQL;
Query.SQL.Clear;
Query.SQL.Add( 'INSERT INTO counter (number) VALUES ('+ IntToStr( Result + 1 ) +')' );
Query.ExecSQL;
end;
procedure TZakazList.PrintAtPos( Canvas : TCanvas; X, Y, Width, Height : integer );
const Margin = 50;
var I, J, K : integer;
dX, dY : integer;
begin
// Bounding rectangle
Canvas.Pen.Color := clBlack;
Canvas.Pen.Width := 1;
Canvas.Rectangle( X , Y , X+Width , Y+Height );
// Top header
Canvas.MoveTo( X , Y+250 );
Canvas.LineTo( X+Width , Y+250 );
// Center texts
dX := X;
dY := Y+250;
Canvas.MoveTo( dX , dY+8*Margin );
Canvas.LineTo( dX+Width , dY+8*Margin );
Canvas.TextOut( dX+Margin , dY+Margin , 'Zákazkový list č. :' );
Canvas.TextOut( dX+Margin+300 , dY+Margin , ZakListCislo );
Canvas.TextOut( dX+Margin , dY+2*Margin , 'Odberateľ :' );
J := Odberatel.Count;
if (J > 5) then
J := 5;
for I := 0 to J-1 do
Canvas.TextOut( dX+Margin+300 , dY+(2+I)*Margin , Odberatel[I] );
Canvas.TextOut( dX+Margin , dY+7*Margin , 'Objednávka č. :' );
Canvas.TextOut( dX+Margin+300 , dY+7*Margin , ObjCislo );
Canvas.TextOut( dX+((Width div 4)*3) , dY+Margin , 'Dátum prijatia :' );
Canvas.TextOut( dX+((Width div 4)*3)+300 , dY+Margin , DatumPrij );
Canvas.TextOut( dX+((Width div 4)*3) , dY+2*Margin , 'Vybavené dňa :' );
Canvas.TextOut( dX+((Width div 4)*3)+300 , dY+2*Margin , VybDna );
Canvas.TextOut( dX+((Width div 4)*3) , dY+7*Margin , 'Záruka :' );
if (Zaruka) then
Canvas.TextOut( dX+((Width div 4)*3)+300 , dY+7*Margin , 'Áno' )
else
Canvas.TextOut( dX+((Width div 4)*3)+300 , dY+7*Margin , 'Nie' );
// Bottom texts
dX := X;
dY := dY + 8*Margin;
Canvas.Brush.Color := clLtGray;
Canvas.Brush.Style := bsSolid;
Canvas.Rectangle( dX , dY , dX + Width , dY + Margin );
Canvas.MoveTo( dX+(Width div 2) , dY );
Canvas.LineTo( dX+(Width div 2) , Y + Height );
Canvas.MoveTo( dX , dY + Margin );
Canvas.LineTo( dX + Width , dY + Margin );
Canvas.TextOut( dX + (Width div 4)-(Canvas.TextWidth( 'Príjem' ) div 2) , dY + 1, 'Príjem' );
Canvas.TextOut( dX + 3*(Width div 4)-(Canvas.TextWidth( 'Výdaj' ) div 2) , dY + 1, 'Výdaj' );
Canvas.Brush.Color := clWhite;
dY := dY + Margin;
I := (Height - (dY - Y)) div 5;
Canvas.MoveTo( dX , dY + I );
Canvas.LineTo( dX + (Width div 2) , dY + I );
Canvas.TextOut( dX + Margin , dY + 1 , 'Druh zariadenia :' );
K := DruhZar.Count;
if (K > 2) then
K := 2;
for J := 0 to K-1 do
Canvas.TextOut( dX + Margin , dY + 1 + (J+1)*Margin , DruhZar[J] );
Canvas.TextOut( dX + (Width div 2) + Margin , dY + 1 , 'Popis výkonu :' );
K := PopisVyk.Count;
if (K > 5) then
K := 5;
for J := 0 to K-1 do
Canvas.TextOut( dX + (Width div 2) + Margin , dY + 1 + (J+1)*Margin , PopisVyk[J] );
Canvas.MoveTo( dX , dY + 2*I );
Canvas.LineTo( dX + Width , dY + 2*I );
Canvas.TextOut( dX + Margin , dY + I + 1 , 'Popis poruchy :' );
K := PopisPor.Count;
if (K > 2) then
K := 2;
for J := 0 to K-1 do
Canvas.TextOut( dX + Margin , dY + I + 1 + (J+1)*Margin , PopisPor[J] );
Canvas.MoveTo( dX , dY + 3*I );
Canvas.LineTo( dX + Width , dY + 3*I );
Canvas.TextOut( dX + Margin , dY + 2*I + 1, 'Príslušenstvo :' );
K := Prisl.Count;
if (K > 2) then
K := 2;
for J := 0 to K-1 do
Canvas.TextOut( dX + Margin , dY + 2*I + 1 + (J+1)*Margin , Prisl[J] );
Canvas.TextOut( dX + (Width div 2) + Margin , dY + 2*I + 1 , 'Príslušenstvo :' );
K := PrislVyk.Count;
if (K > 2) then
K := 2;
for J := 0 to K-1 do
Canvas.TextOut( dX + (Width div 2) + Margin , dY + 2*I + 1 + (J+1)*Margin , PrislVyk[J] );
Canvas.TextOut( dX + (Width div 4)-(Canvas.TextWidth( 'Príjem do opravy' ) div 2) , Y + Height - Margin , 'Príjem do opravy' );
Canvas.TextOut( dX + 3*(Width div 4)-(Canvas.TextWidth( 'Prevzatie z opravy' ) div 2) , Y + Height - Margin , 'Prevzatie z opravy' );
end;
procedure TZakazList.Clear;
begin
Odberatel.Clear;
DruhZar.Clear;
PopisPor.Clear;
Prisl.Clear;
PopisVyk.Clear;
PrislVyk.Clear;
ZakListCislo := '';
ObjCislo := '';
DatumPrij := '';
VybDna := '';
Zaruka := true;
end;
procedure TZakazList.Print( Canvas : TCanvas; Width, Height : integer );
begin
PrintAtPos( Canvas , PageMargin , PageMargin , Width-2*PageMargin , (Height-3*PageMargin) div 2 );
// Dividing line
Canvas.Pen.Style := psDash;
Canvas.MoveTo( 0 , Height div 2 );
Canvas.LineTo( Width , Height div 2 );
Canvas.Pen.Style := psSolid;
PrintAtPos( Canvas , PageMargin , (Height+PageMargin) div 2 , Width-2*PageMargin , (Height-3*PageMargin) div 2 );
end;
procedure TZakazList.Save( FileName : string );
var F : TextFile;
procedure WriteStrings( Strings : TStrings );
var I : integer;
begin
Writeln( F , Strings.Count );
for I := 0 to Strings.Count-1 do
Writeln( F , Strings[I] );
end;
begin
AssignFile( F , FileName );
try
Rewrite( F );
Writeln( F , ZakListCislo );
Writeln( F , ObjCislo );
Writeln( F , DatumPrij );
Writeln( F , VybDna );
if (Zaruka) then
Writeln( F , 'ANO' )
else
Writeln( F , 'NIE' );
WriteStrings( Odberatel );
WriteStrings( DruhZar );
WriteStrings( PopisPor );
WriteStrings( Prisl );
WriteStrings( PopisVyk );
WriteStrings( PrislVyk );
finally
CloseFile( F );
end;
end;
procedure TZakazList.Open( FileName : string );
var F : TextFile;
S : string;
procedure ReadStrings( Strings : TStrings );
var I, J : integer;
begin
Readln( F , J );
for I := 0 to J-1 do
begin
Readln( F , S );
Strings.Add( S );
end;
end;
begin
Clear;
AssignFile( F , FileName );
try
Reset( F );
Readln( F , ZakListCislo );
Readln( F , ObjCislo );
Readln( F , DatumPrij );
Readln( F , VybDna );
Readln( F , S );
Zaruka := (S = 'ANO');
ReadStrings( Odberatel );
ReadStrings( DruhZar );
ReadStrings( PopisPor );
ReadStrings( Prisl );
ReadStrings( PopisVyk );
ReadStrings( PrislVyk );
finally
CloseFile( F );
end;
end;
end.
|
(*!------------------------------------------------------------
* Fano CLI Application (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano-cli
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT)
*------------------------------------------------------------- *)
unit CreateProjectNoCommitTaskFactoryImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
TaskIntf,
TaskFactoryIntf,
TextFileCreatorIntf,
ContentModifierIntf,
CreateProjectTaskFactoryImpl;
type
(*!--------------------------------------
* Factory class for create project task that
* initialize git repository but without actually
* commit them.
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------*)
TCreateProjectNoCommitTaskFactory = class(TCreateProjectTaskFactory)
protected
function buildProjectTask(
const textFileCreator : ITextFileCreator;
const contentModifier : IContentModifier
) : ITask; override;
end;
implementation
uses
DirectoryCreatorImpl,
NullTaskImpl,
CreateDirTaskImpl,
CreateAppConfigsTaskImpl,
CreateAdditionalFilesTaskImpl,
CreateShellScriptsTaskImpl,
CreateAppBootstrapTaskImpl,
InitGitRepoTaskImpl,
CreateProjectTaskImpl;
function TCreateProjectNoCommitTaskFactory.buildProjectTask(
const textFileCreator : ITextFileCreator;
const contentModifier : IContentModifier
) : ITask;
begin
result := TCreateProjectTask.create(
TCreateDirTask.create(TDirectoryCreator.create()),
TCreateShellScriptsTask.create(textFileCreator, contentModifier),
TCreateAppConfigsTask.create(textFileCreator, contentModifier),
TCreateAdditionalFilesTask.create(textFileCreator, contentModifier),
TCreateAppBootstrapTask.create(textFileCreator, contentModifier),
//replace git commit task with NullTaskImpl to disable Git commit
TInitGitRepoTask.create(TNullTask.create())
);
end;
end.
|
unit Timon_Dalton_PAT_Fase3_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, jpeg, ComCtrls, Spin;
type
TForm1 = class(TForm)
pgcSpaceMissionPlanner: TPageControl;
tsGeneral: TTabSheet;
tsDestination: TTabSheet;
tsVehicle: TTabSheet;
img2StageRocket: TImage;
img1StageRocket: TImage;
img3StageRocket: TImage;
pnlFirstStage: TPanel;
pnl2ndStage: TPanel;
pnl3rdStage: TPanel;
pnlStage1MassLost: TPanel;
pnlStage2MassLost: TPanel;
pnlPayload: TPanel;
cbbRocketModel: TComboBox;
pnlRocketDetails: TPanel;
pnlCapableAcceleration: TPanel;
lblCapAcc: TLabel;
lblCapAccNum: TLabel;
pgcDestination: TPageControl;
tsOrbit: TTabSheet;
tsPlanet: TTabSheet;
pnlEarthAndSat: TPanel;
imgEarth1: TImage;
imgEarth2: TImage;
imgEarth3: TImage;
imgEarth4: TImage;
imgEarth5: TImage;
imgEarth6: TImage;
imgSatellite: TImage;
pnlOrbitSpecs: TPanel;
lblOrbitSpecs: TLabel;
mmoMoreInfo: TMemo;
pnlPickOrbit: TPanel;
lblDistanceFromSurface: TLabel;
lblSpdInObt: TLabel;
trckbrPickOrbit: TTrackBar;
cbbOrbits: TComboBox;
edtDistanceFromSurface: TEdit;
edtSpdInObt: TEdit;
udDistanceFromSurface: TUpDown;
udSpdInObt: TUpDown;
pnlKindOfObt: TPanel;
lblKindOfObt: TLabel;
lblOrbit: TLabel;
pgc1: TPageControl;
ts1: TTabSheet;
rgLanguage: TRadioGroup;
pnlRocketGeneral: TPanel;
lblRocketTitle: TLabel;
lblVehicleBasicCapableDeltaV: TLabel;
lblVehicleBasicAccNum: TLabel;
cbb3: TComboBox;
btn1: TButton;
pnlGeneralRocketExtra: TPanel;
lbl2: TLabel;
lbl4: TLabel;
lbl6: TLabel;
lbl7: TLabel;
lbl3: TLabel;
lbl5: TLabel;
lbl1: TLabel;
se1: TSpinEdit;
edt3: TEdit;
edt4: TEdit;
cbb2: TComboBox;
edt2: TEdit;
edt5: TEdit;
pnlGeneralDestinationExtra: TPanel;
lblDestinationGeneralOrbits: TLabel;
lblGeneralDvPlanets: TLabel;
lbl9: TLabel;
lblPickOne: TLabel;
rgGeneralDvDesType: TRadioGroup;
cbbDestintionGeneral: TComboBox;
cbbGeneralDvPlanets: TComboBox;
edt1: TEdit;
btnResetAll: TButton;
pnlBasicPresets: TPanel;
pnlGenPresetMissions: TPanel;
lblPreviousMissions: TLabel;
cbbFamousMissions: TComboBox;
pnlBasicRocket_Des: TPanel;
pnlExampleVehicles: TPanel;
lblExampleRockets: TLabel;
cbbFamousRockets: TComboBox;
pnlExampleDestinations: TPanel;
lblExampleDestinations: TLabel;
cbbFamousDestinations: TComboBox;
pnlDeltaVGeneral: TPanel;
lblDestinationTitle: TLabel;
lblBasicDestinationRequiredAcc: TLabel;
lblBasicRequiredAccNum: TLabel;
cbbGeneralDvMoreOpp: TComboBox;
btnGoToDvPage: TButton;
tsDeltaVDestination: TTabSheet;
tsRocket: TTabSheet;
pnlUdChangePAge: TPanel;
udChangePage: TUpDown;
pnlSolarSystemPic: TPanel;
imgPlanets: TImage;
btnMars: TButton;
btnJupiter: TButton;
btnSaturn: TButton;
btnNeptune: TButton;
btnUranus: TButton;
btnMoon: TButton;
btnVenus: TButton;
btnMercury: TButton;
pnlAboutPlanet: TPanel;
mmoMorePlanetInfo: TMemo;
pnlSelectDestination: TPanel;
cbbSelectedInterplanetary: TComboBox;
rgActionAtDestination: TRadioGroup;
rgReturn: TRadioGroup;
pnlDeltaVRequired: TPanel;
lblMinDeltaVTxt: TLabel;
lblDeltaVByRocket: TLabel;
edtDeltaVRequired: TEdit;
edtRocketDeltaV: TEdit;
pnl1: TPanel;
lbl8: TLabel;
procedure trckbrPickOrbitChange(Sender: TObject);
procedure Arrange_Orbit;
procedure Stop_Wrong_In;
procedure FormCreate(Sender: TObject);
procedure edtDistanceFromSurfaceChange(Sender: TObject);
procedure udDistanceFromSurfaceClick(Sender: TObject;
Button: TUDBtnType);
procedure btn1Click(Sender: TObject);
procedure btnGoToDvPageClick(Sender: TObject);
procedure cbbGeneralDvMoreOppClick(Sender: TObject);
procedure cbb3Click(Sender: TObject);
procedure udChangePageClick(Sender: TObject; Button: TUDBtnType);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
udDFromSurfaceStarted :Boolean;
Prev : Integer;
input :string;
AlphaNumInErrMsgShown : Boolean;
RequiredDeltaV,DFromSurf,DFromCen,VeloInObt,TperObt : Real;
ChangingVar:string;
Orbit,LEO,MEO,HEO,GEO:string;
const
mu = 398588738000000;
E1_KmPerUnt = 10;
E2_KmPerUnt = 12.25;
E3_KmPerUnt = 22;
E4_KmPerUnt = 31.85;
E5_KmPerUnt = 63.7;
E6_KmPerUnt = 90;
E1_SurfPos = 320;
E2_SurfPos = 260;
E3_SurfPos = 145;
E4_SurfPos = 100;
E5_SurfPos = 50;
E6_SurfPos = 36;
sRequiredDeltaV = 'RequiredDeltaV';
sDFromSurf = 'DistanceFromSurface';
sDFromCen = 'DistanceFromEarthCentre';
sVeloInObt = 'VelocityInOrbit';
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
LEO := 'Low Earth Orbit';
MEO := 'Medium Earth Orbit';
HEO := 'High Earth Orbit';
GEO := 'Geostationary Earth Orbit';
pnlGeneralDestinationExtra.Visible := False;
udDFromSurfaceStarted := False;;
pnlUdChangePAge.Visible := False;
pnl1.Visible := False;
end;
function Calculate_VeloAtOrbitalAltitude(Value:Real):Real;
begin
Result := Sqr(mu*(1/Value));
end;
function Calculate_OrbitalAltitudeAtVelo(Velo:Real):Real;
begin
Result := mu/((Velo*Velo));
end;
function Calculate_Satellite_GUI_Pos(DFromSurf,KmPerUnt,SurfacePos : Real) :integer;
begin
Result := Round((DFromSurf/ KmPerUnt) + SurfacePos);
end;
function StopEmptyErr(VarIn : string) :Boolean;
begin
if VarIn = '' then Result := False
else Result := True
end;
{
Voutvang!!!
}
procedure TForm1.Stop_Wrong_In; //dit is steeds moontlik om errors te kry maar hierdie verwyder die algemeenstes
var
ViableChar :array[1..12] of Char;
CurrentPlace,CharCounter:Integer;
const
AlphaNumInErr = 'Only real numbers are allowed as input';
begin //stop meeste errors vir wanneer die values heeltyd geread word.
if StopEmptyErr(Input) = True then
if Length(Input) = 10 then Delete(Input,10,1);
begin
ViableChar[1] := '1';
ViableChar[2] := '2';
ViableChar[3] := '3';
ViableChar[4] := '4';
ViableChar[5] := '5';
ViableChar[6] := '6';
ViableChar[7] := '7';
ViableChar[8] := '8';
ViableChar[9] := '9';
ViableChar[10]:= '0';
ViableChar[11]:= ',';
ViableChar[12]:=' ';
CurrentPlace := 1;
CharCounter := 1;
while CurrentPlace <= Length(Input)
do
if Copy(Input,CurrentPlace,1)= ViableChar[CharCounter]
then
begin
Inc(CurrentPlace);
CharCounter := 1;
end
else
begin
Inc(CharCounter);
if CharCounter = 13
then
begin
CharCounter := 1;
Delete(Input,CurrentPlace,1);{<-----------removes wrong input}
//CurrentPlace not incremented on porpoise
if AlphaNumInErrMsgShown =False then //Shows error message. The If statement is present because the message popped up mulitple times while running
begin
ShowMessage(AlphaNumInErr);
AlphaNumInErrMsgShown := True;
end;
end;
end;
end;
end;
procedure TForm1.Arrange_Orbit;
begin
if DFromSurf >= 300 then
begin
if DFromSurf <= 2000 then
begin
Orbit := LEO;
imgEarth1.BringToFront;
imgSatellite.BringToFront;
imgSatellite.Left := Calculate_Satellite_GUI_Pos(DFromSurf, E1_KmPerUnt,E1_SurfPos);
end
else if DFromSurf <= 3200 then
begin
Orbit := MEO;
imgEarth2.BringToFront;
imgSatellite.BringToFront;
imgSatellite.Left := Calculate_Satellite_GUI_Pos(DFromSurf, E2_KmPerUnt,E2_SurfPos);
end
else if DFromSurf <= 8200 then
begin
Orbit := MEO;
imgEarth3.BringToFront;
imgSatellite.BringToFront;
imgSatellite.Left := Calculate_Satellite_GUI_Pos(DFromSurf, E3_KmPerUnt,E3_SurfPos);
end
else if DFromSurf <= 13500 then
begin
Orbit := MEO;
imgEarth4.BringToFront;
imgSatellite.BringToFront;
imgSatellite.Left := Calculate_Satellite_GUI_Pos(DFromSurf, E4_KmPerUnt,E4_SurfPos);
end
else if DFromSurf <= 30000 then
begin
Orbit := MEO;
imgEarth5.BringToFront;
imgSatellite.BringToFront;
imgSatellite.Left := Calculate_Satellite_GUI_Pos(DFromSurf, E5_KmPerUnt,E5_SurfPos);
end
else if DFromSurf <= 45000 then
begin
if DFromSurf > 35786 then Orbit := HEO;
imgEarth6.BringToFront;
imgSatellite.BringToFront;
imgSatellite.Left := Calculate_Satellite_GUI_Pos(DFromSurf, E6_KmPerUnt,E6_SurfPos);
end;
end;
end;
procedure TForm1.trckbrPickOrbitChange(Sender: TObject);
begin
case trckbrPickOrbit.Position of
1: DfromSurf := 300;
2: DfromSurf := 500;
3: DfromSurf := 1000;
4: DfromSurf := 2000; {Low earth orbit---> Medium earth orbit}
5: DfromSurf := 5000;
6: DfromSurf := 12000;
7: DfromSurf := 25000;
8: DfromSurf := 35786; {Geosychronus earth orbit, marks MEO----> HEO}
end;
Arrange_Orbit;
edtDistanceFromSurface.Text := FloatToStr(DFromSurf);
{edtSpdInObt.Text := FloatToStr(VeloInObt(DFromSurf));}//Error
end;
procedure TForm1.edtDistanceFromSurfaceChange(Sender: TObject);
begin
input := edtDistanceFromSurface.Text;
Stop_Wrong_In;
AlphaNumInErrMsgShown := False;
Arrange_Orbit;
end;
function check_IncDec(Prev,New :Integer) :Boolean;
begin
if prev < New
then Result := True
else Result := False;
end;
procedure TForm1.udDistanceFromSurfaceClick(Sender: TObject;
Button: TUDBtnType);
var
New , IncAmount :Integer;
begin
IncAmount := 100;
New := udDistanceFromSurface.Position;
if check_IncDec(Prev,New) = True
then DFromSurf := DFromSurf + IncAmount
else DFromSurf := DFromSurf - IncAmount;
Prev := udDistanceFromSurface.Position;
udDFromSurfaceStarted := True;
edtDistanceFromSurface.Text := FloatToStr(DFromSurf);
Arrange_Orbit;
end;
procedure TForm1.btn1Click(Sender: TObject);
begin
pgcSpaceMissionPlanner.ActivePage := tsVehicle;
end;
procedure TForm1.btnGoToDvPageClick(Sender: TObject);
begin
pgcSpaceMissionPlanner.ActivePage := tsDestination;
end;
procedure TForm1.cbbGeneralDvMoreOppClick(Sender: TObject);
begin
pnlGeneralDestinationExtra.Visible := True;
end;
procedure TForm1.cbb3Click(Sender: TObject);
begin
pnlGeneralRocketExtra.Visible := True;
end;
procedure TForm1.udChangePageClick(Sender: TObject; Button: TUDBtnType);
begin
pgcSpaceMissionPlanner.ActivePageIndex := udChangePage.Position;
end;
end.
|
unit MessagePaser;
interface
uses
ExtCtrls, Classes, SysUtils;
type
TStringParser = Class(TObject)
private
FMsg: String;
FReceiveCode: string;
FText: String;
FSendCode: String;
Fprotocol: String;
procedure SetMsg(const Value: String);
procedure SetReceiveCode(const Value: string);
procedure SetSendCode(const Value: String);
procedure SetText(const Value: String);
procedure Setprotocol(const Value: String);
public
property Text : String read FText write SetText;
property protocol : String read Fprotocol write Setprotocol;
Property SendCode : String read FSendCode write SetSendCode;
property ReceiveCode : string read FReceiveCode write SetReceiveCode;
property Msg : String read FMsg write SetMsg;
End;
var
stringParser : TStringParser;
implementation
{ StringParser }
procedure TStringParser.SetMsg(const Value: String);
begin
FMsg := Value;
end;
procedure TStringParser.Setprotocol(const Value: String);
begin
Fprotocol := Value;
end;
procedure TStringParser.SetReceiveCode(const Value: string);
begin
FReceiveCode := Value;
end;
procedure TStringParser.SetSendCode(const Value: String);
begin
FSendCode := Value;
end;
procedure TStringParser.SetText(const Value: String);
begin
FText := Value;
protocol := Copy(value, 1, 1);
SendCode := Copy(Value, 3, 8);
ReceiveCode := Copy(Value, 12, 8);
Msg := Copy(Value, 21, Length(Value)-21);
end;
end.
|
{$A+,B-,E-,F-,G+,I-,N-,O-,P-,Q-,R-,S-,T-,V-,X-}
{-------------------------------
VGA unit - Turbo Pascal 7.0
-------------------------------}
unit vga;
interface
const
vgascreen : pointer = ptr($a000,0000);
procedure vga_pal(color,r,g,b:byte);
procedure mode(which:word);
procedure vga_synch(num:word);
procedure vga_addr(where:pointer);
procedure getscreen(where:pointer);
procedure putscreen(where:pointer);
procedure vgaputscreen(where:pointer);
function read_pcx(image:pointer; pal:pointer) : byte;
procedure put(x,y:integer; what:pointer);
procedure get(x,y,x1,y1:integer; what:pointer);
procedure cput(x,y:integer; what:pointer);
procedure cpaste(x,y:integer; what:pointer);
procedure cpasteadd(x,y:integer; what:pointer);
procedure cls(color:byte);
procedure pset(x,y:integer; color:byte);
function point(x,y:integer) : byte;
procedure boxfill(x,y,x1,y1:integer; color:byte);
procedure boxfilladd(x,y,x1,y1:integer; adder:byte);
procedure line(x,y,x1,y1:integer; color:word);
procedure drawto(x,y,x1,y1:integer; color:word);
procedure hline(x,y,x1:integer; color:byte);
procedure vline(x,y,y1:integer; color:byte);
procedure box(x,y,x1,y1:integer; color:word);
{--------------------------------------------------------------------}
implementation
{$L VGA.OBJ}
procedure vga_pal(color,r,g,b:byte); external;
procedure mode(which:word); external;
procedure vga_synch(num:word); external;
procedure vga_addr(where:pointer); external;
procedure getscreen(where:pointer); external;
procedure putscreen(where:pointer); external;
procedure vgaputscreen(where:pointer); external;
function read_pcx(image:pointer; pal:pointer) : byte; external;
procedure put(x,y:integer; what:pointer); external;
procedure get(x,y,x1,y1:integer; what:pointer); external;
procedure cput(x,y:integer; what:pointer); external;
procedure cpaste(x,y:integer; what:pointer); external;
procedure cpasteadd(x,y:integer; what:pointer); external;
procedure cls(color:byte); external;
procedure pset(x,y:integer; color:byte); external;
function point(x,y:integer) : byte; external;
procedure boxfill(x,y,x1,y1:integer; color:byte); external;
procedure boxfilladd(x,y,x1,y1:integer; adder:byte); external;
procedure line(x,y,x1,y1:integer; color:word); external;
procedure drawto(x,y,x1,y1:integer; color:word); external;
procedure hline(x,y,x1:integer; color:byte); external;
procedure vline(x,y,y1:integer; color:byte); external;
procedure box(x,y,x1,y1:integer; color:word); external;
begin
end.
|
unit uWebBrowser;
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,Forms, Dialogs, ExtCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.EventArgs, CNClrLib.Control.Base,
CNClrLib.Component.ImageList, CNClrLib.Control.ButtonBase, CNClrLib.Control.Button,
CNClrLib.Control.ListControl, CNClrLib.Control.ComboBox, CNClrLib.Control.TextBoxBase,
CNClrLib.Control.TextBox, CNClrLib.Control.LabelA, CNClrLib.Control.ProgressBar,
CNClrLib.Control.WebBrowser;
type
TForm23 = class(TForm)
Panel1: TPanel;
btnBack: TCnButton;
btnHome: TCnButton;
btnForward: TCnButton;
CnImageList1: TCnImageList;
btnPrint: TCnButton;
btnRefresh: TCnButton;
btnGo: TCnButton;
txtAddress: TCnTextBox;
CnWebBrowser1: TCnWebBrowser;
Panel2: TPanel;
pbProgressStatus: TCnProgressBar;
lblStatus: TCnLabel;
procedure btnPrintClick(Sender: TObject; E: _EventArgs);
procedure btnRefreshClick(Sender: TObject; E: _EventArgs);
procedure btnGoClick(Sender: TObject; E: _EventArgs);
procedure btnForwardClick(Sender: TObject; E: _EventArgs);
procedure btnHomeClick(Sender: TObject; E: _EventArgs);
procedure btnBackClick(Sender: TObject; E: _EventArgs);
procedure CnWebBrowser1ProgressChanged(Sender: TObject;
E: _WebBrowserProgressChangedEventArgs);
procedure CnWebBrowser1DocumentTitleChanged(Sender: TObject; E: _EventArgs);
procedure CnWebBrowser1DocumentCompleted(Sender: TObject;
E: _WebBrowserDocumentCompletedEventArgs);
procedure CnWebBrowser1StatusTextChanged(Sender: TObject; E: _EventArgs);
procedure CnWebBrowser1Navigated(Sender: TObject;
E: _WebBrowserNavigatedEventArgs);
procedure FormShow(Sender: TObject);
private
procedure DoInitialiseWebBrowser;
{ Private declarations }
public
{ Public declarations }
end;
var
Form23: TForm23;
implementation
{$R *.dfm}
procedure TForm23.DoInitialiseWebBrowser;
begin
CnWebBrowser1.Navigate(txtAddress.Text);
btnBack.Enabled := False;
btnForward.Enabled := False;
end;
procedure TForm23.FormShow(Sender: TObject);
begin
DoInitialiseWebBrowser;
end;
procedure TForm23.btnBackClick(Sender: TObject; E: _EventArgs);
begin
CnWebBrowser1.GoBack;
end;
procedure TForm23.btnHomeClick(Sender: TObject; E: _EventArgs);
begin
CnWebBrowser1.GoHome;
end;
procedure TForm23.btnForwardClick(Sender: TObject; E: _EventArgs);
begin
CnWebBrowser1.GoForward;
end;
procedure TForm23.btnPrintClick(Sender: TObject; E: _EventArgs);
begin
CnWebBrowser1.ShowPrintPreviewDialog;
end;
procedure TForm23.btnRefreshClick(Sender: TObject; E: _EventArgs);
begin
CnWebBrowser1.Refresh;
end;
procedure TForm23.btnGoClick(Sender: TObject; E: _EventArgs);
begin
CnWebBrowser1.Navigate(txtAddress.Text);
end;
procedure TForm23.CnWebBrowser1DocumentCompleted(Sender: TObject;
E: _WebBrowserDocumentCompletedEventArgs);
begin
btnBack.Enabled := CnWebBrowser1.CanGoBack;
btnForward.Enabled := CnWebBrowser1.CanGoForward;
lblStatus.Text := 'Done';
end;
procedure TForm23.CnWebBrowser1DocumentTitleChanged(Sender: TObject;
E: _EventArgs);
begin
Caption := CnWebBrowser1.DocumentTitle;
end;
procedure TForm23.CnWebBrowser1Navigated(Sender: TObject;
E: _WebBrowserNavigatedEventArgs);
begin
txtAddress.Text := CnWebBrowser1.Url.ToString();
end;
procedure TForm23.CnWebBrowser1ProgressChanged(Sender: TObject;
E: _WebBrowserProgressChangedEventArgs);
begin
pbProgressStatus.Maximum := E.MaximumProgress;
if (E.CurrentProgress < 0) or (E.MaximumProgress < E.CurrentProgress) then
pbProgressStatus.Value := E.MaximumProgress
else
pbProgressStatus.Value := E.CurrentProgress;
end;
procedure TForm23.CnWebBrowser1StatusTextChanged(Sender: TObject;
E: _EventArgs);
begin
lblStatus.Text := CnWebBrowser1.StatusText;
end;
end.
|
unit uPaiVisual;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.StdCtrls, uPaiControle, FMX.Objects,
uRESTDWPoolerDB, Data.DB;
type
TSentidoDados = (sdObjetoCampo, sdCampoObjeto);
TTipoAcao = (taIncluir, taAlterar, taCancelar, taSalvar, taDeletar,
taPrimeiro, taAnterior, taProximo, taUltimo);
TPaiFrm = class(TForm)
RecCabecalho: TRectangle;
BtnIncluir: TButton;
BtnAlterar: TButton;
BtnExcluir: TButton;
BtnCancelar: TButton;
BtnSalvar: TButton;
BtnUltimo: TButton;
BtnProximo: TButton;
BtnAnterior: TButton;
BtnPrimeiro: TButton;
PnlAreaCadastro: TPanel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure OnClick(Sender: TObject);
private
FAfterScroll: TOnAfterScroll;
FStateChange: TNotifyEvent;
procedure HabilitarEdicao(pbInserindoEditando: boolean);
procedure AtribuirEventos;
protected
FControle: TControle;
procedure StateChange(Sender: TObject); virtual;
procedure AfterScroll(DataSet: TDataSet); virtual;
end;
var
PaiFrm: TPaiFrm;
implementation
{$R *.fmx}
procedure TPaiFrm.AfterScroll(DataSet: TDataSet);
begin
if Assigned(FAfterScroll) then
FAfterScroll(DataSet);
HabilitarEdicao(DataSet.State in dsEditModes);
end;
procedure TPaiFrm.StateChange(Sender: TObject);
begin
if Assigned(FStateChange) then
FStateChange(Sender);
HabilitarEdicao(TDataSource(Sender).State in dsEditModes);
end;
procedure TPaiFrm.AtribuirEventos;
begin
FAfterScroll := FControle.AfterScroll;
FControle.AfterScroll := AfterScroll;
FStateChange := FControle.DataSource.OnStateChange;
FControle.DataSource.OnStateChange := StateChange;
end;
procedure TPaiFrm.FormCreate(Sender: TObject);
begin
if not Assigned(FControle) then
raise Exception.Create('Desenvolvedor, atribuir a variável de controle ao criar o formulário ' + TForm(Sender).Name);
AtribuirEventos;
HabilitarEdicao(False);
end;
procedure TPaiFrm.FormDestroy(Sender: TObject);
begin
FAfterScroll := nil;
FStateChange := nil;
FreeAndNil(FControle);
end;
procedure TPaiFrm.OnClick(Sender: TObject);
begin
case TTipoAcao(TRectangle(Sender).Tag) of
taIncluir: FControle.Insert;
taAlterar: FControle.Edit;
taCancelar: FControle.Cancel;
taSalvar: begin
FControle.Post;
if FControle.MassiveCount > 0 then
FControle.ApplyUpdates;
end;
taDeletar: begin
FControle.Delete;
FControle.ApplyUpdates;
end;
taPrimeiro: FControle.First;
taAnterior: FControle.Prior;
taProximo: FControle.Next;
taUltimo: FControle.Last;
end;
end;
procedure TPaiFrm.HabilitarEdicao(pbInserindoEditando: boolean);
var
bInserindoEditandoVazio: boolean;
begin
bInserindoEditandoVazio := pbInserindoEditando or FControle.IsEmpty;
BtnIncluir.Enabled := not pbInserindoEditando;
BtnAlterar.Enabled := not bInserindoEditandoVazio;
BtnCancelar.Enabled := pbInserindoEditando;
BtnSalvar.Enabled := pbInserindoEditando;
BtnExcluir.Enabled := not bInserindoEditandoVazio;
BtnPrimeiro.Enabled := not bInserindoEditandoVazio;
BtnAnterior.Enabled := not bInserindoEditandoVazio;
BtnProximo.Enabled := not bInserindoEditandoVazio;
BtnUltimo.Enabled := not bInserindoEditandoVazio;
PnlAreaCadastro.Enabled := pbInserindoEditando;
end;
end.
|
unit Strings;
interface
const
Letters = ['0'..'9', 'A'..'Z', 'a'..'z', 'À'..'Ï', 'Ð'..'ß', 'à'..'ï',
'ð'..'ÿ', '¨', '¸', '_'];
LegalChars = Letters + ['$', '@', '#'];
Type_Exts = ['$', '@'];
ID_LENGTH = 40;
type
TStringArray = array of String;
PID = ^TID;
TID = String[ID_LENGTH];
function ThisStr(const S: String; const AStrings: array of String): Boolean;
procedure Subtract(var S: String; const ASubS: String);
function GetSubtract(const S, ASubS: String): String;
function Cut(var S, ABuffer: String; const AIndex, ACount: Integer): String;
procedure Prepare(var S: String);
function Type_ID(const S: String; var AType_, AID: String): Boolean;
function Brackets(var AText: String): String; overload;
procedure Brackets(var AText: String; ADelimiter: Char;
var AStrings: TStringArray); overload;
procedure NameValue(const S: String; ADelimiter: Char; var AName,
AValue: String);
function ReadItem(var S: String; ADelimiter: Char): String;
function FirstItem(S: String; ADelimiter: Char): String;
function ReadCompileItem(var S: String): String;
function Number(const AValue: String; var AInt, APos: Boolean): Boolean;
implementation
uses
SysUtils;
function ThisStr(const S: String; const AStrings: array of String): Boolean;
var
I: Integer;
begin
Result := False;
for I := Low(AStrings) to High(AStrings) do
if S = AStrings[I] then
begin
Result := True;
Break;
end;
end;
procedure Subtract(var S: String; const ASubS: String);
var
I: Integer;
begin
I := Pos(ASubS, S);
if I > 0 then
Delete(S, I, Length(ASubS));
end;
function GetSubtract(const S, ASubS: String): String;
begin
Result := S;
Subtract(Result, ASubS);
end;
function Cut(var S, ABuffer: String; const AIndex, ACount: Integer): String;
begin
ABuffer := Copy(S, AIndex, ACount);
Delete(S, AIndex, ACount);
end;
procedure Prepare(var S: String);
var
I, C: Integer;
B: Boolean;
begin
S := StringReplace(S, #13#10, ' ', [rfReplaceAll]);
S := Trim(S);
if S = '' then
Exit;
B := True;
I := 0;
while I <= Length(S) do
if S[I] = '"' then
begin
B := not B;
I := I + 1;
end
else if (S[I] = '{') and B then
begin
C := 0;
while I <= Length(S) do
begin
case S[I] of
'{': C := C + 1;
'}': begin
C := C - 1;
if C = 0 then
begin
Delete(S, I, 1);
Break;
end;
end;
end;
Delete(S, I, 1);
end;
end
else if (S[I] = ' ') and B then
if (I > 1) and (I < Length(S)) then
if (S[I - 1] in Letters) and (S[I + 1] in Letters) then
I := I + 1
else
Delete(S, I, 1)
else
Delete(S, I, 1)
else
I := I + 1;
end;
function Type_ID(const S: String; var AType_, AID: String): Boolean;
var
I, lBuf: Integer;
lSBuf: array [0..1] of String;
begin
Result := False;
for I := 0 to 1 do
lSBuf[I] := '';
lBuf := 0;
for I := 1 to Length(S) do
if S[I] in LegalChars then
lSBuf[lBuf] := lSBuf[lBuf] + S[I]
else if S[I] = ' ' then
if lBuf = 0 then
lBuf := 1
else
Exit
else
Exit;
Result := lBuf = 1;
if Result then
begin
AType_ := lSBuf[0];
AID := lSBuf[1];
end;
end;
function Brackets(var AText: String): String;
var
BC: Integer;
C: Char;
begin
Result := '';
BC := 0;
while AText <> '' do
begin
C := AText[1];
Delete(AText, 1, 1);
case C of
'(':
begin
if BC > 0 then
Result := Result + C;
BC := BC + 1;
end;
')': begin
BC := BC - 1;
if BC > 0 then
Result := Result + C
else
Break;
end;
else
Result := Result + C;
end;
end;
end;
procedure Brackets(var AText: String; ADelimiter: Char;
var AStrings: TStringArray);
var
I, BC: Integer;
C: Char;
begin
I := 0;
SetLength(AStrings, I + 1);
BC := 0;
while AText <> '' do
begin
C := AText[1];
Delete(AText, 1, 1);
case C of
'(': BC := BC + 1;
')':
begin
BC := BC - 1;
if BC = 0 then
Break;
end;
else
if (C = ADelimiter) and (BC = 1) then
begin
I := I + 1;
SetLength(AStrings, I + 1);
end
else
AStrings[I] := AStrings[I] + C;
end;
end;
if (I = 0) and (Trim(AStrings[0]) = '') then
SetLength(AStrings, 0);
end;
procedure NameValue(const S: String; ADelimiter: Char; var AName,
AValue: String);
var
I: Integer;
F: Boolean;
begin
AName := '';
AValue := '';
F := True;
for I := 1 to Length(S) do
if S[I] = ADelimiter then
if F then
F := False
else
AValue := AValue + S[I]
else
if F then
AName := AName + S[I]
else
AValue := AValue + S[I];
end;
function ReadItem(var S: String; ADelimiter: Char): String;
var
C: Char;
begin
Result := '';
while S <> '' do
begin
C := S[1];
Delete(S, 1, 1);
if C = ADelimiter then
Break;
Result := Result + C;
end;
end;
function FirstItem(S: String; ADelimiter: Char): String;
var
C: Char;
begin
Result := '';
while S <> '' do
begin
C := S[1];
Delete(S, 1, 1);
if C = ADelimiter then
Break;
Result := Result + C;
end;
end;
function ReadCompileItem(var S: String): String;
var
C: Char;
B: Integer;
begin
Result := '';
B := 0;
while S <> '' do
begin
C := S[1];
Delete(S, 1, 1);
case C of
'(': B := B + 1;
')': B := B - 1;
';':
if B = 0 then
Break;
end;
Result := Result + C;
end;
end;
function Number(const AValue: String; var AInt, APos: Boolean): Boolean;
var
I: Integer;
lFloat, lNeg, lNum: Boolean;
begin
Result := False;
lFloat := False;
lNeg := False;
lNum := False;
if AValue = '' then
Exit;
for I := 1 to Length(AValue) do
if not (AValue[I] in ['0'..'9', ',', '.', 'E', '+', '-']) then
Exit
else
begin
if AValue[I] in ['0'..'9'] then
lNum := True;
if AValue[I] in [',', '.'] then
if ((I = 1) or (I = Length(AValue)) or lFloat) then
Exit
else
lFloat := True;
if AValue[I] in ['+', '-'] then
if I > 1 then
if AValue[I - 1] <> 'E' then
Exit
else
lNeg := True;
if (AValue[I] = 'E') then
if I in [1, Length(AValue)] then
Exit
else
if not (AValue[I - 1] in ['0'..'9']) then
Exit
else
if not (AValue[I + 1] in ['0'..'9', '+', '-']) then
Exit;
end;
Result := lNum;
AInt := not lFloat;
APos := not lNeg;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2010-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
//
// Delphi-Objective-C Bridge
// Interfaces for IOKit framework
//
unit Macapi.IOKit;
interface
uses
Macapi.CoreFoundation,
Macapi.Mach;
const
kIOMasterPortDefault: mach_port_t = 0;
kIOPlatformUUIDKey = 'IOPlatformUUID';
// ===== External functions =====
const
libIOKit = '/System/Library/Frameworks/IOKit.framework/IOKit';
type
io_object_t = mach_port_t;
io_registry_entry_t = io_object_t;
io_service_t = io_object_t;
IOOptionBits = UInt32;
function IOServiceGetMatchingService(masterPort: mach_port_t; matching: CFDictionaryRef): io_service_t; cdecl; external libIOKit name _PU + 'IOServiceGetMatchingService';
function IOServiceMatching(name: MarshaledAString): CFMutableDictionaryRef; cdecl; external libIOKit name _PU + 'IOServiceMatching';
function IORegistryEntryCreateCFProperty(entry: io_registry_entry_t; key: CFStringRef; allocator: CFAllocatorRef; options: IOOptionBits): CFTypeRef; cdecl; external libIOKit name _PU + 'IORegistryEntryCreateCFProperty';
function IOObjectRelease(anObject: io_object_t): kern_return_t; cdecl; external libIOKit name _PU + 'IOObjectRelease';
implementation
uses System.SysUtils;
var
IOKitModule: HMODULE;
initialization
IOKitModule := LoadLibrary(libIOKit);
finalization
if IOKitModule <> 0 then
FreeLibrary(IOKitModule);
end.
|
unit fGAF;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fPCEBase, StdCtrls, Buttons, ExtCtrls, Grids, ORFn, ORNet, ORCtrls,
ORDtTm, ComCtrls, fPCEBaseGrid, Menus, VA508AccessibilityManager;
type
TfrmGAF = class(TfrmPCEBaseGrid)
lblGAF: TStaticText;
edtScore: TCaptionEdit;
udScore: TUpDown;
dteGAF: TORDateBox;
lblEntry: TStaticText;
lblScore: TLabel;
lblDate: TLabel;
lblDeterminedBy: TLabel;
cboGAFProvider: TORComboBox;
btnURL: TButton;
Spacer1: TLabel;
Spacer2: TLabel;
procedure cboGAFProviderNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure edtScoreChange(Sender: TObject);
procedure dteGAFExit(Sender: TObject);
procedure cboGAFProviderExit(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnURLClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FDataLoaded: boolean;
procedure LoadScores;
function BADData(ShowMessage: boolean): boolean;
public
procedure AllowTabChange(var AllowChange: boolean); override;
procedure GetGAFScore(var Score: integer; var Date: TFMDateTime; var Staff: Int64);
end;
function ValidGAFData(Score: integer; Date: TFMDateTime; Staff: Int64): boolean;
var
frmGAF: TfrmGAF;
implementation
uses rPCE, rCore, uCore, uPCE, fEncounterFrame, VA508AccessibilityRouter;
{$R *.DFM}
function ValidGAFData(Score: integer; Date: TFMDateTime; Staff: Int64): boolean;
begin
if(Score < 1) or (Score > 100) or (Date <= 0) or (Staff = 0) then
Result := FALSE
else
Result := ((Patient.DateDied <= 0) or (Date <= Patient.DateDied));
end;
procedure TfrmGAF.LoadScores;
var
i: integer;
tmp: string;
begin
RecentGafScores(3);
if(RPCBrokerV.Results.Count > 0) and (RPCBrokerV.Results[0] = '[DATA]') then
begin
for i := 1 to RPCBrokerV.Results.Count-1 do
begin
tmp := RPCBrokerV.Results[i];
lstCaptionList.Add(Piece(tmp,U,5) + U + Piece(Piece(tmp,U,2),NoPCEValue,1) + U +
Piece(tmp,U,7) + U + Piece(tmp,U,8));
end;
end;
if lstCaptionList.Items.Count = 0 then
lstCaptionList.Add('No GAF scores found.');
end;
procedure TfrmGAF.cboGAFProviderNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
begin
inherited;
cboGAFProvider.ForDataUse(SubSetOfPersons(StartFrom, Direction));
end;
function TfrmGAF.BADData(ShowMessage: boolean): boolean;
var
PName, msg: string;
GAFDate: TFMDateTime;
UIEN: Int64;
begin
GAFDate := dteGAF.FMDateTime;
msg := ValidateGAFDate(GAFDate);
if(dteGAF.FMDateTime <> GAFDate) then
dteGAF.FMDateTime := GAFDate;
if(cboGAFProvider.ItemID = '') then
begin
if(msg <> '') then
msg := msg + CRLF;
msg := msg + 'A determining party is required to enter a GAF score.';
UIEN := uProviders.PCEProvider;
if(UIEN <> 0) then
begin
PName := uProviders.PCEProviderName;
msg := msg + ' Determined By changed to ' + PName + '.';
cboGAFProvider.SelectByIEN(UIEN);
if(cboGAFProvider.ItemID = '') then
begin
cboGAFProvider.InitLongList(PName);
cboGAFProvider.SelectByIEN(UIEN);
end;
end;
end;
if(ShowMessage and (msg <> '')) then
InfoBox(msg, 'Invalid GAF Data', MB_OK);
if(udScore.Position > udScore.Min) then
Result := (msg <> '')
else
Result := FALSE;
end;
procedure TfrmGAF.edtScoreChange(Sender: TObject);
var
i: integer;
begin
inherited;
i := StrToIntDef(edtScore.Text,udScore.Min);
if(i < udScore.Min) or (i > udScore.Max) then
i := udScore.Min;
udScore.Position := i;
edtScore.Text := IntToStr(i);
edtScore.SelStart := length(edtScore.Text);
end;
procedure TfrmGAF.dteGAFExit(Sender: TObject);
begin
inherited;
// BadData(TRUE);
end;
procedure TfrmGAF.cboGAFProviderExit(Sender: TObject);
begin
inherited;
BadData(TRUE);
end;
procedure TfrmGAF.AllowTabChange(var AllowChange: boolean);
begin
AllowChange := (not BadData(TRUE));
end;
procedure TfrmGAF.GetGAFScore(var Score: integer; var Date: TFMDateTime; var Staff: Int64);
begin
Score := udScore.Position;
if(Score > 0) then BadData(TRUE);
Date := dteGAF.FMDateTime;
Staff := cboGAFProvider.ItemIEN;
if(not ValidGAFData(Score, Date, Staff)) then
begin
Score := 0;
Date := 0;
Staff := 0
end;
end;
procedure TfrmGAF.FormActivate(Sender: TObject);
begin
inherited;
if(not FDataLoaded) then
begin
FDataLoaded := TRUE;
LoadScores;
cboGAFProvider.InitLongList(Encounter.ProviderName);
BadData(FALSE);
end;
end;
procedure TfrmGAF.FormShow(Sender: TObject);
begin
inherited;
FormActivate(Sender);
end;
procedure TfrmGAF.btnURLClick(Sender: TObject);
begin
inherited;
GotoWebPage(GAFURL);
end;
procedure TfrmGAF.FormCreate(Sender: TObject);
begin
inherited;
FTabName := CT_GAFNm;
btnURL.Visible := (User.WebAccess and (GAFURL <> ''));
FormActivate(Sender);
end;
initialization
SpecifyFormIsNotADialog(TfrmGAF);
end.
|
unit IWRegion;
interface
uses
{$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF}
{$IFDEF Linux}QForms,{$ELSE}Forms,{$ENDIF}
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
{$IFDEF Linux}Qt, Types,{$ELSE}Windows, Messages,{$ENDIF}
Classes,
IWContainer, IWControl, IWHTMLTag, IWLayoutMgr, IWCompRectangle,
IWLayoutMgrForm;
type
TIWRegion = class(TIWContainer)
protected
FCanvas: TControlCanvas;
FRectangle: TIWRectangle;
//
{$IFDEF Linux}
procedure Painting(Sender: QObjectH; EventRegion: QRegionH); override;
procedure Resize; override;
{$ELSE}
procedure Resizing(State: TWindowState); override;
{$IFNDEF RUNTIME}
procedure PaintWindow(ADC: HDC); override;
{$ENDIF}
{$ENDIF}
procedure Loaded; override;
function GetColor: TColor;
procedure SetColor(const Value: TColor);
procedure RequestAlign; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Rectangle: TIWRectangle read FRectangle;
published
property Align;
property Anchors;
property TabOrder;
property Color: TColor read GetColor write SetColor;
end;
implementation
uses
IWForm,
SWSystem, SysUtils;
{ TIWRegion }
constructor TIWRegion.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if csDesigning in ComponentState then begin
FCanvas := TControlCanvas.Create;
FCanvas.Control := Self;
ControlState := [csCustomPaint];
{$IFNDEF Linux}
DoubleBuffered := true;
{$ENDIF}
{$IFDEF Linux}
VertScrollBar.Visible := false;
HorzScrollBar.Visible := false;
{$ENDIF}
FRectangle := nil;
end
else begin
FRectangle := TIWRectangle.Create(Owner);
end;
Width := 20;
Height := 20;
Color := clNone;
ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csSetCaption, csDoubleClicks];
Visible := True;
end;
destructor TIWRegion.Destroy;
begin
FreeAndNil(FCanvas);
inherited Destroy;
end;
procedure TIWRegion.Loaded;
{Var
i: Integer;}
begin
inherited Loaded;
if not (csDesigning in ComponentState) then begin
{if Form is TIWForm and ((TIWForm(Form).TemplateProcessor = nil) or
(TIWForm(Form).TemplateProcessor is TIWLayoutMgrForm)) then begin}
FRectangle.Parent := self;
FRectangle.ComponentIndex := 0;
(Form as TIWForm).TabOrderList.Insert(0, FRectangle);
FRectangle.SetBounds(0, 0, Width, Height);
FRectangle.Align := Align;
FRectangle.Anchors := Anchors;
FRectangle.ZIndex := -100;
FRectangle.Color := Color;
FRectangle.Text := '';
FRectangle.Visible := Visible;
{end
else begin
FreeAndNil(FRectangle);
// Move all controls to the form.
i := 0;
while i < ControlCount do begin
if Controls[i].Parent = self then begin
Controls[i].Parent := Parent;
end
else
Inc(i);
end;
end;}
end;
end;
{$IFNDEF Linux}
{$IFNDEF RUNTIME}
procedure TIWRegion.PaintWindow(ADC: HDC);
begin
FCanvas.Lock; try
FCanvas.Handle := ADC; try
if Color <> clNone then begin
FCanvas.Brush.Color := Color;
end
else begin
FCanvas.Brush.Color := clWhite;
end;
FCanvas.Brush.Style := bsSolid;
FCanvas.FillRect(ClientRect);
FCanvas.Brush.Color := clBlack;
FCanvas.FrameRect(ClientRect);
finally FCanvas.Handle := 0; end;
finally FCanvas.Unlock; end;
end;
{$ENDIF}
procedure TIWRegion.Resizing(State: TWindowState);
begin
inherited Resizing(State);
if Assigned(FRectangle) then begin
FRectangle.SetBounds(0, 0, Width, Height);
end;
Invalidate;
end;
{$ENDIF}
{$IFDEF Linux}
procedure TIWRegion.Painting(Sender: QObjectH; EventRegion: QRegionH);
Var
LPoints: array[0..4] of TPoint;
begin
inherited Painting(Sender, EventRegion);
TControlCanvas(FCanvas).StartPaint;
try
if Color <> clNone then begin
FCanvas.Brush.Color := Color;
end
else begin
FCanvas.Brush.Color := clWhite;
end;
FCanvas.Brush.Style := bsSolid;
FCanvas.FillRect(ClientRect);
LPoints[0] := Point(0, 0);
LPoints[1] := Point(Width - 1, 0);
LPoints[2] := Point(Width - 1, Height - 1);
LPoints[3] := Point(0, Height - 1);
LPoints[4] := Point(0, 0);
FCanvas.Polyline(LPoints);
finally
TControlCanvas(FCanvas).StopPaint;
end;
end;
procedure TIWRegion.Resize;
begin
inherited Resize;
if Assigned(FRectangle) then begin
FRectangle.SetBounds(0, 0, Width, Height);
end;
Invalidate;
end;
{$ENDIF}
function TIWRegion.GetColor: TColor;
begin
result := inherited Color;
end;
procedure TIWRegion.SetColor(const Value: TColor);
begin
inherited Color := Value;
if Assigned(FRectangle) then begin
FRectangle.Color := Value;
end;
end;
procedure TIWRegion.RequestAlign;
begin
inherited RequestAlign;
if Assigned(FRectangle) then begin
FRectangle.Visible := Visible;
FRectangle.SetBounds(0, 0, Width, Height);
end;
end;
end.
|
unit Values;
interface
uses
Strings;
const
TYPE_VOID = 0;
TYPE_FLOAT = 1;
TYPE_INT = 2;
TYPE_BYTE = 3;
TYPE_STR = 4;
TYPE_ARRAY = 5;
TYPE_CLASS = 6;
STR_TYPE: array [0..6] of String = (
'void',
'float',
'int',
'byte',
'str',
'array',
'class'
);
type
Float = Single;
TCID = type Cardinal;
TType_ = Integer;
TType_Ext = (teGlobal, teRef);
TType_Exts = set of TType_Ext;
TArgument = record
ID: TID;
Type_: TType_;
Exts: TType_Exts;
end;
TArguments = array of TArgument;
TValue = class;
TValueProc = procedure (const AID: TID; AValue: TValue;
ASetType: Boolean = False) of object;
TValues = array of TValue;
TValue = class
private
FType_: TType_;
FID: PID;
FAddr: Pointer;
FFreeMem: Boolean;
function GetID(): TID;
function GetF(): Float;
function GetI(): Integer;
function GetB(): Byte;
function GetS(): String;
function GetL(): Boolean;
function GetV(): Variant;
function GetP(): Pointer;
function GetString(): String;
function GetValue(Index: Integer): TValue;
function GetCount(): Integer;
function GetCID(): TCID;
procedure SetID(const Value: TID);
procedure SetAddr(const Value: Pointer);
procedure SetF(Value: Float);
procedure SetI(Value: Integer);
procedure SetB(Value: Byte);
procedure SetS(const Value: String);
procedure SetL(Value: Boolean);
procedure SetV(const Value: Variant);
procedure SetP(const Value: Pointer);
procedure SetString(const Value: String);
procedure SetValue(Index: Integer; const Value: TValue);
procedure GetData();
procedure SetData();
procedure FreeID();
procedure FreeAddr();
public
constructor Create(AType_: TType_ = TYPE_VOID; const AID: TID = '';
AAddr: Pointer = nil);
destructor Destroy(); override;
procedure Assign(ASource: TValue);
procedure Copy(ASource: TValue);
procedure Ref(ASource: TValue);
procedure Equal(ASource: TValue);
function Compare(ASource: TValue): Boolean;
procedure Add(AValue: TValue; AIndex: Integer = -1);
procedure Set_(AValue: TValue; AIndex: Integer);
procedure Delete(AIndex: TValue);
procedure Clear();
procedure CreateClass(ACID: TCID; const AArguments: TArguments);
procedure DestroyClass();
function IndexOf(const AID: TID): Integer;
function Field(const AID: TID): TValue;
function Offset(AIndex: TValue): TValue;
procedure Put(const AValue; AType_: TType_; ASetType: Boolean = False);
procedure Get(var AValue);
property Type_: TType_ read FType_;
property ID: TID read GetID write SetID;
property Addr: Pointer read FAddr write SetAddr;
property F: Float read GetF write SetF;
property I: Integer read GetI write SetI;
property B: Byte read GetB write SetB;
property S: String read GetS write SetS;
property L: Boolean read GetL write SetL;
property V: Variant read GetV write SetV;
property P: Pointer read GetP write SetP;
property Value[Index: Integer]: TValue read GetValue
write SetValue; default;
property Count: Integer read GetCount;
property CID: TCID read GetCID;
end;
function Type_(const S: String): TType_;
function Value(F: Float): TValue; overload;
function Value(I: Integer): TValue; overload;
function Value(B: Byte): TValue; overload;
function Value(const S: String): TValue; overload;
function Value(L: Boolean): TValue; overload;
function ValueAssign(AValue: TValue): TValue;
function ValueCopy(AValue: TValue): TValue;
function ValueRef(AValue: TValue): TValue;
procedure CopyValues(ASource: TValues; var ADestantion: TValues);
procedure FreeValues(var AValues: TValues);
var
GetProc: TValueProc = nil;
SetProc: TValueProc = nil;
implementation
uses
ClassDefs, SysUtils;
{ Routines }
function Type_(const S: String): TType_;
var
I: Integer;
begin
Result := TYPE_VOID;
for I := Low(STR_TYPE) to High(STR_TYPE) do
if S = STR_TYPE[I] then
begin
Result := I;
Break;
end;
end;
function Value(F: Float): TValue;
begin
Result := TValue.Create(TYPE_FLOAT);
Result.F := F;
end;
function Value(I: Integer): TValue;
begin
Result := TValue.Create(TYPE_INT);
Result.I := I;
end;
function Value(B: Byte): TValue;
begin
Result := TValue.Create(TYPE_BYTE);
Result.B := B;
end;
function Value(const S: String): TValue;
begin
Result := TValue.Create(TYPE_STR);
Result.S := S;
end;
function Value(L: Boolean): TValue;
begin
Result := TValue.Create(TYPE_INT);
if L then
Result.I := 1
else
Result.I := 0;
end;
function ValueAssign(AValue: TValue): TValue;
begin
Result := TValue.Create;
Result.Assign(AValue);
end;
function ValueCopy(AValue: TValue): TValue;
begin
Result := TValue.Create;
Result.Copy(AValue);
end;
function ValueRef(AValue: TValue): TValue;
begin
Result := TValue.Create;
Result.Ref(AValue);
end;
procedure CopyValues(ASource: TValues; var ADestantion: TValues);
var
I: Integer;
begin
SetLength(ADestantion, High(ASource) + 1);
for I := 0 to High(ADestantion) do
ADestantion[I] := ASource[I];
end;
procedure FreeValues(var AValues: TValues);
var
I: Integer;
begin
for I := 0 to High(AValues) do
begin
AValues[I].Free;
AValues[I] := nil;
end;
SetLength(AValues, 0);
end;
{ TValue }
{ private }
function TValue.GetID(): TID;
begin
if Assigned(FID) then
Result := FID^
else
Result := '';
end;
function TValue.GetF(): Float;
begin
GetData();
case FType_ of
TYPE_FLOAT: Result := Float(FAddr^);
TYPE_INT: Result := Integer(FAddr^);
TYPE_BYTE: Result := Byte(FAddr^);
TYPE_STR: Result := StrToFloat(GetString);
TYPE_ARRAY: Result := GetValue(0).F;
else
Result := 0;
end;
end;
function TValue.GetI(): Integer;
begin
GetData();
case FType_ of
TYPE_FLOAT: Result := Round(Float(FAddr^));
TYPE_INT: Result := Integer(FAddr^);
TYPE_BYTE: Result := Byte(FAddr^);
TYPE_STR: Result := StrToInt(GetString);
TYPE_ARRAY: Result := GetValue(0).I;
else
Result := 0;
end;
end;
function TValue.GetB(): Byte;
begin
GetData();
case FType_ of
TYPE_FLOAT: Result := Round(Float(FAddr^));
TYPE_INT: Result := Integer(FAddr^);
TYPE_BYTE: Result := Byte(FAddr^);
TYPE_STR: Result := StrToInt(GetString);
TYPE_ARRAY: Result := GetValue(0).B;
else
Result := 0;
end;
end;
function TValue.GetS(): String;
begin
GetData();
Result := GetString();
end;
function TValue.GetL(): Boolean;
begin
case FType_ of
TYPE_FLOAT: Result := GetF() <> 0;
TYPE_INT: Result := GetI() <> 0;
TYPE_BYTE: Result := GetB() <> 0;
TYPE_STR: Result := GetS() <> '';
TYPE_ARRAY: Result := GetValue(0).L;
else
Result := True;
end;
end;
function TValue.GetV(): Variant;
begin
case FType_ of
TYPE_FLOAT: Result := GetF();
TYPE_INT: Result := GetI();
TYPE_BYTE: Result := GetB();
TYPE_STR: Result := GetS();
TYPE_ARRAY: Result := GetValue(0).V;
else
Result := 0;
end;
end;
function TValue.GetP(): Pointer;
var
I, L: Integer;
S: String;
begin
case FType_ of
TYPE_FLOAT:
begin
GetMem(Result, SizeOf(Float));
Float(Result^) := GetF();
end;
TYPE_INT:
begin
GetMem(Result, SizeOf(Integer));
Integer(Result^) := GetI();
end;
TYPE_BYTE:
begin
GetMem(Result, SizeOf(Byte));
Byte(Result^) := GetB();
end;
TYPE_STR:
begin
S := GetS();
L := Length(S);
GetMem(Result, L + 1);
for I := 1 to L do
Byte(Pointer(Integer(Result) + I - 1)^) := Ord(S[I]);
Byte(Pointer(Integer(Result) + L)^) := 0;
end;
TYPE_ARRAY: Result := GetValue(0).P;
else
Result := nil;
end;
end;
function TValue.GetString(): String;
var
I: Integer;
B: Byte;
begin
case FType_ of
TYPE_FLOAT: Result := FloatToStr(Float(FAddr^));
TYPE_INT: Result := IntToStr(Integer(FAddr^));
TYPE_BYTE: Result := IntToStr(Byte(FAddr^));
TYPE_STR:
begin
Result := '';
I := 0;
B := Byte(Pointer(Integer(FAddr^) + I)^);
while B <> 0 do
begin
Result := Result + Chr(B);
I := I + 1;
B := Byte(Pointer(Integer(FAddr^) + I)^);
end;
end;
TYPE_ARRAY: Result := GetValue(0).S;
else
Result := '';
end;
end;
function TValue.GetValue(Index: Integer): TValue;
var
lCID: Integer;
begin
if FType_ = TYPE_STR then
begin
GetData();
if (Index < 0) or (Index >= Length(S)) then
Result := TValue.Create()
else
Result := TValue.Create(TYPE_BYTE, '',
Pointer(Integer(FAddr^) + Index));
end
else if FType_ in [TYPE_ARRAY, TYPE_CLASS] then
begin
GetData();
if FType_ = TYPE_CLASS then
lCID := SizeOf(TCID)
else
lCID := 0;
if (Index < 0) or (Index >= Count) then
Result := TValue.Create()
else
Result := ValueRef(TValue(Pointer(Integer(FAddr^) + lCID +
Index * SizeOf(TValue))^));
end
else
Result := Self;
end;
function TValue.GetCount(): Integer;
var
lCID: Integer;
lValue: TValue;
begin
if Assigned(Pointer(FAddr^)) then
case FType_ of
TYPE_VOID: Result := 0;
TYPE_ARRAY, TYPE_CLASS:
begin
Result := 0;
if FType_ = TYPE_CLASS then
lCID := SizeOf(TCID)
else
lCID := 0;
lValue := TValue(Pointer(Integer(FAddr^) + lCID +
Result * SizeOf(TValue))^);
while Assigned(lValue) do
begin
Result := Result + 1;
lValue := TValue(Pointer(Integer(FAddr^) + lCID +
Result * SizeOf(TValue))^);
end;
end;
else
Result := 1;
end
else
Result := 0;
end;
function TValue.GetCID(): TCID;
begin
if FType_ = TYPE_CLASS then
Result := TCID(Pointer(FAddr^)^)
else
Result := 0;
end;
procedure TValue.SetID(const Value: TID);
begin
if Value = '' then
FreeID()
else
begin
if not Assigned(FID) then
GetMem(FID, SizeOf(TID));
FID^ := Value;
end;
end;
procedure TValue.SetAddr(const Value: Pointer);
begin
FreeAddr();
FAddr := Value;
FFreeMem := False;
end;
procedure TValue.SetF(Value: Float);
begin
case FType_ of
TYPE_FLOAT: Float(FAddr^) := Value;
TYPE_INT: Integer(FAddr^) := Round(Value);
TYPE_BYTE: Byte(FAddr^) := Round(Value);
TYPE_STR: SetString(FloatToStr(Value));
TYPE_ARRAY: GetValue(0).F := Value;
end;
SetData();
end;
procedure TValue.SetI(Value: Integer);
begin
case FType_ of
TYPE_FLOAT: Float(FAddr^) := Value;
TYPE_INT: Integer(FAddr^) := Value;
TYPE_BYTE: Byte(FAddr^) := Value;
TYPE_STR: SetString(IntToStr(Value));
TYPE_ARRAY: GetValue(0).I := Value;
end;
SetData();
end;
procedure TValue.SetB(Value: Byte);
begin
case FType_ of
TYPE_FLOAT: Float(FAddr^) := Value;
TYPE_INT: Integer(FAddr^) := Value;
TYPE_BYTE: Byte(FAddr^) := Value;
TYPE_STR: SetString(IntToStr(Value));
TYPE_ARRAY: GetValue(0).B := Value;
end;
SetData();
end;
procedure TValue.SetS(const Value: String);
begin
SetString(Value);
SetData();
end;
procedure TValue.SetL(Value: Boolean);
begin
if Value then
SetI(1)
else
SetI(0);
end;
procedure TValue.SetV(const Value: Variant);
begin
case FType_ of
TYPE_FLOAT: SetF(Value);
TYPE_INT: SetI(Value);
TYPE_BYTE: SetB(Value);
TYPE_STR: SetS(Value);
TYPE_ARRAY: GetValue(0).V := Value;
end;
end;
procedure TValue.SetP(const Value: Pointer);
var
I, L: Integer;
begin
case FType_ of
TYPE_FLOAT: Float(FAddr^) := Float(Value^);
TYPE_INT: Integer(FAddr^) := Integer(Value^);
TYPE_BYTE: Byte(FAddr^) := Byte(Value^);
TYPE_STR:
begin
L := 0;
while Byte(Pointer(Integer(Value) + L)^) <> 0 do
L := L + 1;
if Assigned(Pointer(FAddr^)) then
begin
FreeMem(Pointer(FAddr^));
Pointer(FAddr^) := nil;
end;
GetMem(Pointer(FAddr^), L + 1);
for I := 0 to L do
Byte(Pointer(Integer(FAddr^) + I)^) :=
Byte(Pointer(Integer(Value) + I)^);
end;
TYPE_ARRAY: GetValue(0).P := Value;
end;
end;
procedure TValue.SetString(const Value: String);
var
I, L: Integer;
begin
case FType_ of
TYPE_FLOAT: Float(FAddr^) := StrToFloat(Value);
TYPE_INT: Integer(FAddr^) := StrToInt(Value);
TYPE_BYTE: Byte(FAddr^) := StrToInt(Value);
TYPE_STR: begin
if Assigned(Pointer(FAddr^)) then
begin
FreeMem(Pointer(FAddr^));
Pointer(FAddr^) := nil;
end;
L := Length(Value);
GetMem(Pointer(FAddr^), L + 1);
for I := 1 to L do
Byte(Pointer(Integer(FAddr^) + I - 1)^) := Ord(Value[I]);
Byte(Pointer(Integer(FAddr^) + L)^) := 0;
end;
TYPE_ARRAY: GetValue(0).S := Value;
end;
end;
procedure TValue.SetValue(Index: Integer; const Value: TValue);
var
lCID: Integer;
begin
if not Assigned(Value) then
Exit;
if FType_ = TYPE_STR then
begin
GetData();
if (Index >= 0) and (Index < Length(S)) then
Byte(Pointer(Integer(FAddr^) + Index)^) := Value.B;
end
else if FType_ in [TYPE_ARRAY, TYPE_CLASS] then
begin
GetData();
if FType_ = TYPE_CLASS then
lCID := SizeOf(TCID)
else
lCID := 0;
if (Index >= 0) and (Index < Count) then
TValue(Pointer(Integer(FAddr^) + lCID +
Index * SizeOf(TValue))^).Equal(Value);
end
else
Equal(Value);
end;
procedure TValue.GetData();
begin
if Assigned(FID) and Assigned(GetProc) then
if FType_ > TYPE_VOID then
GetProc(FID^, Self);
end;
procedure TValue.SetData();
begin
if Assigned(FID) and Assigned(SetProc) then
if FType_ > TYPE_VOID then
SetProc(FID^, Self);
end;
procedure TValue.FreeID();
begin
if Assigned(FID) then
begin
FreeMem(FID);
FID := nil;
end;
end;
procedure TValue.FreeAddr();
begin
if Assigned(FAddr) and FFreeMem then
begin
if FType_ = TYPE_STR then
if Assigned(Pointer(FAddr^)) then
FreeMem(Pointer(FAddr^))
else
else if FType_ = TYPE_ARRAY then
begin
Clear();
FreeMem(Pointer(FAddr^));
end
else if FType_ = TYPE_CLASS then
begin
DestroyClass();
FreeMem(Pointer(FAddr^));
end;
FreeMem(FAddr);
FAddr := nil;
end;
end;
{ public }
constructor TValue.Create(AType_: TType_; const AID: TID;
AAddr: Pointer);
begin
inherited Create();
FType_ := AType_;
FID := nil;
if AID <> '' then
ID := AID;
FAddr := AAddr;
FFreeMem := not Assigned(FAddr);
if (FType_ > TYPE_VOID) and FFreeMem then
case FType_ of
TYPE_FLOAT: GetMem(FAddr, SizeOf(Float));
TYPE_INT: GetMem(FAddr, SizeOf(Integer));
TYPE_BYTE: GetMem(FAddr, SizeOf(Byte));
TYPE_STR:
begin
GetMem(FAddr, SizeOf(Pointer));
GetMem(Pointer(FAddr^), SizeOf(Byte));
Byte(Pointer(FAddr^)^) := 0;
end;
TYPE_ARRAY:
begin
GetMem(FAddr, SizeOf(Pointer));
GetMem(Pointer(FAddr^), SizeOf(TValue));
TValue(Pointer(FAddr^)^) := nil;
end;
TYPE_CLASS:
begin
GetMem(FAddr, SizeOf(Pointer));
GetMem(Pointer(FAddr^), SizeOf(TCID) + SizeOf(TValue));
TCID(Pointer(FAddr^)^) := 0;
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID))^) := nil;
end;
end;
end;
destructor TValue.Destroy();
begin
FreeID();
FreeAddr();
inherited;
end;
procedure TValue.Assign(ASource: TValue);
var
I, Size: Integer;
begin
if (not Assigned(ASource)) or (ASource = Self) then
Exit;
FreeAddr();
FType_ := ASource.FType_;
ID := ASource.ID;
FFreeMem := ASource.FFreeMem;
if FFreeMem then
begin
case FType_ of
TYPE_FLOAT: Size := SizeOf(Float);
TYPE_INT: Size := SizeOf(Integer);
TYPE_BYTE: Size := SizeOf(Byte);
TYPE_STR:
begin
GetMem(FAddr, SizeOf(Pointer));
Pointer(FAddr^) := nil;
SetString(ASource.GetString());
Exit;
end;
TYPE_ARRAY:
begin
GetMem(FAddr, SizeOf(Pointer));
GetMem(Pointer(FAddr^), SizeOf(TValue) * ASource.Count + 1);
for I := 0 to ASource.Count - 1 do
TValue(Pointer(Integer(FAddr^) + I * SizeOf(TValue))^) :=
ValueCopy(TValue(Pointer(Integer(ASource.FAddr^) +
I * SizeOf(TValue))^));
TValue(Pointer(Integer(FAddr^) +
ASource.Count * SizeOf(TValue))^) := nil;
Exit;
end;
TYPE_CLASS:
begin
GetMem(Pointer(FAddr^), SizeOf(TCID) +
SizeOf(TValue) * ASource.Count + 1);
TCID(Pointer(FAddr^)^) := TCID(Pointer(ASource.FAddr^)^);
for I := 0 to ASource.Count - 1 do
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^) :=
ValueCopy(TValue(Pointer(Integer(ASource.FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^));
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
ASource.Count * SizeOf(TValue))^) := nil;
Exit;
end;
else
Exit;
end;
GetMem(FAddr, Size);
Move(ASource.FAddr^, FAddr^, Size);
end
else
FAddr := ASource.FAddr;
end;
procedure TValue.Copy(ASource: TValue);
var
I, Size: Integer;
begin
if (not Assigned(ASource)) or (ASource = Self) then
Exit;
FreeAddr();
FType_ := ASource.FType_;
ID := ASource.ID;
FFreeMem := True;
case FType_ of
TYPE_FLOAT: Size := SizeOf(Float);
TYPE_INT: Size := SizeOf(Integer);
TYPE_BYTE: Size := SizeOf(Byte);
TYPE_STR:
begin
GetMem(FAddr, SizeOf(Pointer));
Pointer(FAddr^) := nil;
SetString(ASource.GetString());
Exit;
end;
TYPE_ARRAY:
begin
GetMem(FAddr, SizeOf(Pointer));
GetMem(Pointer(FAddr^), SizeOf(TValue) * ASource.Count + 1);
for I := 0 to ASource.Count - 1 do
TValue(Pointer(Integer(FAddr^) + I * SizeOf(TValue))^) :=
ValueCopy(TValue(Pointer(Integer(ASource.FAddr^) +
I * SizeOf(TValue))^));
TValue(Pointer(Integer(FAddr^) +
ASource.Count * SizeOf(TValue))^) := nil;
Exit;
end;
TYPE_CLASS:
begin
GetMem(Pointer(FAddr^), SizeOf(TCID) +
SizeOf(TValue) * ASource.Count + 1);
TCID(Pointer(FAddr^)^) := TCID(Pointer(ASource.FAddr^)^);
for I := 0 to ASource.Count - 1 do
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^) :=
ValueCopy(TValue(Pointer(Integer(ASource.FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^));
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
ASource.Count * SizeOf(TValue))^) := nil;
Exit;
end;
else
Exit;
end;
GetMem(FAddr, Size);
Move(ASource.FAddr^, FAddr^, Size);
end;
procedure TValue.Ref(ASource: TValue);
begin
if (not Assigned(ASource)) or (ASource = Self) then
Exit;
FreeAddr();
FType_ := ASource.FType_;
ID := ASource.ID;
FFreeMem := False;
FAddr := ASource.FAddr;
end;
procedure TValue.Equal(ASource: TValue);
var
J: Integer;
begin
if (not Assigned(ASource)) or (ASource = Self) then
Exit;
case FType_ of
TYPE_FLOAT: F := ASource.F;
TYPE_INT: I := ASource.I;
TYPE_BYTE: B := ASource.B;
TYPE_STR: S := ASource.S;
TYPE_ARRAY:
if ASource.Type_ = TYPE_ARRAY then
begin
Clear();
FreeMem(Pointer(FAddr^));
GetMem(Pointer(FAddr^), SizeOf(TValue) * ASource.Count + 1);
for J := 0 to ASource.Count - 1 do
TValue(Pointer(Integer(FAddr^) + J * SizeOf(TValue))^) :=
ValueCopy(TValue(Pointer(Integer(ASource.FAddr^) +
J * SizeOf(TValue))^));
TValue(Pointer(Integer(FAddr^) +
ASource.Count * SizeOf(TValue))^) := nil;
end;
TYPE_CLASS:
if ASource.Type_ = TYPE_CLASS then
begin
DestroyClass();
FreeMem(Pointer(FAddr^));
GetMem(Pointer(FAddr^), SizeOf(TCID) +
SizeOf(TValue) * ASource.Count + 1);
TCID(Pointer(FAddr^)^) := TCID(Pointer(ASource.FAddr^)^);
for J := 0 to ASource.Count - 1 do
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
J * SizeOf(TValue))^) :=
ValueCopy(TValue(Pointer(Integer(ASource.FAddr^) + SizeOf(TCID) +
J * SizeOf(TValue))^));
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
ASource.Count * SizeOf(TValue))^) := nil;
end;
end;
end;
function TValue.Compare(ASource: TValue): Boolean;
begin
if (not Assigned(ASource)) or (ASource = Self) then
Result := True
else
case FType_ of
TYPE_FLOAT: Result := F = ASource.F;
TYPE_INT: Result := I = ASource.I;
TYPE_BYTE: Result := B = ASource.B;
TYPE_STR: Result := S = ASource.S;
else
Result := False;
end;
end;
procedure TValue.Add(AValue: TValue; AIndex: Integer);
var
I, lCount: Integer;
lPtr: Pointer;
begin
if (not Assigned(AValue)) or (AValue = Self) then
Exit;
if FType_ = TYPE_ARRAY then
begin
lCount := Count + 1;
if (AIndex < -1) or (AIndex >= lCount) then
Exit;
GetMem(lPtr, SizeOf(TValue) * (lCount + 1));
if AIndex = -1 then
AIndex := lCount - 1;
for I := 0 to AIndex - 1 do
TValue(Pointer(Integer(lPtr) + I * SizeOf(TValue))^) :=
TValue(Pointer(Integer(FAddr^) + I * SizeOf(TValue))^);
TValue(Pointer(Integer(lPtr) + AIndex * SizeOf(TValue))^) :=
ValueCopy(AValue);
for I := AIndex + 1 to lCount - 1 do
TValue(Pointer(Integer(lPtr) + I * SizeOf(TValue))^) :=
TValue(Pointer(Integer(FAddr^) + (I - 1) * SizeOf(TValue))^);
TValue(Pointer(Integer(lPtr) + lCount * SizeOf(TValue))^) := nil;
FreeMem(Pointer(FAddr^));
Pointer(FAddr^) := lPtr;
end;
end;
procedure TValue.Set_(AValue: TValue; AIndex: Integer);
var
lPtr: Pointer;
begin
if (not Assigned(AValue)) or (AValue = Self) then
Exit;
if (AIndex < 0) or (AIndex >= Count) then
Exit;
lPtr := Pointer(Integer(FAddr^) + AIndex * SizeOf(TValue));
TValue(lPtr^).Free();
TValue(lPtr^) := ValueCopy(AValue);
end;
procedure TValue.Delete(AIndex: TValue);
var
I, lIndex, lCount: Integer;
lPtr: Pointer;
begin
if not Assigned(AIndex) then
Exit;
if FType_ = TYPE_ARRAY then
begin
if AIndex.Type_ = TYPE_STR then
lIndex := IndexOf(AIndex.S)
else
lIndex := AIndex.I;
lCount := Count;
if (lIndex < 0) or (lIndex >= lCount) then
Exit;
TValue(Pointer(Integer(FAddr^) + lIndex * SizeOf(TValue))^).Free();
lCount := lCount - 1;
GetMem(lPtr, SizeOf(TValue) * (lCount + 1));
for I := 0 to lIndex - 1 do
TValue(Pointer(Integer(lPtr) + I * SizeOf(TValue))^) :=
TValue(Pointer(Integer(FAddr^) + I * SizeOf(TValue))^);
for I := lIndex to lCount - 1 do
TValue(Pointer(Integer(lPtr) + I * SizeOf(TValue))^) :=
TValue(Pointer(Integer(FAddr^) + (I + 1) * SizeOf(TValue))^);
TValue(Pointer(Integer(lPtr) + lCount * SizeOf(TValue))^) := nil;
FreeMem(Pointer(FAddr^));
Pointer(FAddr^) := lPtr;
end;
end;
procedure TValue.Clear();
var
I: Integer;
lValue: TValue;
begin
if FType_ = TYPE_ARRAY then
begin
if Assigned(Pointer(FAddr^)) then
begin
I := 0;
lValue := TValue(Pointer(Integer(FAddr^) + I * SizeOf(TValue))^);
while Assigned(lValue) do
begin
lValue.Free();
I := I + 1;
lValue := TValue(Pointer(Integer(FAddr^) + I * SizeOf(TValue))^);
end;
end;
FreeMem(Pointer(FAddr^));
GetMem(Pointer(FAddr^), SizeOf(TValue));
TValue(Pointer(FAddr^)^) := nil;
end;
end;
procedure TValue.CreateClass(ACID: TCID; const AArguments: TArguments);
var
I: Integer;
begin
if FType_ = TYPE_CLASS then
begin
DestroyClass();
FreeMem(Pointer(FAddr^));
GetMem(Pointer(FAddr^), SizeOf(TCID) +
(High(AArguments) + 2) * SizeOf(TValue));
TCID(Pointer(FAddr^)^) := ACID;
for I := 0 to High(AArguments) do
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^) := TValue.Create(AArguments[I].Type_,
AArguments[I].ID);
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
(High(AArguments) + 1) * SizeOf(TValue))^) := nil;
end;
end;
procedure TValue.DestroyClass();
var
I: Integer;
lValue: TValue;
begin
if FType_ = TYPE_CLASS then
begin
if Assigned(Pointer(FAddr^)) then
begin
I := 0;
lValue := TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^);
while Assigned(lValue) do
begin
lValue.Free();
I := I + 1;
lValue := TValue(Pointer(Integer(FAddr^) + SizeOf(TCID) +
I * SizeOf(TValue))^);
end;
end;
FreeMem(Pointer(FAddr^));
GetMem(Pointer(FAddr^), SizeOf(TCID) + SizeOf(TValue));
TCID(Pointer(FAddr^)^) := 0;
TValue(Pointer(Integer(FAddr^) + SizeOf(TCID))^) := nil;
end;
end;
function TValue.IndexOf(const AID: TID): Integer;
var
I, lCID: Integer;
lValue: TValue;
begin
Result := -1;
if not (FType_ in [TYPE_ARRAY, TYPE_CLASS]) then
Exit;
if FType_ = TYPE_CLASS then
lCID := SizeOf(TCID)
else
lCID := 0;
for I := 0 to Count - 1 do
begin
lValue := TValue(Pointer(Integer(FAddr^) + lCID + I * SizeOf(TValue))^);
if AID = lValue.ID then
begin
Result := I;
Break;
end;
end;
end;
function TValue.Field(const AID: TID): TValue;
var
I, lCID: Integer;
lValue: TValue;
begin
Result := nil;
if not (FType_ in [TYPE_ARRAY, TYPE_CLASS]) then
Exit;
if FType_ = TYPE_CLASS then
lCID := SizeOf(TCID)
else
lCID := 0;
for I := 0 to Count - 1 do
begin
lValue := TValue(Pointer(Integer(FAddr^) + lCID + I * SizeOf(TValue))^);
if AID = lValue.ID then
begin
Result := ValueRef(lValue);
Break;
end;
end;
end;
function TValue.Offset(AIndex: TValue): TValue;
var
I, lCID: Integer;
lID: String;
lValue: TValue;
begin
if not Assigned(AIndex) then
begin
Result := TValue.Create();
Exit;
end;
if FType_ = TYPE_STR then
begin
GetData();
I := AIndex.I;
if (I < 0) or (I >= Length(S)) then
Result := TValue.Create()
else
Result := TValue.Create(TYPE_BYTE, '',
Pointer(Integer(FAddr^) + I));
end
else if FType_ in [TYPE_ARRAY, TYPE_CLASS] then
begin
GetData();
if FType_ = TYPE_CLASS then
lCID := SizeOf(TCID)
else
lCID := 0;
if AIndex.Type_ = TYPE_STR then
begin
lID := AIndex.S;
Result := nil;
for I := 0 to Count - 1 do
begin
lValue := TValue(Pointer(Integer(FAddr^) + lCID +
I * SizeOf(TValue))^);
if lID = lValue.ID then
begin
Result := ValueRef(lValue);
Break;
end;
end;
if not Assigned(Result) then
Result := TValue.Create();
end
else
begin
I := AIndex.I;
if (I < 0) or (I >= Count) then
Result := TValue.Create()
else
Result := ValueRef(TValue(Pointer(Integer(FAddr^) + lCID +
I * SizeOf(TValue))^));
end;
end
else
Result := TValue.Create();
end;
procedure TValue.Get(var AValue);
begin
case FType_ of
TYPE_FLOAT: Float(AValue) := Float(FAddr^);
TYPE_INT: Integer(AValue) := Integer(FAddr^);
TYPE_BYTE: Byte(AValue) := Byte(FAddr^);
TYPE_STR: String(AValue) := GetString();
end;
end;
procedure TValue.Put(const AValue; AType_: TType_; ASetType: Boolean);
begin
if ASetType and (AType_ <> FType_) and FFreeMem then
begin
FreeAddr();
FType_ := AType_;
end;
case FType_ of
TYPE_FLOAT:
begin
if not Assigned(FAddr) then
GetMem(FAddr, SizeOf(Float));
Float(FAddr^) := Float(AValue);
end;
TYPE_INT:
begin
if not Assigned(FAddr) then
GetMem(FAddr, SizeOf(Integer));
Integer(FAddr^) := Integer(AValue);
end;
TYPE_BYTE:
begin
if not Assigned(FAddr) then
GetMem(FAddr, SizeOf(Byte));
Byte(FAddr^) := Byte(AValue);
end;
TYPE_STR: SetString(String(AValue));
end;
end;
end.
|
{ 14/02/2007 08:38:55 (GMT+0:00) > [Akadamia] checked in }
{ 14/02/2007 08:38:40 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:15:12 (GMT+0:00) > [Akadamia] checked in }
{ 08/02/2007 14:06:18 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: SDU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of Variable String example to Delphi
Shows how to extract three variable length strings from a
structure
History:
-----------------------------------------------------------------------------}
unit VSU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// Use enumerated types to create unique IDs as required
TEventID = (EventSimStart);
TDataDefineId = (Definition1);
TDataRequestId = (Request1);
// Structure which gets mapped onto the received data
// in practice "Strings" will be longer than 1 character
StructVS = packed record
Strings: packed array[0..0] of char; // variable-length strings
end;
PStructVS = ^StructVS;
// The form
TVariableStringsForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer);
end;
var
VariableStringsForm: TVariableStringsForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
VariableStringsForm.DispatchHandler(pData, cbData, pContext);
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TVariableStringsForm.DispatchHandler(pData: PSimConnectRecv; cbData:
DWORD;
pContext: Pointer);
var
hr: HRESULT;
pszTitle: PChar;
pszAirline: Pchar;
pszType: Pchar;
cbTitle: DWORD;
cbAirline: DWORD;
cbType: DWORD;
ps: PStructVS;
pObjData: PSimConnectRecvSimObjectDataByType;
Evt: PSimconnectRecvEvent;
OpenData: PSimConnectRecvOpen;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
// Only keep the last 200 lines in the Memo
while Memo.Lines.Count > 200 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor, dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
EventSimStart:
begin
hr := SimConnect_RequestDataOnSimObjectType(hSimConnect,
Ord(Request1), Ord(Definition1), 0,
SIMCONNECT_SIMOBJECT_TYPE_USER);
end;
end;
end;
SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE:
begin
pObjData := PSimConnectRecvSimObjectDataByType(pData);
Memo.Lines.Add('SimObject received');
case TDataRequestId(pObjData^.dwRequestID) of
Request1:
begin
pS := pStructVS(@pObjData^.dwData);
if Succeeded(SimConnect_RetrieveString(pData, cbData,
@pS^.strings[0], pszTitle, cbTitle))
and Succeeded(SimConnect_RetrieveString(pData, cbData,
@pS^.strings[cbTitle], pszAirline, cbAirline))
and Succeeded(SimConnect_RetrieveString(pData, cbData,
@pS^.strings[cbTitle + cbAirline], pszType, cbType))
then
begin
Memo.Lines.Add(Format('Title = "%s" ', [pszTitle]));
Memo.Lines.Add(Format('Airline = "%s" ', [pszAirline]));
Memo.Lines.Add(Format('Type = "%s" ', [pszType]));
end
else
Memo.Lines.Add(Format('Received %s', [pS^.strings]));
end;
end;
end;
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TVariableStringsForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TVariableStringsForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TVariableStringsForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TVariableStringsForm.StartEventExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Variable Strings', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up a data definition contained a number of variable length strings
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(Definition1),
'TITLE', '', SIMCONNECT_DATATYPE_STRINGV);
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(Definition1),
'ATC AIRLINE', '', SIMCONNECT_DATATYPE_STRINGV);
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(Definition1),
'ATC TYPE', '', SIMCONNECT_DATATYPE_STRINGV);
// Request a simulation start event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart),
'SimStart');
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TVariableStringsForm.StartPollExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up a data definition contained a number of variable length strings
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(Definition1),
'TITLE', '', SIMCONNECT_DATATYPE_STRINGV);
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(Definition1),
'ATC AIRLINE', '', SIMCONNECT_DATATYPE_STRINGV);
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(Definition1),
'ATC TYPE', '', SIMCONNECT_DATATYPE_STRINGV);
// Request a simulation start event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart),
'SimStart');
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TTeeBISource FMX Editor Dialog }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit FMXBI.Editor.Chart.Source;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.ListBox, FMX.Edit, FMX.Layouts,
{$IF CompilerVersion<=27}
{$DEFINE HASFMX20}
{$ENDIF}
{$IFNDEF HASFMX20}
FMX.Controls.Presentation,
{$ENDIF}
FMXTee.Constants, FMXTee.Engine, FMXTee.Editor.Source, FMXBI.Chart.Source;
type
TValueControl=record
public
Text : TLabel;
Combo : TComboBox;
end;
TBISourceEditor = class(TBaseSourceEditor)
LayoutData: TLayout;
GroupFields: TLayout;
LLabels: TLabel;
CBLabelsField: TComboBox;
BSelectData: TButton;
LData: TLabel;
procedure BApplyClick(Sender: TObject);
procedure CBLabelsFieldChange(Sender: TObject);
procedure BSelectDataClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
FValueControls : Array of TValueControl;
procedure ChangedCombo(Sender: TObject);
procedure CreateControls;
procedure DestroyCombos;
procedure FillCombos;
procedure RefreshControls;
procedure RefreshDataLabel;
function Source:TTeeBISource;
public
{ Public declarations }
class procedure Edit(const AOwner:TComponent; const ASource:TTeeBISource); static;
end;
implementation
|
unit TestDelphiNetWebService;
{ AFS March 2006
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility }
interface
uses
System.Collections, System.ComponentModel,
System.Data, System.Diagnostics, System.Web,
System.Web.Services;
type
/// <summary>
/// Summary description for WebService1.
/// </summary>
TWebService1 = class(System.Web.Services.WebService)
{$REGION 'Designer Managed Code'}
strict private
/// <summary>
/// Required designer variable.
/// </summary>
components: IContainer;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure InitializeComponent;
{$ENDREGION}
strict protected
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure Dispose(disposing: boolean); override;
private
{ Private Declarations }
public
constructor Create;
// Sample Web Service Method
[WebMethod(Description='A Sample Web Method')]
function HelloWorld: string;
end;
implementation
{$REGION 'Designer Managed Code'}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TWebService1.InitializeComponent;
begin
end;
{$ENDREGION}
constructor TWebService1.Create;
begin
inherited;
//
// Required for Designer support
//
InitializeComponent;
//
// TODO: Add any constructor code after InitializeComponent call
//
end;
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure TWebService1.Dispose(disposing: boolean);
begin
if disposing and (components <> nil) then
components.Dispose;
inherited Dispose(disposing);
end;
// Sample Web Service Method
// The following method is provided to allow for testing a new web service.
(*
function TWebService1.HelloWorld: string;
begin
Result := 'Hello World';
end;
*)
function TWebService1.HelloWorld: string;
begin
Result := 'Hello, interweb';
end;
end.
|
unit Menus;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
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/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
Version 1.01:
Version 1.00:
* File creation.
* TMenuItem, TMenu, TMainMenu and TPopupMenu implemented
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
LLCLOSInt, Windows,
Classes, Controls;
type
TMenuItem = class(TControl)
private
fItems: TList;
fHandle: THandle;
fMenuIdent: integer;
fCaption: string;
fEnabled,
fChecked,
fAutoCheck: boolean;
function GetItem(Index: integer): TMenuItem;
procedure SetCaption(const Value: string);
procedure SetEnabled(Value: boolean);
procedure SetChecked(Value: boolean);
procedure SetMenuItem(ParentMenuHandle: THandle; FirstCallType: integer; var MenuIdent: integer);
function ClickMenuItem(MenuIdent: integer): boolean;
protected
procedure ReadProperty(const PropName: string; Reader: TReader); override;
procedure SetParentComponent(Value: TComponent); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Items[Index: integer]: TMenuItem read GetItem; default;
property Handle: THandle read fHandle;
property Caption: string read fCaption write SetCaption;
property Enabled: boolean read fEnabled write SetEnabled;
property Checked: boolean read fChecked write SetChecked;
property AutoCheck: boolean read fAutoCheck write fAutoCheck;
end;
TMenu = class(TControl)
private
fHandle: THandle;
fItems: TMenuItem;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Handle: THandle read fHandle;
property Items: TMenuItem read fItems;
end;
TMainMenu = class(TMenu)
protected
procedure SetParentComponent(Value: TComponent); override;
procedure SetMainMenuForm(FormHandle: THandle; var BaseMenuIdent: integer);
procedure ClickMainMenuForm(MsgItemID: word; var MsgResult: LRESULT);
public
constructor Create(AOwner: TComponent); override;
end;
TPopupMenu = class(TMenu)
public
constructor Create(AOwner: TComponent); override;
procedure Popup(X, Y: integer);
end;
//------------------------------------------------------------------------------
implementation
uses
Forms;
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
type
TPCustomForm = class(TCustomForm); // To access to protected part
const
SMFC_NOTFIRSTCALL = 0;
SMFC_MAINMENU = 1;
SMFC_POPUPMENU = 2;
//------------------------------------------------------------------------------
{ TMenuItem }
constructor TMenuItem.Create(AOwner: TComponent);
begin
inherited;
fItems := TList.Create;
fEnabled := true;
ATType := ATTMenuItem;
end;
destructor TMenuItem.Destroy;
begin
if fHandle<>0 then
LLCL_DestroyMenu(fHandle);
fHandle := 0;
fItems.Free;
inherited;
end;
procedure TMenuItem.ReadProperty(const PropName: string; Reader: TReader);
const Properties: array[0..3] of PChar = (
'Caption', 'Enabled', 'Checked', 'AutoCheck');
begin
case StringIndex(PropName, Properties) of
0 : fCaption := Reader.StringProperty;
1 : fEnabled := Reader.BooleanProperty;
2 : fChecked := Reader.BooleanProperty;
3 : fAutoCheck := Reader.BooleanProperty;
else inherited;
end;
end;
procedure TMenuItem.SetParentComponent(Value: TComponent);
begin
inherited;
if Value<>nil then
if Value.InheritsFrom(TMenu) then // TMainMenu or TPopupMenu
TMenu(Value).fItems.fITems.Add(self)
else // TMenuItem
TMenuItem(Value).fITems.Add(self);
end;
function TMenuItem.GetItem(Index: integer): TMenuItem;
begin
result := TMenuItem(fItems[Index]);
end;
procedure TMenuItem.SetCaption(const Value: string);
var Flags: integer;
begin
fCaption := Value;
Flags := MF_STRING;
if fEnabled then
Flags := Flags or MF_ENABLED
else
Flags := Flags or MF_GRAYED;
if fChecked then
Flags := Flags or MF_CHECKED
else
Flags := Flags or MF_UNCHECKED;
LLCL_ModifyMenu(fHandle, fMenuIdent, MF_BYCOMMAND or Flags, 0, @fCaption[1]);
end;
procedure TMenuItem.SetEnabled(Value: boolean);
var Flags: integer;
begin
fEnabled := Value;
if fEnabled then
Flags := MF_ENABLED
else
Flags := MF_GRAYED;
LLCL_EnableMenuItem(fHandle, fMenuIdent, MF_BYCOMMAND or Flags);
end;
procedure TMenuItem.SetChecked(Value: boolean);
var Flags: integer;
begin
fChecked := Value;
if fChecked then
Flags := MF_CHECKED
else
Flags := MF_UNCHECKED;
LLCL_CheckMenuItem(fHandle, fMenuIdent, MF_BYCOMMAND or Flags);
end;
procedure TMenuItem.SetMenuItem(ParentMenuHandle: THandle; FirstCallType: integer; var MenuIdent: integer);
var aHandle: THandle;
var Flags: integer;
var i: integer;
begin
Flags := MF_STRING;
if FirstCallType=SMFC_NOTFIRSTCALL then
begin
if fCaption='-' then
Flags := Flags or MF_SEPARATOR
else
begin
if fEnabled then
Flags := Flags or MF_ENABLED
else
Flags := Flags or MF_GRAYED;
if fChecked then
Flags := Flags or MF_CHECKED;
end;
end;
if fItems.Count=0 then
begin
fHandle := ParentMenuHandle;
Inc(MenuIdent);
fMenuIdent := MenuIdent;
aHandle := fMenuIdent;
end
else
begin
if FirstCallType=SMFC_MAINMENU then
fHandle := LLCL_CreateMenu()
else
fHandle := LLCL_CreatePopupMenu();
for i := 0 to fItems.Count-1 do
TMenuItem(fItems[i]).SetMenuItem(fHandle, SMFC_NOTFIRSTCALL, MenuIdent);
Flags := Flags or MF_POPUP;
aHandle := fHandle;
end;
if FirstCallType=SMFC_NOTFIRSTCALL then
LLCL_AppendMenu(ParentMenuHandle, Flags, aHandle, @fCaption[1]);
end;
function TMenuItem.ClickMenuItem(MenuIdent: integer): boolean;
var i: integer;
begin
result := true;
if fMenuIdent = MenuIdent then
begin
if fAutoCheck then
Checked := (not fChecked);
if Assigned(OnClick) then
OnClick(self);
exit;
end;
for i := 0 to fItems.Count-1 do
if TMenuItem(fItems[i]).ClickMenuItem(MenuIdent) then
exit;
result := false;
end;
{ TMenu }
constructor TMenu.Create(AOwner: TComponent);
begin
inherited;
fItems := TMenuItem.Create(self);
end;
destructor TMenu.Destroy;
begin
if fHandle<>0 then
LLCL_DestroyMenu(fHandle);
fHandle := 0;
inherited;
end;
{ TMainMenu }
constructor TMainMenu.Create(AOwner: TComponent);
begin
inherited;
ATType := ATTMainMenu
end;
procedure TMainMenu.SetParentComponent(Value: TComponent);
begin
inherited;
TCustomForm(Parent).Menu := self;
end;
procedure TMainMenu.SetMainMenuForm(FormHandle: THandle; var BaseMenuIdent: integer);
begin
if fHandle=0 then
begin
Items.SetMenuItem(0, SMFC_MAINMENU, BaseMenuIdent);
fHandle := Items.Handle;
end;
LLCL_SetMenu(FormHandle, fHandle);
LLCL_DrawMenuBar(fHandle);
end;
procedure TMainMenu.ClickMainMenuForm(MsgItemID: word; var MsgResult: LRESULT);
begin
if fHandle<>0 then
if Items.ClickMenuItem(MsgItemID) then
MsgResult := 0;
end;
{ TPopupMenu }
constructor TPopupMenu.Create(AOwner: TComponent);
begin
inherited;
ATType := ATTPopupMenu
end;
procedure TPopupMenu.Popup(X, Y: integer);
var MenuItemChoice: integer;
var i: integer;
begin
if fHandle=0 then
begin
i := TPCustomForm(Parent).LastMenuIdent;
Items.SetMenuItem(0, SMFC_POPUPMENU, i);
TPCustomForm(Parent).LastMenuIdent := i;
fHandle := Items.Handle;
end;
if fHandle<>0 then
begin
MenuItemChoice := integer(LLCL_TrackPopupMenu(fHandle,
TPM_LEFTALIGN or TPM_LEFTBUTTON or TPM_NONOTIFY or TPM_RETURNCMD,
X, Y, 0, TCustomForm(Parent).Handle, nil));
if MenuItemChoice<>0 then
Items.ClickMenuItem(MenuItemChoice);
end;
end;
//------------------------------------------------------------------------------
initialization
RegisterClasses([TMenuItem, TMainMenu, TPopupMenu]);
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Specific Paths : Load all definiton for Specific Paths
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
unit SpecificPath;
interface
uses Classes,
SysUtils;
type
TSpecificPath = class
private
fSpecificPathName : String; // Nom du Path Spécifique
fPaths : TStringList;
fGroupName : String; // Liste des chemins
procedure SetGroupName(S : String);
public
constructor Create(PathName : String; Paths : String);
destructor Destroy; Override;
property Paths: TStringList read FPaths;
property GroupName: String read FGroupName write SetGroupName;
end;
ESpecificPathGroupDuplicate = class(Exception);
Implementation
constructor TSpecificPath.Create(PathName : String; Paths : String);
begin
fSpecificPathName := PathName;
fPaths := TStringList.create();
// Important : Needed for Space in paths
fPaths.Delimiter := ',';
fPaths.StrictDelimiter := True;
fPaths.Delimitedtext := Paths;
end;
destructor TSpecificPath.Destroy;
begin
// writeln(fSpecificPathName+ ' -> ' + fPaths.Commatext);
fPaths.free;
fSpecificPathName := '';
fGroupName := '';
inherited Destroy;
end;
procedure TSpecificPath.SetGroupName(S : String);
begin
if fGroupName='' then
fGroupName := S
else
raise ESpecificPathGroupDuplicate.create('['+S+'] Duplicates');
end;
end. |
unit FC.Trade.Brokers.Stub.Order;
{$I Compiler.inc}
interface
uses
SysUtils,BaseUtils,Graphics,
Serialization, FC.Definitions,FC.Trade.Brokers.BrokerBase,
StockChart.Definitions,FC.Trade.Brokers.OrderBase;
type
//Специальное расширение для поддержки брокеров-"заглушек"
IStockBrokerStubSupport = interface
['{CAFBB2D1-1E2C-499E-A585-99EB8FCEF041}']
procedure OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
//Добавить произволный комментарий. Время установи комментария берется текущее
function AddMessage(const aOrder:IStockOrder; const aMessage: string; aColor: TColor=clDefault): IStockBrokerMessage; overload;
function GetCurrentPrice(const aSymbol: string; aKind: TStockBrokerPriceKind): TStockRealNumber;
function GetCurrentTime: TDateTime;
end;
{ TStockOrder }
TStockOrder = class (TStockOrderBase)
private
FBrokerCallBack : IStockBrokerStubSupport;
protected
procedure OnModifyOrder(const aModifyEventArgs: TStockOrderModifyEventArgs); override;
public
//Implementation
procedure Tick;
procedure Dispose; override;
constructor Create(const aStockBroker: IStockBrokerStubSupport; const aStockTrader: IStockTrader); overload;
end;
implementation
uses Math;
{ TStockOrder }
constructor TStockOrder.Create(const aStockBroker: IStockBrokerStubSupport; const aStockTrader: IStockTrader);
begin
inherited Create(aStockBroker as IStockBroker,aStockTrader);
FBrokerCallBack:=aStockBroker;
end;
procedure TStockOrder.Dispose;
begin
inherited;
FBrokerCallBack:=nil;
end;
procedure TStockOrder.OnModifyOrder(const aModifyEventArgs: TStockOrderModifyEventArgs);
begin
inherited;
FBrokerCallBack.OnModifyOrder(Self,aModifyEventArgs);
end;
procedure TStockOrder.Tick;
var
aPrice: TStockRealNumber;
begin
//Ордер уже открыт
if GetState = osOpened then
begin
case GetKind of
okBuy: begin
aPrice:=FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkAsk);
FWorstPrice:=min(FWorstPrice,aPrice);
FBestPrice:=max(FBestPrice,aPrice);
aPrice:=FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkBid);
FCurrentProfit:=aPrice-GetOpenPrice;
FWorstProfit:=min(FWorstProfit, FCurrentProfit);
FBestProfit:=max(FBestProfit,FCurrentProfit);
//Trailing Stop
if (GetTrailingStop<>0) then
begin
//Если лучшая цена изменилась, то двигаем StopLoss ближе, так, чтобы
//от лучшей цены до SL был наш TS
if ((GetStopLoss=0) or (GetStopLoss<GetBestPrice-GetTrailingStop)) and
(GetBestPrice-GetTrailingStop>=GetOpenPrice) then
SetStopLossInternal(GetBestPrice-GetTrailingStop,true);
end;
//Stop Loss
if (GetStopLoss<>0) and (aPrice<=GetStopLoss) then
Close('Broker: Stop loss triggered')
//Take profit
else if (GetTakeProfit<>0) and (aPrice>=GetTakeProfit) then
Close('Broker: Take profit triggered');
end;
okSell: begin
aPrice:=FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkBid);
FWorstPrice:=max(FWorstPrice,aPrice);
FBestPrice:=min(FBestPrice,aPrice);
aPrice:=FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkAsk);
FCurrentProfit:=GetOpenPrice-aPrice;
FWorstProfit:=min(FWorstProfit, FCurrentProfit);
FBestProfit:=max(FBestProfit,FCurrentProfit);
//Trailing Stop
if (GetTrailingStop<>0) then
begin
//Если лучшая цена изменилась, то двигаем StopLoss ближе, так, чтобы
//от лучшей цены до SL был наш TS
if ((GetStopLoss=0) or (GetStopLoss>GetBestPrice+GetTrailingStop)) and
(GetBestPrice+GetTrailingStop<=GetOpenPrice) then
SetStopLossInternal(GetBestPrice+GetTrailingStop,true);
end;
//Stop Loss
if (GetStopLoss<>0) and (aPrice>=GetStopLoss) then
Close('Broker: Stop loss triggered')
//Take profit
else if (GetTakeProfit<>0) and (aPrice<=GetTakeProfit) then
Close('Broker: Take profit triggered');
end
else
raise EAlgoError.Create;
end;
end
//Ордер не открыт, он отложенный
else if (GetState=osPending) and (not IsPendingSuspended) then
begin
if (GetPendingExpirationTime<>0) and (FBrokerCallBack.GetCurrentTime>=GetPendingExpirationTime) then
RevokePending
else begin
Assert(GetPendingOpenPrice<>0);
//Стоповый ордер на покупку
if (GetKind=okBuy) and (GetPendingType=ptStop) and (FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkAsk)>=GetPendingOpenPrice) then
OpenInternal(GetSymbol, GetKind,GetLots,'Broker: Buy Stop order triggered')
//Лимитный ордер на покупку
else if (GetKind=okBuy) and (GetPendingType=ptLimit) and (FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkAsk)<=GetPendingOpenPrice) then
OpenInternal(GetSymbol,GetKind,GetLots,'Broker: Buy Limit order triggered')
//Стоповый ордер на продажу
else if (GetKind=okSell) and (GetPendingType=ptStop) and (FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkBid)<=GetPendingOpenPrice) then
OpenInternal(GetSymbol,GetKind,GetLots,'Broker: Sell Stop order triggered')
//Лимитный ордер на продажу
else if (GetKind=okSell) and (GetPendingType=ptLimit) and (FBrokerCallBack.GetCurrentPrice(GetSymbol,bpkBid)>=GetPendingOpenPrice) then
OpenInternal(GetSymbol,GetKind,GetLots,'Broker: Sell Limit order triggered')
end;
end;
end;
end.
|
unit SimpleDAO;
interface
uses
SimpleInterface,
System.RTTI,
System.Generics.Collections,
System.Classes,
Data.DB,
{$IFNDEF CONSOLE}
{$IFDEF FMX}
FMX.Forms,
{$ELSE}
Vcl.Forms,
{$ENDIF}
{$ENDIF}
SimpleDAOSQLAttribute,
System.Threading;
Type
TSimpleDAO<T: class, constructor> = class(TInterfacedObject, iSimpleDAO<T>)
private
FQuery: iSimpleQuery;
FDataSource: TDataSource;
FSQLAttribute: iSimpleDAOSQLAttribute<T>;
{$IFNDEF CONSOLE}
FForm: TForm;
{$ENDIF}
FList: TObjectList<T>;
function FillParameter(aInstance: T): iSimpleDAO<T>; overload;
function FillParameter(aInstance: T; aId: Variant)
: iSimpleDAO<T>; overload;
procedure OnDataChange(Sender: TObject; Field: TField);
public
constructor Create(aQuery: iSimpleQuery);
destructor Destroy; override;
class function New(aQuery: iSimpleQuery): iSimpleDAO<T>; overload;
function DataSource(aDataSource: TDataSource): iSimpleDAO<T>;
function Insert(aValue: T): iSimpleDAO<T>; overload;
function Update(aValue: T): iSimpleDAO<T>; overload;
function Delete(aValue: T): iSimpleDAO<T>; overload;
function Delete(aField: String; aValue: String): iSimpleDAO<T>;
overload;
function LastID: iSimpleDAO<T>;
function LastRecord: iSimpleDAO<T>;
{$IFNDEF CONSOLE}
function Insert: iSimpleDAO<T>; overload;
function Update: iSimpleDAO<T>; overload;
function Delete: iSimpleDAO<T>; overload;
{$ENDIF}
function Find(aBindList: Boolean = True): iSimpleDAO<T>; overload;
function Find(var aList: TObjectList<T>): iSimpleDAO<T>; overload;
function Find(aId: Integer): T; overload;
function Find(aKey: String; aValue: Variant): iSimpleDAO<T>; overload;
function SQL: iSimpleDAOSQLAttribute<T>;
{$IFNDEF CONSOLE}
function BindForm(aForm: TForm): iSimpleDAO<T>;
{$ENDIF}
end;
implementation
uses
System.SysUtils,
SimpleAttributes,
System.TypInfo,
SimpleRTTI,
SimpleSQL;
{ TGenericDAO }
{$IFNDEF CONSOLE}
function TSimpleDAO<T>.BindForm(aForm: TForm): iSimpleDAO<T>;
begin
Result := Self;
FForm := aForm;
end;
{$ENDIF}
constructor TSimpleDAO<T>.Create(aQuery: iSimpleQuery);
begin
FQuery := aQuery;
FSQLAttribute := TSimpleDAOSQLAttribute<T>.New(Self);
FList := TObjectList<T>.Create;
end;
function TSimpleDAO<T>.DataSource(aDataSource: TDataSource): iSimpleDAO<T>;
begin
Result := Self;
FDataSource := aDataSource;
FDataSource.DataSet := FQuery.DataSet;
FDataSource.OnDataChange := OnDataChange;
end;
function TSimpleDAO<T>.Delete(aValue: T): iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(aValue).Delete(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
Self.FillParameter(aValue);
FQuery.ExecSQL;
end;
{$IFNDEF CONSOLE}
function TSimpleDAO<T>.Delete: iSimpleDAO<T>;
var
aSQL: String;
Entity: T;
begin
Result := Self;
Entity := T.Create;
try
TSimpleSQL<T>.New(Entity).Delete(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
TSimpleRTTI<T>.New(nil).BindFormToClass(FForm, Entity);
Self.FillParameter(Entity);
FQuery.ExecSQL;
finally
FreeAndNil(Entity);
end;
end;
{$ENDIF}
function TSimpleDAO<T>.Delete(aField, aValue: String): iSimpleDAO<T>;
var
aSQL: String;
Entity: T;
aTableName: string;
begin
Result := Self;
Entity := T.Create;
try
TSimpleSQL<T>.New(Entity).Delete(aSQL);
TSimpleRTTI<T>.New(Entity).TableName(aTableName);
aSQL := 'DELETE FROM ' + aTableName + ' WHERE ' + aField +
' = ' + aValue;
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
FQuery.ExecSQL;
finally
FreeAndNil(Entity);
end;
end;
destructor TSimpleDAO<T>.Destroy;
begin
FreeAndNil(FList);
inherited;
end;
function TSimpleDAO<T>.Find(aBindList: Boolean = True): iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(nil).Fields(FSQLAttribute.Fields).Join(FSQLAttribute.Join)
.Where(FSQLAttribute.Where).GroupBy(FSQLAttribute.GroupBy)
.OrderBy(FSQLAttribute.OrderBy).Select(aSQL);
FQuery.DataSet.DisableControls;
FQuery.Open(aSQL);
if aBindList then
TSimpleRTTI<T>.New(nil).DataSetToEntityList(FQuery.DataSet, FList);
FSQLAttribute.Clear;
FQuery.DataSet.EnableControls;
end;
function TSimpleDAO<T>.Find(aId: Integer): T;
var
aSQL: String;
begin
Result := T.Create;
TSimpleSQL<T>.New(nil).SelectId(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
Self.FillParameter(Result, aId);
FQuery.Open;
TSimpleRTTI<T>.New(nil).DataSetToEntity(FQuery.DataSet, Result);
end;
{$IFNDEF CONSOLE}
function TSimpleDAO<T>.Insert: iSimpleDAO<T>;
var
aSQL: String;
Entity: T;
begin
Result := Self;
Entity := T.Create;
try
TSimpleSQL<T>.New(Entity).Insert(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
TSimpleRTTI<T>.New(nil).BindFormToClass(FForm, Entity);
Self.FillParameter(Entity);
FQuery.ExecSQL;
finally
FreeAndNil(Entity);
end;
end;
{$ENDIF}
function TSimpleDAO<T>.LastID: iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(nil).LastID(aSQL);
FQuery.Open(aSQL);
end;
function TSimpleDAO<T>.LastRecord: iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(nil).LastRecord(aSQL);
FQuery.Open(aSQL);
end;
function TSimpleDAO<T>.Find(var aList: TObjectList<T>): iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(nil).Fields(FSQLAttribute.Fields).Join(FSQLAttribute.Join)
.Where(FSQLAttribute.Where).GroupBy(FSQLAttribute.GroupBy)
.OrderBy(FSQLAttribute.OrderBy).Select(aSQL);
FQuery.Open(aSQL);
TSimpleRTTI<T>.New(nil).DataSetToEntityList(FQuery.DataSet, aList);
FSQLAttribute.Clear;
end;
function TSimpleDAO<T>.Insert(aValue: T): iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(aValue).Insert(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
Self.FillParameter(aValue);
FQuery.ExecSQL;
end;
class function TSimpleDAO<T>.New(aQuery: iSimpleQuery): iSimpleDAO<T>;
begin
Result := Self.Create(aQuery);
end;
procedure TSimpleDAO<T>.OnDataChange(Sender: TObject; Field: TField);
begin
if (FList.Count > 0) and (FDataSource.DataSet.RecNo - 1 <= FList.Count) then
begin
{$IFNDEF CONSOLE}
if Assigned(FForm) then
TSimpleRTTI<T>.New(nil).BindClassToForm(FForm,
FList[FDataSource.DataSet.RecNo - 1]);
{$ENDIF}
end;
end;
function TSimpleDAO<T>.SQL: iSimpleDAOSQLAttribute<T>;
begin
Result := FSQLAttribute;
end;
{$IFNDEF CONSOLE}
function TSimpleDAO<T>.Update: iSimpleDAO<T>;
var
aSQL: String;
Entity: T;
begin
Result := Self;
Entity := T.Create;
try
TSimpleSQL<T>.New(Entity).Update(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
TSimpleRTTI<T>.New(nil).BindFormToClass(FForm, Entity);
Self.FillParameter(Entity);
FQuery.ExecSQL;
finally
FreeAndNil(Entity)
end;
end;
{$ENDIF}
function TSimpleDAO<T>.Update(aValue: T): iSimpleDAO<T>;
var
aSQL: String;
aPK: String;
aPkValue: Integer;
begin
Result := Self;
TSimpleSQL<T>.New(aValue).Update(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
Self.FillParameter(aValue);
FQuery.ExecSQL;
end;
function TSimpleDAO<T>.FillParameter(aInstance: T): iSimpleDAO<T>;
var
Key: String;
DictionaryFields: TDictionary<String, Variant>;
P: TParams;
begin
DictionaryFields := TDictionary<String, Variant>.Create;
TSimpleRTTI<T>.New(aInstance).DictionaryFields(DictionaryFields);
try
for Key in DictionaryFields.Keys do
begin
if FQuery.Params.FindParam(Key) <> nil then
FQuery.Params.ParamByName(Key).Value :=
DictionaryFields.Items[Key];
end;
finally
FreeAndNil(DictionaryFields);
end;
end;
function TSimpleDAO<T>.FillParameter(aInstance: T; aId: Variant): iSimpleDAO<T>;
var
I: Integer;
ListFields: TList<String>;
begin
ListFields := TList<String>.Create;
TSimpleRTTI<T>.New(aInstance).ListFields(ListFields);
try
for I := 0 to Pred(ListFields.Count) do
begin
if FQuery.Params.FindParam(ListFields[I]) <> nil then
FQuery.Params.ParamByName(ListFields[I]).Value := aId;
end;
finally
FreeAndNil(ListFields);
end;
end;
function TSimpleDAO<T>.Find(aKey: String; aValue: Variant): iSimpleDAO<T>;
var
aSQL: String;
begin
Result := Self;
TSimpleSQL<T>.New(nil).Where(aKey + ' = :' + aKey).Select(aSQL);
FQuery.SQL.Clear;
FQuery.SQL.Add(aSQL);
FQuery.Params.ParamByName(aKey).Value := aValue;
FQuery.Open;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit PaletteAPI;
{ Component Palette / ToolBox API }
interface
uses System.Classes, ToolsAPI, Vcl.Graphics, Winapi.ActiveX, Vcl.Menus, Vcl.GraphUtil;
type
TNTAPaintIconSize = (pi16x16, pi24x24, pi32x32);
{ INTAPalettePaintIcon }
{ Palette items which implement INTAPalettePaintIcon will be called to paint
their icon to the given Canvas. }
INTAPalettePaintIcon = interface
['{D9BAD01A-99D9-4661-A470-90C7BC743DC9}']
procedure Paint(const Canvas: TCanvas; const X, Y: Integer;
const IconSize: TNTAPaintIconSize);
end;
INTAPalettePaintIcon160 = interface(INTAPalettePaintIcon)
['{EAF90D7D-0C59-4B90-AF44-EE525719EEFC}']
procedure Paint(const Canvas: TCanvas; const X, Y: Integer;
const IconSize: TNTAPaintIconSize; Enabled: Boolean); overload;
end;
{ TPalDragState: same as QControls.TDragState and Controls.TDragState.
Added here for a more generic TDragState. }
TPalDragState = (pdsDragEnter, pdsDragLeave, pdsDragMove);
{ IOTAPaletteDragAcceptor }
{ Register your IOTAPaletteDragAcceptor to mark that window
as acceptable for a drop target from the Palette. Handle
is topmost parent handle for your accepting window.
You can either use this, or register your window as an OLE drop target
and implement the IOTAPaletteOleDragDropOp interface to fill in the
OLE IDataObject drag and drop interface that will be "dragged over" the window.
}
IOTAPaletteDragAcceptor = interface
['{44E0BDCA-EEDD-45A5-8170-A764D9E26056}']
function GetHandle: THandle;
property Handle: THandle read GetHandle;
end;
{ IOTADesignerDragAcceptor }
{ Use this interface to see if your item is being dragged over
the VCL designer. }
IOTADesignerDragAcceptor = interface(IOTAPaletteDragAcceptor)
['{0047B6A0-D238-4627-8EBD-9F66A57CF2F5}']
end;
{ IOTACodeEditorDragAcceptor }
{ Use this interface to see if your item is being dragged over the code
editor. }
IOTACodeEditorDragAcceptor = interface(IOTAPaletteDragAcceptor)
['{7A8E3301-46A6-4226-9B8F-0BCEC7E9E801}']
function GetEditorControl: TObject;
{ Returns the EditorControl object for this acceptor. You can only
access this if you are NTA, however, the interface query is valid for OTA. }
property EditorControl: TObject read GetEditorControl;
end;
{ TOTAPaletteDragDropOp }
{ If your Palette Item implements this interface, DragOver will
be called when the item is dragged over something that supports
items being dropped on it, such as the Code Editor or
Designer. If the item was droped there, DragDrop will be called
for the item. }
IOTAPaletteDragDropOp = interface
['{A6364D92-37AB-4C39-ACA3-4CB1F8BD0C94}']
procedure DragOver(Target: IOTAPaletteDragAcceptor; X, Y: Integer;
State: TPalDragState; var Accept: Boolean);
procedure DragDrop(Target: IOTAPaletteDragAcceptor; X, Y: Integer);
end;
{ IOTAPaletteOleDragDropOp }
{ If your Palette Item implementes this interface, it will be called
to fill in the OLE IDataObject that will be dragged around.
This is required for designers or windows that use OLE drag and drop. }
IOTAPaletteOleDragDropOp = interface
['{5B524357-BB75-4C8A-B88F-954075A60FFD}']
{ Provides the TFormatEtc indicating the data that the IDataObject
will contain. }
function GetFormatRec: TFormatEtc;
{ Allows you to return true if you return data in the SourceFormat }
function QueryGetData(const SourceFormat: TFormatEtc): Boolean;
{ Allows you to fill in the Medium with the requested SourceFormat }
function GetData(const SourceFormat: TFormatEtc; out Medium: TStgMedium): Boolean;
end;
{ IOTAPaletteCursor }
{ Implement this interface to set the cursor when the palette item is dragged onto a designer.
WebForms uses this interface. }
IOTAPaletteCursor = interface
['{26DDEB04-1FFC-45B0-98E7-02AD8706AF70}']
function SetCursor: Boolean;
end;
{ IOTABasePaletteItem }
{ A base bare minimum item on the component palette. Base interface
for other items. }
IOTABasePaletteItem = interface
['{9CAEBEBF-6BFB-4E9A-B5E7-C3146DEFA6E8}']
function GetCanDelete: Boolean;
function GetEnabled: Boolean;
function GetHelpName: string;
function GetHintText: string;
function GetIDString: string;
function GetName: string;
function GetVisible: Boolean;
procedure SetEnabled(Value: Boolean);
procedure SetHelpName(const Value: string);
procedure SetName(const Value: string);
procedure SetVisible(const Value: Boolean);
procedure SetHintText(const Value: string);
{ If this item can be deleted (permanently), return true.
When Delete is called, you should remove the item (permanently) }
property CanDelete: Boolean read GetCanDelete;
property Enabled: Boolean read GetEnabled;
{ HelpName: used for displaying a help page for this item }
property HelpName: string read GetHelpName write SetHelpName;
{ HintText: The tool tip that is displayed for this item }
property HintText: string read GetHintText write SetHintText;
{ IDString: uniquely identifies the item, and never changes }
property IDString: string read GetIDString;
{ Name: the display name for a given item }
property Name: string read GetName write SetName;
{ Visible: if the item should be shown or not. Items should
be hidden when they are not valid for the current designer. Hidden
items may be shown when customizing the palette. }
property Visible: Boolean read GetVisible write SetVisible;
{ Execute: call it when you want this item to create itself
or execute its action. Groups will do nothing. Palette items
will typically create themselves. }
procedure Execute;
{ Delete is called when an item is removed from the IDE permanently.
CanDelete should be checked before calling Delete. }
procedure Delete;
end;
{ IOTAGetPaletteItem }
{ This interface is used to get a palette item from an IDataObject during
ole drag drop processing }
IOTAGetPaletteItem = interface
['{ED77C99B-5994-4C8B-92BB-CB72B3BEEBD9}']
function GetPaletteItem: IOTABasePaletteItem;
end;
{ IOTAExecutePaletteItem }
{ Modules implement this interface if they support execution of a palette item.
This interface is used when a snippet is double clicked. }
IOTAExecutePaletteItem = interface
['{70FAFCB8-EE3D-487F-B546-00E002AA7027}']
procedure ExecutePaletteItem(Item: IOTABasePaletteItem);
end;
{ IOTAComponentPaletteItem }
IOTAComponentPaletteItem = interface(IOTABasePaletteItem)
['{5A1A13FD-48B6-4A76-BB3F-374102172767}']
procedure SetPackageName(const Value: string);
procedure SetClassName(const Value: string);
procedure SetUnitName(const Value: string);
function GetClassName: string;
function GetPackageName: string;
function GetUnitName: string;
{ ClassName: the classname of the item. May be different, or the
same thing as the Name. }
property ClassName: string read GetClassName write SetClassName;
{ PackageName: the base package that this item exists in. }
property PackageName: string read GetPackageName write SetPackageName;
{ UnitName: the full unit name that contains the given item.
It may be blank for items that don't have units (such as templates) }
property UnitName: string read GetUnitName write SetUnitName;
end;
{ IOTAPaletteGroup }
{ Each group can contain regular palette items and/or other
groups. If the Item is a IOTAPaletteGroup, it is a subgroup. }
IOTAPaletteGroup = interface(IOTABasePaletteItem)
['{C7593CE8-1A0B-409F-B21F-84D983593F77}']
function GetCount: Integer;
function GetItem(const Index: Integer): IOTABasePaletteItem;
property Count: Integer read GetCount;
property Items[const Index: Integer]: IOTABasePaletteItem read GetItem; default;
{ AddGroup: adds a new sub-group to this group, or returns an existing
group if IDString was already found. }
function AddGroup(const Name, IDString: string): IOTAPaletteGroup;
{ AddItem: adds an item and returns its current index. The current
index may change if an item is deleted before it. }
function AddItem(const Item: IOTABasePaletteItem): Integer;
procedure Clear;
{ FindItem*: for locating particular items. If Recurse is True, it will
iterate through subgroups. }
function FindItem(const IDString: string; Recurse: Boolean): IOTABasePaletteItem;
function FindItemByName(const Name: string; Recurse: Boolean): IOTABasePaletteItem;
{ FindItemGroup: Finds the group for which the given item is contained in.
It should always be recursive, and can return the current group,
if it contains the item. Returns nil if it could not find the item. }
function FindItemGroup(const IDString: string): IOTAPaletteGroup;
function FindItemGroupByName(const Name: string): IOTAPaletteGroup;
{ InsertItem: Add an item at a particular index }
procedure InsertItem(const Index: Integer; const Item: IOTABasePaletteItem);
{ IndexOf: Returns the index of an Item in the group, or -1 if not found }
function IndexOf(const Item: IOTABasePaletteItem): Integer;
{ Move: Moves the item at CurIndex to NewIndex. If NewIndex < 0 then the item
is deleted. }
procedure Move(const CurIndex, NewIndex: Integer);
{ RemoveItem: remove the Item from the Group, searching all the
subgroups if Recursive is True. }
function RemoveItem(const IDString: string; Recurse: Boolean): Boolean;
end;
{ IOTAPaletteNotifier }
{ Add this notifier to the IOTAPaletteServices to be notified when
the palette has changed.
Modifed: called when you should refresh all your items.
Destroyed: Release your hold on the IOTAPaletteServices.
***NOTE:*** When ItemAdded or ItemRemoved are called, Modified will not
be called. This allows you to keep your updates to a minimum.
}
IOTAPaletteNotifier = interface(IOTANotifier)
['{6A3D2F2D-19BD-487E-A715-F1E7FECF8791}']
{ ItemAdded: called when a particular item is added to a group. }
procedure ItemAdded(const Group: IOTAPaletteGroup;
const Item: IOTABasePaletteItem);
{ ItemRemoved: called when a particular item is deleted from the
palette. You should release your references to the item at this time. }
procedure ItemRemoved(const Group: IOTAPaletteGroup;
const Item: IOTABasePaletteItem);
{ SelectedToolChanged: a new tool was selected. If you show a selected
tool, you should "unselect" it, and display this Tool as selected. }
procedure SelectedToolChanged(const Tool: IOTABasePaletteItem);
{ BeginUpdate/EndUpdate: will be called before multiple items are added
or removed. You should refresh your UI and list of items on the
last EndUpdate. }
procedure BeginUpdate;
procedure EndUpdate;
end;
TOTAPaletteColorItem = record
StartColor: TColor;
EndColor: TColor;
TextColor: TColor;
end;
TOTAPaletteButtonColors = record
RegularColor, SelectedColor, HotColor: TColor;
end;
TOTAPaletteOptions = record
BackgroundColor, BackgroundGradientColor: TColor;
BoldCaptions: Boolean;
CaptionOnlyBorder: Boolean;
UsePlusMinus: Boolean;
CategoryGradientDirection: TGradientDirection;
BackgroundGradientDirection: TGradientDirection;
end;
{ IOTAPaletteColorScheme }
{ A Color scheme used by the default palette. Can be used by other
palette via the IOTAPaletteServices, if you wish }
IOTAPaletteColorScheme = interface
['{75D3424A-6518-4465-B940-E004D7FFBB0C}']
function GetButtonColors: TOTAPaletteButtonColors;
function GetColor(const Index: Integer): TOTAPaletteColorItem;
function GetCount: Integer;
function GetIDString: string;
function GetName: string;
function GetOptions: TOTAPaletteOptions;
property ButtonColors: TOTAPaletteButtonColors read GetButtonColors;
property Options: TOTAPaletteOptions read GetOptions;
{ Colors are the colors to iterate through for each category when
using a Scheme }
property Colors[const Index: Integer]: TOTAPaletteColorItem read GetColor; default;
property Count: Integer read GetCount;
property IDString: string read GetIDString;
property Name: string read GetName;
end;
{ IOTAPaletteServices }
{ Query BorlandIDEServices for IOTAPaletteServices.
Use IOTAPaletteServices to iterate through all the top level groups,
add a notifier, and notify when you add/remove items. }
IOTAPaletteServices = interface
['{6963F71C-0A3F-4598-B6F6-9574CE0E6847}']
procedure SetSelectedTool(const Value: IOTABasePaletteItem);
function GetBaseGroup: IOTAPaletteGroup;
function GetSelectedTool: IOTABasePaletteItem;
function AddNotifier(const Notifier: IOTAPaletteNotifier): Integer;
{ BaseGroup: the first group in the palette which contains all of the
other groups. Iterate through it to find all the items. }
property BaseGroup: IOTAPaletteGroup read GetBaseGroup;
{ BeginUpdate: Call when you are adding or removing multiple items.
Always match with an EndUpdate. }
procedure BeginUpdate;
procedure EndUpdate;
{ Call ItemAdded when you add an item to a group. }
procedure ItemAdded(const Group: IOTAPaletteGroup;
const Item: IOTABasePaletteItem);
{ Call ItemRemoved when you delete an item. }
procedure ItemRemoved(const Group: IOTAPaletteGroup;
const Item: IOTABasePaletteItem);
{ Call Modifed when one or more items state has changed. }
procedure Modified;
{ RegisterDragAcceptor: returns the index of a newly registered acceptor }
function RegisterDragAcceptor(const Acceptor: IOTAPaletteDragAcceptor): Integer;
{ RemoveDragAcceptor: removes the acceptor at Index }
procedure UnRegisterDragAcceptor(const Index: Integer);
{ GetDragAcceptors: returns a list of all acceptors.
Each item in the list is a IOTAPaletteDragAcceptor }
function GetDragAcceptors: IInterfaceList;
function RegisterColorScheme(const ColorScheme: IOTAPaletteColorScheme): Integer;
procedure UnRegisterColorScheme(const Index: Integer);
function GetColorSchemes: IInterfaceList;
procedure RemoveNotifier(const Index: Integer);
{ SelectedTool: The current selected tool (may be nil). When you
visually change what the selected tool is, you must set this
property. It will notify each Notifier. }
property SelectedTool: IOTABasePaletteItem read GetSelectedTool write SetSelectedTool;
{ PaletteState: a string which contains multiple "states" that the IDE
is in. This allows palette items to determine if they should
be visible or not, based on what is in the state. }
procedure AddPaletteState(const State: string);
procedure RemovePaletteState(const State: string);
{ If your state is a "designer" state, use this method to add your state.
The "cPSDesignerActive" state will be set when at least one
designer state is in the PaletteState string. }
procedure AddPaletteDesignerState(const State: string);
function ContainsPaletteState(const State: string): Boolean;
function GetPaletteState: string;
end;
{ INTAPaletteContextMenu}
{ Query the BorlandIDEServices for this service. It allows you to dynamically
add context menus to the palette. Consumers can use menu items from the
interface, producers can add menu items to the interface. }
INTAPaletteContextMenu = interface
['{B58639BC-4332-45BF-A79E-D4977EE7E024}']
function GetCount: Integer;
function GetContextMenuItem(const Index: Integer): TMenuItem;
{ Adds a context menu to the internal list. }
procedure AddContextMenuItem(const MenuItem: TMenuItem);
{ Remove a context menu item previously added }
procedure RemoveContextMenuItem(const MenuItem: TMenuItem);
{ Retrieves the menu items. Since the item may have already been used
by someone else, you should remove it from the parent before
using it:
NewMenuItem := ContextMenuItems[I];
if NewMenuItem.Parent <> nil then
NewMenuItem.Parent.Remove(NewMenuItem);
}
property ContextMenuItems[const Index: Integer]: TMenuItem read GetContextMenuItem; default;
property Count: Integer read GetCount;
end;
(*
Note: snipplets have been removed in favor of code templates.
Please see CodeTemplateAPI.pas.
{ IOTASnippletManager }
{ Allows you to add/remove/query for code snipplets }
IOTASnippletManager = interface
['{8E96E78C-1153-4CCA-B8D2-CF5F4DBA7329}']
function GetCount: Integer;
{ Adds a snipplet to the palette; returns the IDString for the new snipplet as UTF8 }
function AddSnipplet(const Text: string): string; overload;
{ Remove a snipplet with the given IDString}
function RemoveSnipplet(const IDString: string): Boolean;
{ Remove all snipplet's }
procedure RemoveAllSnipplets;
{ The count of all snipplets }
property Count: Integer read GetCount;
{ Gets a particular id string at a given index }
function GetIDString(const Index: Integer): string;
{ Retrieves the snipplet text at a particular index }
function GetSnipplet(const Index: Integer): string; overload;
end deprecated;
{ IOTAWideSnippletManager }
{ Wide string support }
IOTAWideSnippletManager = interface
['{D30FBAC1-653C-405F-AF8A-6048A8B79ED2}']
{ AddSnipplet: Wide string version }
function AddSnippletW(const Text: Widestring): string;
{ GetSnipplet: Wide string version }
function GetSnippletW(const Index: Integer): Widestring;
end deprecated;
*)
const
{ Some predefined palette states }
cPSCodeEditorActive = 'CodeEditorActive';
cPSDesignerActive = 'DesignerActive';
{ The cPSDesignerActive state is special. If you remove it,
it clears all states added with AddDesignerState.
If you add a state with AddDesignerState, it implicitly adds
the cPSDesignerActive state. When you remove the last designer state
previously added with AddDesignerState, then cPSDesignerActive is
automatically removed.
}
implementation
end.
|
unit PascalCoin.Utils.Interfaces;
interface
uses System.Classes, System.SysUtils, System.Generics.Collections,
ClpIAsymmetricCipherKeyPair;
type
TRawBytes = TBytes;
HexStr = string;
TStringPair = TPair<string, string>;
TParamPair = TPair<string, variant>;
TECDSA_Signature = record
R: string;
RLen: Integer;
S: string;
SLen: Integer;
end;
TPascalOutcome = (poFalse, poTrue, poCancelled);
{$SCOPEDENUMS ON}
TKeyType = (SECP256K1, SECP384R1, SECP521R1, SECT283K1);
TKeyEncoding = (Base58, Hex);
TPayloadEncryption = (
/// <summary>
/// Not encrypted. Will be visible for everybody
/// </summary>
None,
/// <summary>
/// Using sender Public key. Only "sender" will be able to decrypt this
/// payload
/// </summary>
SendersKey,
/// <summary>
/// (default) : Using Public key of "target" account. Only "target" will be
/// able to decrypt this payload
/// </summary>
RecipientsKey,
/// <summary>
/// Encrypted data using pwd param, needs password to decrypt
/// </summary>
Password);
TPayloadEncode = (Hex, Base58, ASCII);
{$SCOPEDENUMS OFF}
IPascalCoinList<T> = Interface
['{18B01A91-8F0E-440E-A6C2-B4B7D4ABA473}']
function GetItem(const Index: Integer): T;
procedure Delete(const Index: Integer);
function Count: Integer;
function Add(Item: T): Integer;
procedure Clear;
property Item[const Index: Integer]: T read GetItem; default;
End;
IPascalCoinTools = interface
['{BC2151DE-5278-4B11-AB7C-28120557E88C}']
function IsHexaString(const Value: string): boolean;
function AccountNumberCheckSum(const Value: Cardinal): Integer;
function ValidAccountNumber(const Value: string): boolean;
function SplitAccount(const Value: string; out AccountNumber: Cardinal;
out CheckSum: Integer): boolean;
function ValidateAccountName(const Value: string): boolean;
function UnixToLocalDate(const Value: Integer): TDateTime;
function StrToHex(const Value: string): string;
end;
IKeyTools = interface
['{16D43FE0-6A73-446D-A95E-2C7250C10DA4}']
function UInt32ToLittleEndianByteArrayTwoBytes(AValue: UInt32): TBytes;
function TwoBytesByteArrayToDec(const AValue: TBytes): Int32;
function RetrieveKeyType(AValue: Int32): TKeyType;
function GetKeyTypeNumericValue(AKeyType: TKeyType): Int32;
function GetPascalCoinPublicKeyAsHexString(AKeyType: TKeyType;
const AXInput, AYInput: TRawBytes): string;
function GetPascalCoinPublicKeyAsBase58(const APascalCoinPublicKey
: string): String;
function DecryptPascalCoinPrivateKey(const AEncryptedPascalCoinPrivateKey,
APassword: string; out ADecryptedPascalCoinPrivateKey: TRawBytes)
: boolean;
function EncryptPascalCoinPrivateKey(const APascalCoinPrivateKey,
APassword: string): TRawBytes;
function GetPascalCoinPrivateKeyAsHexString(AKeyType: TKeyType;
const AInput: TRawBytes): string;
function GetPascalCoinPrivateKeyEncryptedAsHexString
(const APascalCoinPrivateKey, APassword: string): string;
function GenerateECKeyPair(AKeyType: TKeyType): IAsymmetricCipherKeyPair;
function GetPrivateKey(const AKeyPair: IAsymmetricCipherKeyPair): TRawBytes;
function GetPublicKeyAffineX(const AKeyPair: IAsymmetricCipherKeyPair)
: TRawBytes;
function GetPublicKeyAffineY(const AKeyPair: IAsymmetricCipherKeyPair)
: TRawBytes;
function ComputeSHA2_256_ToBytes(const AInput: TBytes): TBytes;
function EncryptPayloadWithPassword(const APassword,
APayload: string): string;
function EncryptPayloadWithPublicKey(const AKeyType: TKeyType;
const ABase58PublicKey, APayload: string): string;
{$IFDEF UNITTEST}
function SignOperation(const APrivateKey: string; const AKeyType: TKeyType;
const AMessage: string; var ASignature: TECDSA_Signature;
const K: string = ''): boolean; overload;
{$ELSE}
function SignOperation(const APrivateKey: string; const AKeyType: TKeyType;
const AMessage: string; var ASignature: TECDSA_Signature)
: boolean; overload;
{$ENDIF UNITTEST}
function SignOperation(const APrivateKey: TBytes; const AKeyType: TKeyType;
const AMessage: string; var ASignature: TECDSA_Signature)
: boolean; overload;
end;
IPascalCoinURI = interface
['{555F182F-0894-49E7-873A-149F37959BC1}']
function GetAccountNumber: string;
procedure SetAccountNumber(const Value: string);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetPayload: string;
procedure SetPayload(const Value: string);
function GetPayLoadEncode: TPayloadEncode;
procedure SetPayloadEncode(const Value: TPayloadEncode);
function GetPayloadEncrypt: TPayloadEncryption;
procedure SetPayloadEncrypt(const Value: TPayloadEncryption);
function GetPassword: string;
procedure SetPassword(const Value: string);
function GetURI: string;
procedure SetURI(const Value: string);
property AccountNumber: string read GetAccountNumber write SetAccountNumber;
property Amount: Currency read GetAmount write SetAmount;
property Payload: string read GetPayload write SetPayload;
property PayloadEncode: TPayloadEncode read GetPayLoadEncode
write SetPayloadEncode;
property PayloadEncrypt: TPayloadEncryption read GetPayloadEncrypt
write SetPayloadEncrypt;
property Password: string read GetPassword write SetPassword;
property URI: string read GetURI write SetURI;
end;
const
PascalCoinEncoding = ['a' .. 'z', '0' .. '9', '!', '@', '#', '$', '%', '^',
'&', '*', '(', ')', '-', '+', '{', '}', '[', ']', '_', ':', '`', '|', '<',
'>', ',', '.', '?', '/', '~'];
PascalCoinNameStart = ['a' .. 'z', '!', '@', '#', '$', '%', '^', '&', '*',
'(', ')', '-', '+', '{', '}', '[', ']', '_', ':', '`', '|', '<', '>', ',',
'.', '?', '/', '~'];
PascalCoinBase58 = ['1' .. '9', 'A' .. 'H', 'J' .. 'N', 'P' .. 'Z',
'a' .. 'k', 'm' .. 'z'];
PayloadEncryptionCode: array [TPayloadEncryption] of Char = ('N', 'S',
'R', 'P');
PayloadEncryptionFullCode: array [TPayloadEncryption] of String = ('None',
'Sender', 'Recipient', 'Password');
PayloadEncrptRPCValue: array [TPayloadEncryption] of string = ('none',
'sender', 'dest', 'aes');
PayloadEncodeCode: array [TPayloadEncode] of Char = ('H', 'B', 'A');
PayloadEncodeFullCode: array [TPayloadEncode] of String = ('Hex',
'Base58', 'ASCII');
implementation
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls,
OpenGL;
type
TfrmMain = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
procedure Init;
procedure SetDCPixelFormat;
procedure PrepareImage;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmMain: TfrmMain;
Angle : GLfloat = 0;
time : LongInt;
implementation
uses DGLUT;
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmMain.Init;
const
light_diffuse : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 0.0);
light_specular : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 0.0);
mat_specular : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
lmodel_ambient : Array [0..3] of GLfloat = (0.0, 0.0, 0.0, 0.0);
mat_shininess : GLfloat = 50.0;
begin
glEnable(GL_DEPTH_TEST);
glLightfv(GL_LIGHT0, GL_DIFFUSE, @light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, @light_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, @mat_shininess);
glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glColor3f(1.0, 1.0, 0.0);
PrepareImage;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
end;
{=======================================================================
Перерисовка окна}
procedure TfrmMain.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
glOrtho(-50.0,50.0,-50.0,50.0,200.0,300.0);
glMatrixMode(GL_MODELVIEW);
// без записи в буфер глубины
glDepthMask(FALSE);
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glNormal3f(0.0,0.0,1.0);
glTexCoord2f(0.0,0.0);
glVertex3f(0.0,0.0,0.0);
glTexCoord2f(1.0,0.0);
glVertex3f(100.0,0.0,0.0);
glTexCoord2f(1.0,1.0);
glVertex3f(100.0,100.0,0.0);
glTexCoord2f(0.0,1.0);
glVertex3f(0.0,100.0,0.0);
glEnd;
glDisable(GL_TEXTURE_2D);
glDepthMask(TRUE);
glMatrixMode(GL_PROJECTION);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glTranslatef(50.0, 50.0, 150.0);
glRotatef(Angle, 1.0, 1.0, 0.0);
glRotatef(Angle / (random (1) + 1), 0.0, 0.0, 1.0);
glutSolidIcosahedron;
glPopMatrix;
SwapBuffers(DC);
EndPaint(Handle, ps);
Angle := Angle + 0.25 * (GetTickCount - time) * 360 / 1000;
If Angle >= 360.0 then Angle := 0.0;
time := GetTickCount;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmMain.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glFrustum(-1.0, 1.0, -1.0, 1.0, 50.0, 300.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(-50.0, -50.0, -250.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC(DC);
end;
{=======================================================================
Создание окна}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Init;
time := GetTickCount;
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmMain.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmMain.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{======================================================================
Подготовка текстуры}
procedure TfrmMain.PrepareImage;
type
PPixelArray = ^TPixelArray;
TPixelArray = array [0..0] of Byte;
var
Bitmap : TBitmap;
Data : PPixelArray;
BMInfo : TBitmapInfo;
I, ImageSize : Integer;
Temp : Byte;
MemDC : HDC;
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile ('..\earth.bmp');
with BMinfo.bmiHeader do begin
FillChar (BMInfo, SizeOf(BMInfo), 0);
biSize := sizeof (TBitmapInfoHeader);
biBitCount := 24;
biWidth := Bitmap.Width;
biHeight := Bitmap.Height;
ImageSize := biWidth * biHeight;
biPlanes := 1;
biCompression := BI_RGB;
MemDC := CreateCompatibleDC (0);
GetMem (Data, ImageSize * 3);
try
GetDIBits (MemDC, Bitmap.Handle, 0, biHeight, Data, BMInfo, DIB_RGB_COLORS);
For I := 0 to ImageSize - 1 do begin
Temp := Data [I * 3];
Data [I * 3] := Data [I * 3 + 2];
Data [I * 3 + 2] := Temp;
end;
glTexImage2d(GL_TEXTURE_2D, 0, 3, biWidth,
biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, Data);
finally
FreeMem (Data);
DeleteDC (MemDC);
Bitmap.Free;
end;
end;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, ExtCtrls, Stacks, Jpeg, Tree, Spin;
const
_CellWidth = 60;
_CellHeight = 60;
_IndentLeft = 15;
_IndentTop = 15;
defBoardSize = 5;
type
TQueenAction = (GetBoard, CheckingIfSolution, FindPlaceToNewQueen);
TQueenForm = class(TForm)
LogMemo: TMemo;
Button1: TButton;
Timer1: TTimer;
Button2: TButton;
Button3: TButton;
Label1: TLabel;
ScrollBox: TScrollBox;
Image: TImage;
StopCheckBox: TCheckBox;
SolutionsList: TListBox;
ResetButton: TButton;
Label2: TLabel;
VisualBoard: TImage;
BoardSizeEdit: TSpinEdit;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure StopCheckBoxClick(Sender: TObject);
procedure ResetButtonClick(Sender: TObject);
procedure StartTimer;
procedure StopTimer;
procedure BoardSizeEditChange(Sender: TObject);
procedure BoardSizeEditKeyPress(Sender: TObject; var Key: Char);
procedure LogMemoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
SolutionCounter: integer; {счётчик количества решений}
board: TBoard; {собственно доска, тип объявлен в модуле Stacks}
Stack: PStack; {собственно указатель на стек. тип объявлен в модуле Stacks}
CurrQueen: byte; {текущий расставляемый ферзь}
itr, QueenHereCounter, Egg: byte; {переменная-итератор (нужна для поиска места установки нового ферзя)}
PrevAbsBoardPos: integer; //позиция предыдущего ферзя на предыдущей линии (нужно для дерева)
CurrAction: TQueenAction; {действие, выполняемой в данный момент}
FirstIteration: boolean; {флаг, указывающий - будет ли следующая выполняемая итерация - первой во всём бектрекинге}
StopIfFoundSolution: boolean;
function ClearBoard: TBoard; {функция очищает доску}
procedure SetQueenOnBoard(var a: TBoard; x,y: byte); {процедура помещает ферзя на доску в коодинаты (x;y) и помечает клетки доски, находящиеся по ударом этого ферзя}
procedure DrawBoard(board: TBoard); {вывести состояние доски в Grid}
function IterateS: boolean; {собственно сама ключевая процедура}
procedure WriteSolutionIntoList(board: TBoard);
procedure SetBoardSize(Value: byte);
public
{ Public declarations }
end;
var
QueenForm: TQueenForm;
BoardSize: byte;
implementation
{$R *.dfm}
{ TQueenForm }
procedure ClearCanvas(Canvas: TCanvas);
var
o_brush,o_pen: TColor;
begin
o_brush:=Canvas.Brush.Color;
o_pen:=Canvas.Pen.Color;
Canvas.Pen.Color:=clWhite;
Canvas.Brush.Color:=clWhite;
Canvas.Rectangle(Canvas.ClipRect);
Canvas.Pen.Color:=o_pen;
Canvas.Brush.Color:=o_brush;
end;
procedure TQueenForm.DrawBoard(board: TBoard);
//быдлорисовка шахматного поля. быдло-пребыдло.
//но мне нравится :3
const
GlyphDir = 'glyph\';
chars = 'ABCDEFGHIJ';
var
i,j: byte;
BlackCell: boolean;
FileName: string;
TempBMP: TBitmap;
begin
{output board into VisualBoard - TImage}
TempBMP:=TBitmap.Create;
VisualBoard.Picture:= nil;
VisualBoard.Width:= BoardSize * _CellWidth + _IndentLeft;
VisualBoard.Height:= BoardSize * _CellHeight + _IndentTop;
// ClearCanvas(VisualBoard.Canvas);
BlackCell:=False;
//draw cells of board
for i:=1 to BoardSize do
begin
for j:=1 to BoardSize do
begin
case board[j,i] of {ктати если сделать board[i,j] - то визуально ферзи будут расставляться по столбцам}
cQueen: FileName:= Format('queen-%d.bmp',[ord(BlackCell)]);
cFree: FileName:= Format('free-%d.bmp',[ord(BlackCell)]);
cUnderAttack: FileName:= Format('underattack-%d.bmp',[ord(BlackCell)]);
end;
TempBMP.LoadFromFile(GlyphDir + FileName);
{ VisualBoard.Canvas.CopyRect(rect(i*_CellWidth, j*_CellHeight, (i+1)*_CellWidth, (j+1)*_CellHeight),
TempBMP.Canvas,
rect(0, 0, _CellWidth, _CellHeight)
); }
BitBlt(VisualBoard.Canvas.Handle,
_IndentLeft + (i-1)*_CellWidth, _IndentTop + (j-1)*_CellHeight,
_CellWidth, _CellHeight,
TempBMP.Canvas.Handle,
0, 0, SRCCOPY);
BlackCell:= not BlackCell;
end;
if (BoardSize mod 2) = 0 then
BlackCell:=not BlackCell;
end;
//draw captions for rows and columns
for i:=1 to BoardSize do
begin
With VisualBoard.Canvas do
begin
Font.Size:= 9;
Font.Style:=Font.Style + [fsBold];
TextOut(_IndentLeft + (i-1)*_CellWidth + (_CellWidth - TextWidth(chars[i])) div 2,
(_IndentTop - TextHeight(chars[i])) div 2,
chars[i]
); {columns}
TextOut((_IndentLeft - TextWidth(inttostr(BoardSize - i + 1))) div 2,
_IndentTop + (i-1)*_CellHeight + (_CellHeight - TextHeight(inttostr(BoardSize - i + 1))) div 2,
inttostr(BoardSize - i + 1)
); {rows}
end;
end;
TempBMP.Free;
end;
function TQueenForm.ClearBoard: TBoard;
var
i,j: byte;
board: TBoard;
begin
for i:= 1 to BoardSize do
for J:= 1 to BoardSize do
board[i,j]:= cFree;
Result:= board;
end;
procedure TQueenForm.SetQueenOnBoard(var a: TBoard; x, y: byte);
{x, y — координаты вставки ферзя}
var
i, j:integer;
begin
for i:= 1 to BoardSize do
begin
a[x,i]:=cUnderAttack; {помечаем строку и столбец, где будет стоять новоявленный ферзь как «под боем»}
a[i,y]:=cUnderAttack;
end;
i:=x-1; {переходим в левую верхнюю клетку по диагонали от (x;y)}
j:=y-1;
while (i<>0) and (j<>0) do
begin
a[i,j]:=cUnderAttack; {помечаем диагональ слева и вверх от (x,y) }
dec(i);
dec(j);
end;
i:=x+1; {переходим в правую нижнюю клетку по диагонали от (x,y)}
j:=y+1;
while (i<>BoardSize+1) and (j<>BoardSize+1) do
begin
a[i,j]:=cUnderAttack; {помечаем диагональ справа вниз от (x,y) }
inc(i);
inc(j);
end;
i:=x-1; {переходим в правую верхнюю клетку}
j:=y+1;
while (i<>0) and (j<>BoardSize+1) do
begin
a[i,j]:=cUnderAttack; {помечаем диагональ справа вверх от (x,y)}
dec(i);
inc(j);
end;
i:=x+1; {переходим в левую нижнюю клетку от (x,y)}
j:=y-1;
while (i<>BoardSize+1) and (j<>0) do
begin
a[i,j]:=cUnderAttack; {помечаем диагональ слева вниз от (x,y)}
inc(i);
dec(j);
end;
a[x,y]:=cQueen; {помечаем "ферзём" клетку (x,y)}
end;
procedure TQueenForm.Button1Click(Sender: TObject);
begin
if timer1.Enabled then
StopTimer
else
StartTimer;
end;
procedure TQueenForm.Timer1Timer(Sender: TObject);
begin
if IterateS then
begin
StopTimer;
LogMemo.Lines.Add('Цикл завершён.');
LogMemo.Lines.Add(Format('Найдено %d решений(я)',[SolutionCounter]));
end;
end;
procedure TQueenForm.FormCreate(Sender: TObject);
begin
FirstIteration:=True;
StopIfFoundSolution:= True;
SolutionCounter:=0;
BoardSizeEdit.MaxValue:= Stacks.maxBoardSize;
BoardSizeEdit.Value:= defBoardSize;
BoardSize:= defBoardSize;
board:= ClearBoard;
DrawBoard (board);
Tree.ImageInit;
Application.HintPause:=50;
Application.HintHidePause:=5000;
end;
procedure TQueenForm.Button2Click(Sender: TObject);
begin
if IterateS then
begin
LogMemo.Lines.Add('Цикл завершён.');
LogMemo.Lines.Add(Format('Найдено %d решений(я)',[SolutionCounter]));
end;
end;
procedure TQueenForm.Button3Click(Sender: TObject);
var
c: boolean;
begin
c:=False;
while not c do
begin
c:=IterateS;
Application.ProcessMessages;
end;
LogMemo.Lines.Add('Цикл завершён.');
LogMemo.Lines.Add(Format('Найдено %d решений(я)',[SolutionCounter]));
end;
procedure TQueenForm.SetBoardSize (Value: byte);
begin
Main.BoardSize:= Value;
Tree.ImageInit;
QueenForm.ResetButtonClick (Self);
if not FirstIteration then
FirstIteration:= True;
board:= ClearBoard;
DrawBoard (board);
end;
function TQueenForm.IterateS: boolean;
{процедура, выполняющая один шаг итерационного бектрекинга со стеком.
В папке backtracking-pascal, в файле btr.pas расписаны процедуры, послужившие
основой создания этой процедуры.
возвращает True, если цикл завершён}
const
chars= 'ABCDEFGHIJ';
var
copy: TBoard;
begin
LogMemo.Lines.Add('<Начало итерации.>');
if FirstIteration then
begin
LogMemo.Lines.Add ('Это первая итерация.');
LogMemo.Lines.Add('Добавляем в стек пустую расстановку');
CreateStack (Stack);
PrevAbsBoardPos:= 1;
PushStack (Stack, 1, ClearBoard, PrevAbsBoardPos);
CurrAction:= GetBoard;
FirstIteration:= False;
QueenHereCounter:= 0; //порядковый номер фезря, который можно поставить на текущей строке
DrawUnit (1, 1, PrevAbsBoardPos, 1);
end;
case CurrAction of
GetBoard:
begin
LogMemo.Lines.Add('Получаем текущую расстановку из стека.');
if Stack = nil then
begin
LogMemo.Lines.Add('Стек пуст, цикл завершается.');
result:=True;
exit;
end;
PopStack (Stack, currQueen, board, PrevAbsBoardPos);
DrawBoard(board); //необязательная строка кажись
CurrAction:= CheckingIfSolution;
itr:= BoardSize;
end;
CheckingIfSolution:
begin
LogMemo.Lines.Add ('Проверяем, является ли текущая расстановка готовым решением.');
if CurrQueen = BoardSize + 1 then {we got a new solution, lets remind about it}
begin
LogMemo.Lines.Add ('Проверка пройдена, у нас есть решение.');
WriteSolutionIntoList (board);
MarkGoodThread (CurrQueen - 1, PrevAbsBoardPos);
if StopIfFoundSolution then
StopTimer; //выключить таймер при нахождении решения
Inc (SolutionCounter);
CurrAction:= GetBoard;
end
else
begin
CurrAction:= FindPlaceToNewQueen;
LogMemo.Lines.Add (Format('Находим позицию для ферзя номер %d.',[CurrQueen]));
end;
end;
FindPlaceToNewQueen:
begin {what about skiping this part in timer and just show a free place to set?}
//LogMemo.Lines.Add (Format('Находим позицию для ферзя номер %d.',[CurrQueen]));
if board[currQueen, itr] = cFree then
begin
LogMemo.Lines.Add (Format('Ферзя можно поставить на позицию %s%d.',[chars[itr],BoardSize - currQueen + 1]));
LogMemo.Lines.Add('Добавляем его в расстановку и добавляем расстановку в стек.');
copy:= board;
SetQueenOnBoard (copy, currQueen, itr);
//{}DrawBoard(copy);
Inc (QueenHereCounter);
PushStack (Stack, CurrQueen + 1, copy, CurrAbsBoardPos (CurrQueen, QueenHereCounter, PrevAbsBoardPos));
DrawUnit (CurrQueen, QueenHereCounter, PrevAbsBoardPos, itr);
end
else
LogMemo.Lines.Add (Format('Нельзя ставить ферзя на позицию %s%d.',[chars[itr],BoardSize - currQueen + 1]));
if itr = 1 then
begin
LogMemo.Lines.Add('Поиск позиции для нового ферзя завершён.');
CurrAction:= GetBoard;
if QueenHereCounter = 0 then
MarkBadThread (CurrQueen - 1, PrevAbsBoardPos);
QueenHereCounter:= 0;
end
else
Dec(itr);
end;
end;
//DrawBoard(board);
LogMemo.Lines.Add ('<Конец итерации.>');
result:= False;
end;
procedure EasterEgg;
begin
Application.MessageBox ('Developers:' + #13#10 + ' upcdownc' + #13#10 + ' freemanoid' + #13#10 + #13#10 + 'Github: http://github.com/group93492', 'Easter Egg');
end;
procedure TQueenForm.StopCheckBoxClick(Sender: TObject);
begin
StopIfFoundSolution:=StopCheckBox.Checked;
end;
procedure TQueenForm.ResetButtonClick (Sender: TObject);
begin
StopTimer;
FirstIteration:= True;
SolutionCounter:=0;
board:= ClearBoard;
DrawBoard (board);
SolutionsList.Clear;
ClearStack (Stack);
Tree.ClearTree;
end;
procedure TQueenForm.WriteSolutionIntoList(board: TBoard);
const
chars= 'ABCDEFGHIJ';
var
i,j: byte;
Solution: string;
begin
for i:=1 to BoardSize do
for j:=1 to BoardSize do
if board[i,j]= cQueen then
Solution:= Solution + chars[j] + IntToStr (BoardSize - i + 1) + ' ';
SolutionsList.Items.Add (Solution);
end;
procedure TQueenForm.StartTimer;
begin
button1.Caption:='Остановить автоматическое выполнение';
Timer1.enabled:= True;
end;
procedure TQueenForm.StopTimer;
begin
button1.Caption:='Запустить автоматическое выполнение';
Timer1.enabled:= False;
end;
procedure TQueenForm.BoardSizeEditChange(Sender: TObject);
begin
SetBoardSize (BoardSizeEdit.Value);
end;
procedure TQueenForm.BoardSizeEditKeyPress(Sender: TObject; var Key: Char);
begin
Key:=#0;
end;
procedure TQueenForm.LogMemoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
const
PassPhrase = '93492';
PhraseLength = Length (PassPhrase);
begin
if Key = Ord(PassPhrase[Egg + 1]) then
begin
Inc (Egg);
if Egg = PhraseLength then
begin
EasterEgg;
Egg:= 0;
end;
end
else
Egg:= 0;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ Connection classes }
{*******************************************************}
unit Datasnap.Win.TConnect;
interface
uses System.Variants, System.SysUtils, System.Classes, Datasnap.Midas, Data.DB, Datasnap.DBClient,
{$IFDEF MSWINDOWS}Winapi.Windows, Winapi.ActiveX, System.Win.ComObj, {$ENDIF}{$IFDEF LINUX}Libc,{$ENDIF}
Datasnap.Provider;
type
{ TLocalConnection }
TLocalConnection = class(TCustomRemoteServer, IAppServer{$IFDEF MSWINDOWS}, ISupportErrorInfo{$ENDIF})
private
FAppServer: IAppServer;
FProviders: TList;
function GetProviderCount: Integer;
protected
function GetProvider(const ProviderName: string): TCustomProvider; virtual;
{ IAppServer }
function AS_GetProviderNames: OleVariant; safecall;
function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer;
var OwnerData: OleVariant): OleVariant; safecall;
function AS_GetRecords(const ProviderName: WideString; Count: Integer;
out RecsOut: Integer; Options: Integer; const CommandText: WideString;
var Params, OwnerData: OleVariant): OleVariant; safecall;
function AS_DataRequest(const ProviderName: WideString;
Data: OleVariant): OleVariant; safecall;
function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall;
function AS_RowRequest(const ProviderName: WideString; Row: OleVariant;
RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall;
procedure AS_Execute(const ProviderName: WideString;
const CommandText: WideString; var Params, OwnerData: OleVariant); safecall;
{$IFDEF MSWINDOWS}
{ ISupportErrorInfo }
function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall;
{$ENDIF}
protected
function GetConnected: Boolean; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure RegisterProvider(Prov: TCustomProvider);
procedure UnRegisterProvider(Prov: TCustomProvider);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property AppServer: IAppServer read FAppServer;
function GetServer: IAppServer; override;
procedure GetProviderNames(Proc: TGetStrProc); override;
property Providers[const ProviderName: string]: TCustomProvider read GetProvider;
property ProviderCount: Integer read GetProviderCount;
{$IFDEF MSWINDOWS}
function SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult; override;
{$ENDIF}
end;
implementation
uses Datasnap.MidConst, System.Generics.Collections, System.Types;
{ TLocalConnection }
function TLocalConnection.GetProviderCount: Integer;
begin
Result := FProviders.Count;
end;
function TLocalConnection.GetConnected: Boolean;
begin
Result := True;
end;
constructor TLocalConnection.Create(AOwner: TComponent);
var
I: Integer;
begin
inherited Create(AOwner);
RCS;
FProviders := TList.Create;
FAppServer := Self as IAppServer;
for I:=0 to AOwner.ComponentCount - 1 do
if AOwner.Components[I] is TCustomProvider then
RegisterProvider(TCustomProvider(AOwner.Components[I]));
end;
destructor TLocalConnection.Destroy;
begin
FProviders.Free;
FAppServer := nil;
inherited;
end;
function TLocalConnection.GetServer: IAppServer;
begin
Result := FAppServer;
end;
procedure TLocalConnection.GetProviderNames(Proc: TGetStrProc);
var
List: Variant;
I: Integer;
begin
Connected := True;
VarClear(List);
try
List := AppServer.AS_GetProviderNames;
except
{ Assume any errors means the list is not available. }
end;
if VarIsArray(List) and (VarArrayDimCount(List) = 1) then
for I := VarArrayLowBound(List, 1) to VarArrayHighBound(List, 1) do
Proc(List[I]);
end;
procedure TLocalConnection.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (AComponent is TCustomProvider) then
if (Operation = opInsert) then
RegisterProvider(TCustomProvider(AComponent)) else
UnRegisterProvider(TCustomProvider(AComponent));
end;
procedure TLocalConnection.RegisterProvider(Prov: TCustomProvider);
begin
FProviders.Add(Prov);
end;
procedure TLocalConnection.UnRegisterProvider(Prov: TCustomProvider);
begin
FProviders.Remove(Prov);
end;
function TLocalConnection.AS_GetProviderNames: OleVariant;
var
List: TStringList;
I: Integer;
begin
List := TStringList.Create;
try
for I := 0 to FProviders.Count - 1 do
if TCustomProvider(FProviders[I]).Exported then
List.Add(TCustomProvider(FProviders[I]).Name);
List.Sort;
Result := VarArrayFromStrings(List);
finally
List.Free;
end;
end;
function TLocalConnection.AS_ApplyUpdates(const ProviderName: WideString;
Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer;
var OwnerData: OleVariant): OleVariant;
begin
Result := Providers[ProviderName].ApplyUpdates(Delta, MaxErrors, ErrorCount, OwnerData);
end;
function TLocalConnection.AS_GetRecords(const ProviderName: WideString; Count: Integer;
out RecsOut: Integer; Options: Integer; const CommandText: WideString;
var Params, OwnerData: OleVariant): OleVariant;
begin
Result := Providers[ProviderName].GetRecords(Count, RecsOut, Options,
CommandText, Params, OwnerData);
end;
function TLocalConnection.AS_RowRequest(const ProviderName: WideString;
Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant;
begin
Result := Providers[ProviderName].RowRequest(Row, RequestType, OwnerData);
end;
function TLocalConnection.AS_DataRequest(const ProviderName: WideString;
Data: OleVariant): OleVariant; safecall;
begin
Result := Providers[ProviderName].DataRequest(Data);
end;
function TLocalConnection.AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant;
begin
Result := Providers[ProviderName].GetParams(OwnerData);
end;
procedure TLocalConnection.AS_Execute(const ProviderName: WideString;
const CommandText: WideString; var Params, OwnerData: OleVariant);
begin
Providers[ProviderName].Execute(CommandText, Params, OwnerData);
end;
function TLocalConnection.GetProvider(const ProviderName: string): TCustomProvider;
var
I: Integer;
begin
Result := nil;
for I := 0 to FProviders.Count - 1 do
if AnsiCompareText(TCustomProvider(FProviders[I]).Name, ProviderName) = 0 then
begin
Result := TCustomProvider(FProviders[I]);
if not Result.Exported then
Result := nil;
Break;
end;
if not Assigned(Result) then
raise Exception.CreateResFmt(@SProviderNotExported, [ProviderName]);
end;
{$IFDEF MSWINDOWS}
function TLocalConnection.InterfaceSupportsErrorInfo(
const iid: TIID): HResult;
begin
if IsEqualGUID(IAppServer, iid) then
Result := S_OK else
Result := S_FALSE;
end;
function TLocalConnection.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
begin
Result := HandleSafeCallException(ExceptObject, ExceptAddr, IAppServer, '', '');
end;
{$ENDIF}
end.
|
unit SrvrDM;
{
This is the server side of the demo. A Login procedure has been added to the
RemoteDataModule which the client will use to login. You can use the Type
Library Editor or the Edit | Add To Interface menu to add a procedure to the
type library.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComServ, ComObj, VCLCom, StdVcl, BdeProv, DataBkr, DBClient, Server_TLB,
Db, DBTables;
type
TLoginDemo = class(TRemoteDataModule, ILoginDemo)
Country: TTable;
procedure LoginDemoCreate(Sender: TObject);
procedure LoginDemoDestroy(Sender: TObject);
private
FLoggedIn: Boolean;
FUserName: string;
procedure CheckLogin;
protected
function Get_Country: IProvider; safecall;
procedure Login(const UserName, Password: WideString); safecall;
end;
var
LoginDemo: TLoginDemo;
implementation
uses SrvrFrm;
{$R *.DFM}
{ This procedure is a helper to check that someone has actually logged into the
server. }
procedure TLoginDemo.CheckLogin;
begin
if not FLoggedIn then
raise Exception.Create('Not logged in');
end;
function TLoginDemo.Get_Country: IProvider;
begin
{ Add the call to CheckLogin so that if you can only get information if you
have logged in. }
CheckLogin;
Result := Country.Provider;
end;
procedure TLoginDemo.Login(const UserName, Password: WideString);
begin
{ Just add the UserName to the ListBox on Form1 and set the login flag to
true.}
Form1.ListBox1.Items.Add(UserName);
FLoggedIn := True;
FUserName := UserName;
end;
procedure TLoginDemo.LoginDemoCreate(Sender: TObject);
begin
FLoggedIn := False;
end;
procedure TLoginDemo.LoginDemoDestroy(Sender: TObject);
begin
{ Remove the Name from the list}
with Form1.ListBox1.Items do Delete(IndexOf(FUserName));
end;
initialization
TComponentFactory.Create(ComServer, TLoginDemo,
Class_LoginDemo, ciMultiInstance, tmSingle);
end.
|
unit UComboBoxCursos;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls;
type
TComboBoxCursos = class(TComboBox)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
FKey: TStringList;
constructor Create(AOwner: TComponent); override;
Function getItem: TStringList;
Procedure setItem(Value: TStringList);
function getKey: String;
published
{ Published declarations }
property Key: TStringList read getItem write setItem;
Procedure addMega(text1, text2: string);
Procedure chooseIndex(Code: string);
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TComboBoxCursos]);
end;
{ TComboBoxCursos }
procedure TComboBoxCursos.addMega(text1, text2: string);
begin
Items.Add(text1);
Key.Add(text2);
end;
procedure TComboBoxCursos.chooseIndex(Code: string);
begin
ItemIndex := FKey.IndexOf(Code);
end;
constructor TComboBoxCursos.Create(AOwner: TComponent);
begin
inherited;
FKey := TStringList.Create;
end;
function TComboBoxCursos.getItem: TStringList;
begin
result := FKey;
end;
function TComboBoxCursos.getKey: String;
begin
result := FKey[ItemIndex];
end;
procedure TComboBoxCursos.setItem(Value: TStringList);
begin
if Assigned(FKey) then
FKey.Assign(Value)
else
FKey := Value;
end;
end.
|
unit Fonetiza.Core.Test;
interface
uses TestFramework, System.SysUtils, Fonetiza.Core;
type
TTestFonetizaCore = class(TTestCase)
strict private
FFonetizaCore: TFonetizaCore;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestGerarConteudoFonetico;
end;
implementation
procedure TTestFonetizaCore.SetUp;
begin
FFonetizaCore := TFonetizaCore.Create;
end;
procedure TTestFonetizaCore.TearDown;
begin
FFonetizaCore.Free;
FFonetizaCore := nil;
end;
procedure TTestFonetizaCore.TestGerarConteudoFonetico;
begin
CheckEquals('GIUZI', FFonetizaCore.GerarConteudoFonetico('JOSE'));
CheckEquals('KARLU', FFonetizaCore.GerarConteudoFonetico('CARLOS'));
end;
initialization
RegisterTest(TTestFonetizaCore.Suite);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ODBC driver base classes }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ODBCBase;
interface
uses
System.SysUtils, System.Classes, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper;
type
TFDPhysODBCBaseDriverLink = class(TFDPhysDriverLink)
private
FODBCAdvanced: String;
FODBCDriver: String;
protected
function IsConfigured: Boolean; override;
procedure ApplyTo(const AParams: IFDStanDefinition); override;
public
procedure GetDrivers(AList: TStrings);
procedure GetDSNs(AList: TStrings; AWithDescription: Boolean = False);
published
property ODBCDriver: String read FODBCDriver write FODBCDriver;
property ODBCAdvanced: String read FODBCAdvanced write FODBCAdvanced;
end;
TFDPhysODBCBaseService = class (TFDPhysDriverService)
private
function GetLib: TODBCLib;
protected
function GetEnv: TODBCEnvironment; virtual;
public
procedure ExecuteBase(ARequest: Word; ADriver: String; AAttributes: String);
property Env: TODBCEnvironment read GetEnv;
property Lib: TODBCLib read GetLib;
end;
TFDPhysODBCDriverBase = class;
TFDPhysODBCConnectionBase = class;
TFDPhysODBCTransaction = class;
TFDPhysODBCCommand = class;
TFDPhysODBCCliHandles = array [0..1] of SQLHandle;
PFDPhysODBCCliHandles = ^TFDPhysODBCCliHandles;
IFDPhysODBCDriver = interface
['{A52C2247-E07C-4BEB-821B-6DF097828ED0}']
function GetODBCDriver: String;
function GetODBCAdvanced: String;
// public
property ODBCDriver: String read GetODBCDriver;
property ODBCAdvanced: String read GetODBCAdvanced;
end;
TFDPhysODBCDriverBase = class(TFDPhysDriver,
IFDPhysDriverConnectionWizard, IFDPhysODBCDriver)
private
FODBCLib: TODBCLib;
FODBCEnvironment: TODBCEnvironment;
FODBCDriver: String;
FODBCAdvanced: String;
FKeywords: TFDStringList;
protected
// TFDPhysDriver
procedure InternalLoad; override;
procedure InternalUnload; override;
function GetCliObj: Pointer; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
// IFDPhysDriverConnectionWizard
function RunConnectionWizard(const AConnectionDef: IFDStanConnectionDef;
AParentWnd: THandle): Boolean;
function IFDPhysDriverConnectionWizard.Run = RunConnectionWizard;
// IFDPhysODBCDriver
function GetODBCDriver: String;
function GetODBCAdvanced: String;
// introduced
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); virtual;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
function BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): string; virtual;
function FindBestDriver(const ADrivers: array of String;
const ADefaultDriver: String = ''): String;
property ODBCDriver: String read FODBCDriver write FODBCDriver;
property ODBCAdvanced: String read FODBCAdvanced write FODBCAdvanced;
property ODBCLib: TODBCLib read FODBCLib;
property ODBCEnvironment: TODBCEnvironment read FODBCEnvironment;
end;
TFDPhysODBCSupportedOptions = set of (soPKFunction, soFKFunction, soParamSet,
soRowSet, soMoney, soArrayBatch);
TFDPhysODBCConnectionBase = class(TFDPhysConnection)
private
FODBCEnvironment: TODBCEnvironment;
FODBCConnection: TODBCConnection;
FCliHandles: TFDPhysODBCCliHandles;
FSupportedOptions: TFDPhysODBCSupportedOptions;
FTxnIsolations: array[TFDTxIsolation] of SQLUInteger;
procedure MapTxIsolations;
function GetDriverKind: TODBCDriverKind; inline;
protected
// TFDPhysConnection
procedure InternalConnect; override;
procedure InternalSetMeta; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateTransaction: TFDPhysTransaction; override;
procedure InternalDisconnect; override;
{$IFDEF FireDAC_MONITOR}
procedure InternalTracingChanged; override;
{$ENDIF}
procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override;
procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant;
out AKind: TFDMoniAdapterItemKind); override;
function GetItemCount: Integer; override;
function GetMessages: EFDDBEngineException; override;
function GetCliObj: Pointer; override;
function InternalGetCliHandle: Pointer; override;
function InternalGetCurrentCatalog: String; override;
function InternalGetCurrentSchema: String; override;
// introduced
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); virtual;
function GetStrsType: TFDDataType; virtual;
function GetNumType: TFDDataType; virtual;
procedure UpdateDecimalSep; virtual;
function GetExceptionClass: EODBCNativeExceptionClass; virtual;
procedure SetupConnection; virtual;
function GetODBCVersion: Integer; virtual;
function GetKeywords: String;
procedure GetVersions(out AServer, AClient: TFDVersion);
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override;
destructor Destroy; override;
property ODBCEnvironment: TODBCEnvironment read FODBCEnvironment;
property ODBCConnection: TODBCConnection read FODBCConnection;
property DriverKind: TODBCDriverKind read GetDriverKind;
end;
TFDPhysODBCTransaction = class(TFDPhysTransaction)
private
function GetODBCConnection: TODBCConnection;
procedure DisconnectCommandsBeforeCommit;
procedure DisconnectCommandsBeforeRollback;
protected
procedure InternalStartTransaction(ATxID: LongWord); override;
procedure InternalChanged; override;
procedure InternalCommit(ATxID: LongWord); override;
procedure InternalRollback(ATxID: LongWord); override;
procedure InternalReleaseHandle; override;
procedure InternalNotify(ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); override;
public
property ODBCConnection: TODBCConnection read GetODBCConnection;
end;
PFDODBCColInfoRec = ^TFDODBCVarInfoRec;
PFDODBCParInfoRec = ^TFDODBCVarInfoRec;
TFDODBCVarInfoRec = record
FName: String;
FExtName: String;
FOriginCatalogName,
FOriginSchemaName,
FOriginTabName,
FOriginColName: String;
FPos: SQLSmallInt;
FParamIndex: SQLSmallInt;
FColSize: SQLInteger;
FScale: SQLInteger;
FSrcSQLDataType,
FOutSQLDataType: SQLSmallInt;
FSrcDataType,
FOutDataType,
FDestDataType: TFDDataType;
FVar: TODBCVariable;
FSubInfos: array of TFDODBCVarInfoRec;
// FAttrs moved to here out of True case due to C++Builder incompatibility
FAttrs: TFDDataAttributes;
case Boolean of
True: (
FInKey: Boolean;
FFDLen: LongWord;
FFDScale: Integer;
);
False: (
FIsNull: Boolean;
FParamType: TParamType;
FDataType: TFieldType;
);
end;
TFDPhysODBCStatementProp = (cpParamSet, cpRowSet, cpLateBindedData, cpOutResParams,
cpOutParams, cpDefaultCrs, cpOnNextResult, cpOnNextResultValue, cpNotFirstCursor,
cpResetOnArrayOffset, cpUnifyParams);
TFDPhysODBCStatementProps = set of TFDPhysODBCStatementProp;
TFDPhysODBCCommand = class(TFDPhysCommand)
private
FColumnIndex: Integer;
FStatement: TODBCStatementBase;
[weak] FCommandStatement: TODBCCommandStatement;
[weak] FMetainfoStatement: TODBCMetaInfoStatement;
FMetainfoAddonView: TFDDatSView;
FStatementProps: TFDPhysODBCStatementProps;
function GetConnection: TFDPhysODBCConnectionBase;
procedure DestroyDescribeInfos;
procedure DestroyParamInfos;
function FetchMetaRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowIndex, ARowNo: SQLUInteger): Boolean;
procedure FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowIndex: SQLUInteger);
procedure GetParamValues(ATimes, AOffset: Integer; AFromParIndex: Integer);
function OpenMetaInfo: Boolean;
procedure SetParamValues(ATimes, AOffset: Integer; AFromParIndex: Integer);
procedure SetupStatementBeforePrepare(AStmt: TODBCStatementBase);
procedure SetupStatementAfterDescribe(AStmt: TODBCStatementBase);
procedure SetupStatementBeforeExecute(AStmt: TODBCStatementBase);
function GetRowsetSize(ARowsetSize: Integer): Integer;
function GetParamsetSize(AParamsetSize: Integer): Integer;
function MatchParamsetSize(AParamsetSize1, AParamsetSize2: Integer): Boolean;
function UseExecDirect: Boolean;
function UseInformationSchema: Boolean;
function UseStatement: Boolean;
procedure CloseStatement(AIndex: Integer; AForceClose, AGetOutParams,
AIgnoreErrors: Boolean);
function GetCursor(var ARows: SQLLen): Boolean;
protected
FColInfos: array of TFDODBCVarInfoRec;
FParInfos: array of TFDODBCVarInfoRec;
function CheckFetchColumn(ADataType: TFDDataType; AAttributes: TFDDataAttributes;
ASQLDataType: Smallint): Boolean; overload;
function FD2SQLDataType(AFDType: TFDDataType; AFixedLen: Boolean;
var AColSize, AScale: SQLInteger): SQLSmallint;
function FD2CDataType(AFDType: TFDDataType; ANestedColumn: Boolean): SQLSmallint;
procedure SQL2FDColInfo(ASQLDataType: SQLSmallint; AUnsigned: Boolean;
const ASQLTypeName: String; var ASQLSize: SQLInteger; ASQLDecimals: SQLInteger;
var AType: TFDDataType; var AAttrs: TFDDataAttributes; var ALen: LongWord;
var APrec, AScale: Integer);
function FD2SQLParamType(AParamType: TParamType): SQLSmallint;
// TFDPhysCommand
procedure InternalAbort; override;
procedure InternalClose; override;
function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; override;
function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; override;
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
procedure InternalCloseStreams; override;
function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow;
ARowsetSize: LongWord): LongWord; override;
function InternalNextRecordSet: Boolean; override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
procedure InternalPrepare; override;
procedure InternalUnprepare; override;
function GetCliObj: Pointer; override;
// introduced
procedure CreateDescribeInfos; virtual;
procedure CreateParamInfos; virtual;
procedure CreateParamColumns(AParam: TFDParam); virtual;
procedure CreateParamColumnInfos(ApInfo: PFDODBCParInfoRec; AParam: TFDParam); virtual;
function GetIsCustomParam(ADataType: TFDDataType): Boolean; virtual;
procedure SetCustomParamValue(ADataType: TFDDataType; AVar: TODBCVariable;
AParam: TFDParam; AVarIndex, AParIndex: Integer); virtual;
procedure GetCustomParamValue(ADataType: TFDDataType; AVar: TODBCVariable;
AParam: TFDParam; AVarIndex, AParIndex: Integer); virtual;
public
property ODBCStatement: TODBCStatementBase read FStatement;
property ODBCConnection: TFDPhysODBCConnectionBase read GetConnection;
end;
implementation
uses
System.Variants, Data.FmtBcd,
{$IFDEF MSWINDOWS}
// Preventing from "Inline has not expanded"
Winapi.Windows,
{$ENDIF}
FireDAC.Stan.Consts, FireDAC.Stan.Factory, FireDAC.Stan.Util,
FireDAC.Stan.SQLTimeInt, FireDAC.Stan.ResStrs;
const
C_FD_TxI2ODBCTxI: array[TFDTxIsolation] of SQLUInteger = (
SQL_TXN_READ_COMMITTED, SQL_TXN_READ_UNCOMMITTED, SQL_TXN_READ_COMMITTED,
SQL_TXN_REPEATABLE_READ, SQL_TXN_SS_SNAPSHOT, SQL_TXN_SERIALIZABLE);
C_FD_Type2SQLDataType: array [TFDDataType] of SQLSmallint = (
SQL_UNKNOWN_TYPE,
SQL_BIT,
SQL_TINYINT, SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT,
SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT, SQL_BIGINT,
SQL_REAL, SQL_DOUBLE, SQL_DOUBLE,
SQL_DECIMAL, SQL_DECIMAL, SQL_DECIMAL,
SQL_TIMESTAMP, SQL_TYPE_TIME, SQL_TYPE_DATE, SQL_TIMESTAMP,
SQL_UNKNOWN_TYPE, SQL_INTERVAL_YEAR_TO_MONTH, SQL_INTERVAL_DAY_TO_SECOND,
SQL_VARCHAR, SQL_WVARCHAR, SQL_VARBINARY,
SQL_LONGVARBINARY, SQL_LONGVARCHAR, SQL_WLONGVARCHAR, SQL_UNKNOWN_TYPE,
SQL_LONGVARBINARY, SQL_LONGVARCHAR, SQL_WLONGVARCHAR,
SQL_LONGVARBINARY,
SQL_UNKNOWN_TYPE, SQL_REFCURSOR, SQL_UNKNOWN_TYPE,
SQL_UNKNOWN_TYPE, SQL_UNKNOWN_TYPE,
SQL_GUID, SQL_UNKNOWN_TYPE
);
C_FD_Type2CDataType: array [TFDDataType] of SQLSmallint = (
SQL_TYPE_NULL,
SQL_C_BIT,
SQL_C_STINYINT, SQL_C_SSHORT, SQL_C_SLONG, SQL_C_SBIGINT,
SQL_C_UTINYINT, SQL_C_USHORT, SQL_C_ULONG, SQL_C_UBIGINT,
SQL_C_FLOAT, SQL_C_DOUBLE, SQL_C_DOUBLE,
SQL_C_NUMERIC, SQL_C_NUMERIC, SQL_C_NUMERIC,
SQL_C_TYPE_TIMESTAMP, SQL_C_TYPE_TIME, SQL_C_TYPE_DATE, SQL_C_TYPE_TIMESTAMP,
SQL_TYPE_NULL, SQL_C_INTERVAL_YEAR_TO_MONTH, SQL_C_INTERVAL_DAY_TO_SECOND,
SQL_C_CHAR, SQL_C_WCHAR, SQL_C_BINARY,
SQL_C_BINARY, SQL_C_CHAR, SQL_C_WCHAR, SQL_C_WCHAR,
SQL_C_BINARY, SQL_C_CHAR, SQL_C_WCHAR,
SQL_C_BINARY,
SQL_TYPE_NULL, SQL_TYPE_NULL, SQL_TYPE_NULL,
SQL_TYPE_NULL, SQL_TYPE_NULL,
SQL_C_GUID, SQL_TYPE_NULL
);
C_FD_ParType2SQLParType: array [TParamType] of SQLSmallint = (
SQL_PARAM_INPUT,
SQL_PARAM_INPUT,
SQL_PARAM_OUTPUT,
SQL_PARAM_INPUT_OUTPUT,
SQL_PARAM_OUTPUT
);
C_FD_BestRowID: String = 'SQL_BEST_ROWID';
{-------------------------------------------------------------------------------}
{ TFDPhysODBCBaseDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysODBCBaseDriverLink.IsConfigured: Boolean;
begin
Result := inherited IsConfigured or (FODBCDriver <> '') or (FODBCAdvanced <> '');
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCBaseDriverLink.ApplyTo(const AParams: IFDStanDefinition);
begin
inherited ApplyTo(AParams);
if FODBCDriver <> '' then
AParams.AsString[S_FD_ConnParam_ODBC_ODBCDriver] := FODBCDriver;
if FODBCAdvanced <> '' then
AParams.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := FODBCAdvanced;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCBaseDriverLink.GetDrivers(AList: TStrings);
begin
if FDPhysManager.State = dmsInactive then
FDPhysManager.Open;
DriverIntf.Employ;
try
TODBCEnvironment(DriverIntf.CliObj).GetDrivers(AList);
finally
DriverIntf.Vacate;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCBaseDriverLink.GetDSNs(AList: TStrings; AWithDescription: Boolean = False);
begin
if FDPhysManager.State = dmsInactive then
FDPhysManager.Open;
DriverIntf.Employ;
try
TODBCEnvironment(DriverIntf.CliObj).GetDSNs(AList, AWithDescription);
finally
DriverIntf.Vacate;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCBaseService }
{-------------------------------------------------------------------------------}
function TFDPhysODBCBaseService.GetEnv: TODBCEnvironment;
begin
Result := CliObj as TODBCEnvironment;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCBaseService.GetLib: TODBCLib;
begin
Result := Env.Lib;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCBaseService.ExecuteBase(ARequest: Word; ADriver, AAttributes: String);
var
i: Integer;
iErrCode: UDword;
iErrMsgLen: WORD;
aErrMsg: array [0 .. SQL_MAX_MESSAGE_LENGTH - 1] of SQLChar;
sErrMsg: String;
oExc: EODBCNativeException;
sDrvID: String;
begin
if not Assigned(Lib.SQLConfigDataSource) then begin
if DriverLink <> nil then
sDrvID := DriverLink.ActualDriverID
else
sDrvID := S_FD_ODBCId;
FDCapabilityNotSupported(Self, [S_FD_LPhys, sDrvID]);
end;
if not Lib.SQLConfigDataSource(0, ARequest, PSQLChar(ADriver), PSQLChar(AAttributes)) then begin
oExc := EODBCNativeException.Create;
for i := 1 to 8 do begin
if Lib.SQLInstallerError(i, iErrCode, @aErrMsg[0], High(aErrMsg) - 1, iErrMsgLen) <> SQL_SUCCESS then
Break;
SetString(sErrMsg, aErrMsg, iErrMsgLen);
if i = 1 then
oExc.Message := sErrMsg;
EFDDBEngineException(oExc).AppendError(i, iErrCode, sErrMsg, '', ekOther, -1, -1);
end;
FDException(Self, oExc {$IFDEF FireDAC_Monitor}, False {$ENDIF});
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCDriverBase }
{-------------------------------------------------------------------------------}
constructor TFDPhysODBCDriverBase.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
FKeywords := TFDStringList.Create;
GetODBCConnectStringKeywords(FKeywords);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysODBCDriverBase.Destroy;
begin
FDFreeAndNil(FKeywords);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCDriverBase.InternalLoad;
var
sHome, sLib, sMan: String;
begin
GetVendorParams(sHome, sLib);
if sLib = '' then
sMan := C_ODBC
else
sMan := sLib;
Messages.Msg(Format(S_FD_ODBCLoadingManager, [sMan]));
FODBCLib := TODBCLib.Allocate(sHome, sLib, Self);
Messages.Msg(S_FD_ODBCCreatingEnv);
FODBCEnvironment := TODBCEnvironment.Create(FODBCLib, Self, SQL_OV_ODBC3);
if Params <> nil then begin
if Params.OwnValue(S_FD_ConnParam_ODBC_ODBCDriver) then begin
ODBCDriver := Params.AsXString[S_FD_ConnParam_ODBC_ODBCDriver];
if ODBCDriver <> '' then
Messages.Value('ODBCDriver', ODBCDriver);
end;
if Params.OwnValue(S_FD_ConnParam_ODBC_ODBCAdvanced) then begin
ODBCAdvanced := Params.AsXString[S_FD_ConnParam_ODBC_ODBCAdvanced];
if ODBCAdvanced <> '' then
Messages.Value('ODBCAdvanced', ODBCAdvanced);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCDriverBase.InternalUnload;
begin
FDFreeAndNil(FODBCEnvironment);
TODBCLib.Release(FODBCLib);
FODBCLib := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.GetCliObj: Pointer;
begin
Result := FODBCEnvironment;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
begin
Result := inherited GetConnParams(AKeys, AParams);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ODBC_ODBCAdvanced, '@S', '', S_FD_ConnParam_ODBC_ODBCAdvanced, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_LoginTimeout, '@I', '', S_FD_ConnParam_Common_LoginTimeout, -1]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCDriverBase.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
AKeywords.Add('=DRIVER');
AKeywords.Add(S_FD_ConnParam_Common_UserName + '=UID');
AKeywords.Add(S_FD_ConnParam_Common_Password + '=PWD*');
AKeywords.Add('DSN');
AKeywords.Add('FIL');
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): string;
var
sDB, sAdv: String;
oTmpDef: IFDStanConnectionDef;
lHasDSN: Boolean;
i: Integer;
begin
sDB := Trim(AConnectionDef.Params.ExpandedDatabase);
if Pos('=', sDB) <> 0 then begin
FDCreateInterface(IFDStanConnectionDef, oTmpDef);
oTmpDef.Params.SetStrings(AConnectionDef.Params);
i := oTmpDef.Params.IndexOfName(S_FD_ConnParam_Common_Database);
if i >= 0 then
oTmpDef.Params.Delete(i);
oTmpDef.ParseString(oTmpDef.BuildString(FKeywords));
oTmpDef.ParseString(sDB);
Result := oTmpDef.BuildString(FKeywords);
lHasDSN := oTmpDef.HasValue(S_FD_ConnParam_ODBC_DataSource) or
oTmpDef.HasValue('DSN') or oTmpDef.HasValue('FIL');
end
else begin
Result := AConnectionDef.BuildString(FKeywords);
lHasDSN := AConnectionDef.HasValue(S_FD_ConnParam_ODBC_DataSource) or
AConnectionDef.HasValue('DSN') or AConnectionDef.HasValue('FIL');
end;
sAdv := AConnectionDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced];
if sAdv = '' then
sAdv := ODBCAdvanced;
if sAdv <> '' then begin
if Result <> '' then
Result := Result + ';';
Result := Result + sAdv;
end;
if not lHasDSN and (ODBCDriver <> '') then begin
if Result <> '' then
Result := ';' + Result;
Result := 'DRIVER=' + TODBCLib.DecorateKeyValue(ODBCDriver) + Result;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.RunConnectionWizard(const AConnectionDef: IFDStanConnectionDef;
AParentWnd: THandle): Boolean;
var
oODBCConn: TODBCConnection;
sConn: String;
begin
Employ;
try
Result := False;
oODBCConn := TODBCConnection.Create(ODBCEnvironment, Self);
try
try
sConn := oODBCConn.DriverConnect(BuildODBCConnectString(AConnectionDef),
SQL_DRIVER_PROMPT, AParentWnd);
oODBCConn.Disconnect;
AConnectionDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] :=
AConnectionDef.ParseString(sConn, FKeywords);
Result := True;
except
on E: EODBCNativeException do
if E.Kind <> ekNoDataFound then
raise;
end;
finally
FDFree(oODBCConn);
end;
finally
Vacate;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.GetODBCDriver: String;
begin
Result := ODBCDriver;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.GetODBCAdvanced: String;
begin
Result := ODBCAdvanced;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverBase.FindBestDriver(const ADrivers: array of String;
const ADefaultDriver: String = ''): String;
var
i: Integer;
sDriver, sAttr: String;
begin
Result := '';
Messages.Start(S_FD_ODBCSearchingDrv);
try
for i := Low(ADrivers) to High(ADrivers) do begin
Messages.Start(Format(S_FD_ODBCCheckingDrv, [ADrivers[i]]));
try
if ODBCEnvironment.DriverFirst(sDriver, sAttr) then
repeat
if FDStrLike(sDriver, ADrivers[i], True) then begin
Messages.Msg(Format(S_FD_ODBCFound, [sDriver]));
Result := sDriver;
Exit;
end;
until not ODBCEnvironment.DriverNext(sDriver, sAttr);
finally
Messages.Stop;
end;
end;
finally
if Result = '' then begin
Messages.Msg(S_FD_ODBCWarnDrvNotFound);
Result := ADefaultDriver;
if Result <> '' then
Messages.Msg(Format(S_FD_ODBCWillBeUsed, [Result]));
end;
Messages.Stop;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCConnectionBase }
{-------------------------------------------------------------------------------}
constructor TFDPhysODBCConnectionBase.Create(ADriverObj: TFDPhysDriver;
AConnHost: TFDPhysConnectionHost);
begin
inherited Create(ADriverObj, AConnHost);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysODBCConnectionBase.Destroy;
begin
{$IFNDEF AUTOREFCOUNT}
FDHighRefCounter(FRefCount);
{$ENDIF}
ForceDisconnect;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetDriverKind: TODBCDriverKind;
begin
Result := ODBCConnection.DriverKind;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysODBCCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.InternalCreateTransaction: TFDPhysTransaction;
begin
Result := TFDPhysODBCTransaction.Create(Self);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.InternalTracingChanged;
var
oLib: TODBCLib;
begin
if (DriverObj <> nil) and (TFDPhysODBCDriverBase(DriverObj).FODBCLib <> nil) then begin
oLib := TFDPhysODBCDriverBase(DriverObj).FODBCLib;
if FTracing and (FMonitor <> nil) and FMonitor.Tracing then
oLib.ActivateTracing(FMonitor, Self)
else
oLib.DeactivateTracing(Self);
end;
if ODBCConnection <> nil then
ODBCConnection.Tracing := FTracing;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.InternalExecuteDirect(const ASQL: String;
ATransaction: TFDPhysTransaction);
var
oStmt: TODBCCommandStatement;
iTmpCount: SQLLen;
begin
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
iTmpCount := 0;
oStmt.Execute(1, 0, iTmpCount, False, ASQL);
oStmt.Close;
finally
FDFree(oStmt);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := EODBCNativeException;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.SetupConnection;
var
lPrevIgnoreErrors: Boolean;
begin
if ConnectionDef.HasValue(S_FD_ConnParam_Common_LoginTimeout) then begin
// Old informix versions (at least 9.4 and less) do not support LOGIN_TIMEOUT
lPrevIgnoreErrors := ODBCConnection.IgnoreErrors;
ODBCConnection.IgnoreErrors := True;
try
ODBCConnection.LOGIN_TIMEOUT := ConnectionDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout];
finally
ODBCConnection.IgnoreErrors := lPrevIgnoreErrors;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.InternalConnect;
var
oODBCLib: TODBCLib;
oConnMeta: IFDPhysConnectionMetadata;
pCliHandles: PFDPhysODBCCliHandles;
oStmt: TODBCCommandStatement;
begin
oODBCLib := TFDPhysODBCDriverBase(DriverObj).FODBCLib;
if InternalGetSharedCliHandle() <> nil then begin
pCliHandles := PFDPhysODBCCliHandles(InternalGetSharedCliHandle());
FODBCEnvironment := TODBCEnvironment.CreateUsingHandle(oODBCLib, pCliHandles^[0], Self);
FODBCConnection := TODBCConnection.CreateUsingHandle(FODBCEnvironment,
pCliHandles^[1], Self);
end
else begin
FODBCEnvironment := TODBCEnvironment.Create(oODBCLib, Self, GetODBCVersion());
FODBCConnection := TODBCConnection.Create(FODBCEnvironment, Self);
end;
FODBCConnection.ExceptionClass := GetExceptionClass;
FODBCConnection.OnGetMaxSizes := GetStrsMaxSizes;
{$IFDEF FireDAC_MONITOR}
InternalTracingChanged;
{$ENDIF}
if InternalGetSharedCliHandle() = nil then begin
SetupConnection;
ODBCConnection.Connect(TFDPhysODBCDriverBase(DriverObj).
BuildODBCConnectString(ConnectionDef));
end;
CreateMetadata(oConnMeta);
ODBCConnection.RdbmsKind := oConnMeta.Kind;
FSupportedOptions := [];
if InternalGetSharedCliHandle() = nil then
// SQL_ATTR_LONGDATA_COMPAT is not supported by AS400 v 6 or earlier
if (DriverKind = dkDB2) or
(DriverKind = dkDB2_400) and (ODBCConnection.DriverVersion >= avDB2_400_7) then
ODBCConnection.LONGDATA_COMPAT := SQL_LD_COMPAT_YES
else if DriverKind = dkInformix then begin
ODBCConnection.INFX_LO_AUTOMATIC := SQL_TRUE;
ODBCConnection.INFX_ODBC_TYPES_ONLY := SQL_TRUE;
end;
if DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther, dkSQLAnywhere,
dkAdvantage, dkMSAccessJet, dkMSAccessACE, dkInformix, dkSybaseASE] then
Include(FSupportedOptions, soMoney);
if ODBCConnection.GetFunctions(SQL_API_SQLPRIMARYKEYS) = SQL_TRUE then
Include(FSupportedOptions, soPKFunction);
if ODBCConnection.GetFunctions(SQL_API_SQLFOREIGNKEYS) = SQL_TRUE then
Include(FSupportedOptions, soFKFunction);
if DriverKind <> dkSQLAnywhere then
Include(FSupportedOptions, soArrayBatch);
// tests for the rowsets and paramsets support
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
oStmt.IgnoreErrors := True;
if ((ODBCConnection.GETDATA_EXTENSIONS and SQL_GD_BLOCK) = SQL_GD_BLOCK) and
// Firebird ODBC driver returns first record blob values
// for all other records in the rowset.
(ODBCConnection.DriverKind <> dkFirebird) then begin
oStmt.ROW_ARRAY_SIZE := 5;
if oStmt.ROW_ARRAY_SIZE = 5 then
Include(FSupportedOptions, soRowSet);
end;
if not (ODBCConnection.DriverKind in [dkSolidDB, dkDB2_400]) then begin
oStmt.PARAMSET_SIZE := 5;
if oStmt.PARAMSET_SIZE = 5 then
Include(FSupportedOptions, soParamSet);
end;
finally
FDFree(oStmt);
end;
UpdateDecimalSep;
if ODBCConnection.TXN_CAPABLE <> SQL_TC_NONE then
MapTxIsolations;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.InternalSetMeta;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
inherited InternalSetMeta;
CreateMetadata(oConnMeta);
if (oConnMeta.Kind = TFDRDBMSKinds.PostgreSQL) and (FCurrentSchema = '') then
FCurrentSchema := 'public';
// Avoid adding a path to a full object name when DSN has default path.
// Otherwise MS Text Driver returns "Too few parameters. Expected 1"
if (ODBCConnection.FILE_USAGE = SQL_FILE_TABLE) and
DirectoryExists(ODBCConnection.DATABASE_NAME) then
Include(FAvoidImplicitMeta, npCatalog);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize, AByteSize: Integer);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetStrsType: TFDDataType;
begin
Result := dtUnknown;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetNumType: TFDDataType;
begin
Result := dtBCD;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetODBCVersion: Integer;
begin
Result := SQL_OV_ODBC3_80;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.MapTxIsolations;
var
iSuppIsol: SQLUInteger;
eIsol: TFDTxIsolation;
iIsol: SQLUInteger;
begin
iSuppIsol := ODBCConnection.TXN_ISOLATION_OPTION;
for eIsol := Low(TFDTxIsolation) to High(TFDTxIsolation) do begin
iIsol := C_FD_TxI2ODBCTxI[eIsol];
while ((iSuppIsol and iIsol) = 0) and (iIsol <> 0) do
iIsol := iIsol shr 1;
if iIsol = 0 then begin
iIsol := C_FD_TxI2ODBCTxI[eIsol];
while ((iSuppIsol and iIsol) = 0) and (iIsol <> 0) do
iIsol := iIsol shl 1;
end;
FTxnIsolations[eIsol] := iIsol;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.UpdateDecimalSep;
begin
if ODBCConnection.DriverKind = dkQuickBooks then begin
FODBCConnection.DecimalSepCol := ',';
FODBCConnection.DecimalSepPar := ',';
end
else begin
FODBCConnection.DecimalSepCol := '.';
FODBCConnection.DecimalSepPar := '.';
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.InternalDisconnect;
begin
FDFreeAndNil(FODBCConnection);
FDFreeAndNil(FODBCEnvironment);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
if ODBCConnection <> nil then
Inc(Result, 6);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
var
lPrevIgnoreErrors: Boolean;
begin
if AIndex < inherited GetItemCount then
inherited GetItem(AIndex, AName, AValue, AKind)
else begin
case AIndex - inherited GetItemCount of
0:
begin
AName := 'Driver Manager version';
// ICLIT09B.DLL returns SQL_ERROR for SQL_DM_VER, when used
// instead of ODBC32.DLL
lPrevIgnoreErrors := ODBCConnection.IgnoreErrors;
ODBCConnection.IgnoreErrors := True;
try
AValue := ODBCConnection.DM_VER;
finally
ODBCConnection.IgnoreErrors := lPrevIgnoreErrors;
end;
AKind := ikClientInfo;
end;
1:
begin
AName := 'Driver name';
AValue := ODBCConnection.DRIVER_NAME;
AKind := ikSessionInfo;
end;
2:
begin
AName := 'Driver version';
AValue := ODBCConnection.DRIVER_VER;
AKind := ikSessionInfo;
end;
3:
begin
AName := 'Driver conformance';
if ODBCConnection.DriverODBCVersion >= ovODBC3 then
AValue := IntToStr(ODBCConnection.INTERFACE_CONFORMANCE)
else
AValue := '<undefined>';
AKind := ikSessionInfo;
end;
4:
begin
AName := 'DBMS name';
AValue := ODBCConnection.DBMS_NAME;
AKind := ikSessionInfo;
end;
5:
begin
AName := 'DBMS version';
AValue := ODBCConnection.DBMS_VER;
AKind := ikSessionInfo;
end;
end;
end;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysODBCConnectionBase.GetMessages: EFDDBEngineException;
begin
if ODBCConnection <> nil then
Result := ODBCConnection.Info
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetCliObj: Pointer;
begin
Result := ODBCConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.InternalGetCliHandle: Pointer;
begin
if ODBCEnvironment <> nil then begin
FCliHandles[0] := ODBCEnvironment.Handle;
FCliHandles[1] := ODBCConnection.Handle;
Result := @FCliHandles;
end
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.GetKeywords: String;
begin
if (ODBCConnection <> nil) and ODBCConnection.Connected then
Result := ODBCConnection.KEYWORDS
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnectionBase.GetVersions(out AServer, AClient: TFDVersion);
begin
if ODBCConnection <> nil then begin
AServer := FDVerStr2Int(ODBCConnection.DBMS_VER);
if ODBCConnection.FILE_USAGE = SQL_FILE_NOT_SUPPORTED then
AClient := FDVerStr2Int(ODBCConnection.DRIVER_VER)
else
AClient := AServer;
end
else begin
AServer := 0;
AClient := 0;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.InternalGetCurrentCatalog: String;
begin
if (ODBCConnection <> nil) and ODBCConnection.Connected then
Result := ODBCConnection.DATABASE_NAME
else
Result := inherited InternalGetCurrentCatalog;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnectionBase.InternalGetCurrentSchema: String;
begin
if (ODBCConnection <> nil) and ODBCConnection.Connected then
Result := ODBCConnection.USER_NAME
else
Result := inherited InternalGetCurrentSchema;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCTransaction }
{-------------------------------------------------------------------------------}
function TFDPhysODBCTransaction.GetODBCConnection: TODBCConnection;
begin
Result := TFDPhysODBCConnectionBase(ConnectionObj).ODBCConnection;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.InternalChanged;
begin
if xoAutoCommit in GetOptions.Changed then
if GetOptions.AutoCommit then
ODBCConnection.AUTOCOMMIT := SQL_AUTOCOMMIT_ON
else
ODBCConnection.AUTOCOMMIT := SQL_AUTOCOMMIT_OFF;
if xoReadOnly in GetOptions.Changed then
if GetOptions.ReadOnly then
ODBCConnection.ACCESS_MODE := SQL_MODE_READ_ONLY
else
ODBCConnection.ACCESS_MODE := SQL_MODE_READ_WRITE;
if xoIsolation in GetOptions.Changed then
ODBCConnection.TXN_ISOLATION := TFDPhysODBCConnectionBase(ConnectionObj).
FTxnIsolations[GetOptions.Isolation];
end;
{-------------------------------------------------------------------------------}
function DisconnectionBeforeStart(ACmdObj: TObject): Boolean;
var
oStmt: TODBCStatementBase;
begin
oStmt := TODBCStatementBase(ACmdObj);
Result := oStmt.Executed and (oStmt.SS_CURSOR_OPTIONS = SQL_CO_DEFAULT);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.InternalStartTransaction(ATxID: LongWord);
begin
// SQL Native Client and MS Access return SQL_ERROR without any additional
// error description, if there is any active default cursor. No problems
// with MS SQL 2000 client or other cursor kinds.
if ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc] then
DisconnectCommands(DisconnectionBeforeStart, dmRelease)
else if ODBCConnection.RdbmsKind = TFDRDBMSKinds.MSAccess then
DisconnectCommands(nil, dmRelease);
ODBCConnection.TransID := ATxID;
ODBCConnection.StartTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.DisconnectCommandsBeforeCommit;
begin
{$IFDEF POSIX}
// MSSQL: SQL Server ODBC Driver 11 for Linux may return SQL_CURSOR_COMMIT_BEHAVIOR
// = SQL_CB_PRESERVE at first time, although existing cursors will be invalidated.
if ODBCConnection.DriverKind = dkSQLOdbc then
DisconnectCommands(nil, dmRelease)
else
{$ENDIF}
case ODBCConnection.CURSOR_COMMIT_BEHAVIOR of
SQL_CB_DELETE: DisconnectCommands(nil, dmOffline);
SQL_CB_CLOSE: DisconnectCommands(nil, dmRelease);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.DisconnectCommandsBeforeRollback;
begin
{$IFDEF POSIX}
if ODBCConnection.DriverKind = dkSQLOdbc then
DisconnectCommands(nil, dmRelease)
else
{$ENDIF}
case ODBCConnection.CURSOR_ROLLBACK_BEHAVIOR of
SQL_CB_DELETE: DisconnectCommands(nil, dmOffline);
SQL_CB_CLOSE: DisconnectCommands(nil, dmRelease);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.InternalCommit(ATxID: LongWord);
begin
DisconnectCommandsBeforeCommit;
ODBCConnection.Commit;
if Retaining then
InternalStartTransaction(ATxID)
else if CLIAutoCommit then
ODBCConnection.AUTOCOMMIT := SQL_AUTOCOMMIT_ON;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.InternalRollback(ATxID: LongWord);
begin
DisconnectCommandsBeforeRollback;
ODBCConnection.Rollback;
if Retaining then
InternalStartTransaction(ATxID)
else if CLIAutoCommit then
ODBCConnection.AUTOCOMMIT := SQL_AUTOCOMMIT_ON;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.InternalReleaseHandle;
var
lPrevIgnoreErrors: Boolean;
begin
if (ODBCConnection <> nil) and ODBCConnection.Connected then begin
lPrevIgnoreErrors := ODBCConnection.IgnoreErrors;
ODBCConnection.IgnoreErrors := True;
try
ODBCConnection.AUTOCOMMIT := SQL_AUTOCOMMIT_ON;
finally
ODBCConnection.IgnoreErrors := lPrevIgnoreErrors;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCTransaction.InternalNotify(ANotification: TFDPhysTxNotification;
ACommandObj: TFDPhysCommand);
begin
if ANotification = cpBeforeCmdExecute then
case TFDPhysODBCCommand(ACommandObj).GetCommandKind of
skCommit: DisconnectCommandsBeforeCommit;
skRollback: DisconnectCommandsBeforeRollback;
end;
inherited InternalNotify(ANotification, ACommandObj);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCCommand }
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.GetConnection: TFDPhysODBCConnectionBase;
begin
Result := TFDPhysODBCConnectionBase(FConnectionObj);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.GetCliObj: Pointer;
begin
Result := ODBCStatement;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.FD2SQLDataType(AFDType: TFDDataType; AFixedLen: Boolean;
var AColSize, AScale: SQLInteger): SQLSmallint;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
ODBCConnection.CreateMetadata(oConnMeta);
case AFDType of
dtAnsiString:
if AFixedLen then
Result := SQL_CHAR
else
Result := SQL_VARCHAR;
dtWideString:
if AFixedLen then
Result := SQL_WCHAR
else
Result := SQL_WVARCHAR;
dtByteString:
if AFixedLen then
Result := SQL_BINARY
else
Result := SQL_VARBINARY;
dtXML:
case ODBCConnection.DriverKind of
dkDB2,
dkDB2_400:
Result := SQL_XML;
dkSQLNC,
dkSQLOdbc,
dkFreeTDS,
dkSQLSrvOther:
Result := SQL_SS_XML;
dkTeradata:
Result := SQL_TD_XML;
else
Result := SQL_UNKNOWN_TYPE;
end;
dtTime:
if (ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and
(oConnMeta.ClientVersion >= svMSSQL2008) then begin
Result := SQL_SS_TIME2;
AColSize := 16;
AScale := 7;
end
else
Result := SQL_TYPE_TIME;
dtHBFile:
if (ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and
(oConnMeta.ClientVersion >= svMSSQL2008) then begin
Result := SQL_WVARCHAR;
AColSize := MaxInt;
end
else
Result := SQL_LONGVARBINARY;
dtRowSetRef:
if (ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and
(oConnMeta.ClientVersion >= svMSSQL2008) then
Result := SQL_SS_TABLE
else
Result := SQL_UNKNOWN_TYPE;
else
Result := C_FD_Type2SQLDataType[AFDType];
end;
if (soMoney in ODBCConnection.FSupportedOptions) and
(Result <> SQL_UNKNOWN_TYPE) and (AFDType = dtCurrency) then begin
// dtCurrency is strictly mapped to NUMBER(19,4)
AColSize := 19;
AScale := 4;
end;
case ODBCConnection.DriverKind of
dkMSAccessJet,
dkMSAccessACE:
if Result = SQL_DECIMAL then
Result := SQL_NUMERIC
else if Result = SQL_BIGINT then
Result := SQL_NUMERIC
else if Result = SQL_BIT then
Result := SQL_SMALLINT;
dkDB2,
dkDB2_400:
if Result = SQL_BIT then
Result := SQL_DECIMAL;
dkOracleOra,
dkOracleMS,
dkOracleOther:
// Oracle ODBC does not support Int64
if Result = SQL_BIGINT then
Result := SQL_INTEGER;
dkSQLNC,
dkSQLOdbc,
dkFreeTDS,
dkSQLSrvOther:
// SQL Server 2005 ODBC not well supports SQL_LONGxxx data types.
// Use VARxxx(MAX) instead.
if (AColSize = 0) and (oConnMeta.ClientVersion >= svMSSQL2005) then
case Result of
SQL_LONGVARBINARY:
begin
Result := SQL_VARBINARY;
AColSize := MaxInt;
end;
SQL_LONGVARCHAR:
begin
Result := SQL_VARCHAR;
AColSize := MaxInt;
end;
SQL_WLONGVARCHAR:
begin
Result := SQL_WVARCHAR;
AColSize := MaxInt;
end;
SQL_SS_XML:
AColSize := MaxInt;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.FD2CDataType(AFDType: TFDDataType; ANestedColumn: Boolean): SQLSmallint;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
ODBCConnection.CreateMetadata(oConnMeta);
if AFDType = dtRowSetRef then
if (ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and
(oConnMeta.ClientVersion >= svMSSQL2008) then
Result := SQL_C_DEFAULT
else
Result := SQL_TYPE_NULL
else
Result := C_FD_Type2CDataType[AFDType];
if ODBCConnection.ODBCConnection.DriverODBCVersion < ovODBC3 then
case Result of
SQL_C_TYPE_TIMESTAMP: Result := SQL_C_TIMESTAMP;
SQL_C_TYPE_TIME: Result := SQL_C_TIME;
SQL_C_TYPE_DATE: Result := SQL_C_DATE;
SQL_C_NUMERIC: Result := SQL_C_CHAR;
end
else if Result = SQL_C_NUMERIC then
if ODBCConnection.GetNumType = dtAnsiString then
Result := SQL_C_CHAR
else
case ODBCConnection.DriverKind of
dkSQLNC,
dkSQLOdbc,
dkSQLSrvOther:
// TVP columns have more strong req to SQL_C_NUMERIC
if ANestedColumn then
Result := SQL_C_CHAR;
dkFreeTDS:
// FreeTDS fails to transfer numerics with scale > 0
Result := SQL_C_CHAR;
dkDB2,
dkDB2_400:
// Use the character binding for the numerics in DB2, instead of the
// binary binding, which:
// - may return a garbage if CursorKind = ckDefault
// - is about 20% slower than the character binding
Result := SQL_C_CHAR;
dkAdvantage:
// ADS does not support SQL_C_NUMERIC, so it will always return NULL
Result := SQL_C_CHAR;
dkSQLAnywhere:
if (ODBCConnection.ODBCConnection.DriverVersion >= cvSybaseASA8) and
(ODBCConnection.ODBCConnection.DriverVersion < cvSybaseASA9) then
Result := SQL_C_CHAR;
dkInformix:
// Informix fails to transfer several values
Result := SQL_C_CHAR;
dkPWMicroFocus,
dkSybaseASE,
dkCache,
dkPervasive:
// Following drivers have issues with SQL_C_NUMERIC, so map to char:
// * Parkway Connectware Micro Focus
// * Sybase ASE ODBC
// * Intersystems Cache
// * Pervasive SQL
Result := SQL_C_CHAR;
end
else if Result = SQL_C_TYPE_TIME then
if (ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc, dkFreeTDS, dkSQLSrvOther]) and
(oConnMeta.ClientVersion >= svMSSQL2008) then
Result := SQL_C_BINARY;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.SQL2FDColInfo(ASQLDataType: SQLSmallint;
AUnsigned: Boolean; const ASQLTypeName: String; var ASQLSize: SQLInteger;
ASQLDecimals: SQLInteger; var AType: TFDDataType; var AAttrs: TFDDataAttributes;
var ALen: LongWord; var APrec, AScale: Integer);
var
oConnMeta: IFDPhysConnectionMetadata;
oFmt: TFDFormatOptions;
begin
AType := dtUnknown;
ALen := 0;
APrec := 0;
AScale := 0;
Exclude(AAttrs, caFixedLen);
Exclude(AAttrs, caBlobData);
Include(AAttrs, caSearchable);
FConnection.CreateMetadata(oConnMeta);
case ASQLDataType of
SQL_TINYINT:
if AUnsigned or
(oConnMeta.Kind in [TFDRDBMSKinds.SQLAnywhere, TFDRDBMSKinds.MSSQL]) and
(CompareText(ASQLTypeName, 'TINYINT') = 0) then
AType := dtByte
else
AType := dtSByte;
SQL_SMALLINT:
if AUnsigned then
AType := dtUInt16
else
AType := dtInt16;
SQL_INTEGER:
if AUnsigned then
AType := dtUInt32
else
AType := dtInt32;
SQL_BIGINT,
SQL_INFX_UDT_BIGINT:
if AUnsigned then
AType := dtUInt64
else
AType := dtInt64;
SQL_NUMERIC,
SQL_DECIMAL,
SQL_DECFLOAT:
begin
APrec := ASQLSize;
AScale := ASQLDecimals;
oFmt := FOptions.FormatOptions;
if (soMoney in ODBCConnection.FSupportedOptions) and
((ASQLSize = 19) or (ASQLSize = 10)) and (ASQLDecimals = 4) then
AType := dtCurrency
else if oFmt.IsFmtBcd(ASQLSize, ASQLDecimals) then
AType := dtFmtBCD
else
AType := dtBCD;
end;
SQL_DOUBLE,
SQL_FLOAT,
SQL_REAL:
begin
if ASQLSize = 53 then
APrec := 16
else if ASQLSize = 24 then
APrec := 8
else
APrec := ASQLSize;
ASQLSize := APrec;
if (APrec = 0) or (APrec > 8) then
AType := dtDouble
else
AType := dtSingle;
end;
SQL_GUID:
AType := dtGUID;
SQL_CHAR,
SQL_VARCHAR:
begin
AType := dtAnsiString;
ALen := ASQLSize;
if ASQLDataType = SQL_CHAR then
Include(AAttrs, caFixedLen);
if ASQLSize = MAXINT then begin
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
end;
SQL_WCHAR,
SQL_WVARCHAR,
SQL_GRAPHIC,
SQL_VARGRAPHIC,
SQL_LONGVARGRAPHIC:
begin
AType := dtWideString;
ALen := ASQLSize;
if (ASQLDataType = SQL_WCHAR) or (ASQLDataType = SQL_GRAPHIC) then
Include(AAttrs, caFixedLen);
if ASQLSize = MAXINT then begin
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
end;
SQL_SS_VARIANT:
if ODBCConnection.ODBCConnection.MSSQLVariantBinary then begin
AType := dtByteString;
ALen := ASQLSize;
end
else begin
AType := dtWideString;
ALen := 8000;
Include(AAttrs, caBlobData);
end;
SQL_BINARY,
SQL_VARBINARY:
begin
AType := dtByteString;
ALen := ASQLSize;
if ASQLDataType = SQL_BINARY then begin
// In ASA BINARY is equivalent of VARBINARY
if oConnMeta.Kind <> TFDRDBMSKinds.SQLAnywhere then
Include(AAttrs, caFixedLen);
end;
if ASQLSize = MAXINT then begin
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
end;
SQL_TYPE_DATE:
AType := dtDate;
SQL_TYPE_TIME,
SQL_TIME,
SQL_SS_TIME2:
begin
AType := dtTime;
if (ASQLDecimals >= 0) and (ASQLDecimals < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLDecimals];
end;
SQL_DATETIME:
begin
AType := dtDateTime;
if (ASQLDecimals >= 0) and (ASQLDecimals < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLDecimals];
end;
SQL_TYPE_TIMESTAMP,
SQL_TIMESTAMP,
SQL_SS_TIMESTAMPOFFSET:
begin
AType := dtDateTimeStamp;
if oConnMeta.Kind = TFDRDBMSKinds.MSSQL then begin
if ASQLDecimals = 3 then
AScale := 3
else if ASQLDecimals = 0 then
AScale := 60000;
end
else if (ASQLDecimals >= 0) and (ASQLDecimals < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLDecimals];
end;
SQL_BIT:
AType := dtBoolean;
SQL_CLOB,
SQL_LONGVARCHAR,
SQL_INFX_UDT_CLOB,
SQL_TD_JSON:
begin
AType := dtMemo;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
SQL_WLONGVARCHAR,
SQL_DBCLOB,
SQL_TD_WJSON:
begin
AType := dtWideMemo;
ALen := ASQLSize;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
SQL_XML,
SQL_SS_XML,
SQL_TD_XML:
begin
AType := dtXML;
ALen := ASQLSize;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
SQL_BLOB,
SQL_LONGVARBINARY,
SQL_INFX_UDT_BLOB,
SQL_SS_UDT:
begin
AType := dtBlob;
ALen := ASQLSize;
Include(AAttrs, caBlobData);
Exclude(AAttrs, caSearchable);
end;
SQL_INTERVAL_YEAR,
SQL_INTERVAL_MONTH,
SQL_INTERVAL_YEAR_TO_MONTH:
begin
AType := dtTimeIntervalYM;
APrec := ASQLSize;
end;
SQL_INTERVAL_DAY,
SQL_INTERVAL_HOUR,
SQL_INTERVAL_MINUTE,
SQL_INTERVAL_DAY_TO_HOUR,
SQL_INTERVAL_DAY_TO_MINUTE,
SQL_INTERVAL_HOUR_TO_MINUTE:
begin
AType := dtTimeIntervalDS;
APrec := ASQLSize;
end;
SQL_INTERVAL_SECOND,
SQL_INTERVAL_DAY_TO_SECOND,
SQL_INTERVAL_HOUR_TO_SECOND,
SQL_INTERVAL_MINUTE_TO_SECOND:
begin
AType := dtTimeIntervalDS;
if (ASQLDecimals >= 0) and (ASQLDecimals < 3) then
AScale := C_FD_ScaleFactor[3 - ASQLDecimals];
APrec := ASQLSize;
end;
SQL_REFCURSOR:
AType := dtCursorRef;
SQL_SS_TABLE:
begin
AType := dtRowSetRef;
Exclude(AAttrs, caSearchable);
Include(AAttrs, caReadOnly);
end;
else
{$IFDEF POSIX}
// Linux / MacOS / Android drivers do not support all types
// supported by Windows drivers. Eg, SQL_VARIANT.
AType := dtByteString;
{$ELSE}
AType := dtUnknown;
{$ENDIF}
end;
if (oConnMeta.Kind = TFDRDBMSKinds.MSAccess) and (CompareText(ASQLTypeName, 'COUNTER') = 0) or
(oConnMeta.Kind = TFDRDBMSKinds.Advantage) and (CompareText(ASQLTypeName, 'AUTOINC') = 0) then begin
Include(AAttrs, caAutoInc);
Include(AAttrs, caReadOnly);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.FD2SQLParamType(AParamType: TParamType): SQLSmallint;
begin
Result := C_FD_ParType2SQLParType[AParamType];
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.CheckFetchColumn(ADataType: TFDDataType;
AAttributes: TFDDataAttributes; ASQLDataType: Smallint): Boolean;
begin
Result := inherited CheckFetchColumn(ADataType, AAttributes);
if Result and (ASQLDataType = SQL_SS_VARIANT) and
ODBCConnection.ODBCConnection.MSSQLVariantBinary then
Result := fiBlobs in FOptions.FetchOptions.Items;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.CreateDescribeInfos;
var
oFmtOpts: TFDFormatOptions;
i, iNumCols: SQLSmallint;
oSelItem: TODBCSelectItem;
iLen: LongWord;
iPrec, iScale: Integer;
oConnMeta: IFDPhysConnectionMetadata;
iInitBuffSize: SQLUInteger;
lMetadata, lInfxBigSer, lDB2AlwaysIdent: Boolean;
eStrsType: TFDDataType;
rName: TFDPhysParsedName;
pInfo: PFDODBCColInfoRec;
oVar: TODBCVariable;
begin
ODBCConnection.CreateMetadata(oConnMeta);
oFmtOpts := FOptions.FormatOptions;
Exclude(FStatementProps, cpLateBindedData);
iNumCols := FStatement.NumResultCols;
if (GetMetaInfoKind = mkProcArgs) and
not (ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc]) and (iNumCols > 13) then
iNumCols := 13;
iInitBuffSize := 0;
lMetadata := GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone;
eStrsType := ODBCConnection.GetStrsType;
SetLength(FColInfos, iNumCols);
for i := 1 to iNumCols do begin
oSelItem := TODBCSelectItem.Create(FStatement, i);
pInfo := @FColInfos[i - 1];
try
pInfo^.FName := oSelItem.Name;
if (ODBCConnection.ODBCConnection.DriverODBCVersion >= ovODBC3) and
oConnMeta.ColumnOriginProvided then begin
pInfo^.FOriginTabName := oSelItem.BASE_TABLE_NAME;
pInfo^.FOriginColName := oSelItem.BASE_COLUMN_NAME;
if (pInfo^.FOriginTabName = '') or (pInfo^.FOriginColName = '') then begin
pInfo^.FOriginTabName := '';
pInfo^.FOriginColName := '';
end
else begin
pInfo^.FOriginCatalogName := oSelItem.BASE_CATALOG_NAME;
pInfo^.FOriginSchemaName := oSelItem.BASE_SCHEMA_NAME;
end;
end;
pInfo^.FPos := oSelItem.Position;
pInfo^.FSrcSQLDataType := oSelItem.SQLDataType;
pInfo^.FColSize := oSelItem.ColumnSize;
pInfo^.FScale := oSelItem.Scale;
if lMetaData then
// Some ODBC drivers return the textual metadata columns as
// SQL_CHAR / SQL_WCHAR, but FireDAC expects a varlen string
case pInfo^.FSrcSQLDataType of
SQL_CHAR: pInfo^.FSrcSQLDataType := SQL_VARCHAR;
SQL_WCHAR: pInfo^.FSrcSQLDataType := SQL_WVARCHAR;
end
else if eStrsType <> dtUnknown then
if eStrsType = dtWideString then
case pInfo^.FSrcSQLDataType of
SQL_CHAR: pInfo^.FSrcSQLDataType := SQL_WCHAR;
SQL_VARCHAR: pInfo^.FSrcSQLDataType := SQL_WVARCHAR;
SQL_LONGVARCHAR: pInfo^.FSrcSQLDataType := SQL_WLONGVARCHAR;
end
else if eStrsType = dtAnsiString then
case pInfo^.FSrcSQLDataType of
SQL_WCHAR,
SQL_GRAPHIC: pInfo^.FSrcSQLDataType := SQL_CHAR;
SQL_WVARCHAR,
SQL_VARGRAPHIC: pInfo^.FSrcSQLDataType := SQL_VARCHAR;
SQL_WLONGVARCHAR,
SQL_LONGVARGRAPHIC: pInfo^.FSrcSQLDataType := SQL_LONGVARCHAR;
end;
if oConnMeta.ColumnOriginProvided then
if ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc] then
if (pInfo^.FSrcSQLDataType = SQL_SS_XML) and (oSelItem.XML_SCHEMACOLLECTION_NAME <> '') then begin
rName.FCatalog := oSelItem.XML_SCHEMACOLLECTION_CATALOG_NAME;
rName.FSchema := oSelItem.XML_SCHEMACOLLECTION_SCHEMA_NAME;
rName.FObject := oSelItem.XML_SCHEMACOLLECTION_NAME;
pInfo^.FExtName := oConnMeta.EncodeObjName(rName, Self, [eoNormalize]);
end
else if (pInfo^.FSrcSQLDataType = SQL_SS_UDT) and (oSelItem.UDT_TYPE_NAME <> '') then begin
rName.FCatalog := oSelItem.UDT_CATALOG_NAME;
rName.FSchema := oSelItem.UDT_SCHEMA_NAME;
rName.FObject := oSelItem.UDT_TYPE_NAME;
pInfo^.FExtName := oConnMeta.EncodeObjName(rName, Self, [eoNormalize]);
end
else
pInfo^.FExtName := oSelItem.TYPE_NAME
else if not (lMetadata and (ODBCConnection.DriverKind = dkDB2_400)) then
pInfo^.FExtName := oSelItem.TYPE_NAME;
if oSelItem.NULLABLE = SQL_NULLABLE then
Include(pInfo^.FAttrs, caAllowNull);
if oSelItem.AUTO_UNIQUE_VALUE = SQL_TRUE then begin
Include(pInfo^.FAttrs, caAutoInc);
Include(pInfo^.FAttrs, caAllowNull);
end;
// Informix: driver returns improper UPDATABLE and UNSIGNED
// attributes for BIGSERIAL column
lInfxBigSer := (ODBCConnection.DriverKind = dkInformix) and
(oSelItem.SQLDataType = SQL_INFX_UDT_BIGINT) and (caAutoInc in pInfo^.FAttrs);
// DB2: driver describes only GENERATED ALWAYS AS IDENTITY as
// AUTO_UNIQUE_VALUE = SQL_TRUE, but "ALWAYS" must be read-only
lDB2AlwaysIdent := (ODBCConnection.DriverKind in [dkDB2, dkDB2_400]) and
(caAutoInc in pInfo^.FAttrs);
if (oSelItem.UPDATABLE = SQL_ATTR_READONLY) or lInfxBigSer or lDB2AlwaysIdent then
Include(pInfo^.FAttrs, caReadOnly);
if oSelItem.IsFixedLen then
Include(pInfo^.FAttrs, caFixedLen);
if oSelItem.SEARCHABLE <> SQL_PRED_NONE then
Include(pInfo^.FAttrs, caSearchable);
if oSelItem.ROWVER = SQL_TRUE then
Include(pInfo^.FAttrs, caRowVersion);
if CompareText(pInfo^.FName, 'rowid') = 0 then begin
Include(pInfo^.FAttrs, caROWID);
Include(pInfo^.FAttrs, caReadOnly);
end;
pInfo^.FInKey := False;
SQL2FDColInfo(pInfo^.FSrcSQLDataType, (oSelItem.UNSIGNED = SQL_TRUE) or lInfxBigSer, '',
pInfo^.FColSize, pInfo^.FScale, pInfo^.FSrcDataType, pInfo^.FAttrs, iLen, iPrec, iScale);
if lMetaData then
// Some ODBC drivers return the textual metadata columns as
// SQL_VARCHAR, but FireDAC expects an Unicode strings
if pInfo^.FSrcDataType = dtAnsiString then
pInfo^.FDestDataType := dtWideString
else
pInfo^.FDestDataType := pInfo^.FSrcDataType
else
// mapping data types
oFmtOpts.ResolveDataType(pInfo^.FName, pInfo^.FExtName, pInfo^.FSrcDataType,
iLen, iPrec, iScale, pInfo^.FDestDataType, iLen, True);
pInfo^.FOutSQLDataType := FD2SQLDataType(pInfo^.FDestDataType, caFixedLen in pInfo^.FAttrs,
pInfo^.FColSize, pInfo^.FScale);
if pInfo^.FOutSQLDataType <> SQL_UNKNOWN_TYPE then begin
SQL2FDColInfo(pInfo^.FOutSQLDataType, False, '', pInfo^.FColSize, pInfo^.FScale,
pInfo^.FOutDataType, pInfo^.FAttrs, iLen, iPrec, iScale);
if pInfo^.FDestDataType = pInfo^.FSrcDataType then
pInfo^.FOutSQLDataType := pInfo^.FSrcSQLDataType;
end
else begin
SQL2FDColInfo(pInfo^.FSrcSQLDataType, False, '', pInfo^.FColSize, pInfo^.FScale,
pInfo^.FOutDataType, pInfo^.FAttrs, iLen, iPrec, iScale);
pInfo^.FOutSQLDataType := pInfo^.FSrcSQLDataType;
end;
pInfo^.FFDLen := iLen;
pInfo^.FFDScale := iScale;
if (pInfo^.FSrcDataType = dtBCD) and (pInfo^.FOutDataType = dtFmtBCD) then
pInfo^.FOutDataType := dtBCD
else if (pInfo^.FDestDataType in [dtSingle, dtDouble]) and
(pInfo^.FOutDataType in [dtSingle, dtDouble]) then
pInfo^.FOutDataType := pInfo^.FDestDataType;
if CheckFetchColumn(pInfo^.FSrcDataType, pInfo^.FAttrs, pInfo^.FSrcSQLDataType) then begin
pInfo^.FVar := FStatement.ColumnList.Add(TODBCColumn.Create);
oVar := pInfo^.FVar;
oVar.Position := pInfo^.FPos;
oVar.ColumnSize := pInfo^.FColSize;
oVar.Scale := pInfo^.FScale;
oVar.SQLDataType := pInfo^.FOutSQLDataType;
oVar.CDataType := FD2CDataType(pInfo^.FOutDataType, False);
oVar.UpdateFlags;
if oVar.LateBinding then
Include(FStatementProps, cpLateBindedData)
// 1) MSSQL fails to fetch result set, if a BLOB column is in the middle
// of a SELECT list and columns after BLOB are not late binded.
// 2) ASA fails with "invalid cursor position" to fetch late binded
// columns, if they are non BLOB columns.
else if ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc,
dkFreeTDS, dkSQLSrvOther] then
oVar.ForceLateBinding := cpLateBindedData in FStatementProps;
if (pInfo^.FOutDataType = pInfo^.FDestDataType) and
(lMetadata or not (pInfo^.FDestDataType in C_FD_VarLenTypes)) then
if (iInitBuffSize < oVar.DataSize) and (oVar.DataSize <> MAXINT) then
iInitBuffSize := oVar.DataSize;
end
else
pInfo^.FVar := nil;
finally
FDFree(oSelItem);
end;
end;
FBuffer.Check(iInitBuffSize);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.DestroyDescribeInfos;
begin
if Length(FColInfos) = 0 then
Exit;
SetLength(FColInfos, 0);
if FStatement <> nil then
FStatement.UnbindColumns;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.CreateParamColumns(AParam: TFDParam);
begin
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.CreateParamColumnInfos(ApInfo: PFDODBCParInfoRec;
AParam: TFDParam);
begin
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverID]);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.CreateParamInfos;
var
n, i: SQLSmallInt;
oParam: TFDParam;
oParams: TFDParams;
eDestFldType: TFieldType;
iPrec, iScale: Integer;
iLen: LongWord;
eAttrs: TFDDataAttributes;
oFmtOpts: TFDFormatOptions;
oConnMeta: IFDPhysConnectionMetadata;
lFixedLen: Boolean;
pInfo: PFDODBCParInfoRec;
oVar: TODBCParameter;
rName: TFDPhysParsedName;
iDestSize: LongWord;
lUseNames: Boolean;
begin
oParams := GetParams;
if (oParams.Count = 0) or (FCommandStatement = nil) then
Exit;
oFmtOpts := FOptions.FormatOptions;
ODBCConnection.CreateMetadata(oConnMeta);
n := oParams.Markers.Count;
SetLength(FParInfos, n);
lUseNames := ((oConnMeta.Kind = TFDRDBMSKinds.MSSQL) or (ODBCConnection.DriverKind = dkSybaseASE)) and
(GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]);
for i := 0 to n - 1 do begin
pInfo := @FParInfos[i];
case GetParams.BindMode of
pbByName:
begin
oParam := oParams.FindParam(oParams.Markers[i]);
if oParam <> nil then begin
pInfo^.FName := oParam.Name;
if (cpUnifyParams in FStatementProps) and
(pInfo^.FName <> '') and (pInfo^.FName[1] <> '@') then
pInfo^.FName := '@' + pInfo^.FName;
if Length(pInfo^.FName) > oConnMeta.ParamNameMaxLength then
pInfo^.FName := Copy(pInfo^.FName, 1, oConnMeta.ParamNameMaxLength -
1 - Length(IntToStr(i + 1))) + '_' + IntToStr(i + 1);
end;
end;
pbByNumber:
begin
oParam := oParams.FindParam(i + 1);
pInfo^.FName := '';
end;
else
oParam := nil;
end;
if oParam = nil then begin
pInfo^.FPos := -1;
pInfo^.FParamIndex := -1;
Continue;
end;
pInfo^.FPos := i;
pInfo^.FParamIndex := oParam.Index;
case oParam.ParamType of
ptOutput,
ptInputOutput:
begin
Include(FStatementProps, cpOutParams);
Include(FStatementProps, cpOutResParams);
end;
ptResult:
Include(FStatementProps, cpOutResParams);
end;
pInfo^.FParamType := oParam.ParamType;
pInfo^.FDataType := oParam.DataType;
if oParam.DataType = ftUnknown then
ParTypeUnknownError(oParam);
oFmtOpts.ResolveFieldType('', oParam.DataTypeName, oParam.DataType, oParam.FDDataType,
oParam.Size, oParam.Precision, oParam.NumericScale, eDestFldType, iDestSize,
pInfo^.FColSize, pInfo^.FScale, pInfo^.FSrcDataType, pInfo^.FDestDataType, False);
if iDestSize > 0 then
pInfo^.FColSize := iDestSize;
// ASA: cannot correctly return blob out parameters, so map them to
// appropriate types
if (ODBCConnection.DriverKind = dkSQLAnywhere) and
(oParam.ParamType in [ptOutput, ptInputOutput]) then
case pInfo^.FDestDataType of
dtBlob: pInfo^.FDestDataType := dtByteString;
dtMemo: pInfo^.FDestDataType := dtAnsiString;
dtWideMemo: pInfo^.FDestDataType := dtWideString;
end;
lFixedLen := pInfo^.FDataType in [ftFixedChar, ftBytes, ftFixedWideChar];
pInfo^.FSrcSQLDataType := FD2SQLDataType(pInfo^.FSrcDataType, lFixedLen,
iPrec, iScale);
pInfo^.FOutSQLDataType := FD2SQLDataType(pInfo^.FDestDataType, lFixedLen,
pInfo^.FColSize, pInfo^.FScale);
if pInfo^.FOutSQLDataType = SQL_UNKNOWN_TYPE then
ParTypeMapError(oParam);
eAttrs := [];
SQL2FDColInfo(pInfo^.FOutSQLDataType, False, '', pInfo^.FColSize, pInfo^.FScale,
pInfo^.FOutDataType, eAttrs, iLen, iPrec, iScale);
if (pInfo^.FDestDataType = dtBCD) and (pInfo^.FOutDataType = dtFmtBCD) then
pInfo^.FOutDataType := dtBCD;
if (pInfo^.FOutDataType = dtRowSetRef) and (oParam.AsDataSet = nil) and
(oParam.DataTypeName <> '') and (fiMeta in FOptions.FetchOptions.Items) then
CreateParamColumns(oParam);
pInfo^.FVar := FCommandStatement.ParamList.Add(TODBCParameter.Create);
oVar := TODBCParameter(pInfo^.FVar);
oVar.ParamType := FD2SQLParamType(pInfo^.FParamType);
oVar.Position := SQLSmallint(pInfo^.FPos + 1);
if lUseNames then
oVar.Name := pInfo^.FName
{$IFDEF FireDAC_MONITOR}
else
oVar.DumpLabel := pInfo^.FName
{$ENDIF};
oVar.ColumnSize := pInfo^.FColSize;
oVar.Scale := pInfo^.FScale;
oVar.SQLDataType := pInfo^.FOutSQLDataType;
oVar.CDataType := FD2CDataType(pInfo^.FOutDataType, False);
oVar.ForceLongData := oParam.IsObject;
oVar.MSAccBoolean := (oConnMeta.Kind = TFDRDBMSKinds.MSAccess) and (pInfo^.FDestDataType = dtBoolean);
if (oConnMeta.Kind = TFDRDBMSKinds.MSSQL) and (oVar.SQLDataType = SQL_SS_TABLE) then begin
// MSSQL: TVP does not support catalog and schema in type name
oConnMeta.DecodeObjName(oParam.DataTypeName, rName, nil, []);
oVar.DataTypeName := rName.FObject;
end
else
oVar.DataTypeName := oParam.DataTypeName;
oVar.UpdateFlags;
if (pInfo^.FOutDataType = dtRowSetRef) and (oParam.AsDataSet <> nil) then
CreateParamColumnInfos(pInfo, oParam);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.DestroyParamInfos;
begin
if (GetMetaInfoKind <> mkNone) or (Length(FParInfos) = 0) then
Exit;
SetLength(FParInfos, 0);
if FCommandStatement <> nil then
FCommandStatement.UnbindParameters;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.SetupStatementBeforePrepare(AStmt: TODBCStatementBase);
var
oFmtOpts: TFDFormatOptions;
oFtchOpts: TFDFetchOptions;
oResOpts: TFDResourceOptions;
oConnMeta: IFDPhysConnectionMetadata;
lUseRowSet: Boolean;
oStmt: TODBCCommandStatement;
{$IFDEF FireDAC_MONITOR}
procedure Trace1;
begin
Trace(ekCmdPrepare, esProgress, 'MSSQL automatic cursor',
['ServerVersion', oConnMeta.ServerVersion, 'Mode', Integer(oFtchOpts.Mode),
'GetMetainfoKind', Integer(GetMetainfoKind), 'UseExecDirect', UseExecDirect]);
end;
{$ENDIF}
begin
oFmtOpts := FOptions.FormatOptions;
oFtchOpts := FOptions.FetchOptions;
oResOpts := FOptions.ResourceOptions;
ODBCConnection.CreateMetadata(oConnMeta);
lUseRowSet := soRowSet in ODBCConnection.FSupportedOptions;
FStatementProps := [];
if ODBCConnection.DriverKind in [dkSQLNC, dkSQLOdbc] then
Include(FStatementProps, cpResetOnArrayOffset);
if oResOpts.UnifyParams and
((oConnMeta.Kind in [TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.SQLAnywhere]) or
(ODBCConnection.DriverKind = dkSybaseASE)) and
((GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]) or
(GetMetaInfoKind in [mkProcs, mkProcArgs])) then
Include(FStatementProps, cpUnifyParams);
if fiBlobs in oFtchOpts.Items then
Include(FStatementProps, cpLateBindedData);
AStmt.PieceBuffLen := C_FD_DefPieceBuffLen;
AStmt.MaxStringSize := oFmtOpts.MaxStringSize;
AStmt.StrsTrim := oFmtOpts.StrsTrim;
AStmt.StrsEmpty2Null := oFmtOpts.StrsEmpty2Null;
AStmt.StrsTrim2Len := oFmtOpts.StrsTrim2Len;
AStmt.MoneySupported := soMoney in ODBCConnection.FSupportedOptions;
if (AStmt is TODBCCommandStatement) and (GetParams.Count > 0) then begin
oStmt := TODBCCommandStatement(AStmt);
if (ODBCConnection.DriverKind = dkDB2) and
(GetCommandKind in [skDelete, skInsert, skMerge, skUpdate]) then
oStmt.PARAMOPT_ATOMIC := SQL_ATOMIC_NO;
if soParamSet in ODBCConnection.FSupportedOptions then begin
if GetParams.ArraySize > 1 then
oStmt.PARAMSET_SIZE := GetParams.ArraySize;
Include(FStatementProps, cpParamSet);
oStmt.ParamSetSupported := True;
end;
end;
case oFtchOpts.CursorKind of
ckDynamic:
AStmt.CURSOR_TYPE := SQL_CURSOR_DYNAMIC;
ckStatic:
AStmt.CURSOR_TYPE := SQL_CURSOR_STATIC;
ckForwardOnly:
if ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc] then
AStmt.SS_CURSOR_OPTIONS := SQL_CO_FFO
else
AStmt.CURSOR_TYPE := SQL_CURSOR_FORWARD_ONLY;
ckDefault:
if ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc] then begin
AStmt.SS_CURSOR_OPTIONS := SQL_CO_DEFAULT;
Include(FStatementProps, cpDefaultCrs);
end;
ckAutomatic:
case ODBCConnection.DriverKind of
dkSQLSrv,
dkSQLNC,
dkSQLOdbc,
dkFreeTDS,
dkSQLSrvOther:
begin
{$IFDEF FireDAC_MONITOR}
if ODBCConnection.GetTracing then
Trace1;
{$ENDIF}
if (ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc]) and (
(oConnMeta.ServerVersion >= svMSSQL2005) or
(oFtchOpts.Mode in [fmExactRecsMax, fmAll]) or
UseExecDirect
) then begin
AStmt.SS_CURSOR_OPTIONS := SQL_CO_DEFAULT;
Include(FStatementProps, cpDefaultCrs);
end
else
AStmt.CURSOR_TYPE := SQL_CURSOR_STATIC;
end;
dkDB2,
dkDB2_400,
dkTeradata:
AStmt.CURSOR_TYPE := SQL_CURSOR_FORWARD_ONLY;
dkQuickBooks:
Include(FStatementProps, cpDefaultCrs);
else
// 1) In most cases (Sybase SQL Anywhere, MS Access, etc) dynamic cursor
// gives the best performance on result sets with late binded columns
if cpLateBindedData in FStatementProps then
AStmt.CURSOR_TYPE := SQL_CURSOR_DYNAMIC;
end;
end;
if not (cpDefaultCrs in FStatementProps) then begin
if (ODBCConnection.DriverKind <> dkOther) and
not (GetCommandKind in [skSelectForLock, skSelectForUnLock]) then
AStmt.CONCURRENCY := SQL_CONCUR_READ_ONLY;
// 2) If a cursor kind is set by FireDAC or reset by driver to the FORWARD_ONLY
// value, and a result set has the late binded columns, then ODBC returns
// "invalid cursor position" if rowset size > 1 (FD-224, Informix)
if lUseRowSet and (AStmt.CURSOR_TYPE = SQL_CURSOR_FORWARD_ONLY) then
lUseRowSet := not (cpLateBindedData in FStatementProps);
if lUseRowSet then begin
AStmt.ROW_ARRAY_SIZE := oFtchOpts.ActualRowsetSize;
Include(FStatementProps, cpRowSet);
end;
end;
if (oConnMeta.Kind in [TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.DB2]) and
not (GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs]) and
(GetParams.Count = 0) and
oResOpts.MacroExpand and oResOpts.EscapeExpand then
AStmt.NOSCAN := SQL_NOSCAN_ON;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.SetupStatementAfterDescribe(AStmt: TODBCStatementBase);
var
lUseRowSet: Boolean;
oFtchOpts: TFDFetchOptions;
begin
if not (cpDefaultCrs in FStatementProps) and not (cpRowSet in FStatementProps) then begin
oFtchOpts := FOptions.FetchOptions;
lUseRowSet := soRowSet in ODBCConnection.FSupportedOptions;
// See (2) at SetupStatementBeforePrepare
if lUseRowSet and (AStmt.CURSOR_TYPE = SQL_CURSOR_FORWARD_ONLY) then
lUseRowSet := not (cpLateBindedData in FStatementProps);
if lUseRowSet then begin
AStmt.ROW_ARRAY_SIZE := oFtchOpts.ActualRowsetSize;
Include(FStatementProps, cpRowSet);
end;
end;
AStmt.RowSetSupported := cpRowSet in FStatementProps;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.SetupStatementBeforeExecute(AStmt: TODBCStatementBase);
var
oResOpts: TFDResourceOptions;
iTimeout: LongWord;
oConnMeta: IFDPhysConnectionMetadata;
begin
// At moment native ODBC timeout (SQL_ATTR_QUERY_TIMEOUT) is supported at all
// or correctly supported only by SQL Server and Informix ODBC driver.
FConnection.CreateMetadata(oConnMeta);
if oConnMeta.AsyncNativeTimeout then begin
oResOpts := FOptions.ResourceOptions;
iTimeout := oResOpts.CmdExecTimeout;
if (oResOpts.CmdExecMode = amBlocking) and (iTimeout <> $FFFFFFFF) then
AStmt.QUERY_TIMEOUT := (iTimeout + 999) div 1000
else
AStmt.QUERY_TIMEOUT := 0;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.GetRowsetSize(ARowsetSize: Integer): Integer;
begin
if [cpRowSet, cpDefaultCrs] * FStatementProps = [cpRowSet] then
Result := ARowsetSize
else
Result := 1;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.GetParamsetSize(AParamsetSize: Integer): Integer;
begin
if cpParamSet in FStatementProps then
Result := AParamsetSize
else
Result := 1;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.MatchParamsetSize(AParamsetSize1, AParamsetSize2: Integer): Boolean;
begin
if cpParamSet in FStatementProps then
Result := AParamsetSize1 = AParamsetSize2
else
Result := ((AParamsetSize1 = 0) or (AParamsetSize1 = 1)) and
((AParamsetSize2 = 0) or (AParamsetSize2 = 1));
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.UseExecDirect: Boolean;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
Result := FOptions.ResourceOptions.DirectExecute;
ODBCConnection.CreateMetadata(oConnMeta);
if not Result then begin
case GetCommandKind of
skSet,
skSetSchema,
skCreate,
skDrop,
skAlter,
skOther: Result := True;
// No need to prepare stored procedures. That will create temporary SP
// around SP.
skStoredProc,
skStoredProcNoCrs: Result := True; // not (cpOutParams in FStatementProps);
skStoredProcWithCrs: Result := not (cpLateBindedData in FStatementProps);
// Force BATCH (instead of RPC) for non-parameterized SELECT, when user
// need to get all result set.
skSelect,
skSelectForLock,
skSelectForUnLock: Result := (GetParams.Count = 0) and
(FOptions.FetchOptions.Mode in [fmAll, fmExactRecsMax]) and
(oConnMeta.Kind <> TFDRDBMSKinds.SQLAnywhere);
// See TFDQACompSTPTsHolder.TestStoredProcMSSQL3 test. Looks like if EXEC
// will be prepared, then it will fail for many system routines.
skExecute: Result := GetParams.Count = 0;
end;
if Result then
Result := oConnMeta.Kind in [TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.SQLAnywhere];
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.UseInformationSchema: Boolean;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
ODBCConnection.CreateMetadata(oConnMeta);
Result := not (soFKFunction in ODBCConnection.FSupportedOptions) and
(GetMetaInfoKind in [mkForeignKeys, mkForeignKeyFields]) and
not (oConnMeta.Kind in [TFDRDBMSKinds.MSAccess, TFDRDBMSKinds.DB2, TFDRDBMSKinds.Informix]) or
(GetMetaInfoKind = mkResultSetFields);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.UseStatement: Boolean;
begin
Result := (GetMetaInfoKind = mkNone) or UseInformationSchema;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.InternalPrepare;
var
rName: TFDPhysParsedName;
oConnMeta: IFDPhysConnectionMetadata;
begin
if GetMetaInfoKind <> FireDAC.Phys.Intf.mkNone then begin
if GetCommandKind = skUnknown then
SetCommandKind(skSelect);
if not UseInformationSchema then begin
FStatement := TODBCMetaInfoStatement.Create(ODBCConnection.ODBCConnection, Self);
FMetainfoStatement := TODBCMetaInfoStatement(FStatement);
SetupStatementBeforePrepare(FStatement);
Exit;
end
else begin
GetSelectMetaInfoParams(rName);
GenerateSelectMetaInfo(rName);
end;
end
else begin
ODBCConnection.CreateMetadata(oConnMeta);
// generate stored proc call SQL command
if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
oConnMeta.DecodeObjName(Trim(GetCommandText()), rName, Self, []);
FDbCommandText := '';
if fiMeta in FOptions.FetchOptions.Items then
GenerateStoredProcParams(rName);
if FDbCommandText = '' then
GenerateStoredProcCall(rName, GetCommandKind);
end
else begin
if GetCommandKind = skUnknown then
SetCommandKind(skSelect);
end;
end;
// adjust SQL command
GenerateLimitSelect();
GenerateParamMarkers();
FStatement := TODBCCommandStatement.Create(ODBCConnection.ODBCConnection, Self);
FCommandStatement := TODBCCommandStatement(FStatement);
SetupStatementBeforePrepare(FStatement);
if not UseExecDirect then
FCommandStatement.Prepare(FDbCommandText);
if GetParams.Count > 0 then begin
CreateParamInfos;
FCommandStatement.BindParameters(GetParamsetSize(GetParams.ArraySize), True);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.InternalUnprepare;
begin
if FStatement = nil then
Exit;
CloseStatement(-1, True, True, False);
DestroyParamInfos;
DestroyDescribeInfos;
FCommandStatement := nil;
FMetainfoStatement := nil;
FMetainfoAddonView := nil;
FDFreeAndNil(FStatement);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean;
begin
Result := OpenBlocked;
if Result and (ATabInfo.FSourceID = -1) then begin
ATabInfo.FSourceName := GetCommandText;
ATabInfo.FSourceID := 1;
FColumnIndex := 0;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean;
var
pColInfo: PFDODBCColInfoRec;
begin
if FColumnIndex < Length(FColInfos) then begin
pColInfo := @FColInfos[FColumnIndex];
AColInfo.FSourceName := pColInfo^.FName;
AColInfo.FSourceID := FColumnIndex + 1;
AColInfo.FSourceTypeName := pColInfo^.FExtName;
AColInfo.FSourceType := pColInfo^.FSrcDataType;
AColInfo.FOriginTabName.FCatalog := pColInfo^.FOriginCatalogName;
AColInfo.FOriginTabName.FSchema := pColInfo^.FOriginSchemaName;
AColInfo.FOriginTabName.FObject := pColInfo^.FOriginTabName;
AColInfo.FOriginColName := pColInfo^.FOriginColName;
AColInfo.FType := pColInfo^.FDestDataType;
AColInfo.FLen := pColInfo^.FFDLen;
AColInfo.FPrec := pColInfo^.FColSize;
AColInfo.FScale := pColInfo^.FFDScale;
AColInfo.FAttrs := pColInfo^.FAttrs;
AColInfo.FForceAddOpts := [];
if caAutoInc in AColInfo.FAttrs then
Include(AColInfo.FForceAddOpts, coAfterInsChanged);
if pColInfo^.FInKey then
Include(AColInfo.FForceAddOpts, coInKey);
Inc(FColumnIndex);
Result := True;
end
else
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.GetIsCustomParam(ADataType: TFDDataType): Boolean;
begin
Result := False;
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.SetCustomParamValue(ADataType: TFDDataType;
AVar: TODBCVariable; AParam: TFDParam; AVarIndex, AParIndex: Integer);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.SetParamValues(ATimes, AOffset: Integer;
AFromParIndex: Integer);
var
oParams: TFDParams;
oFmtOpts: TFDFormatOptions;
oParam: TFDParam;
iArraySize, i, j: Integer;
iMaxNumBefDot, iMaxNumScale: SQLSmallint;
iMaxStrSize: SQLInteger;
pParInfo: PFDODBCParInfoRec;
lRebind: Boolean;
oVar: TODBCVariable;
procedure ProcessArrayItem(AParam: TFDParam; ApInfo: PFDODBCParInfoRec;
AVarIndex, AParIndex: Integer);
var
pBuffer: PByte;
iDataSize, iSrcSize: LongWord;
iPrec, iScale: Smallint;
oExtStr, oIntStr: TStream;
lExtStream: Boolean;
eStreamMode: TFDStreamMode;
begin
iDataSize := 0;
iSrcSize := 0;
pBuffer := nil;
if GetIsCustomParam(ApInfo^.FSrcDataType) then
SetCustomParamValue(ApInfo^.FSrcDataType, ApInfo^.FVar, AParam, AVarIndex, AParIndex)
else if AParam.IsDatasets[AParIndex] then begin
if (ATimes - AOffset <> 1) or
(AParam.AsDataSets[AParIndex] = nil) or (ApInfo^.FOutDataType <> dtRowSetRef) then
UnsupParamObjError(AParam);
AParam.GetDataReader(@pBuffer, AParIndex);
ApInfo^.FVar.SetDataReader(AVarIndex, @pBuffer);
end
else if AParam.IsStreams[AParIndex] then begin
oExtStr := AParam.AsStreams[AParIndex];
lExtStream := (oExtStr <> nil) and
not ((oExtStr is TODBCLongDataStream) and (TODBCLongDataStream(oExtStr).Param.Statement.OwningObj = Self));
if (ATimes - AOffset <> 1) or
(AParam.DataType <> ftStream) and not lExtStream or
not (ApInfo^.FOutDataType in C_FD_VarLenTypes) then
UnsupParamObjError(AParam);
case AParam.ParamType of
ptUnknown,
ptInput: eStreamMode := smOpenWrite;
ptOutput,
ptResult: eStreamMode := smOpenRead;
else eStreamMode := smOpenReadWrite; // ptInputOutput
end;
if not lExtStream then begin
oIntStr := TODBCLongDataStream.Create(TODBCParameter(ApInfo^.FVar), eStreamMode);
AParam.AsStreams[AParIndex] := oIntStr;
TODBCParameter(ApInfo^.FVar).Streamed := True;
end;
AParam.GetDataReader(@pBuffer, AParIndex);
ApInfo^.FVar.SetDataReader(AVarIndex, @pBuffer);
end
else if AParam.IsNulls[AParIndex] then
ApInfo^.FVar.SetData(AVarIndex, nil, 0)
else begin
if ApInfo^.FSrcDataType = ApInfo^.FOutDataType then
if ApInfo^.FOutDataType in (C_FD_VarLenTypes - [dtByteString]
{$IFDEF NEXTGEN} - C_FD_AnsiTypes {$ENDIF}) then begin
AParam.GetBlobRawData(iDataSize, pBuffer, AParIndex);
ApInfo^.FVar.SetData(AVarIndex, pBuffer, iDataSize);
end
else begin
iSrcSize := AParam.GetDataLength(AParIndex);
FBuffer.Check(iSrcSize);
AParam.GetData(FBuffer.Ptr, AParIndex);
ApInfo^.FVar.SetData(AVarIndex, FBuffer.Ptr, iSrcSize);
end
else begin
iSrcSize := AParam.GetDataLength(AParIndex);
FBuffer.Extend(iSrcSize, iDataSize, ApInfo^.FSrcDataType, ApInfo^.FOutDataType);
AParam.GetData(FBuffer.Ptr, AParIndex);
oFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FOutDataType,
FBuffer.Ptr, iSrcSize, FBuffer.FBuffer, FBuffer.Size, iDataSize,
ODBCConnection.ODBCConnection.Encoder);
ApInfo^.FVar.SetData(AVarIndex, FBuffer.Ptr, iDataSize);
end;
case ApInfo^.FOutDataType of
dtBCD,
dtFmtBCD:
begin
FDBcdGetMetrics(PBcd(FBuffer.Ptr)^, iPrec, iScale);
if iMaxNumScale < iScale then
iMaxNumScale := iScale;
if iMaxNumBefDot < SQLSmallint(iPrec - iScale) then
iMaxNumBefDot := SQLSmallint(iPrec - iScale);
end;
dtBlob,
dtMemo,
dtWideMemo,
dtXML,
dtHBlob,
dtHBFile,
dtHMemo,
dtWideHMemo,
dtAnsiString,
dtWideString,
dtByteString:
begin
if (iSrcSize <> 0) and (iDataSize = 0) then
iDataSize := iSrcSize;
if SQLInteger(iDataSize) < AParam.Size then
iDataSize := AParam.Size;
if iMaxStrSize < SQLInteger(iDataSize) then
iMaxStrSize := iDataSize;
end;
end;
end;
end;
begin
oParams := GetParams;
if (FCommandStatement = nil) or (oParams.Count = 0) then
Exit;
oFmtOpts := GetOptions.FormatOptions;
iArraySize := oParams.ArraySize;
if ATimes < iArraySize then
iArraySize := ATimes;
ASSERT((AFromParIndex <> -1) or (iArraySize = 1) or (cpParamSet in FStatementProps));
if not MatchParamsetSize(GetParamsetSize(iArraySize), FCommandStatement.PARAMSET_SIZE) then
FCommandStatement.BindParameters(GetParamsetSize(iArraySize), True);
for i := 0 to Length(FParInfos) - 1 do begin
pParInfo := @FParInfos[i];
if pParInfo^.FParamIndex <> -1 then begin
oParam := oParams[pParInfo^.FParamIndex];
oVar := pParInfo^.FVar;
if oParam.DataType <> ftCursor then begin
CheckParamMatching(oParam, pParInfo^.FDataType, pParInfo^.FParamType, 0);
if oVar <> nil then begin
iMaxNumBefDot := -1;
iMaxNumScale := -1;
iMaxStrSize := -1;
if AFromParIndex = -1 then
for j := AOffset to iArraySize - 1 do
ProcessArrayItem(oParam, pParInfo, j, j)
else
ProcessArrayItem(oParam, pParInfo, 0, AFromParIndex);
lRebind := False;
if ((oVar.ParamType = SQL_PARAM_OUTPUT) or (oVar.ParamType = SQL_PARAM_OUTPUT_STREAM)) and
not oVar.Binded then
lRebind := True;
if ((iMaxNumBefDot >= 0) or (iMaxNumScale >= 0)) and (
// Without following 3 lines, MSSQL / DB2 may return "Numeric value
// out of range" with ftBCD / ftFmtBCD parameters and the values with
// a different precision and / or scale.
(oVar.ColumnSize < iMaxNumBefDot + iMaxNumScale) or
(oVar.Scale < iMaxNumScale) or
(oVar.ColumnSize - SQLULen(SQLLen(oVar.Scale)) < iMaxNumBefDot)) then begin
if oVar.ColumnSize < iMaxNumBefDot + iMaxNumScale then
oVar.ColumnSize := iMaxNumBefDot + iMaxNumScale;
if oVar.Scale < iMaxNumScale then
oVar.Scale := iMaxNumScale;
lRebind := True;
end;
if (iMaxStrSize >= 0) and (oVar.ColumnSize < iMaxStrSize) then begin
if iMaxStrSize = 0 then
iMaxStrSize := 1;
oVar.ColumnSize := iMaxStrSize;
lRebind := True;
end;
if lRebind then begin
// If not reset the FFlagsUpdated to True, then the DataSize will be
// recalculated according to the new ColumnSize. But the value buffers
// are already allocated and initialized. So, this will lead to a
// garbage will be sent to a server.
oVar.ResetFlagsUpdated;
oVar.Bind;
end;
end;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.GetCustomParamValue(ADataType: TFDDataType;
AVar: TODBCVariable; AParam: TFDParam; AVarIndex, AParIndex: Integer);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.GetParamValues(ATimes, AOffset: Integer;
AFromParIndex: Integer);
var
oParams: TFDParams;
oFmtOpts: TFDFormatOptions;
iArraySize, i, j: Integer;
oParam: TFDParam;
pParInfo: PFDODBCParInfoRec;
procedure ProcessArrayItem(AParam: TFDParam; ApInfo: PFDODBCParInfoRec;
AVarIndex, AParIndex: Integer);
var
iSize: SQLLen;
pData: SQLPointer;
iDestDataLen: LongWord;
begin
pData := nil;
iSize := 0;
if GetIsCustomParam(ApInfo^.FSrcDataType) then
GetCustomParamValue(ApInfo^.FSrcDataType, ApInfo^.FVar, AParam, AVarIndex, AParIndex)
else if AParam.IsObjects[AParIndex] then begin
// nothing
end
else if not ApInfo^.FVar.GetData(AVarIndex, pData, iSize, True) then
AParam.Clear(AParIndex)
else if ApInfo^.FOutDataType = ApInfo^.FSrcDataType then
if ApInfo^.FOutDataType in C_FD_VarLenTypes then
AParam.SetData(PByte(pData), iSize, AParIndex)
else begin
FBuffer.Check(iSize);
ApInfo^.FVar.GetData(AVarIndex, FBuffer.FBuffer, iSize, False);
AParam.SetData(FBuffer.Ptr, iSize, AParIndex);
end
else begin
FBuffer.Check(iSize);
ApInfo^.FVar.GetData(AVarIndex, FBuffer.FBuffer, iSize, False);
iDestDataLen := 0;
FBuffer.Extend(iSize, iDestDataLen, ApInfo^.FOutDataType, ApInfo^.FSrcDataType);
iDestDataLen := 0;
oFmtOpts.ConvertRawData(ApInfo^.FOutDataType, ApInfo^.FSrcDataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestDataLen,
ODBCConnection.ODBCConnection.Encoder);
AParam.SetData(FBuffer.Ptr, iDestDataLen, AParIndex);
end;
end;
begin
oParams := GetParams;
if (FCommandStatement = nil) or (oParams.Count = 0) then
Exit;
oFmtOpts := FOptions.FormatOptions;
if ATimes = -1 then begin
iArraySize := FCommandStatement.PARAMSET_SIZE;
if iArraySize > oParams.ArraySize then
iArraySize := oParams.ArraySize;
end
else begin
iArraySize := oParams.ArraySize;
if ATimes < iArraySize then
iArraySize := ATimes;
end;
if (AFromParIndex = -1) and not (cpParamSet in FStatementProps) then
AFromParIndex := 0;
for i := 0 to Length(FParInfos) - 1 do begin
pParInfo := @FParInfos[i];
if pParInfo^.FParamIndex <> -1 then begin
oParam := oParams[pParInfo^.FParamIndex];
if (oParam.ParamType in [ptOutput, ptResult, ptInputOutput]) and
not (oParam.DataType in [ftCursor, ftDataSet]) then begin
CheckParamMatching(oParam, pParInfo^.FDataType, pParInfo^.FParamType, 0);
if pParInfo^.FVar <> nil then
if AFromParIndex = -1 then
for j := AOffset to iArraySize - 1 do
ProcessArrayItem(oParam, pParInfo, j, j)
else
ProcessArrayItem(oParam, pParInfo, 0, AFromParIndex);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter);
var
i: Integer;
iTmpCount: SQLLen;
oFO: TFDFetchOptions;
sCmd: String;
begin
CloseStatement(-1, True, False, False);
SetupStatementBeforeExecute(FStatement);
Exclude(FStatementProps, cpOnNextResult);
ACount := 0;
oFO := FOptions.FetchOptions;
if UseExecDirect then
sCmd := FDbCommandText
else
sCmd := '';
try
if (cpParamSet in FStatementProps) or (ATimes = 1) and (AOffset = 0) then begin
// MSSQL 2005: FDQA fails on "Batch execute" -> "Error handling" with
// 24000 state (invalid cursor state). Following code is workaround for that.
if (ATimes - AOffset = 1) and (AOffset > 0) and (cpResetOnArrayOffset in FStatementProps) then begin
InternalUnprepare;
InternalPrepare;
end;
SetParamValues(ATimes, AOffset, -1);
FCommandStatement.Execute(ATimes, AOffset, ACount, oFO.Mode = fmExactRecsMax, sCmd);
if (GetState <> csAborting) and
// ASA: After Array DML its execution restarts on SQLMoreResults
((soArrayBatch in ODBCConnection.FSupportedOptions) or (ATimes = 1) and (AOffset = 0)) then begin
if not FCommandStatement.ResultColsExists and (FCommandStatement.FocusedParam = nil) then begin
Include(FStatementProps, cpOnNextResult);
if GetCursor(ACount) then
Include(FStatementProps, cpOnNextResultValue)
else
Exclude(FStatementProps, cpOnNextResultValue);
end;
if cpOutResParams in FStatementProps then
GetParamValues(ATimes, AOffset, -1);
end;
end
else begin
for i := AOffset to ATimes - 1 do begin
SetParamValues(1, 0, i);
iTmpCount := 0;
try
FCommandStatement.Execute(1, 0, iTmpCount, oFO.Mode = fmExactRecsMax, sCmd);
except
on E: EODBCNativeException do begin
E[0].RowIndex := i;
raise;
end;
end;
if iTmpCount = -1 then
ACount := -1
else if ACount >= 0 then
Inc(ACount, iTmpCount);
if GetState <> csAborting then
CloseStatement(i, True, True, False)
else
Break;
end;
end;
except
CloseStatement(-1, True, True, True);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.InternalCloseStreams;
var
i, j: Integer;
oPar: TFDParam;
oStr: TStream;
begin
if FCommandStatement <> nil then begin
for i := 0 to GetParams().Count - 1 do begin
oPar := GetParams()[i];
for j := 0 to oPar.ArraySize - 1 do
if oPar.IsStreams[j] then begin
oStr := oPar.AsStreams[j];
if (oStr is TODBCLongDataStream) and
(TODBCLongDataStream(oStr).Param.Statement.OwningObj = Self) then
TODBCLongDataStream(oStr).Flush;
end;
end;
FCommandStatement.FlushLongData;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.InternalAbort;
begin
FStatement.Cancel;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.GetCursor(var ARows: SQLLen): Boolean;
begin
repeat
// "rows affected" may be not in first result set of command result sets.
// For example, if INSERT fires trigger, it calls PRINT, open cursors, etc.
// See FDQA, TFDQAPhysCMDTsHolder.TestCommandInsRecCnt test.
if (FCommandStatement <> nil) and (ARows < 0) then
FCommandStatement.UpdateRowsAffected(ARows);
Result := FStatement.ResultColsExists;
until Result or not FStatement.MoreResults or (GetState = csAborting);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.InternalOpen(var ACount: TFDCounter): Boolean;
var
sCmd: String;
begin
ACount := 0;
CloseStatement(-1, True, False, False);
if FStatement <> nil then
SetupStatementBeforeExecute(FStatement);
if cpNotFirstCursor in FStatementProps then begin
DestroyDescribeInfos;
Exclude(FStatementProps, cpNotFirstCursor);
end;
Exclude(FStatementProps, cpOnNextResult);
sCmd := '';
if UseStatement then begin
SetParamValues(1, 0, -1);
if UseExecDirect then
sCmd := FDbCommandText;
end;
try
if UseStatement then begin
FCommandStatement.Execute(GetParams.ArraySize, 0, ACount,
FOptions.FetchOptions.Mode = fmExactRecsMax, sCmd);
Result := True;
end
else
Result := OpenMetaInfo;
Result := Result and (GetState <> csAborting) and
GetCursor(ACount);
if Result then begin
if UseStatement and (cpOutResParams in FStatementProps) then
GetParamValues(-1, 0, -1);
if Length(FColInfos) = 0 then begin
CreateDescribeInfos;
SetupStatementAfterDescribe(FStatement);
FStatement.BindColumns(GetRowsetSize(FOptions.FetchOptions.ActualRowsetSize));
end;
end
else
CloseStatement(-1, True, True, False);
except
CloseStatement(-1, True, True, True);
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.InternalClose;
begin
CloseStatement(-1, False, True, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.CloseStatement(AIndex: Integer; AForceClose,
AGetOutParams, AIgnoreErrors: Boolean);
var
oConnMeta: IFDPhysConnectionMetadata;
lPrevIgnoreErrors: Boolean;
begin
if (AForceClose or not GetNextRecordSet) and
(FStatement <> nil) and FStatement.Executed then begin
if (cpOutResParams in FStatementProps) and
((ODBCConnection.DriverKind <> dkTeradata) or not FStatement.NoMoreResults) then begin
ODBCConnection.CreateMetadata(oConnMeta);
// ASA: If after SQLExecute & paramsetsize > 1 & failed row with index < paramsetsize - 1,
// call SQLMoreResults, it will continue command execution on Sybase ASA driver
if ODBCConnection.DriverKind <> dkSQLAnywhere then
while FStatement.MoreResults do
;
if AGetOutParams then
GetParamValues(-1, 0, AIndex);
end;
// MSSQL: No Check call is required to fix potential SQL_ERROR
lPrevIgnoreErrors := FStatement.IgnoreErrors;
if AIgnoreErrors then
FStatement.IgnoreErrors := True;
try
FStatement.Close;
finally
FStatement.IgnoreErrors := lPrevIgnoreErrors;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCCommand.FetchRow(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowIndex: SQLUInteger);
var
oRow: TFDDatSRow;
pData: SQLPointer;
iSize: SQLLen;
oFmtOpts: TFDFormatOptions;
j: Integer;
iDestDataLen: LongWord;
lIsVal: Boolean;
[unsafe] oCol: TFDDatSColumn;
pInfo: PFDODBCColInfoRec;
begin
oFmtOpts := FOptions.FormatOptions;
oRow := ATable.NewRow(False);
try
for j := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[j];
if (oCol.SourceID > 0) and CheckFetchColumn(oCol.SourceDataType, oCol.Attributes) then begin
pInfo := @FColInfos[oCol.SourceID - 1];
if pInfo^.FVar <> nil then begin
pData := nil;
iSize := 0;
if pInfo^.FOutDataType = pInfo^.FDestDataType then
if pInfo^.FDestDataType in C_FD_VarLenTypes then begin
lIsVal := pInfo^.FVar.GetData(ARowIndex, pData, iSize, True);
if lIsVal then
oRow.SetData(j, pData, iSize);
end
else begin
lIsVal := pInfo^.FVar.GetData(ARowIndex, FBuffer.FBuffer, iSize, False);
if lIsVal then
oRow.SetData(j, FBuffer.Ptr, iSize);
end
else begin
lIsVal := pInfo^.FVar.GetData(ARowIndex, pData, iSize, True);
if lIsVal then begin
FBuffer.Check(iSize);
pInfo^.FVar.GetData(ARowIndex, FBuffer.FBuffer, iSize, False);
iDestDataLen := 0;
oFmtOpts.ConvertRawData(pInfo^.FOutDataType, pInfo^.FDestDataType,
FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestDataLen,
ODBCConnection.ODBCConnection.Encoder);
oRow.SetData(j, FBuffer.Ptr, iDestDataLen);
end;
end;
if not lIsVal then
oRow.SetData(j, nil, 0);
end;
end;
end;
if AParentRow <> nil then begin
oRow.ParentRow := AParentRow;
AParentRow.Fetched[ATable.Columns.ParentCol] := True;
end;
ATable.Rows.Add(oRow);
except
FDFree(oRow);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.InternalFetchRowSet(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord;
var
i, iRowsetSize, iRowsFetched: Integer;
oRow: TFDDatSRow;
oResultRow: TFDDatSRow;
procedure CheckResultArg;
begin
oRow := ATable.Rows[ATable.Rows.Count - 1];
if (oRow.GetData(8, rvDefault) = Integer(ptResult)) and
(oRow.GetData(7, rvDefault) <> 1) then
oResultRow := oRow;
end;
procedure AdjustProcArgs;
var
i: Integer;
oParRow: TFDDatSRow;
lMoved: Boolean;
begin
lMoved := oResultRow.List.MoveTo(oResultRow.Index,
ATable.Rows.Count - (FRecordsFetched + Integer(Result)));
oResultRow.SetData(0, 1);
oResultRow.SetData(7, 1);
for i := oResultRow.Index + 1 to ATable.Rows.Count - 1 do begin
oParRow := ATable.Rows[i];
if (VarToStr(oParRow.GetData(1, rvDefault)) = VarToStr(oResultRow.GetData(1, rvDefault))) and
(VarToStr(oParRow.GetData(2, rvDefault)) = VarToStr(oResultRow.GetData(2, rvDefault))) and
(VarToStr(oParRow.GetData(3, rvDefault)) = VarToStr(oResultRow.GetData(3, rvDefault))) and
(VarToStr(oParRow.GetData(4, rvDefault)) = VarToStr(oResultRow.GetData(4, rvDefault))) and
(VarToStr(oParRow.GetData(5, rvDefault)) = VarToStr(oResultRow.GetData(5, rvDefault))) then begin
oParRow.SetData(0, oParRow.GetData(0, rvDefault) + 1);
oParRow.SetData(7, oParRow.GetData(7, rvDefault) + 1);
end;
end;
if lMoved and (ATable.DataHandleMode = lmFetching) then
ATable.Views.Rebuild;
end;
procedure AdjustIndCols;
var
i, iPos: Integer;
oColRow: TFDDatSRow;
lSorted, lMoved: Boolean;
begin
lMoved := False;
repeat
lSorted := True;
for i := ATable.Rows.Count - 1 downto ATable.Rows.Count - Integer(Result) do begin
oColRow := ATable.Rows[i];
iPos := oColRow.GetData(6, rvDefault);
if oColRow.GetData(0, rvDefault) <> iPos then begin
oColRow.SetData(0, iPos);
lMoved := lMoved or oColRow.List.MoveTo(oColRow.Index,
ATable.Rows.Count - (FRecordsFetched + Integer(Result)) + iPos - 1);
lSorted := False;
Break;
end;
end;
until lSorted;
if lMoved and (ATable.DataHandleMode = lmFetching) then
ATable.Views.Rebuild;
end;
begin
Result := 0;
oResultRow := nil;
if (GetMetaInfoKind <> mkNone) and not FStatement.Executed then
Exit;
iRowsetSize := GetRowsetSize(ARowsetSize);
while (Result < ARowsetSize) and (GetState = csFetching) do begin
iRowsFetched := FStatement.Fetch(iRowsetSize);
// If FetchOptions.RecsMax > 0, then MAX_ROWS = RecsMax + 1 and
// ActualRowsetSize = RecMax, so may be that iRowsFetched > iRowsetSize
if iRowsFetched > iRowsetSize then
iRowsFetched := iRowsetSize;
if GetMetaInfoKind = mkNone then begin
for i := 0 to iRowsFetched - 1 do
FetchRow(ATable, AParentRow, i);
Inc(Result, iRowsFetched);
end
else begin
for i := 0 to iRowsFetched - 1 do
if FetchMetaRow(ATable, AParentRow, i, Result + 1) then begin
Inc(Result);
if (GetMetaInfoKind = mkProcArgs) and (oResultRow = nil) then
CheckResultArg;
end;
end;
if iRowsFetched <> iRowsetSize then
Break;
end;
case GetMetaInfoKind of
mkProcArgs:
if oResultRow <> nil then
AdjustProcArgs;
mkIndexFields,
mkPrimaryKeyFields:
AdjustIndCols;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.InternalNextRecordSet: Boolean;
var
iTmpCount: SQLLen;
begin
Result := False;
iTmpCount := 0;
if (GetMetaInfoKind = mkNone) and (FCommandStatement <> nil) then begin
DestroyDescribeInfos;
if cpOnNextResult in FStatementProps then begin
Exclude(FStatementProps, cpOnNextResult);
Result := cpOnNextResultValue in FStatementProps;
end
else
Result := FStatement.MoreResults and GetCursor(iTmpCount);
if not Result then
CloseStatement(-1, True, True, False)
else begin
Include(FStatementProps, cpNotFirstCursor);
CreateDescribeInfos;
FStatement.BindColumns(GetRowsetSize(FOptions.FetchOptions.ActualRowsetSize));
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.OpenMetaInfo: Boolean;
var
sCatalog, sSchema, sName, sTableTypes: String;
oConnMeta: IFDPhysConnectionMetadata;
rName: TFDPhysParsedName;
lQuoteType: Boolean;
procedure AddTableType(const AType: String);
begin
if sTableTypes <> '' then
sTableTypes := sTableTypes + ',';
if lQuoteType then
sTableTypes := sTableTypes + QuotedStr(AType)
else
sTableTypes := sTableTypes + AType;
end;
procedure SetCatalogSchemaFromObj;
begin
sCatalog := rName.FCatalog;
sSchema := rName.FSchema;
if (sSchema = '') and not (npSchema in ODBCConnection.AvoidImplicitMeta) then
sSchema := ODBCConnection.GetCurrentSchema;
end;
procedure SetCatalogSchema;
begin
sCatalog := GetCatalogName;
sSchema := GetSchemaName;
if (GetObjectScopes = [osMy]) and (sSchema = '') and
not (npSchema in ODBCConnection.AvoidImplicitMeta) then
sSchema := ODBCConnection.GetCurrentSchema;
end;
procedure GetObjName;
begin
ODBCConnection.CreateMetadata(oConnMeta);
oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self, [doNormalize, doUnquote]);
if ODBCConnection.DriverKind = dkInformix then begin
if rName.FBaseObject <> '' then
rName.FBaseObject := '"' + rName.FBaseObject + '"';
if rName.FObject <> '' then
rName.FObject := '"' + rName.FObject + '"';
end;
CheckMetaInfoParams(rName);
end;
begin
Result := FMetainfoStatement <> nil;
if Result then
try
case GetMetaInfoKind of
mkCatalogs:
FMetainfoStatement.Catalogs;
mkSchemas:
FMetainfoStatement.Schemas;
mkTables:
begin
SetCatalogSchema;
// Sybase ASE 15 ODBC driver expects table types to be quoted
lQuoteType := ODBCConnection.DriverKind = dkSybaseASE;
if tkTable in GetTableKinds then
AddTableType('TABLE');
if tkView in GetTableKinds then
AddTableType('VIEW');
if tkSynonym in GetTableKinds then
AddTableType('SYNONYM');
if tkTempTable in GetTableKinds then
AddTableType('GLOBAL TEMPORARY');
if tkLocalTable in GetTableKinds then
AddTableType('LOCAL TEMPORARY');
if (osSystem in GetObjectScopes) and (tkTable in GetTableKinds) then
AddTableType('SYSTEM TABLE');
FMetainfoStatement.Tables(sCatalog, sSchema, GetWildcard, sTableTypes);
end;
mkTableFields:
begin
GetObjName;
SetCatalogSchemaFromObj;
FMetainfoStatement.Columns(sCatalog, sSchema, rName.FObject, GetWildcard);
end;
mkTableTypeFields:
begin
GetObjName;
SetCatalogSchemaFromObj;
FMetainfoStatement.TypeColumns(sCatalog, sSchema, rName.FObject, GetWildcard);
end;
mkIndexes:
begin
GetObjName;
SetCatalogSchemaFromObj;
ODBCConnection.CreateMetadata(oConnMeta);
FMetainfoAddonView := oConnMeta.GetTablePrimaryKey(sCatalog, sSchema, GetCommandText);
FMetainfoStatement.Statistics(sCatalog, sSchema, rName.FObject, SQL_INDEX_ALL);
end;
mkIndexFields:
begin
GetObjName;
SetCatalogSchemaFromObj;
FMetainfoStatement.Statistics(sCatalog, sSchema, rName.FBaseObject, SQL_INDEX_ALL);
end;
mkPrimaryKey:
begin
GetObjName;
SetCatalogSchemaFromObj;
if soPKFunction in ODBCConnection.FSupportedOptions then
FMetainfoStatement.PrimaryKeys(sCatalog, sSchema, rName.FObject)
else
FMetainfoStatement.SpecialColumns(sCatalog, sSchema, rName.FObject, SQL_BEST_ROWID);
end;
mkPrimaryKeyFields:
begin
GetObjName;
SetCatalogSchemaFromObj;
if soPKFunction in ODBCConnection.FSupportedOptions then
FMetainfoStatement.PrimaryKeys(sCatalog, sSchema, rName.FBaseObject)
else
FMetainfoStatement.SpecialColumns(sCatalog, sSchema, rName.FBaseObject, SQL_BEST_ROWID);
end;
mkForeignKeys:
if not (soFKFunction in ODBCConnection.FSupportedOptions) then
Result := False
else begin
GetObjName;
SetCatalogSchemaFromObj;
FMetainfoStatement.ForeignKeys('', '', '', sCatalog, sSchema, rName.FObject);
end;
mkForeignKeyFields:
if not (soFKFunction in ODBCConnection.FSupportedOptions) then
Result := False
else begin
GetObjName;
SetCatalogSchemaFromObj;
FMetainfoStatement.ForeignKeys('', '', '', sCatalog, sSchema, rName.FBaseObject);
end;
mkPackages:
Result := False;
mkProcs:
begin
GetObjName;
if rName.FBaseObject <> '' then
SetCatalogSchemaFromObj
else
SetCatalogSchema;
FMetainfoStatement.Procedures(sCatalog, sSchema, GetWildcard);
end;
mkProcArgs:
begin
GetObjName;
SetCatalogSchemaFromObj;
if rName.FBaseObject <> '' then
sName := rName.FBaseObject + '.';
FMetainfoStatement.ProcedureColumns(sCatalog, sSchema, sName + rName.FObject, GetWildcard);
end;
mkGenerators,
mkResultSetFields:
Result := False;
end;
if Result then
FMetainfoStatement.Execute;
except
on E: EODBCNativeException do begin
ODBCConnection.CreateMetadata(oConnMeta);
if (ODBCConnection.DriverKind in [dkMSAccessJet, dkMSAccessACE]) and (E.Errors[0].ErrorCode = -1034) or
// Optional feature not implemented
(E.Errors[0].SQLState = 'HYC00') or
// Driver does not support this function
(E.Errors[0].SQLState = 'IM001') or
// FreeTDS returns NO DATA FOUND
(E.Kind = ekNoDataFound) then
Result := False
else
raise;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCCommand.FetchMetaRow(ATable: TFDDatSTable;
AParentRow: TFDDatSRow; ARowIndex, ARowNo: SQLUInteger): Boolean;
var
oRow: TFDDatSRow;
pData: SQLPointer;
iRecNo: Integer;
iSize: SQLLen;
eTableKind: TFDPhysTableKind;
eScope: TFDPhysObjectScope;
iLen: LongWord;
iPrec, iScale: Integer;
eType: TFDDataType;
eAttrs: TFDDataAttributes;
iODBCType: SQLSmallint;
iODBCSize: SQLInteger;
iODBCDec: SQLSmallint;
eIndKind: TFDPhysIndexKind;
rName: TFDPhysParsedName;
lDeleteRow: Boolean;
oConnMeta: IFDPhysConnectionMetadata;
eProcKind: TFDPhysProcedureKind;
eParType: TParamType;
eCascade: TFDPhysCascadeRuleKind;
i: Integer;
sType: String;
procedure GetScope(ACatalogColIndex, ASchemaColIndex, AObjColIndex: Integer;
var AScope: TFDPhysObjectScope);
var
sCat, sSch, sObj: String;
begin
if not (npSchema in oConnMeta.NameParts) then
AScope := osMy
else begin
sCat := VarToStr(oRow.GetData(ACatalogColIndex, rvDefault));
sSch := VarToStr(oRow.GetData(ASchemaColIndex, rvDefault));
sObj := VarToStr(oRow.GetData(AObjColIndex, rvDefault));
if AnsiCompareText(sSch, oConnMeta.UnQuoteObjName(ODBCConnection.GetCurrentSchema)) = 0 then
AScope := osMy
else if (AnsiCompareText(sSch, 'SYS') = 0) or
(AnsiCompareText(sSch, 'SYSTEM') = 0) or
(AnsiCompareText(sSch, 'INFORMATION_SCHEMA') = 0) or
(oConnMeta.Kind = TFDRDBMSKinds.DB2) and
(AnsiCompareText(sSch, 'SYSPROC') = 0) or
(oConnMeta.Kind = TFDRDBMSKinds.Informix) and
((AnsiCompareText(sCat, 'SYSMASTER') = 0) or
(AnsiCompareText(Copy(sObj, 1, 3), 'SYS') = 0)) then
AScope := osSystem
else
AScope := osOther;
end;
end;
procedure AdjustMaxVarLen(AODBCType: SQLSmallint; var AODBCSize: SQLInteger; AField: Boolean);
begin
case ODBCConnection.DriverKind of
dkSQLNC,
dkSQLOdbc,
dkFreeTDS,
dkSQLSrvOther:
if (AODBCSize = SQL_SS_LENGTH_UNLIMITED) and
((AODBCType = SQL_VARCHAR) or (AODBCType = SQL_VARBINARY) or
(AODBCType = SQL_WVARCHAR) or (AODBCType = SQL_SS_XML)) then
AODBCSize := MAXINT;
dkInformix:
// Workaround for "p like tab.fld", where "fld CHAR(N)"
if not AField and (AODBCType = SQL_CHAR) and (AODBCSize = 1) then
AODBCSize := 0;
end;
end;
// Workaround for some ODBC drivers, which return #0 instead of NULL
// as a catalog or a schema name, when they are not supported. Eg,
// IB/FB ODBC returns #0 as a catalog name.
function TrimZeros(AColIndex: Integer): Boolean;
begin
case FStatement.ColumnList[AColIndex].CDataType of
SQL_C_WCHAR:
while (iSize > 0) and ((PWideChar(pData) + iSize - 1)^ = #0) do
Dec(iSize);
SQL_C_CHAR:
while (iSize > 0) and ((PFDAnsiString(pData) + iSize - 1)^ = TFDAnsiChar(#0)) do
Dec(iSize);
else
ASSERT(False);
end;
Result := iSize > 0;
end;
function AdjustOverloaded(var AOverload: Integer): Boolean;
var
pCh: PWideChar;
begin
Result := False;
pCh := PWideChar(pData) + iSize - 1;
while (pCh >= pData) and (pCh^ <> ';') do
Dec(pCh);
if (pCh >= pData) and (pCh^ = ';') then begin
Inc(pCh);
if pCh^ = '1' then
Dec(iSize, 2)
else begin
Result := True;
FDStr2Int(pCh, iSize - (pCh - PWideChar(pData)), @AOverload, SizeOf(AOverload));
end;
end;
end;
begin
lDeleteRow := False;
iRecNo := FRecordsFetched + ARowNo;
if not UseInformationSchema then begin
oRow := ATable.NewRow(False);
pData := FBuffer.Ptr;
end
else begin
FetchRow(ATable, AParentRow, ARowIndex);
ATable.Rows[ATable.Rows.Count - 1].SetData(0, iRecNo);
Result := True;
Exit;
end;
try
FConnection.CreateMetadata(oConnMeta);
case GetMetaInfoKind of
mkCatalogs:
begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
if (GetWildcard <> '') and
not FDStrLike(VarToStr(oRow.GetData(1, rvDefault)), GetWildcard, True) then
lDeleteRow := True
else
for i := 0 to ATable.Rows.Count - 1 do
if VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault)) then begin
lDeleteRow := True;
Break;
end;
end;
mkSchemas:
begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
if (GetWildcard <> '') and
not FDStrLike(VarToStr(oRow.GetData(2, rvDefault)), GetWildcard, True) then
lDeleteRow := True
else if (GetCatalogName <> '') and
(CompareText(VarToStr(oRow.GetData(1, rvDefault)), GetCatalogName) <> 0) then
lDeleteRow := True
else
for i := 0 to ATable.Rows.Count - 1 do
if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) then begin
lDeleteRow := True;
Break;
end;
end;
mkTables:
begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
eTableKind := tkTable;
eScope := osOther;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) then begin
GetScope(1, 2, 3, eScope);
if StrLIComp(PWideChar(pData), 'TABLE', iSize) = 0 then
eTableKind := tkTable
else if StrLIComp(PWideChar(pData), 'VIEW', iSize) = 0 then
eTableKind := tkView
else if StrLIComp(PWideChar(pData), 'SYSTEM TABLE', iSize) = 0 then begin
eTableKind := tkTable;
eScope := osSystem;
end
else if StrLIComp(PWideChar(pData), 'GLOBAL TEMPORARY', iSize) = 0 then
eTableKind := tkTempTable
else if StrLIComp(PWideChar(pData), 'LOCAL TEMPORARY', iSize) = 0 then
eTableKind := tkLocalTable
else if StrLIComp(PWideChar(pData), 'ALIAS', iSize) = 0 then
eTableKind := tkSynonym
else if StrLIComp(PWideChar(pData), 'SYNONYM', iSize) = 0 then
eTableKind := tkSynonym;
end;
oRow.SetData(4, Smallint(eTableKind));
oRow.SetData(5, Smallint(eScope));
lDeleteRow := not (eTableKind in GetTableKinds) or
not (eScope in GetObjectScopes);
end;
mkTableFields,
mkTableTypeFields:
begin
eAttrs := [caBase];
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) then
oRow.SetData(4, pData, iSize);
iSize := 0;
if FStatement.ColumnList.Count >= 17 then begin
if FStatement.ColumnList[16].GetData(ARowIndex, pData, iSize) then begin
// Informix: ORDINAL_POSITION is defined as SQL_SMALLINT instead of SQL_INTEGER.
// TData: ORDINAL_POSITION is defined as SQL_BIGINT instead of SQL_INTEGER.
case FStatement.ColumnList[16].CDataType of
SQL_C_STINYINT,
SQL_C_UTINYINT,
SQL_C_TINYINT:
oRow.SetData(5, PSQLByte(pData)^);
SQL_C_SSHORT,
SQL_C_USHORT,
SQL_C_SHORT:
oRow.SetData(5, PSQLSmallint(pData)^);
SQL_C_SLONG,
SQL_C_ULONG,
SQL_C_LONG:
oRow.SetData(5, PSQLInteger(pData)^);
SQL_C_SBIGINT,
SQL_C_UBIGINT:
oRow.SetData(5, PSQLBigInt(pData)^);
else
ASSERT(False);
end;
end;
end
else
oRow.SetData(5, iRecNo);
iSize := 0;
if FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) then
oRow.SetData(7, pData, iSize);
iSize := 0;
if FStatement.ColumnList.Count >= 13 then
if FStatement.ColumnList[12].GetData(ARowIndex, pData, iSize) and (iSize > 0) then
Include(eAttrs, caDefault);
iSize := 0;
if not FStatement.ColumnList[10].GetData(ARowIndex, pData, iSize) or
(PSQLSmallint(pData)^ <> SQL_NO_NULLS) then
Include(eAttrs, caAllowNull);
iSize := 0;
if FStatement.ColumnList[4].GetData(ARowIndex, pData, iSize) then
iODBCType := PSQLSmallint(pData)^
else
iODBCType := SQL_TYPE_NULL;
iSize := 0;
if FStatement.ColumnList[6].GetData(ARowIndex, pData, iSize) then begin
iODBCSize := PSQLInteger(pData)^;
AdjustMaxVarLen(iODBCType, iODBCSize, True);
end
else
iODBCSize := 0;
iSize := 0;
if FStatement.ColumnList[8].GetData(ARowIndex, pData, iSize) then
iODBCDec := PSQLSmallint(pData)^
else
iODBCDec := 0;
SQL2FDColInfo(iODBCType, False, VarToStr(oRow.GetData(7, rvDefault)),
iODBCSize, iODBCDec, eType, eAttrs, iLen, iPrec, iScale);
oRow.SetData(6, Smallint(eType));
oRow.SetData(8, PWord(@eAttrs)^);
oRow.SetData(9, iPrec);
oRow.SetData(10, iScale);
oRow.SetData(11, iLen);
{
if iDbxType and eSQLRowId <> 0 then
Include(eAttrs, caROWID);
if iDbxType and eSQLRowVersion <> 0 then
Include(eAttrs, caRowVersion);
if iDbxType and eSQLAutoIncr <> 0 then
Include(eAttrs, caAutoInc);
}
end;
mkIndexes:
begin
iSize := 0;
if FStatement.ColumnList[6].GetData(ARowIndex, pData, iSize) and
(PSQLSmallint(pData)^ = SQL_TABLE_STAT) then
lDeleteRow := True
else begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) then
oRow.SetData(4, pData, iSize);
iSize := 0;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) and
(PSQLSmallint(pData)^ = SQL_FALSE) then
eIndKind := ikUnique
else
eIndKind := ikNonUnique;
FMetainfoAddonView.RowFilter := 'INDEX_NAME = ''' + VarToStr(oRow.GetData(4)) + '''';
if FMetainfoAddonView.Rows.Count > 0 then begin
eIndKind := ikPrimaryKey;
oRow.SetData(5, FMetainfoAddonView.Rows[0].GetData(5));
end;
oRow.SetData(6, Smallint(eIndKind));
FMetainfoAddonView.RowFilter := '';
for i := 0 to ATable.Rows.Count - 1 do
if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(4, rvDefault)) = VarToStr(oRow.GetData(4, rvDefault))) then begin
lDeleteRow := True;
Break;
end;
end;
end;
mkIndexFields:
begin
iSize := 0;
if FStatement.ColumnList[6].GetData(ARowIndex, pData, iSize) and
(PSQLSmallint(pData)^ = SQL_TABLE_STAT) then
lDeleteRow := True
else begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) then
oRow.SetData(4, pData, iSize);
iSize := 0;
if FStatement.ColumnList[8].GetData(ARowIndex, pData, iSize) then
oRow.SetData(5, pData, iSize);
iSize := 0;
if FStatement.ColumnList[7].GetData(ARowIndex, pData, iSize) then
oRow.SetData(6, PSQLSmallint(pData)^);
iSize := 0;
if FStatement.ColumnList[9].GetData(ARowIndex, pData, iSize) then
oRow.SetData(7, pData, iSize);
iSize := 0;
if FStatement.ColumnList[12].GetData(ARowIndex, pData, iSize) then
oRow.SetData(8, pData, iSize);
oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self,
[doNormalize, doUnquote]);
lDeleteRow := (AnsiCompareText(rName.FObject,
Trim(VarToStr(oRow.GetData(4, rvDefault)))) <> 0);
end;
end;
mkPrimaryKey:
begin
if soPKFunction in ODBCConnection.FSupportedOptions then begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if (FStatement.ColumnList.Count >= 6) and
FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) then begin
oRow.SetData(4, pData, iSize);
oRow.SetData(5, pData, iSize);
end;
oRow.SetData(6, Smallint(ikPrimaryKey));
for i := 0 to ATable.Rows.Count - 1 do
if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(5, rvDefault)) = VarToStr(oRow.GetData(5, rvDefault))) then begin
lDeleteRow := True;
Break;
end;
end
else begin
lDeleteRow := ARowIndex > 0;
if not lDeleteRow then begin
oRow.SetData(0, iRecNo);
oConnMeta.DecodeObjName(Trim(GetCatalogName), rName, Self,
[doNormalize, doUnquote]);
if rName.FObject = '' then
rName.FObject := ODBCConnection.ODBCConnection.CURRENT_CATALOG;
oRow.SetData(1, rName.FObject);
oConnMeta.DecodeObjName(Trim(GetSchemaName), rName, Self,
[doNormalize, doUnquote]);
oRow.SetData(2, rName.FObject);
oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self,
[doNormalize, doUnquote]);
oRow.SetData(3, rName.FObject);
oRow.SetData(4, C_FD_BestRowID);
oRow.SetData(5, C_FD_BestRowID);
oRow.SetData(6, Smallint(ikPrimaryKey));
end;
end;
end;
mkPrimaryKeyFields:
begin
oRow.SetData(0, iRecNo);
if soPKFunction in ODBCConnection.FSupportedOptions then begin
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if (FStatement.ColumnList.Count >= 6) and
FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) then
oRow.SetData(4, pData, iSize);
iSize := 0;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) then
oRow.SetData(5, pData, iSize);
iSize := 0;
if FStatement.ColumnList[4].GetData(ARowIndex, pData, iSize) then
oRow.SetData(6, PSQLSmallint(pData)^);
end
else begin
oConnMeta.DecodeObjName(Trim(GetCatalogName), rName, Self,
[doNormalize, doUnquote]);
if rName.FObject = '' then
rName.FObject := ODBCConnection.ODBCConnection.CURRENT_CATALOG;
oRow.SetData(1, rName.FObject);
oConnMeta.DecodeObjName(Trim(GetSchemaName), rName, Self,
[doNormalize, doUnquote]);
oRow.SetData(2, rName.FObject);
oConnMeta.DecodeObjName(Trim(GetBaseObjectName), rName, Self,
[doNormalize, doUnquote]);
oRow.SetData(3, rName.FObject);
oRow.SetData(4, C_FD_BestRowID);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) then
oRow.SetData(5, pData, iSize);
oRow.SetData(6, iRecNo);
end;
oRow.SetData(7, 'A');
end;
mkForeignKeys:
begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[4].GetData(ARowIndex, pData, iSize) and TrimZeros(4) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) and TrimZeros(5) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[6].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if FStatement.ColumnList[11].GetData(ARowIndex, pData, iSize) then
oRow.SetData(4, pData, iSize);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) then
oRow.SetData(5, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) then
oRow.SetData(6, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then
oRow.SetData(7, pData, iSize);
eCascade := ckRestrict;
iSize := 0;
if FStatement.ColumnList[10].GetData(ARowIndex, pData, iSize) then
case PSQLSmallInt(pData)^ of
SQL_CASCADE: eCascade := ckCascade;
SQL_NO_ACTION,
SQL_RESTRICT: eCascade := ckRestrict;
SQL_SET_NULL: eCascade := ckSetNull;
SQL_SET_DEFAULT: eCascade := ckSetDefault;
end;
oRow.SetData(8, SmallInt(eCascade));
eCascade := ckRestrict;
iSize := 0;
if FStatement.ColumnList[9].GetData(ARowIndex, pData, iSize) then
case PSQLSmallInt(pData)^ of
SQL_CASCADE: eCascade := ckCascade;
SQL_NO_ACTION,
SQL_RESTRICT: eCascade := ckRestrict;
SQL_SET_NULL: eCascade := ckSetNull;
SQL_SET_DEFAULT: eCascade := ckSetDefault;
end;
oRow.SetData(9, SmallInt(eCascade));
for i := 0 to ATable.Rows.Count - 1 do
if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and
(VarToStr(ATable.Rows[i].GetData(4, rvDefault)) = VarToStr(oRow.GetData(4, rvDefault))) then begin
lDeleteRow := True;
Break;
end;
end;
mkForeignKeyFields:
begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[4].GetData(ARowIndex, pData, iSize) and TrimZeros(4) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) and TrimZeros(5) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[6].GetData(ARowIndex, pData, iSize) then
oRow.SetData(3, pData, iSize);
iSize := 0;
if FStatement.ColumnList[11].GetData(ARowIndex, pData, iSize) then
oRow.SetData(4, pData, iSize);
iSize := 0;
if FStatement.ColumnList[7].GetData(ARowIndex, pData, iSize) then
oRow.SetData(5, pData, iSize);
iSize := 0;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) then
oRow.SetData(6, pData, iSize);
iSize := 0;
if FStatement.ColumnList[8].GetData(ARowIndex, pData, iSize) then begin
PInteger(pData)^ := PWord(pData)^;
oRow.SetData(7, pData, SizeOf(Integer));
end;
oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self,
[doNormalize, doUnquote]);
lDeleteRow := (AnsiCompareText(rName.FObject,
Trim(VarToStr(oRow.GetData(4, rvDefault)))) <> 0);
end;
mkProcs:
begin
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then begin
if (oConnMeta.Kind = TFDRDBMSKinds.MSSQL) and AdjustOverloaded(i) then
oRow.SetData(5, @i, SizeOf(i));
oRow.SetData(4, pData, iSize);
end;
iSize := 0;
if FStatement.ColumnList[7].GetData(ARowIndex, pData, iSize) and
(PSQLSmallint(pData)^ = SQL_PT_FUNCTION) then
eProcKind := pkFunction
else
eProcKind := pkProcedure;
oRow.SetData(6, Smallint(eProcKind));
GetScope(1, 2, 4, eScope);
oRow.SetData(7, Smallint(eScope));
iSize := 0;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) then
if PSmallint(pData)^ = -1 then
oRow.SetData(8, 0)
else
oRow.SetData(8, PSmallint(pData)^);
iSize := 0;
if FStatement.ColumnList[4].GetData(ARowIndex, pData, iSize) then
if PSmallint(pData)^ = -1 then
oRow.SetData(9, 0)
else
oRow.SetData(9, PSmallint(pData)^);
lDeleteRow := not (eScope in GetObjectScopes);
end;
mkProcArgs:
begin
eAttrs := [];
oRow.SetData(0, iRecNo);
iSize := 0;
if FStatement.ColumnList[0].GetData(ARowIndex, pData, iSize) and TrimZeros(0) then
oRow.SetData(1, pData, iSize);
iSize := 0;
if FStatement.ColumnList[1].GetData(ARowIndex, pData, iSize) and TrimZeros(1) then
oRow.SetData(2, pData, iSize);
iSize := 0;
if FStatement.ColumnList[2].GetData(ARowIndex, pData, iSize) then begin
if (oConnMeta.Kind = TFDRDBMSKinds.MSSQL) and AdjustOverloaded(i) then
oRow.SetData(5, @i, SizeOf(i));
oRow.SetData(4, pData, iSize);
end;
iSize := 0;
if FStatement.ColumnList[3].GetData(ARowIndex, pData, iSize) then begin
if (cpUnifyParams in FStatementProps) and (PWideChar(pData)^ = '@') then begin
pData := PWideChar(pData) + 1;
Dec(iSize);
end;
oRow.SetData(6, pData, iSize);
end;
iSize := 0;
if FStatement.ColumnList.Count >= 18 then begin
if FStatement.ColumnList[17].GetData(ARowIndex, pData, iSize) then
oRow.SetData(7, PSQLInteger(pData)^);
end
else
oRow.SetData(7, iRecNo);
eParType := ptUnknown;
iSize := 0;
if FStatement.ColumnList[4].GetData(ARowIndex, pData, iSize) then
case PSQLSmallint(pData)^ of
SQL_PARAM_INPUT: eParType := ptInput;
SQL_PARAM_INPUT_OUTPUT: eParType := ptInputOutput;
SQL_PARAM_OUTPUT: eParType := ptOutput;
SQL_RETURN_VALUE: eParType := ptResult;
SQL_RESULT_COL: lDeleteRow := True;
end;
oRow.SetData(8, Smallint(eParType));
if (eParType = ptResult) and (cpUnifyParams in FStatementProps) then
oRow.SetData(6, 'RESULT');
iSize := 0;
if FStatement.ColumnList.Count >= 14 then begin
if FStatement.ColumnList[13].GetData(ARowIndex, pData, iSize) and (iSize > 0) then
Include(eAttrs, caDefault);
end;
iSize := 0;
if not FStatement.ColumnList[11].GetData(ARowIndex, pData, iSize) or
(PSQLSmallint(pData)^ <> SQL_NO_NULLS) then
Include(eAttrs, caAllowNull);
iSize := 0;
if FStatement.ColumnList[5].GetData(ARowIndex, pData, iSize) then
iODBCType := PSQLSmallint(pData)^
else
iODBCType := SQL_TYPE_NULL;
sType := FStatement.ColumnList[6].AsStrings[ARowIndex];
if (sType <> '') and
((iODBCType = SQL_SS_TABLE) or (iODBCType = SQL_SS_UDT) or (iODBCType = SQL_SS_XML)) and
(oConnMeta.Kind = TFDRDBMSKinds.MSSQL) and (FStatement.ColumnList.Count >= 21) then begin
rName.FCatalog := FStatement.ColumnList[19].AsStrings[ARowIndex];
rName.FSchema := FStatement.ColumnList[20].AsStrings[ARowIndex];
rName.FObject := sType;
sType := oConnMeta.EncodeObjName(rName, nil, [eoNormalize]);
end;
iSize := 0;
if FStatement.ColumnList[7].GetData(ARowIndex, pData, iSize) then begin
iODBCSize := PSQLInteger(pData)^;
AdjustMaxVarLen(iODBCType, iODBCSize, False);
end
else
iODBCSize := 0;
iSize := 0;
if FStatement.ColumnList[9].GetData(ARowIndex, pData, iSize) then
iODBCDec := PSQLSmallint(pData)^
else
iODBCDec := 0;
SQL2FDColInfo(iODBCType, False, sType, iODBCSize, iODBCDec, eType,
eAttrs, iLen, iPrec, iScale);
oRow.SetData(9, Smallint(eType));
if sType <> '' then
oRow.SetData(10, sType);
oRow.SetData(11, PWord(@eAttrs)^);
oRow.SetData(12, iPrec);
oRow.SetData(13, iScale);
oRow.SetData(14, iLen);
end;
end;
if lDeleteRow then begin
FDFree(oRow);
Result := False;
end
else begin
ATable.Rows.Add(oRow);
Result := True;
end;
except
FDFree(oRow);
raise;
end;
end;
end.
|
unit App.Types;
interface
uses
System.Sysutils,
System.Classes,
System.StrUtils,
Crypto.Encoding;
const
SIZE_PRIVATE_KEY = 174;
SIZE_PUBLIC_KEY = 96;
type
TMessageState = (Normal, Error, Allert);
TUint64Helper = record helper for UINt64
function AsBytes: TBytes;
end;
Strings = TArray<string>;
StringsHelper = record helper for Strings
procedure SetStrings(const AValue: string);
function Length: uint64;
function AsString(const Splitter: string): string;
function IsEmpty:boolean;
end;
THash = packed record
Hash: array [0..31] of Byte;
class operator Implicit(Buf: THash): string;
class operator Implicit(Buf: THash): TBytes;
class operator Implicit(Buf: string): THash;
class operator Implicit(Buf: TBytes): THash;
class operator Add(buf1: TBytes; buf2: THash): TBytes;
class operator Add(buf2: THash; buf1: TBytes): TBytes;
class operator Add(buf1: string; buf2: THash): string;
class operator Add(buf2: THash; buf1: string): string;
procedure Clear;
end;
TSignedHash = packed record
SignedHash: array [0..63] of Byte;
class operator Implicit(Buf: TSignedHash): string;
class operator Implicit(Buf: TSignedHash): TBytes;
class operator Implicit(Buf: string): TSignedHash;
class operator Implicit(Buf: TBytes): TSignedHash;
class operator Add(buf1: TBytes; buf2: TSignedHash): TBytes;
class operator Add(buf2: TSignedHash; buf1: TBytes): TBytes;
procedure Clear;
end;
TPrivateKey = packed record
PrivateKey : array [0..SIZE_PRIVATE_KEY-1] of Byte;
class operator Implicit(Buf: TPrivateKey): string;
class operator Implicit(Buf: TPrivateKey): TBytes;
class operator Implicit(Buf: string): TPrivateKey;
class operator Implicit(Buf: TBytes): TPrivateKey;
class operator Add(buf1: TBytes; buf2: TPrivateKey): TBytes;
class operator Add(buf2: TPrivateKey; buf1: TBytes): TBytes;
procedure Clear;
end;
TPublicKey = packed record
PublicKey : array [0..SIZE_PUBLIC_KEY-1] of Byte;
class operator Implicit(Buf: TPublicKey): string;
class operator Implicit(Buf: TPublicKey): TBytes;
class operator Implicit(Buf: string): TPublicKey;
class operator Implicit(Buf: TBytes): TPublicKey;
class operator Add(buf1: TBytes; buf2: TPublicKey): TBytes;
class operator Add(buf2: TPublicKey; buf1: TBytes): TBytes;
procedure Clear;
end;
implementation
{$REGION 'StringsHelper'}
function StringsHelper.AsString(const Splitter: string): string;
var
Value: string;
begin
Result := '';
for Value in Self do
Result := Result + Splitter + Value;
end;
procedure StringsHelper.SetStrings(const AValue: string);
begin
Self := SplitString(AValue,' ');
end;
function StringsHelper.IsEmpty: boolean;
begin
Result := Length = 0;
end;
function StringsHelper.Length: uint64;
begin
Result := System.Length(Self);
end;
{$ENDREGION}
{$REGION 'THash'}
class operator THash.Implicit(Buf: THash): TBytes;
var
Data: TBytes;
begin
SetLength(Data,SizeOf(THash));
Move(Buf.Hash[0],Data[0],SizeOf(THash));
Result := Data;
end;
class operator THash.Implicit(Buf: THash): string;
var
Data: Tbytes;
begin
SetLength(Data,SizeOf(THash));
Move(Buf.Hash[0],Data[0],SizeOf(THash));
Result := BytesEncodeBase64URL(Data);
end;
class operator THash.Add(buf1: TBytes; buf2: THash): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(THash));
Move(buf2.Hash[0], LData[0],SizeOf(THash));
RData := RData + LData;
Result := RData;
end;
class operator THash.Add(buf2: THash; buf1: TBytes): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(THash));
Move(buf2.Hash[0], LData[0],SizeOf(THash));
RData := LData + RData;
Result := RData;
end;
class operator THash.Add(buf2: THash; buf1: string): string;
var
Data: TBytes;
begin
SetLength(Data, SizeOf(THash));
Move(buf2.Hash[0], Data[0],SizeOf(THash));
Result := BytesEncodeBase64URL(Data) + buf1;
end;
class operator THash.Add(buf1: string; buf2: THash): string;
var
Data: TBytes;
begin
SetLength(Data, SizeOf(THash));
Move(buf2.Hash[0], Data[0],SizeOf(THash));
Result := buf1 + BytesEncodeBase64URL(Data);
end;
procedure THash.Clear;
begin
fillchar(Hash[0],SizeOf(Hash),0);
end;
class operator THash.Implicit(Buf: TBytes): THash;
var
RHash: THash;
begin
Move(Buf[0], RHash.Hash[0],Length(Buf));
Result := RHash;
end;
class operator THash.Implicit(Buf: string): THash;
var
RHash: THash;
Data: TBytes;
begin
Data := BytesDecodeBase64URL(Buf);
Move(Data[0],RHash.Hash[0],Length(Data));
Result := RHash;
end;
{$ENDREGION}
{$REGION 'TSignedHash'}
class operator TSignedHash.Add(buf1: TBytes; buf2: TSignedHash): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(TSignedHash));
Move(buf2.SignedHash[0], LData[0],SizeOf(TSignedHash));
RData := RData + LData;
Result := RData;
end;
class operator TSignedHash.Add(buf2: TSignedHash; buf1: TBytes): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(TSignedHash));
Move(buf2.SignedHash[0], LData[0],SizeOf(TSignedHash));
RData := LData + RData;
Result := RData;
end;
procedure TSignedHash.Clear;
begin
fillchar(SignedHash[0],SizeOf(SignedHash),0);
end;
class operator TSignedHash.Implicit(Buf: TSignedHash): TBytes;
var
Data: TBytes;
begin
SetLength(Data,SizeOf(TSignedHash));
Move(Buf.SignedHash[0],Data[0],SizeOf(TSignedHash));
Result := Data;
end;
class operator TSignedHash.Implicit(Buf: TSignedHash): string;
var
Data: Tbytes;
begin
SetLength(Data,SizeOf(TSignedHash));
Move(Buf.SignedHash[0],Data[0],SizeOf(TSignedHash));
Result := BytesEncodeBase64URL(Data);
end;
class operator TSignedHash.Implicit(Buf: string): TSignedHash;
var
RHash: TSignedHash;
Data: TBytes;
begin
Data := BytesDecodeBase64URL(Buf);
Move(Data[0],RHash.SignedHash[0],Length(Data));
Result := RHash;
end;
class operator TSignedHash.Implicit(Buf: TBytes): TSignedHash;
var
RHash: TSignedHash;
begin
Move(Buf[0], RHash.SignedHash[0],Length(Buf));
Result := RHash;
end;
{$ENDREGION}
{$REGION 'TPrivateKey'}
class operator TPrivateKey.Add(buf1: TBytes; buf2: TPrivateKey): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(TPrivateKey));
Move(buf2.PrivateKey[0], LData[0],SizeOf(TPrivateKey));
RData := RData + LData;
Result := RData;
end;
class operator TPrivateKey.Add(buf2: TPrivateKey; buf1: TBytes): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(TPrivateKey));
Move(buf2.PrivateKey[0], LData[0],SizeOf(TPrivateKey));
RData := LData + RData;
Result := RData;
end;
procedure TPrivateKey.Clear;
begin
fillchar(PrivateKey[0],SizeOf(PrivateKey),0);
end;
class operator TPrivateKey.Implicit(Buf: TPrivateKey): TBytes;
var
Data: TBytes;
begin
SetLength(Data,SizeOf(TPrivateKey));
Move(Buf.PrivateKey[0],Data[0],SizeOf(TPrivateKey));
Result := Data;
end;
class operator TPrivateKey.Implicit(Buf: TPrivateKey): string;
var
Data: Tbytes;
begin
SetLength(Data,SizeOf(TPrivateKey));
Move(Buf.PrivateKey[0],Data[0],SizeOf(TPrivateKey));
Result := BytesEncodeBase64URL(Data);
end;
class operator TPrivateKey.Implicit(Buf: string): TPrivateKey;
var
RKey: TPrivateKey;
Data: TBytes;
begin
Data := BytesDecodeBase64URL(Buf);
Move(Data[0],RKey.PrivateKey[0],Length(Data));
Result := RKey;
end;
class operator TPrivateKey.Implicit(Buf: TBytes): TPrivateKey;
var
RKey: TPrivateKey;
begin
Move(Buf[0], RKey.PrivateKey[0],Length(Buf));
Result := RKey;
end;
{$ENDREGION}
{$REGION 'TPublicKey'}
class operator TPublicKey.Add(buf1: TBytes; buf2: TPublicKey): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(TPublicKey));
Move(buf2.PublicKey[0], LData[0],SizeOf(TPublicKey));
RData := RData + LData;
Result := RData;
end;
class operator TPublicKey.Add(buf2: TPublicKey; buf1: TBytes): TBytes;
var
LData, RData: TBytes;
begin
RData := buf1;
SetLength(LData, SizeOf(TPublicKey));
Move(buf2.PublicKey[0], LData[0],SizeOf(TPublicKey));
RData := LData + RData;
Result := RData;
end;
procedure TPublicKey.Clear;
begin
fillchar(PublicKey[0],SizeOf(PublicKey),0);
end;
class operator TPublicKey.Implicit(Buf: TPublicKey): TBytes;
var
Data: TBytes;
begin
SetLength(Data,SizeOf(TPublicKey));
Move(Buf.PublicKey[0],Data[0],SizeOf(TPublicKey));
Result := Data;
end;
class operator TPublicKey.Implicit(Buf: TPublicKey): string;
var
Data: Tbytes;
begin
SetLength(Data,SizeOf(TPublicKey));
Move(Buf.PublicKey[0],Data[0],SizeOf(TPublicKey));
Result := BytesEncodeBase64URL(Data);
end;
class operator TPublicKey.Implicit(Buf: string): TPublicKey;
var
RKey: TPublicKey;
Data: TBytes;
begin
Data := BytesDecodeBase64URL(Buf);
Move(Data[0],RKey.PublicKey[0],Length(Data));
Result := RKey;
end;
class operator TPublicKey.Implicit(Buf: TBytes): TPublicKey;
var
RKey: TPublicKey;
begin
Move(Buf[0], RKey.PublicKey[0],Length(Buf));
Result := RKey;
end;
{$ENDREGION}
{ TUint64Helper }
function TUint64Helper.AsBytes: TBytes;
var
buf: TBytes;
begin
SetLength(buf, SizeOf(UINT64));
Move(self,buf[0], SizeOf(UINT64));
Result := buf;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: fAbout
This software and source code are distributed on an as is basis, without
warranty of any kind, either express or implied.
This file can be redistributed, modified if you keep this header.
Copyright © Erwien Saputra 2005 All Rights Reserved.
Author: Erwien Saputra
Purpose: About box.
History:
02/26/2005 - Updated the version number. Release 1.0.
-----------------------------------------------------------------------------}
unit fAbout;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons;
type
TfrmAbout = class(TForm)
btn_Ok: TButton;
StaticText1: TStaticText;
StaticText2: TStaticText;
lblBlog: TLabel;
lblCodeline: TLabel;
StaticText3: TStaticText;
StaticText4: TStaticText;
lblGemmellCom: TLabel;
procedure lblGemmellComClick(Sender: TObject);
procedure lblBlogClick(Sender: TObject);
procedure lblCodelineClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmAbout: TfrmAbout;
implementation
uses ShellUtilities, dmGlyphs;
{$R *.dfm}
procedure TfrmAbout.lblCodelineClick(Sender: TObject);
begin
GotoLink ('http:\\www.codeline.net');
end;
procedure TfrmAbout.lblBlogClick(Sender: TObject);
begin
GotoLink ('http://blogs.slcdug.org/esaputra');
end;
procedure TfrmAbout.lblGemmellComClick(Sender: TObject);
begin
GotoLink ('http://lachlan.gemmell.com');
end;
end.
|
unit sNIF.params.DEF;
{ *******************************************************
sNIF
Utilidad para buscar ficheros ofimáticos con
cadenas de caracteres coincidentes con NIF/NIE.
*******************************************************
2012-2018 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
interface
uses
KV.Definition;
var
GlobalParamDef: TKeyValueValidator;
const
PARAM_CARPETA = 'Carpeta';
PARAM_EXT = 'Extensiones';
PARAM_MAXNIF = 'MaxNIF';
PARAM_MAXSINNIF = 'MaxSinNIF';
PARAM_MINBYTES = 'MinBytesTamaño';
PARAM_MINDIAS = 'MinDiasCreado';
PARAM_HILOS = 'NumeroHilos';
PARAM_ERRORES = 'IncluirErrores';
PARAM_RESUMEN = 'GenerarResumen';
PARAM_SALIDA = 'Salida';
implementation
uses
IOUtils,
IOUtilsFix;
var
d: TKeyDefinition;
validadorCardinal: TValueValidator;
validadorFichero: TValueValidator;
{
En GlobalParamDef se definen los los parámetros del fichero de
configuración y sus valores admitidos. También sus descripciones.
Los valores leídos del fichero de configuración se constrastarán contra
esta definición en "sNIF.cmdline.pas",
}
initialization
GlobalParamDef := TKeyValueValidator.Create;
validadorCardinal := function(const valor: variant): boolean
begin
Result := (valor >= 0);
end;
validadorFichero := function(const valor: variant): boolean
begin
Result := (Length(valor) > 0) and (TPath.isWellFormed(valor, false, false));
end;
d := GlobalParamDef.Add(PARAM_CARPETA, varString, 0, 65535);
d.Description := 'Carpeta a explorar (recursivamente)';
d.ValidValueDescription :=
'Ruta a una carpeta existente. No se admiten comodines (* o ?).';
d.OnValidate := function(const valor: variant): boolean
begin
Result := (Length(valor) > 0) and (TPath.isWellFormed(valor, true, false));
end;
d := GlobalParamDef.Add(PARAM_EXT, varString);
d.Description :=
'Indica las extensiones que puede tener un fichero para que sea elegido para su exploración.';
d.ValidValueDescription :=
'Extensiones de fichero sin punto y separadas por un espacio en blanco. Se admiten comodines. Por omisión, extensiones de ficheros ofimáticos.';
d.OnValidate := function(const valor: variant): boolean
begin
Result := (Length(valor) > 0);
end;
d := GlobalParamDef.Add(PARAM_MAXNIF, varInt64);
d.Description :=
'Indica el número máximo de cadenas coincidentes con el formato de NIF/NIE que serán contabilizadas. Superado este límite, se finalizará la exploración del fichero.';
d.ValidValueDescription := 'Entero mayor que cero. Por omisión, 1000.';
d.OnValidate := validadorCardinal;
d := GlobalParamDef.Add(PARAM_MAXSINNIF, varInt64);
d.Description :=
'Indica, en porcentaje, la porción inicial del fichero que debe contener alguna cadena NIF/NIE para continuar con la exploración.';
d.ValidValueDescription :=
'Entero entre 40 y 100, ambos inclusive. Por omisión, 50.';
d.OnValidate := function(const valor: variant): boolean
begin
Result := (valor >= 40) and (valor <= 100);
end;
d := GlobalParamDef.Add(PARAM_MINBYTES, varInt64);
d.Description :=
'Indica el tamaño mínimo, en bytes, que ha de tener un fichero para que sea elegible para su exploración.';
d.ValidValueDescription := 'Entero mayor que cero. Por omisión, 3 MB.';
d.OnValidate := validadorCardinal;
d := GlobalParamDef.Add(PARAM_MINDIAS, varInt64);
d.Description :=
'Indica el número mínimo de días que han de transcurrir desde la fecha de creación de un fichero para que éste sea elegible para su exploración.';
d.ValidValueDescription := 'Entero mayor que cero. Por omisión, 365.';
d.OnValidate := validadorCardinal;
d := GlobalParamDef.Add(PARAM_HILOS, varInt64);
d.Description := 'Indica el número de exploraciones concurrentes.';
d.ValidValueDescription :=
'Entero entre uno y diez, ambos inclusive. Por omisión, 6.';
d.OnValidate := function(const valor: variant): boolean
begin
Result := (valor > 0) and (valor < 11);
end;
d := GlobalParamDef.Add(PARAM_ERRORES, varBoolean);
d.Description :=
'Indica si se desea dejar constancia de los ficheros que no pudieron ser explorados.';
d.ValidValueDescription := 'true (si, valor por omisión) o false (no).';
d := GlobalParamDef.Add(PARAM_RESUMEN, varBoolean);
d.Description :=
'Indica si se desea generar un fichero adicional a modo de resumen.';
d.ValidValueDescription := 'true (si) o false (no, valor por omisión).';
d := GlobalParamDef.Add(PARAM_SALIDA, varString);
d.Description := 'Indica el fichero a generar con los resultados.';
d.ValidValueDescription := 'Ruta a un nombre de fichero.';
d.OnValidate := validadorFichero;
finalization
GlobalParamDef.Free;
end.
|
unit uPreferences;
interface
uses
uStruct;
const
sApplicationIniSection='Preferences';
var
sIniFilePath: String;
DelphiState: TDelphiState;
PollingInterval: TPollingInterval;
LastPolledTime: TDateTime;
IsDelphiDyingURI, IsDelphiDeadURI: String;
DisastrousSituationLinksURI: String;
procedure SaveDelphiState;
procedure SavePollingIntervalOption;
procedure SaveLastPolledTime;
procedure SaveRunAtStartupOption(bRun: Boolean);
function CheckRunAtStartupOption: Boolean;
implementation
uses
SysUtils, Forms, IniFiles, Registry, Windows;
procedure SaveDelphiState;
var
ifMain: TIniFile;
begin
try
ifMain:=TIniFile.Create(sIniFilePath);
ifMain.WriteInteger(sApplicationIniSection, 'DelphiState', Ord(DelphiState));
ifMain.Free;
except
end;
end;
procedure SavePollingIntervalOption;
var
ifMain: TIniFile;
begin
try
ifMain:=TIniFile.Create(sIniFilePath);
ifMain.WriteInteger(sApplicationIniSection, 'PollingInterval', Ord(PollingInterval));
ifMain.Free;
except
end;
end;
procedure SaveLastPolledTime;
var
ifMain: TIniFile;
begin
try
ifMain:=TIniFile.Create(sIniFilePath);
ifMain.WriteFloat(sApplicationIniSection, 'LastPolledTime', LastPolledTime);
ifMain.Free;
except
end;
end;
procedure SaveRunAtStartupOption(bRun: Boolean);
var
rgMain: TRegistry;
begin
try
rgMain:=TRegistry.Create;
try
rgMain.RootKey:=HKEY_CURRENT_USER;
if bRun then
begin
if rgMain.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', true) then
begin
rgMain.WriteString('Is Delphi Dying Monitor', Application.ExeName);
rgMain.CloseKey;
end;
end
else
begin
if rgMain.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', false) then
begin
rgMain.DeleteValue('Is Delphi Dying Monitor');
rgMain.CloseKey;
end;
end;
finally
rgMain.Free;
end;
except
end;
end;
function CheckRunAtStartupOption: Boolean;
var
rgMain: TRegistry;
begin
Result:=false;
try
rgMain:=TRegistry.Create;
try
rgMain.RootKey:=HKEY_CURRENT_USER;
if rgMain.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', true) then
begin
if SameText(rgMain.ReadString('Is Delphi Dying Monitor'), Application.ExeName) then
Result:=true;
end;
finally
rgMain.Free;
end;
except
end;
end;
procedure LoadPreferences;
var
ifMain: TIniFile;
iTemp: Integer;
begin
if FileExists(sIniFilePath) then
begin
ifMain:=TIniFile.Create(sIniFilePath);
ifMain.UpdateFile;
iTemp:=ifMain.ReadInteger(sApplicationIniSection, 'DelphiState', Ord(dsLiving));
if (iTemp < Ord(Low(TDelphiState))) or (iTemp > Ord(High(TDelphiState))) then
iTemp:=Ord(dsLiving);
DelphiState:=TDelphiState(iTemp);
iTemp:=ifMain.ReadInteger(sApplicationIniSection, 'PollingInterval', Ord(pi10h));
if (iTemp < Ord(Low(TPollingInterval))) or (iTemp > Ord(High(TPollingInterval))) then
iTemp:=Ord(pi10h);
PollingInterval:=TPollingInterval(iTemp);
LastPolledTime:=ifMain.ReadFloat(sApplicationIniSection, 'LastPolledTime', 0);
IsDelphiDyingURI:=ifMain.ReadString(sApplicationIniSection, 'IsDelphiDyingURI', 'http://isdelphidying.com/API/?json');
IsDelphiDeadURI:=ifMain.ReadString(sApplicationIniSection, 'IsDelphiDeadURI', 'http://isdelphidead.com/API/?json');
DisastrousSituationLinksURI:=ifMain.ReadString(sApplicationIniSection, 'DisastrousSituationLinksURI', 'http://www.isdelphidying.narod.ru/links.txt');
ifMain.Free;
end
else
begin
DelphiState:=dsLiving;
PollingInterval:=pi10h;
LastPolledTime:=0;
IsDelphiDyingURI:='http://isdelphidying.com/API/?json';
IsDelphiDeadURI:='http://isdelphidead.com/API/?json';
DisastrousSituationLinksURI:='http://www.isdelphidying.narod.ru/links.txt';
end;
end;
initialization
DecimalSeparator:='.';
sIniFilePath:=ChangeFileExt(Application.ExeName, '.ini');
LoadPreferences;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.EMSMetaTypes;
interface
uses
System.Classes,
System.SysUtils,
System.JSON,
REST.Backend.MetaTypes,
REST.Backend.EMSApi;
type
TMetaFactory = class(TInterfacedObject, IBackendMetaFactory,
IBackendMetaUserFactory, IBackendMetaGroupFactory, IBackendMetaDataTypeFactory)
protected
{ IBackendMetaUserFactory }
function CreateMetaUserObject(const AObjectID: string): TBackendEntityValue;
{ IBackendMetaDataTypeFactory }
function CreateMetaDataType(const ADataType, ABackendClassName: string): TBackendMetaClass;
{ IBackendMetaUserGroupFactory }
function CreateMetaGroupObject(const AGroupID: string): TBackendEntityValue;
end;
// Describe a backend class
TMetaClass = class(TInterfacedObject, IBackendMetaObject)
private
FClassName: string;
FDataType: string;
protected
function GetClassName: string;
function GetDataType: string;
public
constructor Create(const AClassName: string); overload;
constructor Create(const ADataType, AClassName: string); overload;
end;
// Defined backend class with ClassName property
TMetaClassName = class(TMetaClass, IBackendMetaClass, IBackendClassName)
end;
// Defined backend class with ClassName and datatype property
TMetaDataType = class(TMetaClass, IBackendMetaClass, IBackendClassName,
IBackendDataType)
end;
// Describe a user object
TMetaUser = class(TInterfacedObject, IBackendMetaObject)
private
FUser: TEMSClientAPI.TUser;
protected
function GetObjectID: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
function GetUserName: string;
public
constructor Create(const AUser: TEMSClientAPI.TUser);
property User: TEMSClientAPI.TUser read FUser;
end;
// Describe a group object
TMetaGroup = class(TInterfacedObject, IBackendMetaObject)
private
FGroup: TEMSClientAPI.TGroup;
protected
function GetGroupName: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
public
constructor Create(const AGroup: TEMSClientAPI.TGroup);
property Group: TEMSClientAPI.TGroup read FGroup;
end;
// Describe an installation object
TMetaInstallation = class(TInterfacedObject, IBackendMetaObject)
private
FInstallation: TEMSClientAPI.TInstallation;
protected
function GetObjectID: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
public
constructor Create(const AInstallation: TEMSClientAPI.TInstallation);
property Installation: TEMSClientAPI.TInstallation read FInstallation;
end;
// Describe an logged in user
TMetaLogin = class(TMetaUser)
private
FLogin: TEMSClientAPI.TLogin;
protected
function GetAuthTOken: string;
public
constructor Create(const ALogin: TEMSClientAPI.TLogin);
property Login: TEMSClientAPI.TLogin read FLogin;
end;
// Describe a module object
TMetaModule = class(TInterfacedObject, IBackendMetaObject)
private
FModule: TEMSClientAPI.TModule;
protected
function GetObjectID: string;
function GetModuleName: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
public
constructor Create(const AModule: TEMSClientAPI.TModule);
property Module: TEMSClientAPI.TModule read FModule;
end;
// Describe a module Resource object
TMetaModuleResource = class(TInterfacedObject, IBackendMetaObject)
private
FModuleResource: TEMSClientAPI.TModuleResource;
protected
function GetObjectID: string;
function GetModuleName: string;
function GetResourceName: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
public
constructor Create(const AModuleResource: TEMSClientAPI.TModuleResource);
property ModuleResource: TEMSClientAPI.TModuleResource read FModuleResource;
end;
// Define MetaObject with UpdatedAt properties
TMetaUpdatedUser = class(TMetaUser, IBackendMetaObject, IBackendUpdatedAt,
IBackendUserName)
end;
TMetaFoundUser = class(TMetaUser, IBackendMetaObject, IBackendObjectID,
IBackendCreatedAt, IBackendUpdatedAt, IBackendUserName)
end;
TMetaFoundGroup = class(TMetaGroup, IBackendMetaObject,
IBackendCreatedAt, IBackendUpdatedAt, IBackendGroupName)
end;
TMetaFoundInstallation = class(TMetaInstallation, IBackendMetaObject,
IBackendCreatedAt, IBackendUpdatedAt, IBackendObjectID)
end;
TMetaInstallationID = class(TMetaInstallation, IBackendMetaObject,
IBackendObjectID)
end;
TMetaLoginUser = class(TMetaLogin, IBackendMetaObject, IBackendObjectID,
IBackendCreatedAt, IBackendUpdatedAt, IBackendUserName, IBackendAuthToken)
end;
TMetaSignupUser = class(TMetaLogin, IBackendMetaObject, IBackendObjectID,
IBackendCreatedAt, IBackendUserName, IBackendAuthToken)
end;
TMetaFoundModule = class(TMetaModule, IBackendMetaObject,
IBackendCreatedAt, IBackendUpdatedAt, IBackendObjectID, IBackendModuleName)
end;
TMetaFoundModuleResource = class(TMetaModuleResource, IBackendMetaObject,
IBackendCreatedAt, IBackendUpdatedAt, IBackendObjectID, IBackendModuleName,
IBackendModuleResourceName)
end;
// Define MetaObject with UpdatedAt properties
TMetaUpdatedAt = class(TInterfacedObject, IBackendMetaObject, IBackendUpdatedAt)
private
FUpdatedAt: TEMSClientAPI.TUpdatedAt;
protected
function GetUpdatedAt: TDateTime;
public
constructor Create(const AUpdatedAt: TEMSClientAPI.TUpdatedAt);
property UpdatedAt: TEMSClientAPI.TUpdatedAt read FUpdatedAt;
end;
TMetaUpdatedUserAt = TMetaUpdatedAt;
TMetaUpdatedGroupAt = TMetaUpdatedAt;
TEMSMetaFactory = class
private
public
class function CreateMetaClass(const AClassName: string)
: TBackendMetaClass; static;
// Query
class function CreateMetaDataType(const ADataType, AClassName: string)
: TBackendMetaClass; static;
// Users
class function CreateMetaUserObject(const AObjectID: string)
: TBackendEntityValue; overload; static;
class function CreateMetaGroupObject(const AGroupName: string)
: TBackendEntityValue; overload; static;
class function CreateMetaUserObject(const AUser: TEMSClientAPI.TUser)
: TBackendEntityValue; overload; static;
class function CreateMetaGroupObject(const AGroup: TEMSClientAPI.TGroup)
: TBackendEntityValue; overload; static;
class function CreateMetaFoundUser(const AUser: TEMSClientAPI.TUser)
: TBackendEntityValue; static;
class function CreateMetaFoundGroup(const AGroup: TEMSClientAPI.TGroup)
: TBackendEntityValue; static;
class function CreateMetaFoundInstallation(const AInstallation: TEMSClientAPI.TInstallation)
: TBackendEntityValue; static;
class function CreateMetaUpdatedUser(const AUpdatedAt
: TEMSClientAPI.TUpdatedAt): TBackendEntityValue; overload; static;
class function CreateMetaUpdatedGroup(const AUpdatedAt
: TEMSClientAPI.TUpdatedAt): TBackendEntityValue; overload; static;
class function CreateMetaSignupUser(const ALogin: TEMSClientAPI.TLogin)
: TBackendEntityValue; overload; static;
class function CreateMetaLoginUser(const ALogin: TEMSClientAPI.TLogin)
: TBackendEntityValue; overload; static;
class function CreateMetaFoundModule(const AModule: TEMSClientAPI.TModule)
: TBackendEntityValue; static;
class function CreateMetaFoundModuleResource(const AModuleResource: TEMSClientAPI.TModuleResource)
: TBackendEntityValue; static;
end;
implementation
{ TMetaClass }
constructor TMetaClass.Create(const AClassName: string);
begin
inherited Create;
FClassName := AClassName;
end;
constructor TMetaClass.Create(const ADataType, AClassName: string);
begin
Create(AClassName);
FDataType := ADataType;
end;
function TMetaClass.GetClassName: string;
begin
Result := FClassName;
end;
function TMetaClass.GetDataType: string;
begin
Result := FDataType;
end;
{ TMetaUser }
constructor TMetaUser.Create(const AUser: TEMSClientAPI.TUser);
begin
inherited Create;
FUser := AUser;
end;
function TMetaUser.GetCreatedAt: TDateTime;
begin
Result := FUser.CreatedAt;
end;
function TMetaUser.GetObjectID: string;
begin
Result := FUser.UserID;
end;
function TMetaUser.GetUpdatedAt: TDateTime;
begin
Result := FUser.UpdatedAt;
end;
function TMetaUser.GetUserName: string;
begin
Result := FUser.UserName;
end;
{ TMetaGroup }
constructor TMetaGroup.Create(const AGroup: TEMSClientAPI.TGroup);
begin
inherited Create;
FGroup := AGroup;
end;
function TMetaGroup.GetCreatedAt: TDateTime;
begin
Result := FGroup.CreatedAt;
end;
function TMetaGroup.GetUpdatedAt: TDateTime;
begin
Result := FGroup.UpdatedAt;
end;
function TMetaGroup.GetGroupName: string;
begin
Result := FGroup.GroupName;
end;
{ TMetaUserGroup }
constructor TMetaInstallation.Create(const AInstallation: TEMSClientAPI.TInstallation);
begin
inherited Create;
FInstallation := AInstallation;
end;
function TMetaInstallation.GetCreatedAt: TDateTime;
begin
Result := FInstallation.CreatedAt;
end;
function TMetaInstallation.GetUpdatedAt: TDateTime;
begin
Result := FInstallation.UpdatedAt;
end;
function TMetaInstallation.GetObjectID: string;
begin
Result := FInstallation.InstallationID;
end;
{ TMetaFactory }
function TMetaFactory.CreateMetaDataType(const ADataType,
ABackendClassName: string): TBackendMetaClass;
begin
Result := TEMSMetaFactory.CreateMetaDataType(ADataType, ABackendClassName);
end;
function TMetaFactory.CreateMetaGroupObject(
const AGroupID: string): TBackendEntityValue;
begin
Result := TEMSMetaFactory.CreateMetaGroupObject(AGroupID);
end;
function TMetaFactory.CreateMetaUserObject(const AObjectID: string)
: TBackendEntityValue;
begin
Result := TEMSMetaFactory.CreateMetaUserObject(AObjectID);
end;
{ TEMSMetaFactory }
class function TEMSMetaFactory.CreateMetaClass(const AClassName: string)
: TBackendMetaClass;
var
LIntf: IBackendMetaClass;
begin
LIntf := TMetaClassName.Create(AClassName);
Assert(Supports(LIntf, IBackendClassName));
Result := TBackendMetaClass.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaFoundUser
(const AUser: TEMSClientAPI.TUser): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundUser.Create(AUser);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaFoundGroup
(const AGroup: TEMSClientAPI.TGroup): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundGroup.Create(AGroup);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaFoundInstallation
(const AInstallation: TEMSClientAPI.TInstallation): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundInstallation.Create(AInstallation);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaFoundModule(
const AModule: TEMSClientAPI.TModule): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundModule.Create(AModule);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaFoundModuleResource(
const AModuleResource: TEMSClientAPI.TModuleResource): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundModuleResource.Create(AModuleResource);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaLoginUser(const ALogin
: TEMSClientAPI.TLogin): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaLoginUser.Create(ALogin);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaDataType(const ADataType,
AClassName: string): TBackendMetaClass;
var
LIntf: IBackendMetaClass;
begin
LIntf := TMetaDataType.Create(ADataType, AClassName);
Result := TBackendMetaClass.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaSignupUser(const ALogin
: TEMSClientAPI.TLogin): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaSignupUser.Create(ALogin);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaUpdatedUser(const AUpdatedAt
: TEMSClientAPI.TUpdatedAt): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaUpdatedAt.Create(AUpdatedAt);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaUpdatedGroup(const AUpdatedAt
: TEMSClientAPI.TUpdatedAt): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaUpdatedGroupAt.Create(AUpdatedAt);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaUserObject
(const AUser: TEMSClientAPI.TUser): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundUser.Create(AUser);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaGroupObject
(const AGroup: TEMSClientAPI.TGroup): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundGroup.Create(AGroup);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TEMSMetaFactory.CreateMetaUserObject(const AObjectID: string)
: TBackendEntityValue;
var
LUser: TEMSClientAPI.TUser;
begin
LUser := TEMSClientAPI.TUser.Create('', AObjectID);
Result := CreateMetaUserObject(LUser);
end;
class function TEMSMetaFactory.CreateMetaGroupObject(const AGroupName: string)
: TBackendEntityValue;
var
LGroup: TEMSClientAPI.TGroup;
begin
LGroup := TEMSClientAPI.TGroup.Create(AGroupName);
Result := CreateMetaGroupObject(LGroup);
end;
{ TMetaUpdatedUserAt }
constructor TMetaUpdatedAt.Create(const AUpdatedAt
: TEMSClientAPI.TUpdatedAt);
begin
FUpdatedAt := AUpdatedAt;
end;
function TMetaUpdatedAt.GetUpdatedAt: TDateTime;
begin
Result := FUpdatedAt.UpdatedAt;
end;
{ TMetaLogin }
constructor TMetaLogin.Create(const ALogin: TEMSClientAPI.TLogin);
begin
FLogin := ALogin;
inherited Create(FLogin.User);
end;
function TMetaLogin.GetAuthTOken: string;
begin
Result := FLogin.AuthToken;
end;
{ TMetaModule }
constructor TMetaModule.Create(const AModule: TEMSClientAPI.TModule);
begin
inherited Create;
FModule := AModule;
end;
function TMetaModule.GetCreatedAt: TDateTime;
begin
Result := FModule.CreatedAt;
end;
function TMetaModule.GetModuleName: string;
begin
Result := FModule.ModuleName;
end;
function TMetaModule.GetObjectID: string;
begin
Result := FModule.ModuleID;
end;
function TMetaModule.GetUpdatedAt: TDateTime;
begin
Result := FModule.UpdatedAt
end;
{ TMetaModuleResource }
constructor TMetaModuleResource.Create(
const AModuleResource: TEMSClientAPI.TModuleResource);
begin
inherited Create;
FModuleResource := AModuleResource;
end;
function TMetaModuleResource.GetCreatedAt: TDateTime;
begin
Result := FModuleResource.CreatedAt;
end;
function TMetaModuleResource.GetModuleName: string;
begin
Result := FModuleResource.ModuleName;
end;
function TMetaModuleResource.GetObjectID: string;
begin
Result := FModuleResource.ModuleID;
end;
function TMetaModuleResource.GetResourceName: string;
begin
Result := FModuleResource.ResourceName;
end;
function TMetaModuleResource.GetUpdatedAt: TDateTime;
begin
Result := FModuleResource.UpdatedAt;
end;
end.
|
UNIT GrafText;
(* valid only in graphics mode *)
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
interface
uses GRAPH,
MaxRes;
procedure WriteLine;
procedure WriteString(s : STRING); { word wrap is on }
procedure WriteInt(int : LONGINT; minlength : INTEGER);
procedure WriteReal(r : Real; minlength, dec : INTEGER);
procedure SetBaseLine(b : INTEGER);
{ pixels between lines }
(* some graphic text routines *)
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
implementation
VAR
BaseLine : INTEGER;
procedure WriteLine;
begin
MoveTo(0,GetY + TextHeight('AA') + BaseLine);
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure WriteString(s : STRING);
BEGIN
if GetX + TextWidth(s) > GetMaxX then WriteLine;
OutText(s);
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure WriteInt(int : LONGINT; minlength : INTEGER);
var
s : STRING;
BEGIN
str(int:minlength,s);
WriteString(s);
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure WriteReal(r : Real; minlength, dec : INTEGER);
var
s : STRING;
BEGIN
str(r:minlength:dec,s);
WriteString(s);
END;
procedure SetBaseLine(b : INTEGER);
BEGIN
BaseLine := b;
END;
BEGIN
SetBaseLine(1);
END. |
{ ********************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Open Tools API }
{ }
{ Copyright (C) 2000, 2001 Borland Software Corporation }
{ }
{ ********************************************************************** }
unit ClxEditors;
interface
uses
Classes, DesignIntf, DesignEditors, DesignMenus, DsnConst, QControls, QForms,
QMenus, ClxImgEdit, QImgList, QActnList, QDialogs;
{ Custom Module Types }
type
{ ICustomDesignForm
Allows a custom module to create a different form for use by the designer
as the base form.
CreateDesignForm
Create a descendent of TCustomForm for use by the designer as the
instance to design }
ICustomDesignForm = interface
['{833D4D25-3E3D-44DB-82CC-117C02C778B1}']
procedure CreateDesignerForm(const Designer: IDesigner; Root: TComponent;
out DesignForm: TCustomForm; out ComponentContainer: TWidgetControl);
end;
TAlignProperty = class(TEnumProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
{ TColorProperty
Property editor for the TColor type. Displays the color as a clXXX value
if one exists, otherwise displays the value as hex. Also allows the
clXXX value to be picked from a list. }
TColorProperty = class(TIntegerProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TCursorProperty
Property editor for the TCursor type. Displays the cursor as a clXXX value
if one exists, otherwise displays the value as hex. Also allows the
clXXX value to be picked from a list. }
TCursorProperty = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TFontProperty
Property editor for the Font property. Brings up the font dialog as well as
allowing the properties of the object to be edited. }
TFontProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
{ TFontNameProperty
Property editor for the Font's Name property. Displays a drop-down list of all
the fonts known by Qt. }
TFontNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
{ TShortCutProperty
Property editor the ShortCut property. Allows both typing in a short
cut value or picking a short-cut value from a list. }
TShortCutProperty = class(TOrdinalProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TTabOrderProperty
Property editor for the TabOrder property. Prevents the property from being
displayed when more than one component is selected. }
TTabOrderProperty = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
end;
{ TCaptionProperty
Property editor for the Caption and Text properties. Updates the value of
the property for each change instead on when the property is approved. }
TCaptionProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
end;
type
TImageListEditor = class(TComponentEditor)
public
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
type
TModalResultProperty = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
TFileNameProperty = class(TStringProperty)
protected
procedure GetDialogOptions(Dialog: TOpenDialog); virtual;
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
THTMLFileNameProperty = class(TFileNameProperty)
protected
procedure GetDialogOptions(Dialog: TOpenDialog); override;
end;
TNotifyActionListChange = procedure;
procedure CopyStreamToClipboard(S: TStream);
function GetClipboardStream: TMemoryStream;
var
NotifyActionListChange: TNotifyActionListChange = nil;
procedure RegActions(const ACategory: string;
const AClasses: array of TBasicActionClass; AResource: TComponentClass);
procedure UnRegActions(const Classes: array of TBasicActionClass);
procedure EnumActions(Proc: TEnumActionProc; Info: Pointer);
function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction;
implementation
uses SysUtils, TypInfo, Qt, QConsts, QGraphics, QClipbrd, LibHelp, DesignConst;
{ TColorProperty }
procedure TColorProperty.Edit;
var
ColorDialog: TColorDialog;
begin
ColorDialog := TColorDialog.Create(Application);
try
ColorDialog.Color := GetOrdValue;
// TODO 3 -oCPJ: Figure out how to preserve the custom colors
ColorDialog.HelpContext := hcDColorEditor;
ColorDialog.HelpType := htContext;
if ColorDialog.Execute then SetOrdValue(ColorDialog.Color);
finally
ColorDialog.Free;
end;
end;
function TColorProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paDialog, paValueList, paRevertable];
end;
function TColorProperty.GetValue: string;
begin
Result := ColorToString(TColor(GetOrdValue));
end;
procedure TColorProperty.GetValues(Proc: TGetStrProc);
begin
GetColorValues(Proc);
end;
procedure TColorProperty.SetValue(const Value: string);
var
NewValue: Longint;
begin
if IdentToColor(Value, NewValue) then
SetOrdValue(NewValue)
else
inherited SetValue(Value);
end;
{ TCursorProperty }
function TCursorProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList, paRevertable];
end;
function TCursorProperty.GetValue: string;
begin
Result := CursorToString(TCursor(GetOrdValue));
end;
procedure TCursorProperty.GetValues(Proc: TGetStrProc);
begin
GetCursorValues(Proc);
end;
procedure TCursorProperty.SetValue(const Value: string);
var
NewValue: Longint;
begin
if IdentToCursor(Value, NewValue) then
SetOrdValue(NewValue)
else inherited SetValue(Value);
end;
{ TFontProperty }
procedure TFontProperty.Edit;
var
FontDialog: TFontDialog;
begin
FontDialog := TFontDialog.Create(Application);
try
FontDialog.Font := TFont(GetOrdValue);
FontDialog.HelpContext := hcDFontEditor;
FontDialog.HelpType := htContext;
// TODO 4 -oCPJ: Figure out what these TFont dialog options mean for CLX
// FontDialog.Options := FontDialog.Options + [fdShowHelp, fdForceFontExist];
if FontDialog.Execute then SetOrdValue(Longint(FontDialog.Font));
finally
FontDialog.Free;
end;
end;
function TFontProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paSubProperties, paDialog, paReadOnly];
end;
{ TFontNameProperty }
function TFontNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList, paRevertable];
end;
procedure TFontNameProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
for I := 0 to Screen.Fonts.Count - 1 do Proc(Screen.Fonts[I]);
end;
{ TShortCutProperty }
const
ShortCuts: array[0..108] of TShortCut = (
scNone,
Byte('A') or scCtrl,
Byte('B') or scCtrl,
Byte('C') or scCtrl,
Byte('D') or scCtrl,
Byte('E') or scCtrl,
Byte('F') or scCtrl,
Byte('G') or scCtrl,
Byte('H') or scCtrl,
Byte('I') or scCtrl,
Byte('J') or scCtrl,
Byte('K') or scCtrl,
Byte('L') or scCtrl,
Byte('M') or scCtrl,
Byte('N') or scCtrl,
Byte('O') or scCtrl,
Byte('P') or scCtrl,
Byte('Q') or scCtrl,
Byte('R') or scCtrl,
Byte('S') or scCtrl,
Byte('T') or scCtrl,
Byte('U') or scCtrl,
Byte('V') or scCtrl,
Byte('W') or scCtrl,
Byte('X') or scCtrl,
Byte('Y') or scCtrl,
Byte('Z') or scCtrl,
Byte('A') or scCtrl or scAlt,
Byte('B') or scCtrl or scAlt,
Byte('C') or scCtrl or scAlt,
Byte('D') or scCtrl or scAlt,
Byte('E') or scCtrl or scAlt,
Byte('F') or scCtrl or scAlt,
Byte('G') or scCtrl or scAlt,
Byte('H') or scCtrl or scAlt,
Byte('I') or scCtrl or scAlt,
Byte('J') or scCtrl or scAlt,
Byte('K') or scCtrl or scAlt,
Byte('L') or scCtrl or scAlt,
Byte('M') or scCtrl or scAlt,
Byte('N') or scCtrl or scAlt,
Byte('O') or scCtrl or scAlt,
Byte('P') or scCtrl or scAlt,
Byte('Q') or scCtrl or scAlt,
Byte('R') or scCtrl or scAlt,
Byte('S') or scCtrl or scAlt,
Byte('T') or scCtrl or scAlt,
Byte('U') or scCtrl or scAlt,
Byte('V') or scCtrl or scAlt,
Byte('W') or scCtrl or scAlt,
Byte('X') or scCtrl or scAlt,
Byte('Y') or scCtrl or scAlt,
Byte('Z') or scCtrl or scAlt,
Key_F1,
Key_F2,
Key_F3,
Key_F4,
Key_F5,
Key_F6,
Key_F7,
Key_F8,
Key_F9,
Key_F10,
Key_F11,
Key_F12,
Key_F1 or scCtrl,
Key_F2 or scCtrl,
Key_F3 or scCtrl,
Key_F4 or scCtrl,
Key_F5 or scCtrl,
Key_F6 or scCtrl,
Key_F7 or scCtrl,
Key_F8 or scCtrl,
Key_F9 or scCtrl,
Key_F10 or scCtrl,
Key_F11 or scCtrl,
Key_F12 or scCtrl,
Key_F1 or scShift,
Key_F2 or scShift,
Key_F3 or scShift,
Key_F4 or scShift,
Key_F5 or scShift,
Key_F6 or scShift,
Key_F7 or scShift,
Key_F8 or scShift,
Key_F9 or scShift,
Key_F10 or scShift,
Key_F11 or scShift,
Key_F12 or scShift,
Key_F1 or scShift or scCtrl,
Key_F2 or scShift or scCtrl,
Key_F3 or scShift or scCtrl,
Key_F4 or scShift or scCtrl,
Key_F5 or scShift or scCtrl,
Key_F6 or scShift or scCtrl,
Key_F7 or scShift or scCtrl,
Key_F8 or scShift or scCtrl,
Key_F9 or scShift or scCtrl,
Key_F10 or scShift or scCtrl,
Key_F11 or scShift or scCtrl,
Key_F12 or scShift or scCtrl,
Key_Insert,
Key_Insert or scShift,
Key_Insert or scCtrl,
Key_Delete,
Key_Delete or scShift,
Key_Delete or scCtrl,
Key_Backspace or scAlt,
Key_Backspace or scShift or scAlt);
function TShortCutProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paRevertable];
end;
function TShortCutProperty.GetValue: string;
var
CurValue: TShortCut;
begin
CurValue := GetOrdValue;
if CurValue = scNone then
Result := srNone else
Result := ShortCutToText(CurValue);
end;
procedure TShortCutProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
Proc(srNone);
for I := 1 to High(ShortCuts) do Proc(ShortCutToText(ShortCuts[I]));
end;
procedure TShortCutProperty.SetValue(const Value: string);
var
NewValue: TShortCut;
begin
NewValue := 0;
if (Value <> '') and (AnsiCompareText(Value, srNone) <> 0) then
begin
NewValue := TextToShortCut(Value);
if NewValue = 0 then
raise EPropertyError.CreateRes(@sInvalidPropertyValue);
end;
SetOrdValue(NewValue);
end;
{ TTabOrderProperty }
function TTabOrderProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paRevertable];
end;
{ TCaptionProperty }
function TCaptionProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paAutoUpdate];
end;
{ TImageListEditor }
procedure TImageListEditor.Edit;
begin
if EditImageList(Component as TImageList) and Assigned(Designer) then
Designer.Modified;
end;
procedure TImageListEditor.ExecuteVerb(Index: Integer);
begin
if EditImageList(Component as TImageList) and Assigned(Designer) then
Designer.Modified;
end;
function TImageListEditor.GetVerb(Index: Integer): string;
begin
Result := SImageListEditor;
end;
function TImageListEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ Clipboard routines }
procedure CopyStreamToClipboard(S: TStream);
var
T: TStringStream;
I: TValueType;
V: Integer;
begin
// Clipboard.Open;
// try
//Clipboard.SetFormat(SDelphiComponent, S);
S.Position := 0;
T := TStringStream.Create('');
try
repeat
S.Read(I, SizeOf(I));
S.Seek(-SizeOf(I), 1);
if I = vaNull then Break;
ObjectBinaryToText(S, T);
until False;
V := 0;
T.Write(V, 1);
Clipboard.AsText := T.DataString;
finally
T.Free;
end;
// finally
// Clipboard.Close;
// end;
end;
function GetClipboardStream: TMemoryStream;
var
S, T: TMemoryStream;
Format: string;
V: TValueType;
function AnotherObject(S: TStream): Boolean;
var
Buffer: array[0..255] of Char;
Position: Integer;
begin
Position := S.Position;
Buffer[S.Read(Buffer, SizeOf(Buffer))-1] := #0;
S.Position := Position;
Result := PossibleStream(Buffer);
end;
begin
Result := TMemoryStream.Create;
try
{if Clipboard.Provides(SDelphiComponent) then
Format := SDelphiComponent else}
Format := 'text/plain';
Clipboard.GetFormat(Format, Result);
Result.Position := 0;
Result.Size := StrLen(Result.Memory);
{if Format <> SDelphiComponent then
begin}
S := TMemoryStream.Create;
try
while AnotherObject(Result) do ObjectTextToBinary(Result, S);
V := vaNull;
S.Write(V, SizeOf(V));
T := Result;
Result := nil;
T.Free;
except
S.Free;
raise;
end;
Result := S;
Result.Position := 0;
{end;}
except
Result.Free;
raise;
end;
end;
{ TModalResultProperty }
const
ModalResults: array[mrNone..mrYesToAll] of string = (
'mrNone',
'mrOk',
'mrCancel',
'mrYes',
'mrNo',
'mrAbort',
'mrRetry',
'mrIgnore',
'mrAll',
'mrNoToAll',
'mrYesToAll');
function TModalResultProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paRevertable];
end;
function TModalResultProperty.GetValue: string;
var
CurValue: Longint;
begin
CurValue := GetOrdValue;
case CurValue of
Low(ModalResults)..High(ModalResults):
Result := ModalResults[CurValue];
else
Result := IntToStr(CurValue);
end;
end;
procedure TModalResultProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
for I := Low(ModalResults) to High(ModalResults) do Proc(ModalResults[I]);
end;
procedure TModalResultProperty.SetValue(const Value: string);
var
I: Integer;
begin
if Value = '' then
begin
SetOrdValue(0);
Exit;
end;
for I := Low(ModalResults) to High(ModalResults) do
if CompareText(ModalResults[I], Value) = 0 then
begin
SetOrdValue(I);
Exit;
end;
inherited SetValue(Value);
end;
{ TFileNameProperty }
procedure TFileNameProperty.GetDialogOptions(Dialog: TOpenDialog);
begin
Dialog.Filter := SAllFiles;
Dialog.Options := Dialog.Options + [ofFileMustExist];
end;
procedure TFileNameProperty.Edit;
var
OpenDialog: TOpenDialog;
begin
OpenDialog := TOpenDialog.Create(nil);
GetDialogOptions(OpenDialog);
if OpenDialog.Execute then
SetValue(OpenDialog.FileName);
OpenDialog.Free;
end;
function TFileNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paRevertable, paDialog, paMultiSelect];
end;
{ THTMLFileNameProperty }
resourcestring
sHTMLFilter = 'html files (*.htm *.html)';
procedure THTMLFileNameProperty.GetDialogOptions(Dialog: TOpenDialog);
begin
inherited GetDialogOptions(Dialog);
Dialog.Filter := sHTMLFilter;
end;
type
TBasicActionRecord = record
ActionClass: TBasicActionClass;
GroupId: Integer;
end;
TActionClassArray = array of TBasicActionRecord;
TActionClassesEntry = record
Category: string;
Actions: TActionClassArray;
Resource: TComponentClass;
end;
TActionClassesArray = array of TActionClassesEntry;
var
ActionClasses: TActionClassesArray = nil;
procedure RegActions(const ACategory: string;
const AClasses: array of TBasicActionClass; AResource: TComponentClass);
var
CategoryIndex, Len, I, J, NewClassCount: Integer;
NewClasses: array of TBasicActionClass;
Skip: Boolean;
S: string;
begin
{ Determine whether we're adding a new category, or adding to an existing one }
CategoryIndex := -1;
for I := Low(ActionClasses) to High(ActionClasses) do
if CompareText(ActionClasses[I].Category, ACategory) = 0 then
begin
CategoryIndex := I;
Break;
end;
{ Adding a new category }
if CategoryIndex = -1 then
begin
CategoryIndex := Length(ActionClasses);
SetLength(ActionClasses, CategoryIndex + 1);
end;
with ActionClasses[CategoryIndex] do
begin
SetLength(NewClasses, Length(AClasses));
{ Remove duplicate classes }
NewClassCount := 0;
for I := Low(AClasses) to High(AClasses) do
begin
Skip := False;
for J := Low(Actions) to High(Actions) do
if AClasses[I] = Actions[I].ActionClass then
begin
Skip := True;
Break;
end;
if not Skip then
begin
NewClasses[Low(NewClasses) + NewClassCount] := AClasses[I];
Inc(NewClassCount);
end;
end;
{ Pack NewClasses }
SetLength(NewClasses, NewClassCount);
SetString(S, PChar(ACategory), Length(ACategory));
Category := S;
Resource := AResource;
Len := Length(Actions);
SetLength(Actions, Len + Length(NewClasses));
for I := Low(NewClasses) to High(NewClasses) do
begin
RegisterNoIcon([NewClasses[I]]);
RegisterClass(NewClasses[I]);
with Actions[Len + I] do
begin
ActionClass := NewClasses[I];
GroupId := CurrentGroup;
end;
end;
end;
{ Notify all available designers of new TAction class }
if Assigned(NotifyActionListChange) then
NotifyActionListChange;
end;
procedure UnRegActions(const Classes: array of TBasicActionClass);//! far;
var
I, J, K: Integer;
LActionClass: TBasicActionClass;
begin
for I := Low(Classes) to High(Classes) do
begin
LActionClass := Classes[I];
for J := Low(ActionClasses) to High(ActionClasses) do
for K := Low(ActionClasses[J].Actions) to High(ActionClasses[J].Actions) do
with ActionClasses[J].Actions[K] do
if LActionClass = ActionClass then
begin
ActionClass := nil;
GroupId := -1;
end;
end;
if Assigned(NotifyActionListChange) then
NotifyActionListChange;
end;
procedure UnregisterActionGroup(AGroupId: Integer);
var
I, J: Integer;
begin
for I := Low(ActionClasses) to High(ActionClasses) do
for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do
with ActionClasses[I].Actions[J] do
if GroupId = AGroupId then
begin
ActionClass := nil;
GroupId := -1;
end;
if Assigned(NotifyActionListChange) then
NotifyActionListChange;
end;
procedure EnumActions(Proc: TEnumActionProc; Info: Pointer);
var
I, J, Count: Integer;
ActionClass: TBasicActionClass;
begin
if ActionClasses <> nil then
for I := Low(ActionClasses) to High(ActionClasses) do
begin
Count := 0;
for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do
begin
ActionClass := ActionClasses[I].Actions[J].ActionClass;
if ActionClass = nil then
Continue;
Proc(ActionClasses[I].Category, ActionClass, Info);
Inc(Count);
end;
if Count = 0 then
SetLength(ActionClasses[I].Actions, 0);
end;
end;
type
THackAction = class(TCustomAction);
function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction;
var
I, J: Integer;
Res: TComponentClass;
Instance: TComponent;
Action: TBasicAction;
function FindComponentByClass(AOwner: TComponent; const AClassName: string): TComponent;
var
I: Integer;
begin
if (AClassName <> '') and (AOwner.ComponentCount > 0) then
for I := 0 to AOwner.ComponentCount - 1 do
begin
Result := AOwner.Components[I];
if CompareText(Result.ClassName, AClassName) = 0 then Exit;
end;
Result := nil;
end;
procedure CreateMaskedBmp(ImageList: TCustomImageList; ImageIndex: Integer;
var Image, Mask: TBitmap);
begin
Image := TBitmap.Create;
try
Mask := TBitmap.Create;
try
with Image do
begin
Height := ImageList.Height;
Width := ImageList.Width;
end;
with Mask do
begin
Height := ImageList.Height;
Width := ImageList.Width;
Monochrome := True;
end;
ImageList.Draw(Image.Canvas, 0, 0, ImageIndex);
ImageList.Draw(Mask.Canvas, 0, 0, ImageIndex, itMask);
except
FreeAndNil(Mask);
raise;
end;
except
FreeAndNil(Image);
raise
end;
end;
begin
Result := ActionClass.Create(AOwner);
{ Attempt to find the first action with the same class Type as ActionClass in
the Resource component's resource stream, and use its property values as
our defaults. }
Res := nil;
for I := Low(ActionClasses) to High(ActionClasses) do
with ActionClasses[I] do
for J := Low(Actions) to High(Actions) do
if Actions[J].ActionClass = ActionClass then
begin
Res := Resource;
Break;
end;
if Res <> nil then
begin
Instance := Res.Create(nil);
try
Action := FindComponentByClass(Instance, ActionClass.ClassName) as TBasicAction;
if Action <> nil then
begin
with Action as TCustomAction do
begin
TCustomAction(Result).Caption := Caption;
TCustomAction(Result).Checked := Checked;
TCustomAction(Result).Enabled := Enabled;
TCustomAction(Result).HelpContext := HelpContext;
TCustomAction(Result).Hint := Hint;
TCustomAction(Result).ImageIndex := ImageIndex;
TCustomAction(Result).ShortCut := ShortCut;
TCustomAction(Result).Visible := Visible;
if (ImageIndex > -1) and (ActionList <> nil) and
(ActionList.Images <> nil) then
begin
THackAction(Result).FImage.Free;
THackAction(Result).FMask.Free;
CreateMaskedBmp(ActionList.Images, ImageIndex,
TBitmap(THackAction(Result).FImage),
TBitmap(THackAction(Result).FMask));
end;
end;
end;
finally
Instance.Free;
end;
end;
end;
{ TAlignProperty }
procedure TAlignProperty.GetValues(Proc: TGetStrProc);
function AlignNames(AAlign: TAlign): string;
begin
if AAlign in [AlNone..alClient] then
Result := GetEnumName(TypeInfo(TAlign), Ord(AAlign));
end;
var
AAlign: TAlign;
begin
for AAlign := alNone to alClient do Proc(AlignNames(AAlign));
end;
initialization
NotifyGroupChange(UnregisterActionGroup);
finalization
UnNotifyGroupChange(UnregisterActionGroup);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC script console output }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.ConsoleUI.Script;
interface
implementation
uses
System.Classes, System.SysUtils,
FireDAC.Stan.Factory, FireDAC.Stan.Consts,
FireDAC.UI.Intf, FireDAC.UI;
{-------------------------------------------------------------------------------}
{- TFDGUIxConsoleScriptImpl -}
{-------------------------------------------------------------------------------}
type
TFDGUIxConsoleScriptImpl = class(TFDGUIxScriptImplBase)
protected
// IFDGUIxScriptDialog
procedure Show; override;
procedure Progress(const AInfoProvider: IFDGUIxScriptDialogInfoProvider); override;
procedure Output(const AStr: String; AKind: TFDScriptOutputKind); override;
procedure Input(const APrompt: String; var AResult: String); override;
procedure Pause(const APrompt: String); override;
procedure Hide; override;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxConsoleScriptImpl.Show;
begin
if FDGUIxSilent() then
Exit;
if Assigned(FOnShow) then
FOnShow(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxConsoleScriptImpl.Progress(
const AInfoProvider: IFDGUIxScriptDialogInfoProvider);
begin
if FDGUIxSilent() then
Exit;
if Assigned(FOnProgress) then
FOnProgress(Self, AInfoProvider as TObject);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxConsoleScriptImpl.Output(const AStr: String; AKind: TFDScriptOutputKind);
begin
if FDGUIxSilent() then
Exit;
if Assigned(FOnOutput) then
FOnOutput(Self, AStr);
Writeln(AStr);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxConsoleScriptImpl.Input(const APrompt: String; var AResult: String);
begin
if FDGUIxSilent() then
Exit;
if APrompt <> '' then
Writeln(APrompt);
if Assigned(FOnInput) then
FOnInput(Self, APrompt, AResult);
Readln(AResult);
Writeln;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxConsoleScriptImpl.Pause(const APrompt: String);
begin
if FDGUIxSilent() then
Exit;
if APrompt <> '' then
Writeln(APrompt)
else
Writeln('Press Enter to continue ...');
if Assigned(FOnPause) then
FOnPause(Self, APrompt);
Readln;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxConsoleScriptImpl.Hide;
begin
if FDGUIxSilent() then
Exit;
if Assigned(FOnHide) then
FOnHide(Self);
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDSingletonFactory.Create(TFDGUIxConsoleScriptImpl,
IFDGUIxScriptDialog, C_FD_GUIxConsoleProvider);
finalization
FDReleaseFactory(oFact);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.InfxDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf;
type
// TFDPhysInfxConnectionDefParams
// Generated for: FireDAC Infx driver
TFDInfxStringFormat = (sfUnicode, sfANSI);
TFDInfxTxSupported = (tsYes, tsNo, tsChoose);
/// <summary> TFDPhysInfxConnectionDefParams class implements FireDAC Infx driver specific connection definition class. </summary>
TFDPhysInfxConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetODBCAdvanced: String;
procedure SetODBCAdvanced(const AValue: String);
function GetLoginTimeout: Integer;
procedure SetLoginTimeout(const AValue: Integer);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetCharacterSet: String;
procedure SetCharacterSet(const AValue: String);
function GetDBCharacterSet: String;
procedure SetDBCharacterSet(const AValue: String);
function GetStringFormat: TFDInfxStringFormat;
procedure SetStringFormat(const AValue: TFDInfxStringFormat);
function GetReadTimeout: Integer;
procedure SetReadTimeout(const AValue: Integer);
function GetWriteTimeout: Integer;
procedure SetWriteTimeout(const AValue: Integer);
function GetTxSupported: TFDInfxTxSupported;
procedure SetTxSupported(const AValue: TFDInfxTxSupported);
function GetTxRetainLocks: Boolean;
procedure SetTxRetainLocks(const AValue: Boolean);
function GetTxLastCommitted: Boolean;
procedure SetTxLastCommitted(const AValue: Boolean);
function GetMetaDefCatalog: String;
procedure SetMetaDefCatalog(const AValue: String);
function GetMetaDefSchema: String;
procedure SetMetaDefSchema(const AValue: String);
function GetMetaCurCatalog: String;
procedure SetMetaCurCatalog(const AValue: String);
function GetMetaCurSchema: String;
procedure SetMetaCurSchema(const AValue: String);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property ODBCAdvanced: String read GetODBCAdvanced write SetODBCAdvanced stored False;
property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False;
property Server: String read GetServer write SetServer stored False;
property CharacterSet: String read GetCharacterSet write SetCharacterSet stored False;
property DBCharacterSet: String read GetDBCharacterSet write SetDBCharacterSet stored False;
property StringFormat: TFDInfxStringFormat read GetStringFormat write SetStringFormat stored False default sfANSI;
property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout stored False;
property WriteTimeout: Integer read GetWriteTimeout write SetWriteTimeout stored False;
property TxSupported: TFDInfxTxSupported read GetTxSupported write SetTxSupported stored False default tsYes;
property TxRetainLocks: Boolean read GetTxRetainLocks write SetTxRetainLocks stored False default True;
property TxLastCommitted: Boolean read GetTxLastCommitted write SetTxLastCommitted stored False default True;
property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False;
property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False;
property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False;
property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysInfxConnectionDefParams
// Generated for: FireDAC Infx driver
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetODBCAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetODBCAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetLoginTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetLoginTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetCharacterSet: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_CharacterSet];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetCharacterSet(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_CharacterSet] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetDBCharacterSet: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Infx_DBCharacterSet];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetDBCharacterSet(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Infx_DBCharacterSet] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetStringFormat: TFDInfxStringFormat;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_Infx_StringFormat];
if CompareText(s, 'Unicode') = 0 then
Result := sfUnicode
else if CompareText(s, 'ANSI') = 0 then
Result := sfANSI
else
Result := sfANSI;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetStringFormat(const AValue: TFDInfxStringFormat);
const
C_StringFormat: array[TFDInfxStringFormat] of String = ('Unicode', 'ANSI');
begin
FDef.AsString[S_FD_ConnParam_Infx_StringFormat] := C_StringFormat[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetReadTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Infx_ReadTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetReadTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Infx_ReadTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetWriteTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Infx_WriteTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetWriteTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Infx_WriteTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetTxSupported: TFDInfxTxSupported;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_Infx_TxSupported];
if CompareText(s, 'Yes') = 0 then
Result := tsYes
else if CompareText(s, 'No') = 0 then
Result := tsNo
else if CompareText(s, 'Choose') = 0 then
Result := tsChoose
else
Result := tsYes;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetTxSupported(const AValue: TFDInfxTxSupported);
const
C_TxSupported: array[TFDInfxTxSupported] of String = ('Yes', 'No', 'Choose');
begin
FDef.AsString[S_FD_ConnParam_Infx_TxSupported] := C_TxSupported[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetTxRetainLocks: Boolean;
begin
if not FDef.HasValue(S_FD_ConnParam_Infx_TxRetainLocks) then
Result := True
else
Result := FDef.AsYesNo[S_FD_ConnParam_Infx_TxRetainLocks];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetTxRetainLocks(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_Infx_TxRetainLocks] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetTxLastCommitted: Boolean;
begin
if not FDef.HasValue(S_FD_ConnParam_Infx_TxLastCommitted) then
Result := True
else
Result := FDef.AsYesNo[S_FD_ConnParam_Infx_TxLastCommitted];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetTxLastCommitted(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_Infx_TxLastCommitted] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetMetaDefCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetMetaDefCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetMetaDefSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetMetaDefSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetMetaCurCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetMetaCurCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysInfxConnectionDefParams.GetMetaCurSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysInfxConnectionDefParams.SetMetaCurSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue;
end;
end.
|
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, cefvcl, ActnList, Buttons, ExtCtrls;
type
TMainForm = class(TForm)
pages: TPageControl;
actnLst: TActionList;
actGoBack: TAction;
actGoForward: TAction;
actNewTab: TAction;
actGo: TAction;
actCloseTab: TAction;
actRefresh: TAction;
SpeedButton1: TSpeedButton;
actChangeTab: TAction;
saveDlg: TSaveDialog;
procedure FormCreate(Sender: TObject);
procedure openUrlInNewTab(url: string);
procedure openUrl(url: string);
procedure OpenNewTab;
function getActiveBrowser(): TChromium;
function getActiveForm(): TForm;
procedure actGoBackExecute(Sender: TObject);
procedure actGoForwardExecute(Sender: TObject);
procedure actNewTabExecute(Sender: TObject);
procedure actGoExecute(Sender: TObject);
procedure actCloseTabExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure pagesMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pagesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pagesDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure pagesDragDrop(Sender, Source: TObject; X, Y: Integer);
private
procedure setActivePage(ts: TTabSheet);
function getActivePage(): TTabSheet;
{ Private declarations }
public
property activePage: TTabSheet read getActivePage write setActivePage;
{ Public declarations }
end;
var
MF: TMainForm;
implementation
uses BrowserTab;
{$R *.dfm}
function TMainForm.getActiveForm(): TForm;
begin
Result := ActivePage.Controls[0] as TForm;
end;
procedure TMainForm.setActivePage(ts: TTabSheet);
begin
pages.ActivePage := ts;
end;
function TMainForm.getActivePage(): TTabSheet;
begin
Result := pages.ActivePage;
end;
function TMainForm.getActiveBrowser(): TChromium;
begin
Result := (getActivePage().Components[0] as TBrowserTab).Chromium1;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
openNewTab();
end;
procedure TMainForm.openUrlInNewTab(url: string);
var
sh: TTabSheet;
frmBT: TBrowserTab;
begin
sh := TTabSheet.Create(pages);
sh.PageControl := pages;
frmBT := TBrowserTab.Create(sh);
frmBT.Parent := sh;
sh.Parent := pages;
frmBT.BorderStyle := bsNone;
frmBT.Align := alClient;
frmBT.Show;
frmBT.Chromium1.Load(url);
end;
procedure TMainForm.openNewTab;
var
sh: TTabSheet;
frmBT: TBrowserTab;
begin
sh := TTabSheet.Create(pages);
sh.PageControl := pages;
frmBT := TBrowserTab.Create(sh);
frmBT.Parent := sh;
sh.Parent := pages;
frmBT.BorderStyle := bsNone;
frmBT.Align := alClient;
frmBT.Show;
activePage := sh;
end;
procedure TMainForm.openUrl(url: string);
begin
getActiveBrowser().Load(url);
end;
procedure TMainForm.actGoBackExecute(Sender: TObject);
begin
getActiveBrowser.Browser.GoBack;
end;
procedure TMainForm.actGoForwardExecute(Sender: TObject);
begin
getActiveBrowser.Browser.GoForward;
end;
procedure TMainForm.actNewTabExecute(Sender: TObject);
begin
openNewTab();
end;
procedure TMainForm.actGoExecute(Sender: TObject);
begin
openUrl((getActivePage().Components[0] as TBrowserTab).addressBar.Text);
end;
procedure TMainForm.actCloseTabExecute(Sender: TObject);
var
i: integer;
j: integer;
begin
i := pages.ActivePageIndex;
j := -1;
if i = 0 then
begin
j := 1;
end;
if i + j > pages.PageCount - 1 then
begin
close;
end;
activePage := pages.Pages[i+j];
pages.pages[i].Free;
end;
procedure TMainForm.actRefreshExecute(Sender: TObject);
begin
getActiveBrowser().Browser.Reload;
end;
procedure TMainForm.pagesMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if button = mbMiddle then
begin
actCloseTab.Execute;
end;
end;
procedure TMainForm.pagesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
pages.BeginDrag(False);
end;
end;
procedure TMainForm.pagesDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
if (Sender is TPageControl) then Accept := True;
end;
procedure TMainForm.pagesDragDrop(Sender, Source: TObject; X, Y: Integer);
const
TCM_GETITEMRECT = $130A;
var
TabRect: TRect;
j: Integer;
begin
if (Sender is TPageControl) then
for j := 0 to pages.PageCount - 1 do
begin
pages.Perform(TCM_GETITEMRECT, j, LParam(@TabRect)) ;
if PtInRect(TabRect, Point(X, Y)) then
begin
if pages.ActivePage.PageIndex <> j then
pages.ActivePage.PageIndex := j;
Exit;
end;
end;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, rxdbgrid, rxmemds, Forms, Controls, Graphics, DBGrids,
Dialogs, StdCtrls, ExtCtrls, db;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
CheckBox1: TCheckBox;
dsData: TDataSource;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Panel1: TPanel;
rxDataID_R: TLongintField;
rxDataMEMO: TMemoField;
RxDBGrid1: TRxDBGrid;
rxData: TRxMemoryData;
rxDataCODE: TLongintField;
rxDataID: TLongintField;
rxDataNAME: TStringField;
Splitter1: TSplitter;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure rxDataAfterInsert(DataSet: TDataSet);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
rxData.Open;
for i:=1 to 20 do
begin
rxData.AppendRecord([i, i mod 4, Format('Line %d', [i]), i, 'Строка МЕМО ' + IntToStr(i div 2)]);
if i mod 5 = 0 then
rxData.AppendRecord([null, null, 'Пустая строка']);
end;
rxData.First;
Label1.Caption:='';
Label2.Caption:='';
Label3.Caption:='';
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption:=RxDBGrid1.ColumnByFieldName('CODE').Filter.CurrentValues.Text;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Label2.Caption:=RxDBGrid1.ColumnByFieldName('NAME').Filter.CurrentValues.Text;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Label3.Caption:=RxDBGrid1.ColumnByFieldName('ID_R').Filter.CurrentValues.Text;
end;
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
if CheckBox1.Checked then
RxDBGrid1.Options:=RxDBGrid1.Options + [dgDisplayMemoText]
else
RxDBGrid1.Options:=RxDBGrid1.Options - [dgDisplayMemoText];
end;
procedure TForm1.rxDataAfterInsert(DataSet: TDataSet);
begin
rxDataID_R.AsInteger:=rxData.RecordCount + 1;
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Streams;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils, System.RTLConsts,
{$IFDEF MSWINDOWS}WinApi.Windows,{$ENDIF MSWINDOWS}
{$IFDEF POSIX}Posix.UniStd,{$ENDIF POSIX}
{$ELSE}
Classes, SysUtils, RTLConsts,
{$IFDEF MSWINDOWS}Windows,{$ENDIF MSWINDOWS}
{$IFDEF POSIX}Posix,{$ENDIF POSIX}
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Collections.Intf,
ADAPT.Comparers.Intf,
ADAPT.Streams.Intf, ADAPT.Streams.Abstract;
{$I ADAPT_RTTI.inc}
type
{ Forward Declarations }
TADHandleStreamCaret = class;
TADHandleStream = class;
TADFileStreamCaret = class;
TADFileStream = class;
TADMemoryStreamCaret = class;
TADMemoryStream = class;
/// <summary><c>Caret specifically set up for Handle Streams.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADHandleStreamCaret = class(TADStreamCaret)
protected
FHandle: THandle;
{ IADStreamCaret }
function GetPosition: Int64; override;
procedure SetPosition(const APosition: Int64); override;
public
constructor Create(const AStream: IADStream; const AHandle: THandle); reintroduce; overload;
constructor Create(const AStream: IADStream; const AHandle: THandle; const APosition: Int64); reintroduce; overload;
{ IADStreamCaret }
function Delete(const ALength: Int64): Int64; override;
function Insert(const ABuffer; const ALength: Int64): Int64; override;
function Read(var ABuffer; const ALength: Int64): Int64; override;
function Write(const ABuffer; const ALength: Int64): Int64; override;
function Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64; override;
end;
/// <summary><c>Specialized Stream Type for Handle Streams.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADHandleStream = class(TADStream)
protected
FHandle: THandle;
{ IADStream }
function GetSize: Int64; override;
procedure SetSize(const ASize: Int64); override;
{ Internal Methods }
function MakeNewCaret: IADStreamCaret; override;
public
constructor Create(const AHandle: THandle); reintroduce; overload;
constructor Create(const AStream: THandleStream); reintroduce; overload;
{ IADStream }
procedure LoadFromFile(const AFileName: String); override;
procedure LoadFromStream(const AStream: IADStream); overload; override;
procedure LoadFromStream(const AStream: TStream); overload; override;
procedure SaveToFile(const AFileName: String); override;
procedure SaveToStream(const AStream: IADStream); overload; override;
procedure SaveToStream(const AStream: TStream); overload; override;
end;
/// <summary><c>Caret specifically set up for File Streams.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADFileStreamCaret = class(TADHandleStreamCaret); // Nothing needs overriding here... isn't that beautiful?
/// <summary><c>Specialized Stream Type for File Streams.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADFileStream = class(TADHandleStream)
private
FAdoptedHandle: Boolean;
FFileName: String;
protected
{ Internal Methods }
function MakeNewCaret: IADStreamCaret; override;
public
constructor Create(const AFileName: String; const AMode: Word); reintroduce; overload;
constructor Create(const AFileName: String; const AMode: Word; const ARights: Cardinal); reintroduce; overload;
constructor Create(const AStream: TFileStream); reintroduce; overload;
destructor Destroy; override;
end;
/// <summary><c>Caret specifically set up for Memory Streams.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADMemoryStreamCaret = class(TADStreamCaret)
private
FMemory: Pointer;
protected
function GetMemoryStream: IADMemoryStream;
{ IADStreamCaret }
function GetPosition: Int64; override;
procedure SetPosition(const APosition: Int64); override;
public
{ IADStreamCaret }
function Delete(const ALength: Int64): Int64; override;
function Insert(const ABuffer; const ALength: Int64): Int64; override;
function Read(var ABuffer; const ALength: Int64): Int64; override;
function Write(const ABuffer; const ALength: Int64): Int64; override;
function Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64; override;
end;
/// <summary><c>Specialized Stream Type for Memory Streams.</c></summary>
/// <remarks>
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADMemoryStream = class(TADStream, IADMemoryStream)
private
FCapacity: Int64;
FMemory: Pointer;
FSize: Int64;
procedure SetPointer(const APointer: Pointer; const ASize: Int64);
protected
{ IADMemoryStream }
function GetCapacity: Int64; virtual;
procedure SetCapacity(ACapacity: Int64); virtual;
function Realloc(var ACapacity: Int64): Pointer; virtual;
{ IADStream }
function GetSize: Int64; override;
procedure SetSize(const ASize: Int64); override;
{ Internal Methods }
function MakeNewCaret: IADStreamCaret; override;
public
constructor Create; overload; override;
constructor Create(const AStream: TCustomMemoryStream); reintroduce; overload;
destructor Destroy; override;
procedure LoadFromFile(const AFileName: String); override;
procedure LoadFromStream(const AStream: IADStream); overload; override;
procedure LoadFromStream(const AStream: TStream); overload; override;
procedure SaveToFile(const AFileName: String); override;
procedure SaveToStream(const AStream: IADStream); overload; override;
procedure SaveToStream(const AStream: TStream); overload; override;
end;
function ADStreamCaretComparer: IADComparer<IADStreamCaret>;
implementation
uses
ADAPT.Comparers;
{$I ADAPT_RTTI.inc}
var
GStreamCaretComparer: IADComparer<IADStreamCaret>;
function ADStreamCaretComparer: IADComparer<IADStreamCaret>;
begin
Result := GStreamCaretComparer;
end;
{ TADHandleStreamCaret }
constructor TADHandleStreamCaret.Create(const AStream: IADStream; const AHandle: THandle);
begin
inherited Create(AStream);
FHandle := AHandle;
end;
constructor TADHandleStreamCaret.Create(const AStream: IADStream; const AHandle: THandle; const APosition: Int64);
begin
Create(AStream, AHandle);
SetPosition(APosition);
end;
function TADHandleStreamCaret.Delete(const ALength: Int64): Int64;
var
LStartPosition, LSize: Int64;
LValue: TBytes;
begin
inherited;
LStartPosition := Position;
LSize := GetStream.Size;
if GetStream.Size > Position + ALength then
begin
SetLength(LValue, LSize - ALength);
Position := Position + ALength;
Read(LValue[0], LSize - ALength);
Position := LStartPosition;
Write(LValue[0], ALength);
end;
GetStream.Size := LSize - ALength;
// Invalidate the Carets representing the Bytes we've deleted
GetStreamManagement.InvalidateCarets(LStartPosition, ALength);
// Shift subsequent Carets to the left
GetStreamManagement.ShiftCaretsLeft(LStartPosition + ALength, LSize - (LStartPosition + ALength));
if LStartPosition < GetStream.Size then // If this Caret is still in range...
Position := LStartPosition // ...set this Caret's position back to where it began
else // otherwise, if this Caret is NOT in range...
Invalidate; // ...invalidate this Caret
Result := ALength;
end;
function TADHandleStreamCaret.GetPosition: Int64;
begin
Result := FPosition;
end;
function TADHandleStreamCaret.Insert(const ABuffer; const ALength: Int64): Int64;
var
I, LStartPosition, LNewSize: Int64;
LByte: Byte;
begin
Result := inherited;
LStartPosition := FPosition;
// Expand the Stream
LNewSize := GetStream.Size + ALength;
GetStream.Size := LNewSize;
// Move subsequent Bytes to the Right
I := LStartPosition;
repeat
Seek(I, soBeginning); // Navigate to the Byte
Read(LByte, 1); // Read this byte
Seek(I + ALength + 1, soBeginning); // Navigate to this Byte's new location
Write(LByte, 1); // Write this byte
Inc(I); // On to the next
Inc(Result);
until I > LNewSize;
// Insert the Value
Position := LStartPosition;
Write(ABuffer, ALength);
// Shift overlapping Carets to the Right
GetStreamManagement.ShiftCaretsRight(LStartPosition, ALength);
Position := LStartPosition + ALength;
end;
function TADHandleStreamCaret.Read(var ABuffer; const ALength: Int64): Int64;
begin
inherited;
Seek(FPosition, soBeginning);
Result := FileRead(FHandle, ABuffer, ALength);
if Result = -1 then
Result := 0
else
Inc(FPosition, ALength);
end;
function TADHandleStreamCaret.Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64;
begin
inherited;
Result := FileSeek(FHandle, AOffset, Ord(AOrigin));
end;
procedure TADHandleStreamCaret.SetPosition(const APosition: Int64);
begin
FPosition := APosition;
end;
function TADHandleStreamCaret.Write(const ABuffer; const ALength: Int64): Int64;
var
LStartPosition: Int64;
begin
inherited;
LStartPosition := FPosition;
Seek(FPosition, soBeginning);
Result := FileWrite(FHandle, ABuffer, ALength);
if Result = -1 then
Result := 0
else begin
Inc(FPosition, ALength);
GetStreamManagement.InvalidateCarets(LStartPosition, ALength);
end;
end;
{ TADHandleStream }
constructor TADHandleStream.Create(const AHandle: THandle);
begin
FHandle := AHandle;
inherited Create;
end;
constructor TADHandleStream.Create(const AStream: THandleStream);
begin
Create(AStream.Handle);
end;
function TADHandleStream.GetSize: Int64;
var
LPos: Int64;
begin
LPos := FileSeek(FHandle, 0, Ord(soCurrent));
Result := FileSeek(FHandle, 0, Ord(soEnd));
FileSeek(FHandle, LPos, Ord(soBeginning));
end;
procedure TADHandleStream.LoadFromFile(const AFileName: String);
var
LStream: IADStream;
begin
LStream := TADFileStream.Create(AFileName, fmOpenRead);
LoadFromStream(LStream);
end;
procedure TADHandleStream.LoadFromStream(const AStream: TStream);
var
LWriteCaret: IADStreamCaret;
I: Int64;
LValue: Byte;
begin
AStream.Position := 0;
Size := AStream.Size;
LWriteCaret := NewCaret;
I := 0;
repeat
AStream.Read(LValue, 1);
LWriteCaret.Write(LValue, 1);
until I > AStream.Size;
end;
procedure TADHandleStream.LoadFromStream(const AStream: IADStream);
var
LReadCaret, LWriteCaret: IADStreamCaret;
I: Int64;
LValue: Byte;
begin
Size := AStream.Size;
LReadCaret := AStream.NewCaret;
LWriteCaret := NewCaret;
I := 0;
repeat
LReadCaret.Read(LValue, 1);
LWriteCaret.Write(LValue, 1);
Inc(I);
until I > AStream.Size;
end;
function TADHandleStream.MakeNewCaret: IADStreamCaret;
begin
Result := TADHandleStreamCaret.Create(Self, FHandle);
end;
procedure TADHandleStream.SaveToFile(const AFileName: String);
var
LStream: IADStream;
begin
LStream := TADFileStream.Create(AFileName, fmCreate);
SaveToStream(LStream);
end;
procedure TADHandleStream.SaveToStream(const AStream: TStream);
var
LReadCaret: IADStreamCaret;
I: Int64;
LValue: Byte;
begin
AStream.Size := 0;
I := 0;
repeat
LReadCaret.Read(LValue, 1);
AStream.Write(LValue, 1);
Inc(I);
until I > Size;
end;
procedure TADHandleStream.SaveToStream(const AStream: IADStream);
var
LReadCaret, LWriteCaret: IADStreamCaret;
I: Int64;
LValue: Byte;
begin
AStream.Size := 0;
LReadCaret := NewCaret;
LWriteCaret := AStream.NewCaret;
I := 0;
repeat
LReadCaret.Read(LValue, 1);
LWriteCaret.Write(LValue, 1);
Inc(I);
until I > Size;
end;
procedure TADHandleStream.SetSize(const ASize: Int64);
var
{$IFDEF POSIX}LPosition,{$ENDIF POSIX} LOldSize: Int64;
begin
LOldSize := GetSize;
{$IFDEF POSIX}LPosition := {$ENDIF POSIX}FileSeek(FHandle, ASize, Ord(soBeginning));
{$WARNINGS OFF} // We're handling platform-specifics here... we don't NEED platform warnings!
{$IF Defined(MSWINDOWS)}
Win32Check(SetEndOfFile(FHandle));
{$ELSEIF Defined(POSIX)}
if ftruncate(FHandle, LPosition) = -1 then
raise EStreamError(sStreamSetSize);
{$ELSE}
{$FATAL 'No implementation for this platform! Please report this issue on https://github.com/LaKraven/LKSL'}
{$ENDIF}
{$WARNINGS ON}
if ASize < LOldSize then
InvalidateCarets(LOldSize, ASize - LOldSize);
end;
{ TADFileStream }
constructor TADFileStream.Create(const AFileName: String; const AMode: Word);
begin
Create(AFilename, AMode, 0);
end;
constructor TADFileStream.Create(const AFileName: String; const AMode: Word; const ARights: Cardinal);
var
LShareMode: Word;
begin
FAdoptedHandle := False;
if (AMode and fmCreate = fmCreate) then
begin
LShareMode := AMode and $FF;
if LShareMode = $FF then
LShareMode := fmShareExclusive;
inherited Create(FileCreate(AFileName, LShareMode, ARights));
if FHandle = INVALID_HANDLE_VALUE then
raise EFCreateError.CreateResFmt(@SFCreateErrorEx, [ExpandFileName(AFileName), SysErrorMessage(GetLastError)]);
end
else
begin
inherited Create(FileOpen(AFileName, AMode));
if FHandle = INVALID_HANDLE_VALUE then
raise EFOpenError.CreateResFmt(@SFOpenErrorEx, [ExpandFileName(AFileName), SysErrorMessage(GetLastError)]);
end;
FFileName := AFileName;
end;
constructor TADFileStream.Create(const AStream: TFileStream);
begin
inherited Create(AStream.Handle);
FAdoptedHandle := True;
end;
destructor TADFileStream.Destroy;
begin
if (FHandle <> INVALID_HANDLE_VALUE) and (not FAdoptedHandle) then
FileClose(FHandle);
inherited;
end;
function TADFileStream.MakeNewCaret: IADStreamCaret;
begin
Result := TADFileStreamCaret.Create(Self, FHandle);
end;
{ TADMemoryStreamCaret }
function TADMemoryStreamCaret.Delete(const ALength: Int64): Int64;
begin
// Shift elements after Position + Length back to Position
if FPosition + ALength < GetStream.Size then
System.Move(
(PByte(FMemory) + FPosition + ALength)^,
(PByte(FMemory) + FPosition)^,
GetStream.Size - (FPosition + ALength)
);
// Dealloc Memory
GetStream.Size := GetStream.Size - ALength;
// Invalidate the Carets representing the Bytes we've deleted
GetStreamManagement.InvalidateCarets(FPosition, ALength);
// Shift subsequent Carets to the left
GetStreamManagement.ShiftCaretsLeft(FPosition + ALength, ALength - (FPosition + ALength));
Result := ALength;
end;
function TADMemoryStreamCaret.GetMemoryStream: IADMemoryStream;
begin
Result := GetStream as IADMemoryStream;
end;
function TADMemoryStreamCaret.GetPosition: Int64;
begin
Result := FPosition;
end;
function TADMemoryStreamCaret.Insert(const ABuffer; const ALength: Int64): Int64;
var
LStartPosition: Int64;
begin
LStartPosition := FPosition;
GetStream.Size := GetStream.Size + ALength;
// Shift subsequent Bytes to the Right
System.Move(
(PByte(FMemory) + FPosition)^,
(PByte(FMemory) + FPosition + ALength)^,
GetStream.Size - (FPosition + ALength)
);
// Write the Data
Write(ABuffer, ALength);
// Shift subsequent Carets to the Right
GetStreamManagement.ShiftCaretsRight(LStartPosition, (GetStream.Size - ALength) - LStartPosition);
Result := ALength;
end;
function TADMemoryStreamCaret.Read(var ABuffer; const ALength: Int64): Int64;
begin
Result := 0;
if (FPosition < 0) or (ALength < 0) then
Exit;
Result := GetStream.Size - FPosition;
if Result > 0 then
begin
if Result > ALength then Result := ALength;
System.Move((PByte(FMemory) + FPosition)^, ABuffer, Result);
Inc(FPosition, Result);
end;
end;
function TADMemoryStreamCaret.Seek(const AOffset: Int64; const AOrigin: TSeekOrigin): Int64;
begin
case AOrigin of
soBeginning: Result := AOffset;
soCurrent: Result := FPosition + AOffset;
soEnd: Result := GetStream.Size - AOffset;
else
Result := FPosition;
end;
FPosition := Result;
end;
procedure TADMemoryStreamCaret.SetPosition(const APosition: Int64);
begin
FPosition := APosition;
end;
function TADMemoryStreamCaret.Write(const ABuffer; const ALength: Int64): Int64;
var
LPos: Int64;
begin
Result := 0;
LPos := FPosition + ALength;
if (FPosition < 0) or (ALength < 0) or (LPos <= 0) then
Exit;
if LPos > GetStream.Size then
begin
if LPos > GetMemoryStream.Capacity then
GetMemoryStream.Capacity := LPos;
GetStream.Size := LPos;
end;
System.Move(ABuffer, (PByte(FMemory) + FPosition)^, ALength);
FPosition := LPos;
Result := ALength;
end;
{ TADMemoryStream }
constructor TADMemoryStream.Create;
begin
inherited;
SetCapacity(0);
FSize := 0;
end;
constructor TADMemoryStream.Create(const AStream: TCustomMemoryStream);
begin
Create;
FMemory := AStream.Memory;
end;
destructor TADMemoryStream.Destroy;
begin
SetCapacity(0);
FSize := 0;
inherited;
end;
function TADMemoryStream.GetCapacity: Int64;
begin
Result := FCapacity;
end;
function TADMemoryStream.GetSize: Int64;
begin
Result := FSize;
end;
procedure TADMemoryStream.LoadFromFile(const AFileName: String);
var
LStream: IADStream;
begin
LStream := TADFileStream.Create(AFileName, fmOpenRead);
LoadFromStream(LStream);
end;
procedure TADMemoryStream.LoadFromStream(const AStream: TStream);
begin
AStream.Position := 0;
Size := AStream.Size;
AStream.Read(FMemory^, AStream.Size);
end;
procedure TADMemoryStream.LoadFromStream(const AStream: IADStream);
var
LReadCaret: IADStreamCaret;
begin
Size := AStream.Size;
LReadCaret := AStream.NewCaret;
LReadCaret.Read(FMemory^, AStream.Size);
end;
function TADMemoryStream.MakeNewCaret: IADStreamCaret;
begin
Result := TADMemoryStreamCaret.Create(Self);
end;
function TADMemoryStream.Realloc(var ACapacity: Int64): Pointer;
const
MemoryDelta = $2000;
begin
Result := nil;
if (ACapacity > 0) and (ACapacity <> GetSize) then
ACapacity := (ACapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
Result := FMemory;
if ACapacity <> FCapacity then
begin
if ACapacity = 0 then
begin
FreeMem(FMemory);
Result := nil;
end else
begin
if FCapacity = 0 then
GetMem(Result, ACapacity)
else
ReallocMem(Result, ACapacity);
if Result = nil then raise EStreamError.CreateRes(@SMemoryStreamError);
end;
end;
end;
procedure TADMemoryStream.SaveToFile(const AFileName: String);
var
LStream: IADStream;
begin
LStream := TADFileStream.Create(AFileName, fmCreate);
SaveToStream(LStream);
end;
procedure TADMemoryStream.SaveToStream(const AStream: TStream);
begin
if FSize > 0 then
AStream.WriteBuffer(FMemory^, FSize);
end;
procedure TADMemoryStream.SaveToStream(const AStream: IADStream);
var
LCaret: IADStreamCaret;
begin
if FSize > 0 then
begin
LCaret := AStream.NewCaret;
LCaret.Write(FMemory^, FSize);
end;
end;
procedure TADMemoryStream.SetCapacity(ACapacity: Int64);
begin
SetPointer(Realloc(ACapacity), FSize);
FCapacity := ACapacity;
end;
procedure TADMemoryStream.SetPointer(const APointer: Pointer; const ASize: Int64);
begin
FMemory := APointer;
FSize := ASize;
end;
procedure TADMemoryStream.SetSize(const ASize: Int64);
var
LOldSize: Longint;
begin
LOldSize := FSize;
SetCapacity(ASize);
FSize := ASize;
if ASize < LOldSize then
InvalidateCarets(LOldSize, ASize - LOldSize);
end;
initialization
GStreamCaretComparer := TADInterfaceComparer<IADStreamCaret>.Create;
end.
|
{
Subscribing to all topics and printing out incoming messages
Simple test code for the libmosquitto C API interface unit
Copyright (c) 2019 Karoly Balogh <charlie@amigaspirit.hu>
See the LICENSE file for licensing details.
}
program test;
uses
mosquitto, ctypes;
const
MQTT_HOST = 'localhost';
MQTT_PORT = 1883;
var
major, minor, revision: cint;
mq: Pmosquitto;
procedure mqtt_on_log(mosq: Pmosquitto; obj: pointer; level: cint; const str: pchar); cdecl;
begin
writeln(str);
end;
procedure mqtt_on_message(mosq: Pmosquitto; obj: pointer; const message: Pmosquitto_message); cdecl;
var
msg: ansistring;
begin
msg:='';
with message^ do
begin
{ Note that MQTT messages can be binary, but for this test case
we just assume they're printable text }
SetLength(msg,payloadlen);
Move(payload^,msg[1],payloadlen);
writeln('Topic: [',topic,'] - Message: [',msg,']');
end;
end;
{ Here we really just use libmosquitto's C API directly, so see its documentation. }
begin
if mosquitto_lib_init <> MOSQ_ERR_SUCCESS then
begin
writeln('Failed.');
halt(1);
end;
mosquitto_lib_version(@major,@minor,@revision);
writeln('Running against libmosquitto ',major,'.',minor,'.',revision);
mq:=mosquitto_new(nil, true, nil);
if assigned(mq) then
begin
mosquitto_log_callback_set(mq, @mqtt_on_log);
mosquitto_message_callback_set(mq, @mqtt_on_message);
mosquitto_connect(mq, MQTT_HOST, MQTT_PORT, 60);
mosquitto_subscribe(mq, nil, '#', 1);
while mosquitto_loop(mq, 100, 1) = MOSQ_ERR_SUCCESS do
begin
{ This should ideally handle some keypress or something... }
end;
mosquitto_disconnect(mq);
mosquitto_destroy(mq);
mq:=nil;
end
else
writeln('ERROR: Cannot create a mosquitto instance.');
mosquitto_lib_cleanup;
end.
|
unit dlg_ProrataNewUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Mask;
type
Tdlg_ProrataNew = class(TForm)
gb_ProrataYear: TGroupBox;
Label5: TLabel;
Label6: TLabel;
ed_ProrataYear: TEdit;
gb_OtherInformation: TGroupBox;
Label1: TLabel;
cb_Category: TComboBox;
Label2: TLabel;
ed_EffectiveDate: TMaskEdit;
ed_RemovalDate: TMaskEdit;
Label3: TLabel;
Label4: TLabel;
ed_CalculationDate: TMaskEdit;
OKButton: TBitBtn;
CancelButton: TBitBtn;
procedure FormShow(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure ed_ProrataYearExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ProrataYear, Category : String;
EffectiveDate, RemovalDate, CalculationDate : TDateTime;
end;
implementation
{$R *.DFM}
uses GlblCnst, GlblVars;
{=========================================================================}
Procedure Tdlg_ProrataNew.FormShow(Sender: TObject);
begin
ed_ProrataYear.Text := ProrataYear;
ed_CalculationDate.Text := DateToStr(Date);
end; {FormShow}
{=========================================================================}
Procedure Tdlg_ProrataNew.FormKeyPress(Sender: TObject; var Key: Char);
begin
If (Key = #13)
then
begin
Perform(WM_NextDlgCtl, 0, 0);
Key := #0;
end; {If (Key = #13)}
end; {FormKeyPress}
{=========================================================================}
Procedure Tdlg_ProrataNew.ed_ProrataYearExit(Sender: TObject);
begin
cb_Category.SetFocus;
end;
{=========================================================================}
Procedure Tdlg_ProrataNew.OKButtonClick(Sender: TObject);
begin
ProrataYear := ed_ProrataYear.Text;
case cb_Category.ItemIndex of
0 : Category := mtfnCounty;
1 : case GlblMunicipalityType of
MTTown : Category := mtfnTown;
MTCity : Category := mtfnCity;
MTVillage : Category := mtfnVillage;
end;
2 : Category := mtfnSchool;
3 : Category := mtfnVillage;
else Category := mtfnTown;
end;
Category := ANSIUpperCase(Category);
try
EffectiveDate := StrToDate(ed_EffectiveDate.Text);
except
end;
try
RemovalDate := StrToDate(ed_RemovalDate.Text);
except
end;
try
CalculationDate := StrToDate(ed_CalculationDate.Text);
except
end;
ModalResult := mrOK;
end; {OKButtonClick}
end.
|
unit fNoteBD;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ORFN,
StdCtrls, ExtCtrls, ORCtrls, ORDtTm, uTIU, fBase508Form,
VA508AccessibilityManager;
type
TfrmNotesByDate = class(TfrmBase508Form)
pnlBase: TORAutoPanel;
lblBeginDate: TLabel;
calBeginDate: TORDateBox;
lblEndDate: TLabel;
calEndDate: TORDateBox;
radSort: TRadioGroup;
cmdOK: TButton;
cmdCancel: TButton;
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure calBeginDateKeyPress(Sender: TObject; var Key: Char);
procedure calEndDateKeyPress(Sender: TObject; var Key: Char);
private
FChanged: Boolean;
FBeginDate: string;
FFMBeginDate: TFMDateTime;
FEndDate: string;
FFMEndDate: TFMDateTime;
FAscending: Boolean;
end;
TNoteDateRange = record
Changed: Boolean;
BeginDate: string;
FMBeginDate: TFMDateTime;
EndDate: string;
FMEndDate: TFMDateTime;
Ascending: Boolean;
end;
procedure SelectNoteDateRange(FontSize: Integer; CurrentContext: TTIUContext; var NoteDateRange: TNoteDateRange);
implementation
{$R *.DFM}
uses rCore, rTIU;
const
TX_DATE_ERR = 'Enter valid beginning and ending dates or press Cancel.';
TX_DATE_ERR_CAP = 'Error in Date Range';
procedure SelectNoteDateRange(FontSize: Integer; CurrentContext: TTIUContext; var NoteDateRange: TNoteDateRange);
{ displays date range select form for progress notes and returns a record of the selection }
var
frmNotesByDate: TfrmNotesByDate;
W, H: Integer;
begin
frmNotesByDate := TfrmNotesByDate.Create(Application);
try
with frmNotesByDate do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlBase.Width := W;
ClientHeight := H; pnlBase.Height := W;
FChanged := False;
calBeginDate.Text := CurrentContext.BeginDate;
calEndDate.Text := CurrentContext.EndDate;
if calEndDate.Text = '' then calEndDate.Text := 'TODAY';
FAscending := CurrentContext.TreeAscending;
with radSort do if FAscending then ItemIndex := 0 else ItemIndex := 1;
ShowModal;
with NoteDateRange do
begin
Changed := FChanged;
BeginDate := FBeginDate;
FMBeginDate := FFMBeginDate;
EndDate := FEndDate;
FMEndDate := FFMEndDate;
Ascending := FAscending;
end; {with NoteDateRange}
end; {with frmNotesByDate}
finally
frmNotesByDate.Release;
end;
end;
procedure TfrmNotesByDate.cmdOKClick(Sender: TObject);
var
bdate, edate: TFMDateTime;
begin
if calBeginDate.Text <> '' then
bdate := StrToFMDateTime(calBeginDate.Text)
else
bdate := 0 ;
if calEndDate.Text <> '' then
edate := StrToFMDateTime(calEndDate.Text)
else
edate := 0 ;
if (bdate <= edate) then
begin
FChanged := True;
FBeginDate := calBeginDate.Text;
FFMBeginDate := bdate;
FEndDate := calEndDate.Text;
FFMEndDate := edate;
FAscending := radSort.ItemIndex = 0;
end
else
begin
InfoBox(TX_DATE_ERR, TX_DATE_ERR_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
Close;
end;
procedure TfrmNotesByDate.cmdCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmNotesByDate.calBeginDateKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = #13) then cmdOKClick(Self);
end;
procedure TfrmNotesByDate.calEndDateKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = #13) then cmdOKClick(Self);
end;
end.
|
unit GPFWinAmpControl;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
WACM_TRACK_PREV = 40044;
WACM_TRACK_NEXT = 40048;
WACM_PLAY_CUR = 40045;
WACM_PAUSE = 40046;
WACM_CONTINUE = 40046;
WACM_STOP = 40047;
WACM_STOP_FADEOUT = 40147;
WACM_STOP_AFTERENDED = 40157;
WACM_FF_5SECS = 40148;
WACM_FR_5SECS = 40144;
WACM_PLAYLIST_START = 40154;
WACM_PLAYLIST_END = 40158;
WACM_OPEN_FILE = 40029;
WACM_OPEN_URL = 40155;
WACM_FILE_INFO = 40188;
WACM_TIME_ELAPSED = 40037;
WACM_TIME_REMAINING = 40038;
WACM_PREFERENCES = 40012;
WACM_VIZ_OPTIONS = 40190;
WACM_VIZ_PLUGINOPTS = 40191;
WACM_VIZ_EXEC = 40192;
WACM_ABOUT = 40041;
WACM_TITLE_SCROLL = 40189;
WACM_ALWAYSONTOP = 40019;
WACM_WINSH = 40064;
WACM_WINSH_PL = 40065;
WACM_DOUBLESIZE = 40165;
WACM_EQ = 40036;
WACM_PL = 40040;
WACM_MAIN = 40258;
WACM_BROWSER = 40298;
WACM_EASYMOVE = 40186;
WACM_VOL_RAISE = 40058;
WACM_VOL_LOWER = 40059;
WACM_REPEAT = 40022;
WACM_SHUFFLE = 40023;
WACM_OPEN_JUMPTIME = 40193;
WACM_OPEN_JUMPFILE = 40194;
WACM_OPEN_SKINSEL = 40219;
WACM_VIZ_PLUGINCONF = 40221;
WACM_SKIN_RELOAD = 40291;
WACM_QUIT = 40001;
WAUM_VERSION = 0;
WAUM_START_PLAYBACK = 100;
WAUM_PLAYLIST_CLEAR = 101;
WAUM_PLAY_SEL_TRACK = 102;
WAUM_CHDIR = 103;
WAUM_PLAYBACK_STATUS = 104;
WAUM_PLAYBACK_POS = 105;
WAUM_TRACK_LENGTH = 105;
WAUM_PLAYBACK_SEEK = 106;
WAUM_PLAYLIST_WRITE = 120;
WAUM_PLAYLIST_SETPOS = 121;
WAUM_VOL_SET = 122;
WAUM_PAN_SET = 123;
WAUM_PLAYLIST_COUNT = 124;
WAUM_PLAYLIST_GETINDEX= 125;
WAUM_TRACK_INFO = 126;
WAUM_EQ_DATA = 127;
WAUM_EQ_AUTOLOAD = 128;
WAUM_BOOKMARK_ADDFILE = 129;
WAUM_RESTART = 135;
{ plugin only }
WAUM_SKIN_SET = 200;
WAUM_SKIN_GET = 201;
WAUM_VIZ_SET = 202;
WAUM_PLAYLIST_GETFN = 211;
WAUM_PLAYLIST_GETTIT = 212;
WAUM_MB_OPEN_URL = 241;
WAUM_INET_AVAIL = 242;
WAUM_TITLE_UPDATE = 243;
WAUM_PLAYLIST_SETITEM = 245;
WAUM_MB_RETR_URL = 246;
WAUM_PLAYLIST_CACHEFL = 247;
WAUM_MB_BLOCKUPD = 248;
WAUM_MB_BLOCKUPD2 = 249;
WAUM_SHUFFLE_GET = 250;
WAUM_REPEAT_GET = 251;
WAUM_SHUFFLE_SET = 252;
WAUM_REPEAT_SET = 253;
type
TGPFWinAmpTimeDisplayMode = (watdmUnknown,watdmElapsed,watdmRemaining);
TGPFWinAmpPlayBackStatus = (wapsPlaying,wapsStopped,wapsPaused);
TGPFWinAmpPluginType = (waplNone,waplGeneric,waplDSP,waplInput,waplOutput,waplVisual);
TGPFWinAmpCustomPlugin = class(TComponent)
private
{ Private declarations }
FDescription : String;
protected
{ Protected declarations }
function GetHWindow : HWND; virtual; abstract;
function GetPluginType : TGPFWinAmpPluginType; virtual; abstract;
function GetDescription : String;
procedure SetDescription(Value:String); virtual;
public
{ Public declarations }
property PluginType : TGPFWinAmpPluginType read GetPluginType;
published
{ Published declarations }
property Description : String read GetDescription write SetDescription;
end;
TGPFWinAmpNonePlugin = class(TGPFWinAmpCustomPlugin)
protected
{ Protected declarations }
function GetHWindow : HWND; override;
function GetPluginType : TGPFWinAmpPluginType; override;
end;
TGPFWinAmpControl = class(TComponent)
private
{ Private declarations }
FWindowClassName : String;
FTimeDisplayMode : TGPFWinAmpTimeDisplayMode;
FPlugin : TGPFWinAmpCustomPlugin;
FWindowFinder : TGPFWinAmpNonePlugin;
function GetHWindow : HWND;
procedure SetWindowClassName(Value:String);
function IsRunning : Boolean;
procedure SetTimeDisplayMode(Value:TGPFWinAmpTimeDisplayMode);
function GetVersion : Word;
function GetVersionString : String;
{ user msg stuff }
function GetPlayBackStatus : TGPFWinAmpPlayBackStatus;
function GetTrackPosition : Longword;
procedure SetTrackPosition(Value:Longword);
function GetTrackLength : Longword;
function GetPlaylistIndex : Integer;
procedure SetPlaylistIndex(Value:Integer);
procedure SetVolume(Value:Byte);
procedure SetPanning(Value:Byte);
function GetPlaylistCount : integer;
function GetTrackSampleRate : Word;
function GetTrackBitRate : word;
function GetTrackChannels : Word;
function GetEQData(Index:Integer):Byte;
procedure SetEQData(Index:Integer;Value:Byte);
function GetEQPreamp : Byte;
function GetEQEnabled : Boolean;
procedure SetSkin(FileName:String);
function GetSkin : String;
function GetPlaylistFileName(Index:Integer):String;
function GetPlaylistTitle(Index:Integer):String;
function GetBrowserURL : String;
procedure SetBrowserURL(Value:String);
function GetInternet : Boolean;
function GetShuffle : Boolean;
procedure SetShuffle(Value:Boolean);
function GetRepeat : Boolean;
procedure SetRepeat(Value:Boolean);
procedure SetBrowserBlock(Value:Boolean);
function GetPlugin : TGPFWinAmpCustomPlugin;
procedure SetPlugin(AComponent : TGPFWinAmpCustomPlugin);
protected
{ Protected declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property HWindow : HWND read GetHWindow;
property Running : Boolean read IsRunning;
{ == commands == }
procedure TrackNext;
procedure TrackPrev;
procedure TrackPlay;
procedure TrackPause;
procedure TrackContinue;
procedure TrackStop(Fadeout:Boolean=false;After:Boolean=false);
procedure TrackFF;
procedure TrackFR;
procedure PlaylistStart;
procedure PlaylistEnd;
procedure OpenFileDialog;
procedure OpenURLDialog;
procedure OpenInfoDialog;
procedure OpenJumpToTime;
procedure OpenJumpToFile;
procedure VizOpenOptions;
procedure VizOpenPluginOptions;
procedure VizExec;
procedure VizConfigurePlugIn;
procedure TogglePreferences;
procedure ToggleAbout;
procedure ToggleAutoScroll;
procedure ToggleAlwaysOnTop;
procedure ToggleWindowShade;
procedure TogglePlaylistWindowShade;
procedure ToggleDoubleSize;
procedure ToggleEQ;
procedure TogglePL;
procedure ToggleMain;
procedure ToggleBrowser;
procedure ToggleEasyMove;
procedure ToggleRepeat;
procedure ToggleShuffle;
procedure VolRaise;
procedure VolLower;
procedure SkinSelect;
procedure SkinReload;
procedure Quit;
{ == wm_user things == }
procedure PlaybackStart(FileName:String);
procedure PlaylistClear;
procedure TrackPlaySelected;
procedure ChangeDir(Value:String);
function PlaylistSave : Longword;
procedure AddToBookmarkList(FileName:String);
procedure Restart;
procedure VizSelExec(FileName:String;Index:Integer=0);
procedure UpdateInfo;
procedure BrowserForceURL(Value:String);
{ == properties == }
property TimeDisplayMode : TGPFWinAmpTimeDisplayMode read FTimeDisplayMode write SetTimeDisplayMode;
property Version : Word read GetVersion;
property VersionString : String read GetVersionString;
property PlaybackStatus : TGPFWinAmpPlayBackStatus read GetPlaybackStatus;
property TrackPosition : Longword read GetTrackPosition write SetTrackPosition;
property TrackLength : Longword read GetTrackLength;
property TrackSampleRate : Word read GetTrackSampleRate;
property TrackBitRate : Word read GetTrackBitRate;
property TrackChannels : Word read GetTrackChannels;
property PlaylistIndex : Integer read GetPlaylistIndex write SetPlaylistIndex;
property PlaylistCount : Integer read GetPlaylistCount;
property Volume : Byte write SetVolume;
property Panning : Byte write SetPanning;
property EQData[Index:Integer] : Byte read GetEQData write SetEQData;
property EQPreamp : Byte read GetEQPreamp;
property EQEnabled : Boolean read GetEQEnabled;
property Skin : String read GetSkin write SetSkin;
property PlaylistFileName[Index:Integer]:String read GetPlaylistFileName;
property PlaylistTitle[Index:Integer]:String read GetPlaylistTitle;
property BrowserURL : String read GetBrowserURL write SetBrowserURL;
property Internet : Boolean read GetInternet;
property ShuffleOn : Boolean read GetShuffle write SetShuffle;
property RepeatOn : Boolean read GetRepeat write SetRepeat;
property BrowserBlock : Boolean write SetBrowserBlock;
published
{ Published declarations }
property WindowClassName : String read FWindowClassName write SetWindowClassName;
property Plugin : TGPFWinAmpCustomPlugin read GetPlugin write SetPlugin;
end;
procedure Register;
implementation
{$R *.dcr}
procedure Register;
begin
RegisterComponents('GPF', [TGPFWinAmpControl]);
end;
{ TGPFWinAmpControl }
procedure TGPFWinAmpControl.AddToBookmarkList(FileName: String);
begin
SendMessage(HWindow,WM_USER,Word(PChar(FileName)),WAUM_BOOKMARK_ADDFILE);
end;
procedure TGPFWinAmpControl.BrowserForceURL(Value: String);
begin
SendMessage(HWindow,WM_USER,Word(PChar(Value)),WAUM_MB_BLOCKUPD2);
end;
procedure TGPFWinAmpControl.ChangeDir(Value: String);
var cds : COPYDATASTRUCT;
begin
cds.dwData := WAUM_CHDIR;
cds.lpData := PChar(Value);
cds.cbData := Length(Value)+1;
SendMessage(HWindow,WM_COPYDATA,0,Integer(@cds));
end;
constructor TGPFWinAmpControl.Create(AOwner: TComponent);
begin
inherited;
FWindowClassName := 'Winamp v1.x';
FPlugin := nil;
FWindowFinder := TGPFWinAmpNonePlugin.Create(Self);
end;
destructor TGPFWinAmpControl.Destroy;
begin
FWindowFinder.Free;
inherited;
end;
function TGPFWinAmpControl.GetBrowserURL: String;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := StrPas(PChar(SendMessage(HWindow,WM_USER,0,WAUM_MB_RETR_URL)));
end
else
Result := '';
end;
function TGPFWinAmpControl.GetEQData(Index: Integer): Byte;
begin
Result := Byte(SendMessage(HWindow,WM_USER,Index,WAUM_EQ_DATA));
end;
function TGPFWinAmpControl.GetEQEnabled: Boolean;
begin
Result := (SendMessage(HWindow,WM_USER,11,WAUM_EQ_DATA) <> 0);
end;
function TGPFWinAmpControl.GetEQPreamp: Byte;
begin
Result := Byte(SendMessage(HWindow,WM_USER,10,WAUM_EQ_DATA));
end;
function TGPFWinAmpControl.GetHWindow: HWND;
var tmp : HWND;
begin
if Assigned(FPlugin) then
begin
tmp := FPlugin.GetHWindow;
if tmp = 0 then
Result := FWindowFinder.GetHWindow
else
Result := tmp;
end
else
Result := FWindowFinder.GetHWindow;
end;
function TGPFWinAmpControl.GetInternet: Boolean;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := (SendMessage(HWindow,WM_USER,0,WAUM_INET_AVAIL) = 1)
else
Result := False;
end
else
Result := False;
end;
function TGPFWinAmpControl.GetPlayBackStatus: TGPFWinAmpPlayBackStatus;
var ret : Integer;
begin
ret := SendMessage(HWindow,WM_USER,0,WAUM_PLAYBACK_STATUS);
if ret = 1 then
Result := wapsPlaying
else if ret = 3 then
Result := wapsPaused
else
Result := wapsStopped;
end;
function TGPFWinAmpControl.GetPlaylistCount: integer;
begin
Result := SendMessage(HWindow,WM_USER,0,WAUM_PLAYLIST_COUNT);
end;
function TGPFWinAmpControl.GetPlaylistFileName(Index: Integer): String;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := StrPas(PChar(SendMessage(HWindow,WM_User,Index,WAUM_PLAYLIST_GETFN)));
end
else
Result := '';
end;
function TGPFWinAmpControl.GetPlaylistIndex: Integer;
begin
Result := SendMessage(HWindow,WM_USER,0,WAUM_PLAYLIST_GETINDEX);
end;
function TGPFWinAmpControl.GetPlaylistTitle(Index: Integer): String;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := StrPas(PChar(SendMessage(HWindow,WM_USER,0,WAUM_PLAYLIST_GETTIT)));
end
else
Result := '';
end;
function TGPFWinAmpControl.GetPlugin: TGPFWinAmpCustomPlugin;
begin
Result := FPlugin;
end;
function TGPFWinAmpControl.GetRepeat: Boolean;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := (SendMessage(HWindow,WM_USER,0,WAUM_REPEAT_GET) = 1)
else
Result := False;
end
else
Result := False;
end;
function TGPFWinAmpControl.GetShuffle: Boolean;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := (SendMessage(HWindow,WM_USER,0,WAUM_SHUFFLE_GET) = 1)
else
Result := False;
end
else
Result := False;
end;
function TGPFWinAmpControl.GetSkin: String;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
Result := StrPas(PChar(SendMessage(HWindow,WM_USER,0,WAUM_SKIN_GET)));
end
else
Result := '';
end;
function TGPFWinAmpControl.GetTrackBitRate: word;
begin
Result := Word(SendMessage(HWindow,WM_USER,1,WAUM_TRACK_INFO));
end;
function TGPFWinAmpControl.GetTrackChannels: Word;
begin
Result := Word(SendMessage(HWindow,WM_USER,2,WAUM_TRACK_INFO));
end;
function TGPFWinAmpControl.GetTrackLength: Longword;
begin
Result := Word(SendMessage(HWindow,WM_USER,1,WAUM_TRACK_LENGTH));
end;
function TGPFWinAmpControl.GetTrackPosition: Longword;
begin
Result := Word(SendMessage(HWindow,WM_USER,0,WAUM_PLAYBACK_POS));
end;
function TGPFWinAmpControl.GetTrackSampleRate: Word;
begin
Result := Word(SendMessage(HWindow,WM_USER,0,WAUM_TRACK_INFO));
end;
function TGPFWinAmpControl.GetVersion: Word;
begin
Result := Word(SendMessage(HWindow,WM_USER,0,WAUM_VERSION));
end;
function TGPFWinAmpControl.GetVersionString: String;
var ver : Word;
begin
ver := GetVersion;
Result := Format('v%d.%d%d',[(ver and $F000) shr 12,(ver and $0FF0) shr 8,ver and $F]);
end;
function TGPFWinAmpControl.IsRunning: Boolean;
begin
Result := (HWindow <> 0);
end;
procedure TGPFWinAmpControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent,Operation);
if (Operation = opRemove) and (AComponent = FPlugin) then
begin
FPlugin := nil;
//FWindowFinder := TGPFWinAmpNonePlugin.Create(Self);
end;
end;
procedure TGPFWinAmpControl.OpenFileDialog;
begin
SendMessage(HWindow,WM_COMMAND,WACM_OPEN_FILE,0);
end;
procedure TGPFWinAmpControl.OpenInfoDialog;
begin
SendMessage(HWindow,WM_COMMAND,WACM_FILE_INFO,0);
end;
procedure TGPFWinAmpControl.OpenJumpToFile;
begin
SendMessage(HWindow,WM_COMMAND,WACM_OPEN_JUMPFILE,0);
end;
procedure TGPFWinAmpControl.OpenJumpToTime;
begin
SendMessage(HWindow,WM_COMMAND,WACM_OPEN_JUMPTIME,0);
end;
procedure TGPFWinAmpControl.OpenURLDialog;
begin
SendMessage(HWindow,WM_COMMAND,WACM_OPEN_URL,0);
end;
procedure TGPFWinAmpControl.PlaybackStart(FileName:String);
var cds : COPYDATASTRUCT;
begin
cds.dwData := WAUM_START_PLAYBACK;
cds.lpData := PChar(FileName);
cds.cbData := Length(FileName)+1;
SendMessage(HWindow,WM_COPYDATA,0,Integer(@cds));
end;
procedure TGPFWinAmpControl.PlaylistClear;
begin
SendMessage(HWindow,WM_USER,0,WAUM_PLAYLIST_CLEAR);
end;
procedure TGPFWinAmpControl.PlaylistEnd;
begin
SendMessage(HWindow,WM_COMMAND,WACM_PLAYLIST_END,0);
end;
function TGPFWinAmpControl.PlaylistSave: Longword;
begin
Result := Longword(SendMessage(HWindow,WM_USER,0,WAUM_PLAYLIST_WRITE));
end;
procedure TGPFWinAmpControl.PlaylistStart;
begin
SendMessage(HWindow,WM_COMMAND,WACM_PLAYLIST_START,0);
end;
procedure TGPFWinAmpControl.Quit;
begin
SendMessage(HWindow,WM_COMMAND,WACM_QUIT,0);
end;
procedure TGPFWinAmpControl.Restart;
begin
SendMessage(HWindow,WM_USER,0,WAUM_RESTART);
end;
procedure TGPFWinAmpControl.SetBrowserBlock(Value: Boolean);
begin
SendMessage(HWindow,WM_USER,Ord(Value),WAUM_MB_BLOCKUPD);
end;
procedure TGPFWinAmpControl.SetBrowserURL(Value: String);
begin
SendMessage(HWindow,WM_USER,Integer(PChar(Value)),WAUM_MB_OPEN_URL);
end;
procedure TGPFWinAmpControl.SetEQData(Index: Integer; Value: Byte);
begin
SendMessage(HWindow,WM_USER,Index,WAUM_EQ_DATA);
SendMessage(HWindow,WM_USER,Value,WAUM_EQ_AUTOLOAD);
end;
procedure TGPFWinAmpControl.SetPanning(Value: Byte);
begin
SendMessage(HWindow,WM_USER,Value,WAUM_PAN_SET);
end;
procedure TGPFWinAmpControl.SetPlaylistIndex(Value: Integer);
begin
SendMessage(HWindow,WM_User,Value,WAUM_PLAYLIST_SETPOS);
end;
procedure TGPFWinAmpControl.SetPlugin(AComponent: TGPFWinAmpCustomPlugin);
begin
FPlugin := AComponent;
FPlugin.FreeNotification(Self);
end;
procedure TGPFWinAmpControl.SetRepeat(Value: Boolean);
begin
if Assigned(FPlugin) then
begin
if (FPlugin.GetPluginType <> waplNone) and (Value xor GetRepeat) then
SendMessage(HWindow,WM_User,Ord(Value),WAUM_REPEAT_SET);
end;
end;
procedure TGPFWinAmpControl.SetShuffle(Value: Boolean);
begin
if Assigned(FPlugin) then
begin
if (FPlugin.GetPluginType <> waplNone) and (Value xor GetShuffle) then
SendMessage(HWindow,WM_User,Ord(Value),WAUM_SHUFFLE_SET);
end;
end;
procedure TGPFWinAmpControl.SetSkin(FileName: String);
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
SendMessage(HWindow,WM_USER,Integer(PChar(FileName)),WAUM_SKIN_SET);
end;
end;
procedure TGPFWinAmpControl.SetTimeDisplayMode(
Value: TGPFWinAmpTimeDisplayMode);
begin
if Value = watdmElapsed then
SendMessage(HWindow,WM_COMMAND,WACM_TIME_ELAPSED,0);
if Value = watdmRemaining then
SendMessage(HWindow,WM_COMMAND,WACM_TIME_REMAINING,0);
end;
procedure TGPFWinAmpControl.SetTrackPosition(Value: Longword);
begin
SendMessage(HWindow,WM_USER,Value,WAUM_PLAYBACK_SEEK);
end;
procedure TGPFWinAmpControl.SetVolume(Value: Byte);
begin
SendMessage(HWindow,WM_USER,Value,WAUM_VOL_SET);
end;
procedure TGPFWinAmpControl.SetWindowClassName(Value: String);
begin
if FWindowClassName <> Value then
begin
FWindowClassName := Value;
end;
end;
procedure TGPFWinAmpControl.SkinReload;
begin
SendMessage(HWindow,WM_COMMAND,WACM_SKIN_RELOAD,0);
end;
procedure TGPFWinAmpControl.SkinSelect;
begin
SendMessage(HWindow,WM_COMMAND,WACM_OPEN_SKINSEL,0);
end;
procedure TGPFWinAmpControl.ToggleAbout;
begin
SendMessage(HWindow,WM_COMMAND,WACM_ABOUT,0);
end;
procedure TGPFWinAmpControl.ToggleAlwaysOnTop;
begin
SendMessage(HWindow,WM_COMMAND,WACM_ALWAYSONTOP,0);
end;
procedure TGPFWinAmpControl.ToggleAutoScroll;
begin
SendMessage(HWindow,WM_COMMAND,WACM_TITLE_SCROLL,0);
end;
procedure TGPFWinAmpControl.ToggleBrowser;
begin
SendMessage(HWindow,WM_COMMAND,WACM_BROWSER,0);
end;
procedure TGPFWinAmpControl.ToggleDoubleSize;
begin
SendMessage(HWindow,WM_COMMAND,WACM_DOUBLESIZE,0);
end;
procedure TGPFWinAmpControl.ToggleEasyMove;
begin
SendMessage(HWindow,WM_COMMAND,WACM_EASYMOVE,0);
end;
procedure TGPFWinAmpControl.ToggleEQ;
begin
SendMessage(HWindow,WM_COMMAND,WACM_EQ,0);
end;
procedure TGPFWinAmpControl.ToggleMain;
begin
SendMessage(HWindow,WM_COMMAND,WACM_MAIN,0);
end;
procedure TGPFWinAmpControl.TogglePL;
begin
SendMessage(HWindow,WM_COMMAND,WACM_PL,0);
end;
procedure TGPFWinAmpControl.TogglePlaylistWindowShade;
begin
SendMessage(HWindow,WM_COMMAND,WACM_WINSH_PL,0);
end;
procedure TGPFWinAmpControl.TogglePreferences;
begin
SendMessage(HWindow,WM_COMMAND,WACM_PREFERENCES,0);
end;
procedure TGPFWinAmpControl.ToggleRepeat;
begin
SendMessage(HWindow,WM_COMMAND,WACM_REPEAT,0);
end;
procedure TGPFWinAmpControl.ToggleShuffle;
begin
SendMessage(HWindow,WM_COMMAND,WACM_SHUFFLE,0);
end;
procedure TGPFWinAmpControl.ToggleWindowShade;
begin
SendMessage(HWindow,WM_COMMAND,WACM_WINSH,0);
end;
procedure TGPFWinAmpControl.TrackContinue;
begin
SendMessage(HWindow,WM_COMMAND,WACM_CONTINUE,0);
end;
procedure TGPFWinAmpControl.TrackFF;
begin
SendMessage(HWindow,WM_COMMAND,WACM_FF_5SECS,0);
end;
procedure TGPFWinAmpControl.TrackFR;
begin
SendMessage(HWindow,WM_COMMAND,WACM_FR_5SECS,0);
end;
procedure TGPFWinAmpControl.TrackNext;
begin
SendMessage(HWindow,WM_COMMAND,WACM_TRACK_NEXT,0);
end;
procedure TGPFWinAmpControl.TrackPause;
begin
SendMessage(HWindow,WM_COMMAND,WACM_PAUSE,0);
end;
procedure TGPFWinAmpControl.TrackPlay;
begin
SendMessage(HWindow,WM_COMMAND,WACM_PLAY_CUR,0);
end;
procedure TGPFWinAmpControl.TrackPlaySelected;
begin
SendMessage(HWindow,WM_USER,0,WAUM_PLAY_SEL_TRACK);
end;
procedure TGPFWinAmpControl.TrackPrev;
begin
SendMessage(HWindow,WM_COMMAND,WACM_TRACK_PREV,0);
end;
procedure TGPFWinAmpControl.TrackStop(Fadeout, After: Boolean);
begin
if Fadeout then
begin
SendMessage(HWindow,WM_COMMAND,WACM_STOP_FADEOUT,0);
end
else
begin
if After then
SendMessage(HWindow,WM_COMMAND,WACM_STOP_AFTERENDED,0)
else
SendMessage(HWindow,WM_COMMAND,WACM_STOP,0);
end;
end;
procedure TGPFWinAmpControl.UpdateInfo;
begin
if Assigned(FPlugin) then
begin
if FPlugin.GetPluginType <> waplNone then
SendMessage(HWindow,WM_USER,0,WAUM_TITLE_UPDATE);
end;
end;
procedure TGPFWinAmpControl.VizConfigurePlugIn;
begin
SendMessage(HWindow,WM_COMMAND,WACM_VIZ_PLUGINCONF,0);
end;
procedure TGPFWinAmpControl.VizExec;
begin
SendMessage(HWindow,WM_COMMAND,WACM_VIZ_EXEC,0);
end;
procedure TGPFWinAmpControl.VizOpenOptions;
begin
SendMessage(HWindow,WM_COMMAND,WACM_VIZ_OPTIONS,0);
end;
procedure TGPFWinAmpControl.VizOpenPluginOptions;
begin
SendMessage(HWindow,WM_COMMAND,WACM_VIZ_PLUGINOPTS,0);
end;
procedure TGPFWinAmpControl.VizSelExec(FileName: String; Index: Integer);
var tmpStr : String;
begin
if Index > 0 then
tmpStr := FileName+','+IntToStr(Index)
else
tmpStr := FileName;
SendMessage(HWindow,WM_USER,Integer(PChar(tmpStr)),WAUM_VIZ_SET);
end;
procedure TGPFWinAmpControl.VolLower;
begin
SendMessage(HWindow,WM_COMMAND,WACM_VOL_LOWER,0);
end;
procedure TGPFWinAmpControl.VolRaise;
begin
SendMessage(HWindow,WM_COMMAND,WACM_VOL_RAISE,0);
end;
{ TGPFWinAmpNonePlugin }
function TGPFWinAmpNonePlugin.GetHWindow: HWND;
begin
Result := FindWindow(PChar(TGPFWinAmpControl(Owner).FWindowClassName),nil);
end;
function TGPFWinAmpNonePlugin.GetPluginType: TGPFWinAmpPluginType;
begin
Result := waplNone;
end;
{ TGPFWinAmpCustomPlugin }
function TGPFWinAmpCustomPlugin.GetDescription: String;
begin
Result := FDescription;
end;
procedure TGPFWinAmpCustomPlugin.SetDescription(Value: String);
begin
FDescription := Value;
end;
end.
|
unit UI.Design.ImageIndex;
interface
uses
Winapi.Windows,
System.SysUtils, System.Classes, FMX.Graphics, Vcl.Graphics,
System.Types, System.UITypes, FMX.ImgList,
DesignIntf, System.TypInfo, DesignEditors, VCLEditors;// Vcl.Controls;
type
TImageIndexProperty = class(TIntegerProperty, ICustomPropertyDrawing, ICustomPropertyListDrawing, ICustomPropertyDrawing80)
private
function GetImages: TCustomImageList;
function DrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean): Boolean;
procedure CreateView(AImageList: TCustomImageList; AIndex: Integer);
public
function GetAttributes: TPropertyAttributes; override;
procedure SetValue(const Value: string); override;
procedure GetValues(Proc: TGetStrProc); override;
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
function PropDrawNameRect(const ARect: TRect): TRect;
function PropDrawValueRect(const ARect: TRect): TRect;
end;
implementation
uses
UI.Base,
System.Math,
FMX.Helpers.Win;
const
ImageWidth = 16;
ImageHeight = 16;
OffsetWidth = 8;
OffsetHeight = 4;
DefaultValue = '-1';
var
FMXBitmap: FMX.Graphics.TBitmap = nil;
VCLBitmap: VCl.Graphics.TBitmap = nil;
{ TImageIndexProperty }
function TImageIndexProperty.DrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean): Boolean;
var
LImageList: TCustomImageList;
LTop: Integer;
LImageIndex: Integer;
begin
LImageList := GetImages;
LImageIndex := StrToIntDef(Value, -1);
ACanvas.FillRect(ARect);
CreateView(LImageList, LImageIndex);
ACanvas.Draw(ARect.Left + 2, ARect.Top, VCLBitmap);
LTop := ARect.Top + (ARect.Bottom - ARect.Top - ACanvas.TextHeight(Value)) div 2;
ACanvas.TextOut(ARect.Left + ImageWidth + OffsetWidth, LTop, Value);
Result := True;
end;
function TImageIndexProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited + [paValueList];
end;
function TImageIndexProperty.GetImages: TCustomImageList;
var
LEditedComponent: TPersistent;
begin
Result := nil;
try
LEditedComponent := GetComponent(0) as TPersistent;
if (LEditedComponent <> nil) and (LEditedComponent is TViewImagesBrush) then
Result := TCustomImageList(TViewImagesBrush(LEditedComponent).Images);
except
end;
end;
procedure TImageIndexProperty.GetValues(Proc: TGetStrProc);
var
LImageList: TCustomImageList;
I: Integer;
begin
Proc(DefaultValue);
LImageList := GetImages;
if LImageList = nil then
Exit;
for I := 0 to LImageList.Count - 1 do
Proc(IntToStr(I));
end;
procedure TImageIndexProperty.SetValue(const Value: string);
begin
if Value = '' then
inherited SetValue(DefaultValue)
else
inherited SetValue(Value);
end;
procedure TImageIndexProperty.CreateView(AImageList: TCustomImageList; AIndex: Integer);
var
LR: TRect;
LHBitmap: Winapi.Windows.HBITMAP;
begin
if FMXBitmap = nil then
FMXBitmap := FMX.Graphics.TBitmap.Create(ImageWidth, ImageHeight);
// 重置
FMXBitmap.Clear(TAlphaColors.White);
if VCLBitmap = nil then
begin
VCLBitmap := VCl.Graphics.TBitmap.Create;
VCLBitmap.SetSize(ImageWidth, ImageHeight);
VCLBitmap.PixelFormat := TPixelFormat.pf32bit;
end;
// 填充下颜色,覆盖掉原来的
with VCLBitmap do
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clWhite;
LR := Rect(0, 0, ImageWidth, ImageHeight);
Canvas.FillRect(LR);
end;
// 画图标
if Assigned(AImageList) and (AImageList.Count > 0) and (AIndex >=0) and (AIndex < AImageList.Count) then
begin
FMXBitmap.Canvas.BeginScene();
try
AImageList.Draw(FMXBitmap.Canvas, Rect(0, 0, ImageWidth, ImageHeight), AIndex);
finally
FMXBitmap.Canvas.EndScene;
end;
LHBitmap := BitmapToWinBitmap(FMXBitmap, True);
try
VCLBitmap.Handle := LHBitmap;
except
if LHBitmap <> 0 then
begin
DeleteObject(LHBitmap);
LHBitmap := 0;
end;
end;
end else
begin
with VCLBitmap do
begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color := $6D6D6D;
Canvas.Pen.Style := psDot;
LR := Rect(LR.Left + 1, LR.Top + 1, LR.Right - 1, LR.Bottom - 1);
Canvas.Rectangle(LR);
// 画个叉
Canvas.Pen.Style := psSolid;
Canvas.MoveTo(LR.Left + 2, LR.Top + 2);
Canvas.LineTo(LR.Left + 9, LR.Top + 9);
Canvas.MoveTo(LR.Left + 9, LR.Top + 2);
Canvas.LineTo(LR.Left + 2, LR.Top + 9);
end;
end;
end;
procedure TImageIndexProperty.ListDrawValue(const Value: string;
ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
begin
DrawValue(Value, ACanvas, ARect, ASelected);
end;
procedure TImageIndexProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
var
LImageList: TCustomImageList;
begin
LImageList := GetImages;
if Assigned(LImageList) and (LImageList.Count > 0) then
AWidth := AWidth + ImageWidth + OffsetWidth;
end;
procedure TImageIndexProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
end;
function TImageIndexProperty.PropDrawNameRect(const ARect: TRect): TRect;
begin
Result := ARect;
end;
procedure TImageIndexProperty.PropDrawValue(ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
begin
DrawValue(GetValue, ACanvas, ARect, ASelected);
end;
function TImageIndexProperty.PropDrawValueRect(const ARect: TRect): TRect;
begin
Result := Rect(ARect.Left, ARect.Top, (ARect.Bottom - ARect.Top) + ARect.Left, ARect.Bottom);
end;
procedure TImageIndexProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
var
LImageList: TCustomImageList;
begin
LImageList := GetImages;
if Assigned(LImageList) and (LImageList.Count > 0) then
begin
if Value = DefaultValue then
AHeight := ImageHeight + OffsetHeight
else
AHeight := Max(AHeight, ImageHeight + OffsetHeight);
end else
AHeight := ImageHeight + OffsetHeight
end;
initialization
finalization
if Assigned(FMXBitmap) then
FreeAndNil(FMXBitmap);
if Assigned(VCLBitmap) then
FreeAndNil(VCLBitmap);
end.
|
unit LetterInsertCodesUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons;
type
TLetterInsertCodesForm = class(TForm)
InsertCodesListBox: TListBox;
OKButton: TBitBtn;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
ParcelIDInsert = '<<ParcelID>>';
LegalAddressInsert = '<<LegalAddress>>';
OwnerInsert = '<<Owner>>';
FirstNameInsert = '<<FirstName>>';
LastNameInsert = '<<LastName>>';
AssessedValueInsert = '<<AssessedValue>>';
LandValueInsert = '<<LandValue>>';
CountyTaxableValueInsert = '<<CountyTaxable>>';
MunicipalTaxableValueInsert = '<<MunicTaxable>>';
SchoolTaxableValueInsert = '<<SchoolTaxable>>';
CountyExemptionTotalInsert = '<<CountyExTot>>';
MunicipalExemptionTotalInsert = '<<MunicExTot>>';
SchoolExemptionTotalInsert = '<<SchoolExTot>>';
PropertyClassInsert = '<<PropertyClass>>';
AccountNumberInsert = '<<AccountNumber>>';
var
LetterInsertCodesForm: TLetterInsertCodesForm;
implementation
{$R *.DFM}
{============================================================}
Procedure TLetterInsertCodesForm.FormCreate(Sender: TObject);
begin
with InsertCodesListBox.Items do
begin
Add(ParcelIDInsert);
Add(LegalAddressInsert);
Add(OwnerInsert);
{CHG03172004-2(2.07l2): Add first name and last name inserts.}
Add(FirstNameInsert);
Add(LastNameInsert);
Add(AssessedValueInsert);
Add(LandValueInsert);
Add(CountyTaxableValueInsert);
Add(MunicipalTaxableValueInsert);
Add(SchoolTaxableValueInsert);
Add(CountyExemptionTotalInsert);
Add(MunicipalExemptionTotalInsert);
Add(SchoolExemptionTotalInsert);
end; {with InsertCodesListBox.Items do}
end; {FormCreate}
end.
|
Dadas las siguientes declaraciones:
implementar la función siguiente:
que, dado un arreglo de enteros positivos, devuelve true si existe algún valor en el
arreglo que es divisor del valor que se encuentra en la celda anterior. En caso contrario,
devuelve false .
Ejemplos:
a = [2, 34, 5, 12, 3, 7, 4] , divAnterior devuelve true
a = [2, 34, 5, 12, 7, 4, 3] , divAnterior devuelve false
a = [2] , divAnterior devuelve false
const N = ...; (* N > 0 *)
type
Positivo = 1 .. MAXINT;
Arreglo = array[1 .. N] of Positivo;
function divAnterior(a : Arreglo) : Boolean;
var i : integer;
divisor :boolean;
begin
divisor := false;
if (N > 1) then
for i := 1 to (N - 1) do
if (a[i] mod a[i + 1] = 0) then
divisor := true;
divAnterior := divisor;
end;
function divAnterior(a: arreglo):boolean;
var i : integer;
begin
i := 2;
while (i <= N) and (a[i - 1] mod a[i] <> o) do
i := i + 1;
divAnterior := (i <= N);
end; |
unit SubParametersExcelDataModule;
interface
uses
System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer,
CustomExcelTable, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.DataSet,
SubParametersInterface;
type
TSubParametersExcelTable = class(TCustomExcelTable)
private
FSubParametersInt: ISubParameters;
function GetName: TField;
function GetTranslation: TField;
protected
function CheckSubParameter: Boolean;
procedure SetFieldsInfo; override;
public
constructor Create(AOwner: TComponent); override;
function CheckRecord: Boolean; override;
property Name: TField read GetName;
property SubParametersInt: ISubParameters read FSubParametersInt write
FSubParametersInt;
property Translation: TField read GetTranslation;
end;
TSubParametersExcelDM = class(TExcelDM)
private
function GetExcelTable: TSubParametersExcelTable;
{ Private declarations }
protected
function CreateExcelTable: TCustomExcelTable; override;
public
property ExcelTable: TSubParametersExcelTable read GetExcelTable;
{ Public declarations }
end;
implementation
uses
FieldInfoUnit, System.Variants, StrHelper, ErrorType, RecordCheck;
constructor TSubParametersExcelTable.Create(AOwner: TComponent);
begin
inherited;
end;
function TSubParametersExcelTable.CheckSubParameter: Boolean;
var
ARecordCheck: TRecordCheck;
begin
Assert(SubParametersInt <> nil);
Result := SubParametersInt.GetSubParameterID(Name.Value) = 0;
// Если не нашли
if not Result then
begin
// Запоминаем, что в этой строке предупреждение
ARecordCheck.ErrorType := etError;
ARecordCheck.Row := ExcelRow.AsInteger;
ARecordCheck.Col := Name.Index + 1;
ARecordCheck.ErrorMessage := Name.AsString;
ARecordCheck.Description := 'Подпараметр с таким наименованием уже существует.';
ProcessErrors(ARecordCheck);
end;
end;
function TSubParametersExcelTable.CheckRecord: Boolean;
begin
Result := inherited;
if Result then
begin
// Проверяем что такой компонент существует
Result := CheckSubParameter;
end;
end;
function TSubParametersExcelTable.GetName: TField;
begin
Result := FieldByName('Name');
end;
function TSubParametersExcelTable.GetTranslation: TField;
begin
Result := FieldByName('Translation');
end;
procedure TSubParametersExcelTable.SetFieldsInfo;
begin
FieldsInfo.Add(TFieldInfo.Create('Name', True,
'Наименование подпараметра не должно быть пустым'));
FieldsInfo.Add(TFieldInfo.Create('Translation'));
end;
function TSubParametersExcelDM.CreateExcelTable: TCustomExcelTable;
begin
Result := TSubParametersExcelTable.Create(Self);
end;
function TSubParametersExcelDM.GetExcelTable: TSubParametersExcelTable;
begin
// TODO -cMM: TSubParametersExcelDM.GetExcelTable default body inserted
Result := CustomExcelTable as TSubParametersExcelTable;
end;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
end.
|
unit CreatePoints;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
DimensionsUnit;
type
TCreatePointsFrm = class(TForm)
RandomBtn: TButton;
HorizontalBtn: TButton;
VerticalBtn: TButton;
FlipZCB: TCheckBox;
CancelBtn: TButton;
CopyToAllZFrames: TCheckBox;
SingleCenterBtn: TButton;
OneHStripeButton: TButton;
Button2: TButton;
btnCheckerd: TButton;
OneVHButn: TButton;
procedure RandomBtnClick(Sender: TObject);
procedure SingleCenterBtnClick(Sender: TObject);
procedure OneHStripeButtonClick(Sender: TObject);
procedure HorizontalBtnClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure VerticalBtnClick(Sender: TObject);
procedure btnCheckerdClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure OneVHButnClick(Sender: TObject);
private
{ Private declarations }
public
procedure Clear;
procedure RunChecks;
procedure CopyToAllFrames;
procedure InverseEachFrame;
end;
var
CreatePointsFrm: TCreatePointsFrm;
implementation
uses
UserIterface;
{$R *.dfm}
procedure TCreatePointsFrm.RandomBtnClick(Sender: TObject);
var
ySpaceIndex: Integer;
begin
Clear;
for ySpaceIndex := 1 to 300 do
UserInterfaceForm.Automata.Space.Points[Random(SpaceSize - 1) + 1, Random(SpaceSize - 1) + 1,1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.CopyToAllFrames;
var
xSpaceIndex,
ySpaceIndex,
zSpaceIndex: Integer;
begin
for zSpaceIndex := 2 to SpaceSize do
for ySpaceIndex := 1 to SpaceSize do
for xSpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex,zSpaceIndex] := UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex,1];
end;
procedure TCreatePointsFrm.InverseEachFrame;
var
Flip: Boolean;
Point: Integer;
xSpaceIndex,
ySpaceIndex,
zSpaceIndex: Integer;
begin
Flip := True;
for zSpaceIndex := 2 to SpaceSize do
begin
for ySpaceIndex := 1 to SpaceSize do
for xSpaceIndex := 1 to SpaceSize do
begin
Point := UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex,zSpaceIndex];
if Flip then
if Point = 0 then
Point := 1
else
Point := 0;
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex,zSpaceIndex] := Point;
end;
Flip := not Flip;
end;
end;
procedure TCreatePointsFrm.RunChecks;
begin
if CopyToAllZFrames.Checked then
CopyToAllFrames;
if FlipZCB.Checked then
InverseEachFrame;
UserInterfaceForm.Automata.Iterations := 0;
end;
procedure TCreatePointsFrm.SingleCenterBtnClick(Sender: TObject);
begin
Clear;
UserInterfaceForm.Automata.Space.Points[1,SpaceSize div 2,1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.Clear;
var
xSpaceIndex,
ySpaceIndex,
zSpaceIndex: Integer;
begin
for zSpaceIndex := 1 to SpaceSize do
for ySpaceIndex := 1 to SpaceSize do
for xSpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex,zSpaceIndex] := 0;
end;
procedure TCreatePointsFrm.OneHStripeButtonClick(Sender: TObject);
var
xSpaceIndex: Integer;
begin
Clear;
for xSpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, 1, 1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.HorizontalBtnClick(Sender: TObject);
var
xSpaceIndex: Integer;
ySpaceIndex: Integer;
begin
Clear;
for ySpaceIndex := 1 to SpaceSize do
if ySpaceIndex mod 2 = 0 then
for xSpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex, 1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.Button2Click(Sender: TObject);
var
ySpaceIndex: Integer;
begin
Clear;
for ySpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[1, ySpaceIndex, 1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.VerticalBtnClick(Sender: TObject);
var
xSpaceIndex: Integer;
ySpaceIndex: Integer;
begin
Clear;
for xSpaceIndex := 1 to SpaceSize do
if xSpaceIndex mod 2 = 0 then
for ySpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex, 1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.btnCheckerdClick(Sender: TObject);
var
xSpaceIndex: Integer;
ySpaceIndex: Integer;
begin
Clear;
for xSpaceIndex := 1 to SpaceSize do
for ySpaceIndex := 1 to SpaceSize do
if (xSpaceIndex + ySpaceIndex) mod 2 = 0 then
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, ySpaceIndex, 1] := 1;
RunChecks;
Close;
end;
procedure TCreatePointsFrm.CancelBtnClick(Sender: TObject);
begin
Close;
end;
procedure TCreatePointsFrm.OneVHButnClick(Sender: TObject);
var
xSpaceIndex: Integer;
ySpaceIndex: Integer;
begin
Clear;
for xSpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[xSpaceIndex, 1, 1] := 1;
for ySpaceIndex := 1 to SpaceSize do
UserInterfaceForm.Automata.Space.Points[1, ySpaceIndex, 1] := 1;
RunChecks;
Close;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TselectState = (ssSelect, ssUnselect, ssMove);
TForm1 = class(TForm)
Image1: TImage;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Bitmap1: TBitmap;
SelectImage: TBitmap;
aSelectState: TselectState;
fOldX, FOldY: Integer;
FOldX1, FOldY1: Integer;
First: Boolean;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
if (aSelectState =ssSelect )then
aSelectState :=ssUnselect
else
aSelectState :=ssSelect;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Bitmap1 := TBitmap.Create;
SelectImage := TBitmap.Create;
Bitmap1.SetSize(500,600);
SelectImage.SetSize(500,600);
aSelectState := ssSelect;
First := True;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Bitmap1.Free;
SelectImage.Free;
end;
procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if ssLeft in Shift then begin
if First then begin
fOldX := X;
fOldY := Y;
First := False;
end;
SelectImage.Canvas.Rectangle(-1,-1, 501,601);
SelectImage.Canvas.Pen.Style := psDash;
SelectImage.Canvas.Rectangle(fOldX, FOldY, X,Y);
SelectImage.Canvas.Pen.Style := psDot;
SelectImage.Canvas.Ellipse(X-5,Y-5,X+5,Y+5);
Image1.Canvas.Draw(0, 0, SelectImage);
end;
if ((fOldX > X)and (FOldY > Y) and (FOldX1 < X) and (FOldY1 < Y)
and (ssLeft in Shift) and(aSelectState = ssMove)) then begin
Image1.Canvas.CopyRect(Rect(fOldX, FOldY, fOldX1, FOldY1),);
end;
end;
procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
First := True;
if ssLeft in Shift then begin
FOldX1 := X;
FOldY1 := Y;
aSelectState :=ssMove;
end;
end;
end.
|
{**********************************************}
{ TLightTool Component and Editor Dialog }
{ Copyright (c) 2003-2004 by David Berneda }
{**********************************************}
unit TeeLighting;
{$I TeeDefs.inc}
interface
uses Classes,
{$IFDEF CLX}
QControls, QGraphics, QStdCtrls, QComCtrls, QExtCtrls, QForms,
{$ELSE}
Controls, Graphics, StdCtrls, ComCtrls, ExtCtrls, Forms,
{$ENDIF}
TeeSurfa, Chart, TeCanvas, TeeProcs, TeEngine, TeeComma;
type
TLightStyle=(lsLinear,lsSpotLight);
TLightTool=class(TTeeCustomTool)
private
FMouse: Boolean;
FTop: Integer;
FLeft: Integer;
FFactor: Integer;
FStyle: TLightStyle;
Buffer : TBitmap;
InsideLighting : Boolean;
procedure SetFactor(const Value: Integer);
procedure SetLeft(const Value: Integer);
procedure SetStyle(const Value: TLightStyle);
procedure SetTop(const Value: Integer);
protected
procedure ChartEvent(AEvent: TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
AButton:TMouseButton;
AShift: TShiftState; X, Y: Integer); override;
class function GetEditorClass: String; override;
procedure SetParentChart(const Value: TCustomAxisPanel); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
class Function Description:String; override;
procedure Iluminate;
published
property Active;
property Factor:Integer read FFactor write SetFactor default 10;
property FollowMouse:Boolean read FMouse write FMouse default False;
property Left:Integer read FLeft write SetLeft default -1;
property Style:TLightStyle read FStyle write SetStyle default lsLinear;
property Top:Integer read FTop write SetTop default -1;
end;
TLightToolEditor=class(TForm)
CheckBox2: TCheckBox;
Label1: TLabel;
TBLeft: TTrackBar;
TBTop: TTrackBar;
Label2: TLabel;
Label3: TLabel;
CBStyle: TComboFlat;
TBFactor: TTrackBar;
Label4: TLabel;
procedure CheckBox2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TBFactorChange(Sender: TObject);
procedure TBTopChange(Sender: TObject);
procedure TBLeftChange(Sender: TObject);
procedure CBStyleChange(Sender: TObject);
private
{ Private declarations }
CreatingForm : Boolean;
Light : TLightTool;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses SysUtils, Math,
TeeConst, TeeProCo;
var Buffer:TBitmap=nil;
Function TeeLight(Bitmap:TBitmap; xx,yy:Integer;
Style:TLightStyle=lsLinear;
Factor:Integer=10):TBitmap;
const BytesPerPixel={$IFDEF CLX}4{$ELSE}3{$ENDIF};
{$IFNDEF CLR}
var bi : TBitmap;
tmpx2,
x,y,
h,w : Integer;
twopercent : Integer;
maxDist,dist : Double;
b1line0,
b2line0,
b1line,
b2line : PByteArray;
tmpFactor,
tmpFactorMaxDist : Double;
{$IFDEF HLS}
hue,lum,sat:double;
{$ENDIF}
b1Dif,b2Dif,
tmpy:Integer;
{$ENDIF}
begin
{$IFNDEF CLR}
h:=Bitmap.Height;
w:=Bitmap.Width;
if (not Assigned(Buffer))
or (Buffer.Width<>w) or (Buffer.Height<>h) then
begin
Buffer.Free;
Buffer:=TBitmap.Create;
{$IFNDEF CLX}
Buffer.IgnorePalette:=True;
{$ENDIF}
Buffer.PixelFormat:=TeePixelFormat;
Buffer.Width:=w;
Buffer.Height:=h;
end;
result:=Buffer;
bi:=Bitmap;
if Assigned(bi) then
begin
maxDist:=100.0/Sqrt((w*w)+(h*h));
tmpFactor:=Factor*0.01;
if Style=lsLinear then
tmpFactor:=20*tmpFactor;
tmpFactorMaxDist:=tmpFactor*MaxDist;
b2line0:=result.ScanLine[0];
b1line0:=bi.ScanLine[0];
b2Dif:=Integer(result.ScanLine[1])-Integer(b2line0);
b1Dif:=Integer(bi.ScanLine[1])-Integer(b1line0);
for y:=0 to h-1 do
begin
b2line:=PByteArray(Integer(b2Line0)+b2Dif*y);
b1line:=PByteArray(Integer(b1Line0)+b1Dif*y);
tmpy:=Sqr(y-yy);
for x:=0 to w-1 do
begin
dist:=Sqrt(Sqr(x-xx)+tmpy);
if Style=lsLinear then
twopercent:=Round(tmpFactorMaxDist*dist)
else
twopercent:=Round(tmpFactor*Sqr(maxdist*(dist+1)));
tmpx2:=BytesPerPixel*x;
if twopercent>0 then
begin
{$IFDEF HLS}
TeeColorRGBToHLS( b1line[tmpx2],
b1line[tmpx2+1],
b1line[tmpx2+2],hue,lum,sat);
lum:=lum-twopercent;
if lum<0 then lum:=0;
TeeColorHLSToRGB(hue, lum, Sat,
b2line[tmpx2],
b2line[1+tmpx2],
b2line[2+tmpx2]);
{$ELSE}
if b1line[tmpx2]-twopercent<0 then
b2line[tmpx2]:=0
else
b2line[tmpx2]:=b1line[tmpx2]-twopercent;
Inc(tmpx2);
if b1line[tmpx2]-twopercent<0 then
b2line[tmpx2]:=0
else
b2line[tmpx2]:=b1line[tmpx2]-twopercent;
Inc(tmpx2);
if b1line[tmpx2]-twopercent<0 then
b2line[tmpx2]:=0
else
b2line[tmpx2]:=b1line[tmpx2]-twopercent;
{$ENDIF}
end
else
begin
b2line[tmpx2]:=b1line[tmpx2];
b2line[1+tmpx2]:=b1line[1+tmpx2];
b2line[2+tmpx2]:=b1line[2+tmpx2];
end;
end;
end;
end;
{$ELSE}
result:=nil;
{$ENDIF}
end;
{ TLightTool }
Constructor TLightTool.Create(AOwner: TComponent);
begin
inherited;
FFactor:=10;
FStyle:=lsLinear;
FLeft:=-1;
FTop:=-1;
end;
Destructor TLightTool.Destroy;
begin
FreeAndNil(Buffer);
inherited;
end;
procedure TLightTool.ChartMouseEvent(AEvent: TChartMouseEvent;
AButton: TMouseButton; AShift: TShiftState; X, Y: Integer);
begin
inherited;
if Active and FMouse and (AEvent=cmeMove) then
begin
FLeft:=X;
FTop:=Y;
Repaint;
end;
end;
procedure TLightTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
if Active and (AEvent=cteAfterDraw) then
begin
FreeAndNil(Buffer);
Iluminate;
end;
end;
class function TLightTool.Description: String;
begin
result:=TeeMsg_LightTool;
end;
class function TLightTool.GetEditorClass: String;
begin
result:='TLightToolEditor';
end;
procedure TLightTool.Iluminate;
Procedure CheckBuffer;
begin
if (not Assigned(Buffer)) or (Buffer.Width<>ParentChart.Width) or
(Buffer.Height<>ParentChart.Height) then
begin
Buffer.Free;
if TTeeCanvas3D(ParentChart.Canvas).Bitmap<>nil then
begin
Buffer:=TBitmap.Create;
Buffer.Width:=ParentChart.Width;
Buffer.Height:=ParentChart.Height;
Buffer.PixelFormat:=TeePixelFormat;
Buffer.Canvas.Draw(0,0,TTeeCanvas3D(ParentChart.Canvas).Bitmap);
end
else
Buffer:=ParentChart.TeeCreateBitmap(ParentChart.Color,ParentChart.ChartBounds,TeePixelFormat);
end;
end;
var b : TBitmap;
tmpX : Integer;
tmpY : Integer;
begin
if (not ParentChart.Canvas.Metafiling) then
if not InsideLighting then
begin
InsideLighting:=True; // set flag to avoid re-entrancy
try
CheckBuffer;
if FLeft=-1 then tmpX:=ParentChart.Left+(ParentChart.Width div 2)
else tmpX:=FLeft;
if FTop=-1 then tmpY:=ParentChart.Top+(ParentChart.Height div 2)
else tmpY:=FTop;
b:=TeeLight(Buffer,tmpX,tmpY,FStyle,FFactor); // create iluminated bitmap
// this Draw call does not work when Canvas.BufferedDisplay=False (ie: Print Preview panel "asBitmap")
ParentChart.Canvas.Draw(0,0,b); // draw bitmap onto Chart
finally
InsideLighting:=False; // reset flag
end;
end;
end;
procedure TLightTool.SetFactor(const Value: Integer);
begin
SetIntegerProperty(FFactor,Value);
end;
procedure TLightTool.SetLeft(const Value: Integer);
begin
SetIntegerProperty(FLeft,Value);
end;
procedure TLightTool.SetStyle(const Value: TLightStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
Repaint;
end;
end;
procedure TLightTool.SetTop(const Value: Integer);
begin
SetIntegerProperty(FTop,Value);
end;
procedure TLightToolEditor.CheckBox2Click(Sender: TObject);
begin
Light.FollowMouse:=CheckBox2.Checked;
end;
procedure TLightToolEditor.FormCreate(Sender: TObject);
begin
Align:=alClient;
CreatingForm:=True;
end;
procedure TLightToolEditor.FormShow(Sender: TObject);
begin
Light:=TLightTool(Tag);
if Assigned(Light) then
with Light do
begin
CheckBox2.Checked:=FollowMouse;
TBLeft.Max:=ParentChart.Width;
TBTop.Max:=ParentChart.Height;
if Left=-1 then
TBLeft.Position:=ParentChart.Left+(ParentChart.Width div 2)
else
TBLeft.Position:=Left;
if Top=-1 then
TBTop.Position:=ParentChart.Top+(ParentChart.Height div 2)
else
TBTop.Position:=Top;
TBFactor.Position:=Factor;
if Style=lsLinear then CBStyle.ItemIndex:=0
else CBStyle.ItemIndex:=1;
end;
CreatingForm:=False;
end;
procedure TLightToolEditor.TBFactorChange(Sender: TObject);
begin
Light.Factor:=TBFactor.Position;
end;
procedure TLightToolEditor.TBTopChange(Sender: TObject);
begin
if not CreatingForm then
Light.Top:=TBTop.Position;
end;
procedure TLightToolEditor.TBLeftChange(Sender: TObject);
begin
if not CreatingForm then
Light.Left:=TBLeft.Position;
end;
procedure TLightToolEditor.CBStyleChange(Sender: TObject);
begin
if CBStyle.ItemIndex=0 then Light.Style:=lsLinear
else Light.Style:=lsSpotLight;
end;
procedure TLightTool.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if Assigned(ParentChart) then Repaint;
end;
initialization
RegisterClass(TLightToolEditor);
RegisterTeeTools([TLightTool]);
finalization
FreeAndNil(Buffer);
UnRegisterTeeTools([TLightTool]);
end.
|
unit BrickCamp.Model.IUser;
interface
uses
Spring;
type
IUser = interface(IInterface)
['{B69AAA6A-253E-47C5-A516-BCEE2DA825A9}']
function GetId: Integer;
function GetName: string;
procedure SetName(const Value: string);
end;
implementation
end.
|
unit AlignTypedef;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is AlignTypedef, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses SourceToken, AlignBase;
type
TAlignTypedef = class(TAlignBase)
protected
{ TokenProcessor overrides }
function IsTokenInContext(const pt: TSourceToken): boolean; override;
{ AlignStatements overrides }
function TokenIsAligned(const pt: TSourceToken): boolean; override;
function TokenEndsStatement(const pt: TSourceToken): boolean; override;
function TokenEndsAlignment(const pt: TSourceToken): boolean; override;
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
end;
implementation
uses FormatFlags, JcfSettings, ParseTreeNodeType, Tokens, TokenUtils;
constructor TAlignTypedef.Create;
begin
inherited;
FormatFlags := FormatFlags + [eAlignTypedef];
end;
function TAlignTypedef.IsIncludedInSettings: boolean;
begin
Result := ( not JcfFormatSettings.Obfuscate.Enabled) and
JcfFormatSettings.Align.AlignTypedef;
end;
function TAlignTypedef.IsTokenInContext(const pt: TSourceToken): boolean;
begin
Result := pt.HasParentNode(nTypeDecl) and ( not pt.HasParentNode(ObjectTypes)) and
(( not JcfFormatSettings.Align.InterfaceOnly) or (pt.HasParentNode(nInterfaceSection)));
end;
function TAlignTypedef.TokenEndsAlignment(const pt: TSourceToken): boolean;
begin
// alignment block ended by a blank line
Result := IsBlankLineEnd(pt);
end;
function InStructuredTypeBody(const pt: TSourceToken): boolean;
begin
Result := pt.HasParentNode(ObjectTypes + [nRecordType]);
if Result then
begin
// exclude the starting word
Result := not (pt.TokenType in StructuredTypeWords + [ttObject]);
end;
end;
function TAlignTypedef.TokenEndsStatement(const pt: TSourceToken): boolean;
begin
if pt = nil then
Result := True
{ only look at solid tokens }
else if (pt.TokenType in [ttReturn, ttWhiteSpace]) then
begin
Result := False;
end
else
begin
Result := ( not pt.HasParentNode(nTypeDecl)) or
(pt.TokenType in [ttSemiColon]) or InStructuredTypeBody(pt);
end;
end;
function TAlignTypedef.TokenIsAligned(const pt: TSourceToken): boolean;
begin
Result := (pt.TokenType = ttEquals);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit Data.DBXPool;
interface
uses
Data.DBXCommon,
Data.DBXPlatform,
System.Classes,
Data.DBXDelegate,
System.Generics.Collections,
System.SyncObjs
;
const
sDriverName = 'DBXPool';
type
///<summary>the DBXPool delegate driver specific connection properties</summary>
TDBXPoolPropertyNames = class
const
/// <remarks>Maximum number of connections allocated in a connection pool.</remarks>
MaxConnections = 'MaxConnections'; { do not localize }
/// <remarks>Minimum number of connections allocated in a connection pool.</remarks>
MinConnections = 'MinConnections'; { do not localize }
/// <remarks>Number of wait time seconds to wait for a connection.</remarks>
ConnectTimeout = 'ConnectTimeout'; { do not localize }
end;
/// <summary>
/// DBXCommand instances that are created with the TDBXCommandType.DBXConnectionPool
/// command type can have their TDBXCommand.Text property set to one of the commands
/// below.
/// </summary>
TDBXPoolCommands = class
const
/// <summary>Returns a TDBXReader instance with the TDBXPoolsTable columns.</summary>
GetPools = 'GetPools'; { Do not localize }
end;
/// <summary>Columns returned by executing the TDBXPoolCommands.GetPools command</summary>
TDBXPoolsTable = class
const
/// <summary>Name of connection if any.</summary>
ConnectionName = 'ConnectionName'; { Do not localize }
/// <summary>Name of driver for this connection.</summary>
DriverName = 'DriverName'; { Do not localize }
/// <summary>Name of database for this connection.</summary>
DatabaseName = 'DatabaseName'; { Do not localize }
/// <summary>Name of user for this connection.</summary>
UserName = 'UserName'; { Do not localize }
/// <summary>Unique path of all delegate drivers used for this connection.</summary>
DelegateSignature = 'DelegateSignature'; { Do not localize }
/// <summary>Integer time out in milliseconds for this connection.</summary>
ConnectTimeout = 'ConnectTimeout'; { Do not localize }
/// <summary>Integer count open connections in the pool available for use.</summary>
AvailableConnections = 'AvailableConnections'; { Do not localize }
/// <summary>Integer count of the total connections in the pool.</summary>
TotalConnections = 'TotalConnections'; { Do not localize }
/// <summary>Integer count of the maximum connections in the pool.</summary>
MaxConnections = 'MaxConnections'; { Do not localize }
end;
TDBXPool = class;
TDBXPoolDriver = class;
TDBXPoolConnection = class(TDBXDelegateConnection)
private
[Weak]FPoolDriver: TDBXPoolDriver;
[Weak]FPool: TDBXPool;
protected
procedure DerivedGetCommandTypes(const List: TStrings); override;
procedure DerivedGetCommands(const CommandType: string;
const List: TStrings); override;
procedure Open; override;
public
constructor Create(Pool: TDBXPool; ConnectionBuilder: TDBXConnectionBuilder;
PoolDriver: TDBXPoolDriver; Connection: TDBXConnection);
destructor Destroy; override;
function CreateCommand: TDBXCommand; overload; override;
end;
TDBXPoolCommand = class(TDBXCommand)
private
[Weak]FPool: TDBXPool;
function ExecuteGetPools: TDBXReader;
protected
procedure SetMaxBlobSize(const MaxBlobSize: Int64); override;
procedure SetRowSetSize(const Value: Int64); override;
procedure DerivedOpen; override;
procedure DerivedClose; override;
function DerivedGetNextReader: TDBXReader; override;
function DerivedExecuteQuery: TDBXReader; override;
procedure DerivedExecuteUpdate; override;
procedure DerivedPrepare; override;
function GetRowsAffected: Int64; override;
constructor Create(DBXContext: TDBXContext; Pool: TDBXPool);
public
destructor Destroy; override;
end;
TDBXPoolReader = class(TDBXReader)
private
FByteReader: TDBXReaderByteReader;
protected
function DerivedNext: Boolean; override;
procedure DerivedClose; override;
function GetByteReader: TDBXByteReader; override;
public
constructor Create(DBXContext: TDBXContext; DbxRow: TDBXRow;
ByteReader: TDBXByteReader);
destructor Destroy; override;
end;
TDBXPoolRow = class(TDBXRow)
private
[Weak]FPoolList: TList<TDBXPool>;
FRow: Integer;
function Next: Boolean;
protected
procedure GetWideString(DbxValue: TDBXWideStringValue;
var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool); override;
procedure GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32;
var IsNull: LongBool); override;
public
constructor Create(PoolList: TList<TDBXPool>; DBXContext: TDBXContext);
end;
TDBXPool = class
private
FSemaphore: TDBXSemaphore;
FCriticalSection: TCriticalSection;
FAllConnectionArray: array of TDBXConnection;
FAvailableConnectionArray: array of TDBXConnection;
[Weak]FPoolDriver: TDBXPoolDriver;
FConnectionName: string;
FDriverName: string;
FDatabaseName: string;
FUserName: string;
FDelegateSignature: string;
FConnectTimeout: Integer;
FTotalConnections: Integer;
FAvailableConnections: Integer;
FMaxConnections: Integer;
constructor Create(Driver: TDBXPoolDriver;
ConnectionBuilder: TDBXConnectionBuilder);
function IsEqual(ConnectionBuilder: TDBXConnectionBuilder; const ConnectionName: string;
const DelegateSignature: string; const DriverName: string;
const DatabaseName: string; const UserName: string): Boolean;
function GetConnection(ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection;
procedure ReleaseConnection(Connection: TDBXConnection);
procedure ClearPool;
public
destructor Destroy; override;
end;
TDBXPoolDriver = class(TDBXDriver)
private
FPoolList: TList<TDBXPool>;
function FindPool(ConnectionBuilder: TDBXConnectionBuilder): TDBXPool;
procedure ClearPools;
function CreatePoolCommand(DBXContext: TDBXContext;
Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand;
protected
procedure Close; override;
public
destructor Destroy; override;
constructor Create(DriverDef: TDBXDriverDef); override;
function CreateConnection(ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection; override;
function GetDriverVersion: string; override;
end;
TDBXPoolProperties = class(TDBXProperties)
strict private
const
StrMaxConnections = 'MaxConnections';
const
StrMinConnections = 'MinConnections';
const
StrConnectTimeout = 'ConnectTimeout';
function GetConnectTimeout: Integer;
function GetMaxConnections: Integer;
function GetMinConnections: Integer;
procedure SetConnectTimeout(const Value: Integer);
procedure SetMaxConnections(const Value: Integer);
procedure SetMinConnections(const Value: Integer);
public
constructor Create(DBXContext: TDBXContext); override;
published
property MaxConnections: Integer read GetMaxConnections write SetMaxConnections;
property MinConnections: Integer read GetMinConnections write SetMinConnections;
property ConnectTimeout: Integer read GetConnectTimeout write SetConnectTimeout;
end;
implementation
uses
System.SysUtils,
Data.DBXCommonResStrs
;
type
TDBXColumnDef = record
Name: string;
DataType: TDBXType;
SubType: TDBXType;
Precision: TInt32;
Scale: TInt32;
Size: TInt32;
ValueTypeFlags: TInt32;
end;
TDBXAccessorConnection = class(TDBXConnection)
end;
const
WideStringPrecision = 96;
PoolValueTypeFlags =
TDBXValueTypeFlags.Nullable or TDBXValueTypeFlags.ReadOnly or
TDBXValueTypeFlags.Searchable;
PoolColumnDefs: array [0 .. 8] of TDBXColumnDef =
(
(Name: TDBXPoolsTable.ConnectionName; DataType: TDBXDataTypes.WideStringType; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.DriverName; DataType: TDBXDataTypes.WideStringType; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.DatabaseName; DataType: TDBXDataTypes.WideStringType; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.UserName; DataType: TDBXDataTypes.WideStringType; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.DelegateSignature; DataType: TDBXDataTypes.WideStringType; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.ConnectTimeout; DataType: TDBXDataTypes.Int32Type; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.AvailableConnections; DataType: TDBXDataTypes.Int32Type; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.TotalConnections; DataType: TDBXDataTypes.Int32Type; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags),
(Name: TDBXPoolsTable.MaxConnections; DataType: TDBXDataTypes.Int32Type; SubType: TDBXDataTypes.UnknownType; Precision: WideStringPrecision; Scale: -1; Size: WideStringPrecision; ValueTypeFlags: PoolValueTypeFlags)
);
{ TDBXPoolDriver }
constructor TDBXPoolDriver.Create(DriverDef: TDBXDriverDef);
begin
inherited Create(DriverDef);
FPoolList := TList<TDBXPool>.Create;
CacheUntilFinalization;
AddCommandFactory(TDBXCommandTypes.DbxPool, CreatePoolCommand);
InitDriverProperties(TDBXPoolProperties.Create(DriverDef.FDBXContext));
end;
function TDBXPoolDriver.CreateConnection(
ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection;
var
Pool: TDBXPool;
begin
Pool := FindPool(ConnectionBuilder);
if Pool = nil then
begin
Pool := TDBXPool.Create(Self, ConnectionBuilder);
FPoolList.Add(Pool);
end;
Result := Pool.GetConnection(ConnectionBuilder);
end;
function TDBXPoolDriver.CreatePoolCommand(DbxContext: TDBXContext;
Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand;
begin
Result := TDBXPoolCommand.Create(DBXContext, TDBXPoolConnection(Connection).FPool);
end;
destructor TDBXPoolDriver.Destroy;
var
Pool: TDBXPool;
Index: Integer;
begin
for Index := 0 to FPoolList.Count - 1 do
begin
Pool := FPoolList[Index];
Pool.Destroy;
end;
FreeAndNil(FPoolList);
inherited;
end;
function TDBXPoolDriver.FindPool(
ConnectionBuilder: TDBXConnectionBuilder): TDBXPool;
var
Index: Integer;
Pool: TDBXPool;
DatabaseName, DelegateSignature, DriverName: string;
begin
DelegateSignature := ConnectionBuilder.DelegationSignature;
DriverName := ConnectionBuilder.InputConnectionProperties[TDBXPropertyNames.DriverName];
DatabaseName := ConnectionBuilder.InputConnectionProperties[TDBXPropertyNames.Database];
for Index := 0 to FPoolList.Count - 1 do
begin
Pool := FPoolList[Index];
if Pool.IsEqual(ConnectionBuilder,
ConnectionBuilder.InputConnectionName,
DelegateSignature,
DriverName,
DatabaseName,
ConnectionBuilder.InputUserName) then
begin
Result := Pool;
Exit;
end;
end;
Result := nil;
end;
function TDBXPoolDriver.GetDriverVersion: string;
begin
Result := 'DBXPoolDriver 1.0'; {Do not localize}
end;
{ TDBXPool }
constructor TDBXPool.Create(Driver: TDBXPoolDriver; ConnectionBuilder: TDBXConnectionBuilder);
var
Properties: TDBXProperties;
begin
inherited Create;
FPoolDriver := Driver;
FConnectionName := ConnectionBuilder.InputConnectionName;
FDelegateSignature := ConnectionBuilder.DelegationSignature;
FDriverName := ConnectionBuilder.InputConnectionProperties[TDBXPropertyNames.DriverName];
FDatabaseName := ConnectionBuilder.InputConnectionProperties[TDBXPropertyNames.Database];
FUserName := ConnectionBuilder.InputUserName;
Properties := ConnectionBuilder.ConnectionProperties;
FTotalConnections := Properties.GetInteger(TDBXPoolPropertyNames.MinConnections);
if FTotalConnections < 0 then
FTotalConnections := 0;
FMaxConnections := Properties.GetInteger(TDBXPoolPropertyNames.MaxConnections);
if FMaxConnections < 1 then
FMaxConnections := 16;
FConnectTimeout := Properties.GetInteger(TDBXPoolPropertyNames.ConnectTimeout);
if FConnectTimeout < 0 then
FConnectTimeout := 0;
FSemaphore := TDBXSemaphore.Create(FMaxConnections);
FCriticalSection := TCriticalSection.Create;
SetLength(FAllConnectionArray, FTotalConnections);
SetLength(FAvailableConnectionArray, FTotalConnections);
end;
procedure TDBXPoolDriver.ClearPools;
var
Pool: TDBXPool;
Index: Integer;
begin
if FPoolList <> nil then
begin
for Index := 0 to FPoolList.Count - 1 do
begin
Pool := FPoolList[Index];
Pool.ClearPool;
end;
end;
end;
procedure TDBXPoolDriver.Close;
begin
ClearPools;
end;
procedure TDBXPool.ClearPool;
var
Index: Integer;
begin
for Index := 0 to FTotalConnections-1 do
FAllConnectionArray[Index].Free;
FTotalConnections := 0;
FAvailableConnections := 0;
end;
destructor TDBXPool.Destroy;
begin
ClearPool;
SetLength(FAllConnectionArray, 0);
SetLength(FAvailableConnectionArray, 0);
FreeandNil(FCriticalSection);
FreeAndNil(FSemaphore);
inherited;
end;
function TDBXPool.IsEqual(
ConnectionBuilder: TDBXConnectionBuilder;
const ConnectionName: string;
const DelegateSignature: string;
const DriverName: string;
const DatabaseName: string;
const UserName: string): Boolean;
begin
if (FConnectionName = ConnectionName) and (ConnectionName <> '') then
begin
if FUserName = UserName then
Result := true
else
Result := false;
end else
begin
if FDatabaseName <> DatabaseName then
Result := false
else if FUserName <> UserName then
Result := false
else if FDriverName <> DriverName then
Result := false
else if FDelegateSignature <> DelegateSignature then
Result := false
else
Result := true;
end;
end;
function TDBXPool.GetConnection(
ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection;
begin
Result := nil;
if not FSemaphore.Acquire(FConnectTimeout) then
ConnectionBuilder.DBXContext.Error(TDBXErrorCodes.ConnectionFailed,
Format(SConnectTimeout, [IntToStr(FConnectTimeout)]));
try
FCriticalSection.Acquire;
try
if FAvailableConnections < 1 then
begin
SetLength(FAllConnectionArray, FTotalConnections+1);
SetLength(FAvailableConnectionArray, FTotalConnections+1);
FAllConnectionArray[FTotalConnections] := ConnectionBuilder.CreateDelegateeConnection;
FAvailableConnectionArray[0] := FAllConnectionArray[FTotalConnections];
Inc(FTotalConnections);
Inc(FAvailableConnections);
end;
Result := TDBXPoolConnection.Create(Self, ConnectionBuilder, FPoolDriver, FAvailableConnectionArray[FAvailableConnections-1]);
dec(FAvailableConnections);
finally
FCriticalSection.Release;
end;
finally
// Something went wrong, let go of the semaphore.
//
if Result = nil then
FSemaphore.Release;
end;
end;
procedure TDBXPool.ReleaseConnection(Connection: TDBXConnection);
begin
FCriticalSection.Acquire;
try
FAvailableConnectionArray[FAvailableConnections] := Connection;
Inc(FAvailableConnections);
finally
FCriticalSection.Release;
end;
FSemaphore.Release;
end;
{ TDBXPoolConnection }
constructor TDBXPoolConnection.Create(Pool: TDBXPool; ConnectionBuilder: TDBXConnectionBuilder;
PoolDriver: TDBXPoolDriver; Connection: TDBXConnection);
begin
inherited Create(ConnectionBuilder, Connection);
FPoolDriver := PoolDriver;
FPool := Pool;
end;
function TDBXPoolConnection.CreateCommand: TDBXCommand;
begin
Result := TDBXMorphicCommand.Create(FDBXContext, Self);
end;
procedure TDBXPoolConnection.DerivedGetCommands(const CommandType: string;
const List: TStrings);
begin
if CommandType = TDBXCommandTypes.DbxPool then
List.Add(TDBXPoolCommands.GetPools);
inherited;
end;
procedure TDBXPoolConnection.Open;
begin
TDBXAccessorConnection(FConnection).Open;
end;
procedure TDBXPoolConnection.DerivedGetCommandTypes(const List: TStrings);
begin
if List.IndexOf(TDBXCommandTypes.DbxPool) < 0 then
List.Add(TDBXCommandTypes.DbxPool);
inherited;
end;
destructor TDBXPoolConnection.Destroy;
begin
FPool.ReleaseConnection(FConnection);
FConnection := nil; // Prevent if from being freed.
inherited;
end;
{ TDBXPoolCommand }
constructor TDBXPoolCommand.Create(DBXContext: TDBXContext; Pool: TDBXPool);
begin
inherited Create(DBXContext);
FPool := Pool;
end;
destructor TDBXPoolCommand.Destroy;
begin
inherited;
end;
function TDBXPoolCommand.ExecuteGetPools: TDBXReader;
var
Column: TDBXValueType;
ColumnDef: TDBXColumnDef;
Values: TDBXValueArray;
ColumnCount, Ordinal: Integer;
DbxPoolReader: TDBXPoolReader;
DbxPoolRow: TDBXPoolRow;
begin
DbxPoolRow := TDBXPoolRow.Create(FPool.FPoolDriver.FPoolList, FDBXContext);
DbxPoolReader := TDBXPoolReader.Create(FDBXContext, DbxPoolRow, nil);
try
ColumnCount := Length(PoolColumnDefs);
SetLength(Values, ColumnCount);
for Ordinal := 0 to ColumnCount-1 do
begin
Column := TDBXDriverHelp.CreateTDBXValueType(FDBXContext);
ColumnDef := PoolColumnDefs[Ordinal];
Column.DataType := ColumnDef.DataType;
Column.SubType := ColumnDef.SubType;
Column.Ordinal := Ordinal;
Column.Precision := ColumnDef.Precision;
Column.Scale := ColumnDef.Scale;
Column.Size := ColumnDef.Size;
Column.ValueTypeFlags := ColumnDef.ValueTypeFlags;
Column.Name := ColumnDef.Name;
Values[Ordinal] := TDBXValue.CreateValue(FDBXContext, Column, DbxPoolRow, true);
end;
DbxPoolReader.SetValues(Values);
Result := DbxPoolReader;
DbxPoolReader := nil;
finally
DbxPoolReader.Free;
end;
end;
function TDBXPoolCommand.GetRowsAffected: Int64;
begin
Result := -1;
end;
procedure TDBXPoolCommand.DerivedClose;
begin
end;
procedure TDBXPoolCommand.SetMaxBlobSize(const MaxBlobSize: Int64);
begin
NotImplemented;
end;
procedure TDBXPoolCommand.SetRowSetSize(const Value: Int64);
begin
NotImplemented;
end;
function TDBXPoolCommand.DerivedExecuteQuery: TDBXReader;
begin
if (Text = TDBXPoolCommands.GetPools) then
begin
Result := ExecuteGetPools;
end
else
begin
FDBXContext.Error(TDBXErrorCodes.NotImplemented,
Format(SInvalidCommand, [Text]));
Result := nil;
end;
end;
procedure TDBXPoolCommand.DerivedExecuteUpdate;
begin
NotImplemented;
end;
function TDBXPoolCommand.DerivedGetNextReader: TDBXReader;
begin
Result := nil;
end;
procedure TDBXPoolCommand.DerivedOpen;
begin
end;
procedure TDBXPoolCommand.DerivedPrepare;
begin
end;
{ TDBXPoolReader }
constructor TDBXPoolReader.Create(DBXContext: TDBXContext; DbxRow: TDBXRow;
ByteReader: TDBXByteReader);
begin
inherited Create(DBXContext, DbxRow, ByteReader);
end;
destructor TDBXPoolReader.Destroy;
begin
inherited;
end;
function TDBXPoolReader.GetByteReader: TDBXByteReader;
begin
if FByteReader = nil then
FByteReader := TDBXReaderByteReader.Create(FDbxContext, Self);
Result := FByteReader;
end;
procedure TDBXPoolReader.DerivedClose;
begin
FreeAndNil(FDbxRow);
FreeAndNil(FByteReader);
end;
function TDBXPoolReader.DerivedNext: Boolean;
begin
if FDbxRow = nil then
Result := False
else
Result := TDBXPoolRow(FDbxRow).Next;
end;
{ TDBXPoolRow }
constructor TDBXPoolRow.Create(PoolList: TList<TDBXPool>; DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
FRow := -1;
FPoolList := PoolList;
end;
procedure TDBXPoolRow.GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32;
var IsNull: LongBool);
var
Pool: TDBXPool;
begin
IsNull := false;
Pool := FPoolList[FRow];
case DbxValue.ValueType.Ordinal of
5: Value := Pool.FConnectTimeout;
6: Value := Pool.FAvailableConnections;
7: Value := Pool.FTotalConnections;
8: Value := Pool.FMaxConnections;
else
Assert(False);
end;
end;
procedure TDBXPoolRow.GetWideString(DbxValue: TDBXWideStringValue;
var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool);
var
Pool: TDBXPool;
Value: string;
begin
IsNull := False;
Pool := FPoolList[FRow];
case DbxValue.ValueType.Ordinal of
0: Value := Pool.FConnectionName;
1: Value := Pool.FDriverName;
2: Value := Pool.FDatabaseName;
3: Value := Pool.FUserName;
4: Value := Pool.FDelegateSignature;
else
Assert(False);
end;
TDBXPlatform.CopyWideStringToBuilder(Value, DBXValue.ValueType.Size, WideStringBuilder);
end;
function TDBXPoolRow.Next: Boolean;
begin
if (FRow+1) >= FPoolList.Count then
Result := False
else
begin
Inc(FRow);
Inc(FGeneration);
Result := True;
end;
end;
{ TDBXPoolProperties }
function TDBXPoolProperties.GetConnectTimeout: Integer;
begin
Result := StrToIntDef(Values[StrConnectTimeout], -1);
end;
function TDBXPoolProperties.GetMaxConnections: Integer;
begin
Result := StrToIntDef(Values[StrMaxConnections], -1);
end;
function TDBXPoolProperties.GetMinConnections: Integer;
begin
Result := StrToIntDef(Values[StrMinConnections], -1);
end;
procedure TDBXPoolProperties.SetConnectTimeout(const Value: Integer);
begin
Values[StrConnectTimeout] := IntToStr(Value);
end;
procedure TDBXPoolProperties.SetMaxConnections(const Value: Integer);
begin
Values[StrMaxConnections] := IntToStr(Value);
end;
procedure TDBXPoolProperties.SetMinConnections(const Value: Integer);
begin
Values[StrMinConnections] := IntToStr(Value);
end;
constructor TDBXPoolProperties.Create(DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
MaxConnections := 20;
MinConnections := 1;
ConnectTimeout := 1000;
Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXPool';
Values[TDBXPropertyNames.DelegateDriver] := BoolToStr(True, True);
end;
initialization
TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXPoolDriver);
finalization
TDBXDriverRegistry.UnloadDriver(sDriverName);
end.
|
namespace RemObjects.Elements.System;
type
Utilities = public static class
private
class var fFinalizer: ^Void;
class var fLoaded: Integer;
public
[SymbolName('__abstract')]
class method AbstractCall;
begin
raise new AbstractMethodException;
end;
[SymbolName('__isinst')]
class method IsInstance(aInstance: Object; aType: ^Void): Object;
begin
if aInstance = nil then exit nil;
var lTTY := ^^IslandTypeInfo(InternalCalls.Cast(aInstance))^;
loop begin
if lTTY = ^IslandTypeInfo(aType) then exit aInstance;
lTTY := lTTY^.ParentType;
if lTTY = nil then exit nil;
end;
end;
[SymbolName('__isintfinst')]
class method IsInterfaceInstance(aInstance: Object; aType: ^Void; aHashCode: Cardinal): ^Void;
begin
if aInstance =nil then exit nil;
var lIntf := ^^IslandTypeInfo(InternalCalls.Cast(aInstance))^^.InterfaceType;
if lIntf = nil then exit nil;
aHashCode := aHashCode mod lIntf^.HashTableSize;
var lHashEntry := (@lIntf^.FirstEntry)[aHashCode];
if lHashEntry = nil then exit nil;
repeat
if lHashEntry^ = aType then
exit aType;
inc(lHashEntry);
until lHashEntry^ = nil;
exit nil;
end;
[SymbolName('__newinvalidcast')]
class method CreateInvalidCastException: Exception;
begin
exit new InvalidCastException('Invalid cast');
end;
[SymbolName('__newinst')]
class method NewInstance(aTTY: ^Void; aSize: NativeInt): ^Void;
begin
if fFinalizer = nil then begin
fFinalizer := ^^Void(InternalCalls.GetTypeInfo<Object>())[4];
end;
if fLoaded = 0 then
if InternalCalls.CompareExchange(var fLoaded, 1, 0 ) <> 1 then begin
gc.GC_INIT;
result := ^void(-1);
end;
result := gc.GC_malloc(aSize);
^^void(result)^ := aTTY;
{$IFDEF WINDOWS}ExternalCalls.{$ELSE}rtl.{$ENDIF}memset(^Byte(result) + sizeof(^Void), 0, aSize - sizeof(^Void));
if ^^void(aTTY)[4] <> fFinalizer then begin
gc.GC_register_finalizer_no_order(result, @GC_finalizer, nil, nil, nil);
end;
end;
[SymbolName('__newarray')]
class method NewArray(aTY: ^Void; aElementSize, aElements: NativeInt): ^Void;
begin
result := NewInstance(aTY, sizeof(^Void) + Sizeof(NativeInt) + aElementSize * aElements);
InternalCalls.Cast<&Array>(result).fLength := aElements;
end;
[SymbolName('__newdelegate')]
class method NewDelegate(aTY: ^Void; aSelf: Object; aPtr: ^Void): &Delegate;
begin
result := InternalCalls.Cast<&Delegate>(NewInstance(aTY, SizeOf(^Void) * 3));
result.fSelf := aSelf;
result.fPtr := aPtr;
end;
[SymbolName('__init')]
class method Initialize;
begin
end;
[SymbolName('llvm.returnaddress')]
class method GetReturnAddress(aLevel: Integer): ^Void; external;
class method SuppressFinalize(o: Object);
begin
if o <> nil then
GC.GC_register_finalizer_no_order(InternalCalls.Cast(o), nil, nil, nil, nil);
end;
class method Collect(c: Integer);
begin
for i: Integer := 0 to c -1 do
GC.GC_gcollect();
end;
class method SpinLockEnter(var x: Integer);
begin
loop begin
if InternalCalls.Exchange(var x, 1) = 0 then exit;
if not Thread.Yield() then
Thread.Sleep(1);
end;
end;
class method SpinLockExit(var x: Integer);
begin
InternalCalls.VolatileWrite(var x, 0);
end;
class method SpinLockClassEnter(var x: NativeInt): Boolean;
begin
var cid := Thread.CurrentThreadId;
var lValue := InternalCalls.CompareExchange(var x, cid, NativeInt(0)); // returns old
if lValue = NativeInt(0) then exit true; // value was zero, we should run.
if lValue = cid then exit false; // same thread, but already running, don't go again.
if lValue = NativeInt(Int64(-1)) then exit false; // it's done in the mean time, we should exit.
// At this point it's NOT the same thread, and not done loading yet;
repeat
if not Thread.&Yield() then
Thread.Sleep(1);
lValue := InternalCalls.VolatileRead(var x); // returns old
until lValue = NativeInt(Int64(-1));
exit false;
end;
class method SpinLockClassExit(var x: NativeInt);
begin
InternalCalls.VolatileWrite(var x, NativeInt(Int64(-1)));
end;
method CalcHash(const buf: ^Void; len: Integer): Integer;
begin
var pb:= ^Byte(buf);
var r: UInt32:= $811C9DC5;
for i:Integer := 0 to Len-1 do begin
r := (r xor pb^) * $01000193;
Inc(pb);
end;
exit ^Integer(@r)^;
end;
end;
// Intrinsics
InternalCalls = public static class
public
class method GetTypeInfo<T>(): ^Void; external;
class method Cast(o: Object): ^Void; external;
class method Cast<T>(o: ^Void): T; external;
class method Undefined<T>: T; external;
class method VoidAsm(aAsm: String; aConstraints: String; aSideEffects, aAlign: Boolean; params aArgs: array of Object); external;
class method Asm(aAsm: String; aConstraints: String; aSideEffects, aAlign: Boolean; params aArgs: array of Object): NativeInt; external;
class method VolatileRead(var address: Byte): Byte; external;
class method VolatileRead(var address: Double): Double; external;
class method VolatileRead(var address: Int16): Int16; external;
class method VolatileRead(var address: Int32): Int32; external;
class method VolatileRead(var address: Int64): Int64; external;
class method VolatileRead(var address: NativeInt): NativeInt; external;
class method VolatileRead(var address: Object): Object; external;
class method VolatileRead(var address: SByte): SByte; external;
class method VolatileRead(var address: Single): Single; external;
class method VolatileRead(var address: UInt16): UInt16; external;
class method VolatileRead(var address: UInt32): UInt32; external;
class method VolatileRead(var address: UInt64): UInt64; external;
class method VolatileRead(var address: NativeUInt): NativeUInt; external;
class method VolatileWrite(var address: Byte; value: Byte); external;
class method VolatileWrite(var address: Double; value: Double); external;
class method VolatileWrite(var address: Int16; value: Int16); external;
class method VolatileWrite(var address: Int32; value: Int32); external;
class method VolatileWrite(var address: Int64; value: Int64); external;
class method VolatileWrite(var address: NativeInt; value: NativeInt); external;
class method VolatileWrite(var address: Object; value: Object); external;
class method VolatileWrite(var address: SByte; value: SByte); external;
class method VolatileWrite(var address: Single; value: Single); external;
class method VolatileWrite(var address: UInt16; value: UInt16); external;
class method VolatileWrite(var address: UInt32; value: UInt32); external;
class method VolatileWrite(var address: UInt64; value: UInt64); external;
class method VolatileWrite(var address: NativeUInt; value: NativeUInt); external;
class method CompareExchange(var address: Int64; value, compare: Int64): Int64; external;
class method CompareExchange(var address: Int32; value, compare: Int32): Int32; external;
class method CompareExchange(var address: NativeInt; value, compare: NativeInt): NativeInt; external;
class method CompareExchange(var address: UInt64; value, compare: UInt64): UInt64; external;
class method CompareExchange(var address: UInt32; value, compare: UInt32): UInt32; external;
class method CompareExchange(var address: NativeUInt; value, compare: NativeUInt): NativeUInt; external;
class method CompareExchange<T>(var address: T; value, compare: T): T; external;
class method Exchange(var address: Int64; value: Int64): Int64; external;
class method Exchange(var address: Int32; value: Int32): Int32; external;
class method Exchange(var address: NativeInt; value: NativeInt): NativeInt; external;
class method Exchange(var address: UInt64; value: UInt64): UInt64; external;
class method Exchange(var address: UInt32; value: UInt32): UInt32; external;
class method Exchange(var address: NativeUInt; value: NativeUInt): NativeUInt; external;
class method Exchange<T>(var address: T; value: T): T; external;
class method Increment(var address: Int64): Int64; external;
class method Increment(var address: Int32): Int32; external;
class method Decrement(var address: Int64): Int64; external;
class method Decrement(var address: Int32): Int32; external;
class method &Add(var address: Int32; value: Int32): Int32; external;
class method &Add(var address: Int64; value: Int64): Int64; external;
end;
{$G+}
method GC_finalizer(obj, d: ^void); assembly;
begin
InternalCalls.Cast<Object>(obj).Finalize;
end;
end.
|
unit bi_timer;
interface
uses Windows, Messages, SysUtils, Classes, Controls;
type
TBI_Timer = class(TComponent)
private
FEnabled: Boolean;
FInterval: Cardinal;
FOnTimer: TNotifyEvent;
FTimerThread: TThread;
FThreadPriority: TThreadPriority;
procedure UpdateTimer;
procedure SetOnTimer(Value: TNotifyEvent);
procedure SetEnabled(Value: Boolean);
procedure SetInterval(Value: Cardinal);
procedure SetThreadPriority(Value: TThreadPriority);
protected
procedure Timer; dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Interval: Cardinal read FInterval write SetInterval default 1000;
property ThreadPriority: TThreadPriority read FThreadPriority write
SetThreadPriority default tpNormal;
property OnTimer: TNotifyEvent read FOnTimer write SetOnTimer;
property Name;
end;
bi_t_thread = class(tthread)
private
FOwner: TBI_Timer;
FWaitForTerminate: Boolean;
protected
procedure Execute; override;
public
constructor Create(timer:tbi_timer);
end;
implementation
procedure bi_t_thread.Execute;
begin
Priority := FOwner.FThreadPriority;
repeat
if SleepEx(FOwner.FInterval, False) = 0 then
if not FWaitforterminate then synchronize(FOwner.Timer); until Terminated;
end;
constructor bi_t_thread.Create(timer:tbi_timer);
begin
inherited Create(False);
FOwner := Timer;
Priority := FOwner.FThreadPriority;
FreeOnTerminate := True;
end;
constructor TBI_Timer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := True;
FInterval := 1000;
FThreadPriority := tpNormal;
FTimerThread := bi_t_thread.Create(Self);
end;
destructor TBI_Timer.Destroy;
begin
FEnabled := False;
UpdateTimer;
if FTimerThread <> nil then
begin
bi_t_thread(FTimerThread).FWaitForTerminate := True;
FTimerThread.Free;
end;
inherited Destroy;
end;
procedure TBI_Timer.UpdateTimer;
begin
if FTimerThread <> nil then
if not FTimerThread.Suspended then FTimerThread.Suspend;
if FTimerThread = nil then FTimerThread := bi_t_thread.Create(Self);
if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then
begin
FTimerThread.Priority := FThreadPriority;
while FTimerThread.Suspended do FTimerThread.Resume;
end;
end;
procedure TBI_Timer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then begin
FEnabled := Value;
UpdateTimer;
end;
end;
procedure TBI_Timer.SetInterval(Value: Cardinal);
begin
if Value <> FInterval then begin
FInterval := Value;
UpdateTimer;
end;
end;
procedure TBI_Timer.SetThreadPriority(Value: TThreadPriority);
begin
if Value <> FThreadPriority then
FThreadPriority := Value;
end;
procedure TBI_Timer.SetOnTimer(Value: TNotifyEvent);
begin
FOnTimer := Value;
UpdateTimer;
end;
procedure TBI_Timer.Timer;
begin
if FEnabled and Assigned(FOnTimer) then FOnTimer(Self);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Data.DbxInformix"'} {Do not Localize}
unit Data.DbxInformix;
interface
uses
Data.DBXDynalink,
Data.DBXDynalinkNative,
Data.DBXCommon, Data.DbxInformixReadOnlyMetaData, Data.DbxInformixMetaData;
type
TDBXInformixProperties = class(TDBXProperties)
strict private
const StrInformixTransIsolation = 'Informix TransIsolation';
const StrTrimChar = 'Trim Char';
function GetHostName: string;
function GetPassword: string;
function GetUserName: string;
function GetBlobSize: Integer;
function GetDatabase: string;
function GetInformixTransIsolation: string;
function GetTrimChar: Boolean;
procedure SetBlobSize(const Value: Integer);
procedure SetDatabase(const Value: string);
procedure SetInformixTransIsolation(const Value: string);
procedure SetTrimChar(const Value: Boolean);
procedure SetHostName(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
public
constructor Create(DBXContext: TDBXContext); override;
published
property HostName: string read GetHostName write SetHostName;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property Database: string read GetDatabase write SetDatabase;
property BlobSize: Integer read GetBlobSize write SetBlobSize;
property InformixTransIsolation:string read GetInformixTransIsolation write SetInformixTransIsolation;
property TrimChar: Boolean read GetTrimChar write SetTrimChar;
end;
TDBXInformixDriver = class(TDBXDynalinkDriverNative)
public
constructor Create(DBXDriverDef: TDBXDriverDef); override;
end;
implementation
uses
Data.DBXPlatform, System.SysUtils;
const
sDriverName = 'Informix';
{ TDBXInformixDriver }
constructor TDBXInformixDriver.Create(DBXDriverDef: TDBXDriverDef);
var
Props: TDBXInformixProperties;
I, Index: Integer;
begin
Props := TDBXInformixProperties.Create(DBXDriverDef.FDBXContext);
if DBXDriverDef.FDriverProperties <> nil then
begin
for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do
begin
Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]);
if Index > -1 then
Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I];
end;
Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties);
DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties);
end;
inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props);
rcs;
end;
{ TDBXInformixProperties }
constructor TDBXInformixProperties.Create(DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXInformix';
Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXInformixDriver160.bpl';
Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXInformixMetaDataCommandFactory,DbxInformixDriver160.bpl';
Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXInformixMetaDataCommandFactory,Borland.Data.DbxInformixDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverINFORMIX';
Values[TDBXPropertyNames.LibraryName] := 'dbxinf.dll';
Values[TDBXPropertyNames.LibraryNameOsx] := 'libsqlinf.dylib';
Values[TDBXPropertyNames.VendorLib] := 'isqlt09a.dll';
Values[TDBXPropertyNames.VendorLibWin64] := 'isqlt09a.dll';
Values[TDBXPropertyNames.VendorLibOsx] := 'libifcli.dylib';
Values[TDBXPropertyNames.HostName] := 'ServerName';
Values[TDBXPropertyNames.Database] := 'Database Name';
Values[TDBXPropertyNames.UserName] := 'user';
Values[TDBXPropertyNames.Password] := 'password';
Values[TDBXPropertyNames.MaxBlobSize] := '-1';
Values[TDBXPropertyNames.ErrorResourceFile] := '';
Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000';
Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted';
Values['TrimChar'] := 'False';
Values['DelimIdent'] := 'True';
end;
function TDBXInformixProperties.GetBlobSize: Integer;
begin
Result := StrToIntDef(Values[TDBXPropertyNames.MaxBlobSize], -1);
end;
function TDBXInformixProperties.GetDatabase: string;
begin
Result := Values[TDBXPropertyNames.Database];
end;
function TDBXInformixProperties.GetInformixTransIsolation: string;
begin
Result := Values[StrInformixTransIsolation];
end;
function TDBXInformixProperties.GetTrimChar: Boolean;
begin
Result := StrToBoolDef(Values[StrTrimChar], False);
end;
function TDBXInformixProperties.GetHostName: string;
begin
Result := Values[TDBXPropertyNames.HostName];
end;
function TDBXInformixProperties.GetPassword: string;
begin
Result := Values[TDBXPropertyNames.Password];
end;
function TDBXInformixProperties.GetUserName: string;
begin
Result := Values[TDBXPropertyNames.UserName];
end;
procedure TDBXInformixProperties.SetBlobSize(const Value: Integer);
begin
Values[TDBXPropertyNames.MaxBlobSize] := IntToStr(Value);
end;
procedure TDBXInformixProperties.SetDatabase(const Value: string);
begin
Values[TDBXPropertyNames.Database] := Value;
end;
procedure TDBXInformixProperties.SetInformixTransIsolation(const Value: string);
begin
Values[StrInformixTransisolation] := Value;
end;
procedure TDBXInformixProperties.SetTrimChar(const Value: Boolean);
begin
Values[StrTrimChar] := BoolToStr(Value, True);
end;
procedure TDBXInformixProperties.SetHostName(const Value: string);
begin
Values[TDBXPropertyNames.HostName] := Value;
end;
procedure TDBXInformixProperties.SetPassword(const Value: string);
begin
Values[TDBXPropertyNames.Password] := Value;
end;
procedure TDBXInformixProperties.SetUserName(const Value: string);
begin
Values[TDBXPropertyNames.UserName] := Value;
end;
initialization
TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXInformixDriver);
end.
|
unit UCampoCodigoGrid;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, Vcl.Imaging.GIFImg, Vcl.ExtCtrls, Vcl.Menus,
Vcl.StdCtrls, UDBCampoCodigo;
type
TFCampoCodigoGrid = class(TForm)
edcdCampoCodigo: TDBCampoCodigo;
lbcdCampoCodigo: TLabel;
btOk: TButton;
procedure btOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FCampoCodigoGrid: TFCampoCodigoGrid;
implementation
{$R *.dfm}
procedure TFCampoCodigoGrid.btOkClick(Sender: TObject);
begin
Self.Close;
end;
procedure TFCampoCodigoGrid.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
btOk.Click;
end;
procedure TFCampoCodigoGrid.FormShow(Sender: TObject);
begin
if Trim(edcdCampoCodigo.ERPEdCampoChaveText) <> '' then
edcdCampoCodigo.ValidaCampoChave(edcdCampoCodigo.ERPEdCampoChaveText);
edcdCampoCodigo.ERPEdCampoChaveSetFocus;
end;
end.
|
unit SaberCompareUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Db, DBTables, ComCtrls, ExtCtrls;
type
TForm1 = class(TForm)
StartButton: TBitBtn;
CancelButton: TBitBtn;
ParcelTable: TTable;
ResidentialBuildingTable: TTable;
ResidentialImprovementTable: TTable;
SaberParcelTable: TTable;
SaberResidentialBuildingTable: TTable;
SaberResidentialImprovementTable: TTable;
Label9: TLabel;
SwisCodeListBox: TListBox;
ProgressBar: TProgressBar;
SwisCodeTable: TTable;
InitializationTimer: TTimer;
SystemTable: TTable;
AssessmentYearControlTable: TTable;
BuildingStyleCodeTable: TTable;
procedure FormCreate(Sender: TObject);
procedure StartButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure InitializationTimerTimer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cancelled : Boolean;
Procedure InitializeForm;
Procedure GetDifferencesThisParcel(DifferencesThisParcel : TList);
Procedure PrintThisParcel(var ExtractFile : TextFile;
SwisSBLKey : String;
Owner : String;
Location : String;
DifferencesThisParcel : TList);
end;
DifferenceRecord = record
DifferenceField : Integer;
PASValue : String;
SaberValue : String;
end;
DifferencePointer = ^DifferenceRecord;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses GlblVars, GlblCnst, Winutils, Utilitys, PASUtils, Types, PASTypes;
const
dfParcelExists = 0;
dfBathrooms = 1;
dfFireplaces = 2;
dfKitchens = 3;
dfStories = 4;
dfSFLA = 5;
dfHalfStory = 6;
dfFirstFloor = 7;
dfSecondFloor = 8;
dfThirdFloor = 9;
dfBuildingStyle = 10;
dfGarageType = 11;
dfFinishedAttic = 12;
dfFinishedBasement = 13;
dfFinishedRecRoom = 14;
dfFinishedOverGarage = 15;
dfPorchType = 16;
dfPorchSquareFeet = 17;
dfInGroundPool = 18;
dfAcreage = 19;
dfPropertyClass = 20;
DecimalEditDisplay = '0.00';
{=============================================}
Procedure TForm1.FormCreate(Sender: TObject);
begin
InitializationTimer.Enabled := True;
end;
{=============================================}
Procedure TForm1.InitializationTimerTimer(Sender: TObject);
begin
InitializationTimer.Enabled := False;
InitializeForm;
end;
{=============================================}
Procedure TForm1.InitializeForm;
begin
ParcelTable.Open;
ResidentialBuildingTable.Open;
ResidentialImprovementTable.Open;
SaberParcelTable.Open;
SaberResidentialBuildingTable.Open;
SaberResidentialImprovementTable.Open;
SystemTable.Open;
SwisCodeTable.Open;
AssessmentYearControlTable.Open;
BuildingStyleCodeTable.Open;
SetGlobalSystemVariables(SystemTable);
SetGlobalSBLSegmentFormats(AssessmentYearControlTable);
FillOneListBox(SwisCodeListBox, SwisCodeTable,
'SwisCode', 'MunicipalityName', 20,
True, True, ThisYear, GlblThisYear);
end; {InitializeForm}
{===========================================}
Function Power10(Places : Byte):Double;
{DS: Raise 10 to the indicated power (limited to 0,1,2,3,4,or 5) }
Var
Res : Double;
begin
Res := 0;
{ensure argument is in range...}
If Places > 5 then Places := 5;
Case Places of
0: Res := 1.0;
1: Res := 10.0;
2: Res := 100.0;
3: Res := 1000.0;
4: Res := 10000.0;
5: Res := 100000.0;
end; {case}
Power10 := Res;
end; { function Power10}
{==================================================================}
Function Roundoff(Number : Extended;
NumPlaces : Integer) : Extended;
var
I, FirstPlaceAfterDecimalPos, Pos,
DeterminingDigit, DigitInt, ReturnCode : Integer;
Digit : Real;
Answer : Extended;
AnswerStr, NumString : Str14;
AddOne : Boolean;
DigitStr : Str1;
begin
{They can only round off up to 5 places.}
If (NumPlaces > 5)
then NumPlaces := 5;
Str(Number:14:6, NumString);
NumString := LTrim(NumString);
{Find the decimal point.}
Pos := 1;
while ((Pos <= Length(NumString)) and (NumString[Pos] <> '.')) do
Pos := Pos + 1;
FirstPlaceAfterDecimalPos := Pos + 1;
{Now let's look at the place that we need to in order to determine
whether to round up or round down.}
DeterminingDigit := FirstPlaceAfterDecimalPos + NumPlaces;
Val(NumString[DeterminingDigit], DigitInt, ReturnCode);
(*DigitInt := Trunc(Digit);*)
{If the determining digit is >= 5, then round up. Otherwise, round
down.}
If (DigitInt >= 5)
then
begin
AnswerStr := '';
AddOne := True;
{We are rounding up, so first let's add one to the digit to
the left of the determining digit. If it takes us to ten,
continue working to the left until we don't roll over a
digit to ten.}
For I := (DeterminingDigit - 1) downto 1 do
begin
If (NumString[I] = '.')
then AnswerStr := '.' + AnswerStr
else
begin {The character is a digit.}
{FXX05261998-1: Not leaving the negative sign if
this is a negative number.}
If (NumString[I] = '-')
then AnswerStr := '-' + AnswerStr
else
begin
Val(NumString[I], Digit, ReturnCode);
DigitInt := Trunc(Digit);
If AddOne
then DigitInt := DigitInt + 1;
If (DigitInt = 10)
then AnswerStr := '0' + AnswerStr
else
begin
AddOne := False;
Str(DigitInt:1, DigitStr);
AnswerStr := DigitStr + AnswerStr;
end; {else of If (((DigitInt + 1) = 10) and AddOne)}
end; {else of If (NumString[I] = '-')}
end; {else of If (NumString[I] = '.')}
end; {For I := Pos to 1 do}
If AddOne
then AnswerStr := '1' + AnswerStr;
end {If (DigitInt >= 5)}
else AnswerStr := Copy(NumString, 1, (DeterminingDigit - 1));
Val(AnswerStr, Answer, ReturnCode);
Roundoff := Answer;
end; { function Roundoff....}
{=============================================}
Procedure AddDifferenceEntry(DifferencesThisParcel : TList;
_DifferenceField : Integer;
_PASValue : String;
_SaberValue : String;
Numeric : Boolean;
Float : Boolean);
var
DifferencePtr : DifferencePointer;
TempIntPAS, TempIntSaber : LongInt;
TempFloatPAS, TempFloatSaber : Double;
begin
New(DifferencePtr);
If Numeric
then
begin
If Float
then
begin
try
TempFloatPAS := StrToFloat(_PASValue);
except
TempFloatPAS := 0;
end;
try
TempFloatSaber := StrToFloat(_SaberValue);
except
TempFloatSaber := 0;
end;
If ((Roundoff(TempFloatPAS, 2) = 0) and
(Roundoff(TempFloatSaber, 2) = 0))
then
begin
_PASValue := '';
_SaberValue := '';
end
else
begin
If (Roundoff(TempFloatPAS, 2) = 0)
then _PASValue := '0'
else _PASValue := FormatFloat(DecimalEditDisplay,
TempFloatPAS);
If (Roundoff(TempFloatSaber, 2) = 0)
then _SaberValue := '0'
else _SaberValue := FormatFloat(DecimalEditDisplay,
TempFloatSaber);
end; {else of If ((TempFloatPAS = 0) and ...}
end {If Float}
else
begin
try
TempIntPAS := StrToInt(_PASValue);
except
TempIntPAS := 0;
end;
try
TempIntSaber := StrToInt(_SaberValue);
except
TempIntSaber := 0;
end;
If ((TempIntPAS = 0) and
(TempIntSaber = 0))
then
begin
_PASValue := '';
_SaberValue := '';
end
else
begin
If (TempIntPAS = 0)
then _PASValue := '0';
If (TempIntSaber = 0)
then _SaberValue := '0';
end; {else of If ((TempIntPAS = 0) and ...}
end; {else of If Float}
end; {If Numeric}
with DifferencePtr^ do
begin
DifferenceField := _DifferenceField;
PASValue := _PASValue;
SaberValue := _SaberValue;
end;
DifferencesThisParcel.Add(DifferencePtr);
end; {AddDifferenceEntry}
{=============================================}
Procedure CompareOneField(DifferencesThisParcel : TList;
DifferenceType : Integer;
FieldName : String;
PASTable : TTable;
SaberTable : TTable;
Numeric : Boolean;
Float : Boolean);
var
PASValue, SaberValue : String;
PASFloat, SaberFloat : Double;
DifferencesExists : Boolean;
begin
try
PASValue := Trim(PASTable.FieldByName(FieldName).Text);
except
PASValue := '';
end;
try
SaberValue := Trim(SaberTable.FieldByName(FieldName).Text);
except
SaberValue := '';
end;
DifferencesExists := (PASValue <> SaberValue);
If (Numeric and Float)
then
begin
try
PASFloat := Roundoff(StrToFloat(PASValue), 2);
except
PASFloat := 0;
end;
try
SaberFloat := Roundoff(StrToFloat(SaberValue), 2);
except
SaberFloat := 0;
end;
DifferencesExists := (Roundoff(PASFloat, 2) <> Roundoff(SaberFloat, 2));
end; {If (Numeric and Float)}
If DifferencesExists
then AddDifferenceEntry(DifferencesThisParcel, DifferenceType,
PASValue, SaberValue, Numeric, Float);
end; {CompareOneField}
{=============================================}
Procedure TForm1.GetDifferencesThisParcel(DifferencesThisParcel : TList);
var
ParcelFound, Done, FirstTimeThrough : Boolean;
PASBuildingStyle, SaberBuildingStyle,
PASBuildingStyleDesc, SaberBuildingStyleDesc,
SwisSBLKey, PASPoolType, SaberPoolType : String;
SBLRec : SBLRecord;
begin
SwisSBLKey := ExtractSSKey(ParcelTable);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
ParcelFound := FindKeyOld(SaberParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'],
['2002', SwisCode, Section,
SubSection, Block, Lot, Sublot, Suffix]);
If ParcelFound
then
begin
SetRangeOld(ResidentialBuildingTable, ['TaxRollYr', 'SwisSBLKey'],
[GlblThisYear, SwisSBLKey], [GlblThisYear, SwisSBLKey]);
SetRangeOld(SaberResidentialBuildingTable, ['TaxRollYr', 'SwisSBLKey'],
['2002', SwisSBLKey], ['2002', SwisSBLKey]);
SetRangeOld(ResidentialImprovementTable, ['TaxRollYr', 'SwisSBLKey'],
[GlblThisYear, SwisSBLKey], [GlblThisYear, SwisSBLKey]);
SetRangeOld(SaberResidentialImprovementTable, ['TaxRollYr', 'SwisSBLKey'],
['2002', SwisSBLKey], ['2002', SwisSBLKey]);
CompareOneField(DifferencesThisParcel, dfBathrooms, 'NumberOfBathrooms',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, False);
CompareOneField(DifferencesThisParcel, dfFireplaces, 'NumberOfFireplaces',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfKitchens, 'NumberOfKitchens',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, False);
CompareOneField(DifferencesThisParcel, dfStories, 'NumberOfStories',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, False);
CompareOneField(DifferencesThisParcel, dfSFLA, 'SqFootLivingArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfHalfStory, 'HalfStoryArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFirstFloor, 'FirstStoryArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfSecondFloor, 'SecondStoryArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfThirdFloor, 'ThirdStoryArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
(* CompareOneField(DifferencesThisParcel, dfBuildingStyle, 'BuildingStyleCode',
ResidentialBuildingTable, SaberResidentialBuildingTable, False, False);*)
{Always show building style and do it as the description.}
PASBuildingStyle := ResidentialBuildingTable.FieldByName('BuildingStyleCode').Text;
SaberBuildingStyle := SaberResidentialBuildingTable.FieldByName('BuildingStyleCode').Text;
PASBuildingStyleDesc := '';
SaberBuildingStyleDesc := '';
If ((Deblank(PASBuildingStyle) <> '') and
FindKeyOld(BuildingStyleCodeTable, ['MainCode'], [PASBuildingStyle]))
then PASBuildingStyleDesc := BuildingStyleCodeTable.FieldByName('Description').Text;
If ((Deblank(SaberBuildingStyle) <> '') and
FindKeyOld(BuildingStyleCodeTable, ['MainCode'], [SaberBuildingStyle]))
then SaberBuildingStyleDesc := BuildingStyleCodeTable.FieldByName('Description').Text;
AddDifferenceEntry(DifferencesThisParcel, dfBuildingStyle,
PASBuildingStyleDesc, SaberBuildingStyleDesc, False, False);
CompareOneField(DifferencesThisParcel, dfFinishedAttic, 'FinishedAtticArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFinishedBasement, 'FinishedBasementArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFinishedRecRoom, 'FinishedRecRoom',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFinishedOverGarage, 'FinishedAreaOverGara',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfPorchType, 'PorchTypeCode',
ResidentialBuildingTable, SaberResidentialBuildingTable, False, False);
CompareOneField(DifferencesThisParcel, dfPorchSquareFeet, 'PorchArea',
ResidentialBuildingTable, SaberResidentialBuildingTable, True, True);
{Do the pool type.}
PASPoolType := '';
SaberPoolType := '';
Done := False;
FirstTimeThrough := True;
ResidentialImprovementTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else ResidentialImprovementTable.Next;
If ResidentialImprovementTable.EOF
then Done := True;
If ((not Done) and
(Copy(ResidentialImprovementTable.FieldByName('StructureCode').Text, 1, 2) = 'LS'))
then PASPoolType := ResidentialImprovementTable.FieldByName('StructureCode').Text;
until Done;
Done := False;
FirstTimeThrough := True;
SaberResidentialImprovementTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else SaberResidentialImprovementTable.Next;
If SaberResidentialImprovementTable.EOF
then Done := True;
If ((not Done) and
(Copy(SaberResidentialImprovementTable.FieldByName('StructureCode').Text, 1, 2) = 'LS'))
then SaberPoolType := SaberResidentialImprovementTable.FieldByName('StructureCode').Text;
until Done;
If (PASPoolType <> SaberPoolType)
then AddDifferenceEntry(DifferencesThisParcel, dfInGroundPool,
PASPoolType, SaberPoolType, False, False);
CompareOneField(DifferencesThisParcel, dfAcreage, 'Acreage',
ParcelTable, SaberParcelTable, True, True);
CompareOneField(DifferencesThisParcel, dfPropertyClass, 'PropertyClassCode',
ParcelTable, SaberParcelTable, False, False);
end {If ParcelFound}
else AddDifferenceEntry(DifferencesThisParcel, dfParcelExists,
ConvertSwisSBLToDashDotNoSwis(SwisSBLKey), '', False, False);
end; {GetDifferencesThisParcel}
{=============================================}
Function FindDifferenceItem( DifferencesThisParcel : TList;
_DifferenceField : Integer;
var Index : Integer) : Boolean;
var
I : Integer;
begin
Result := False;
Index := -1;
For I := 0 to (DifferencesThisParcel.Count - 1) do
If ((Index = -1) and
(DifferencePointer(DifferencesThisParcel[I])^.DifferenceField = _DifferenceField))
then
begin
Index := I;
Result := True;
end;
end; {FindDifferenceItem}
{=============================================}
Procedure WriteOneDifference(var ExtractFile : TextFile;
DifferencesThisParcel : TList;
_DifferenceField : Integer);
var
_PASValue, _SaberValue : String;
I : Integer;
begin
_PASValue := '';
_SaberValue := '';
If FindDifferenceItem(DifferencesThisParcel, _DifferenceField, I)
then
with DifferencePointer(DifferencesThisParcel[I])^ do
begin
_PASValue := PASValue;
_SaberValue := SaberValue;
end;
Write(ExtractFile, FormatExtractField(_PASValue),
FormatExtractField(_SaberValue));
end; {WriteOneDifference}
{=============================================}
Procedure TForm1.PrintThisParcel(var ExtractFile : TextFile;
SwisSBLKey : String;
Owner : String;
Location : String;
DifferencesThisParcel : TList);
var
I : Integer;
begin
Write(ExtractFile, Copy(SwisSBLKey, 1, 6),
FormatExtractField(ConvertSwisSBLToDashDotNoSwis(SwisSBLKey)),
FormatExtractField(Owner),
FormatExtractField(Location));
If FindDifferenceItem(DifferencesThisParcel, dfParcelExists, I)
then Writeln(ExtractFile, FormatExtractField('No Saber parcel found.'))
else
begin
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfBathrooms);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFireplaces);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfKitchens);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfStories);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfSFLA);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfHalfStory);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFirstFloor);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfSecondFloor);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfThirdFloor);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfBuildingStyle);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfGarageType);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFinishedAttic);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFinishedBasement);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFinishedRecRoom);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFinishedOverGarage);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfPorchType);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfPorchSquareFeet);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfInGroundPool);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfAcreage);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfPropertyClass);
Writeln(ExtractFile);
end; {else of If FindDifferenceItem(DifferencesThisParcel, dfParcelExists, I)}
end; {PrintThisParcel}
{=============================================}
Procedure TForm1.StartButtonClick(Sender: TObject);
var
ExtractFile : TextFile;
SpreadsheetFileName : String;
Done, FirstTimeThrough : Boolean;
DifferencesThisParcel : TList;
SelectedSwisCodes : TStringList;
I : Integer;
begin
Cancelled := False;
SelectedSwisCodes := TStringList.Create;
DifferencesThisParcel := TList.Create;
SpreadsheetFileName := GetPrintFileName(Self.Caption, True);
AssignFile(ExtractFile, SpreadsheetFileName);
Rewrite(ExtractFile);
Writeln(ExtractFile, ',,,,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber');
Writeln(ExtractFile, 'Swis,',
'Parcel ID,',
'Owner,',
'Legal Address,',
'# Bathrooms,',
'# Bathrooms,',
'# Fireplaces,',
'# Fireplaces,',
'# Kitchens,',
'# Kitchens,',
'# Stories,',
'# Stories,',
'SFLA,',
'SFLA,',
'Half Story,',
'Half Story,',
'First Floor,',
'First Floor,',
'Second Floor,',
'Second Floor,',
'Third Floor,',
'Third Floor,',
'Bldg Style,',
'Bldg Style,',
'Garage Type,',
'Garage Type,',
'Fin Attic,',
'Fin Attic,',
'Fin Bsmt,',
'Fin Bsmt,',
'Fin Rec Room,',
'Fin Rec Room,',
'Fin Over Gar,',
'Fin Over Gar,',
'Porch Type,',
'Porch Type,',
'Prch Area,',
'Prch Area,',
'Pool Type,',
'Pool Type,',
'Acreage,',
'Acreage,',
'Class,',
'Class');
For I := 0 to (SwisCodeListBox.Items.Count - 1) do
If SwisCodeListBox.Selected[I]
then SelectedSwisCodes.Add(Take(6, SwisCodeListBox.Items[I]));
Done := False;
FirstTimeThrough := True;
ParcelTable.First;
ProgressBar.Max := GetRecordCount(ParcelTable);
ProgressBar.Position := 0;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else ParcelTable.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
If ParcelTable.EOF
then Done := True;
If ((not Done) and
(SelectedSwisCodes.IndexOf(ParcelTable.FieldByName('SwisCode').Text) > -1))
then
begin
ClearTList(DifferencesThisParcel, SizeOf(DifferenceRecord));
GetDifferencesThisParcel(DifferencesThisParcel);
If (DifferencesThisParcel.Count > 0)
then PrintThisParcel(ExtractFile,
ExtractSSKey(ParcelTable),
ParcelTable.FieldByName('Name1').Text,
GetLegalAddressFromTable(ParcelTable),
DifferencesThisParcel);
end; {If not Done}
until (Done or Cancelled);
FreeTList(DifferencesThisParcel, SizeOf(DifferenceRecord));
CloseFile(ExtractFile);
SendTextFileToExcelSpreadsheet(SpreadsheetFileName, True,
False, '');
SelectedSwisCodes.Free;
ProgressBar.Position := 0;
end; {StartButtonClick}
{=================================================================}
Procedure TForm1.CancelButtonClick(Sender: TObject);
begin
If (MessageDlg('Are you sure you want to cancel the comparison?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then Cancelled := True;
end; {CancelButtonClick}
end. |
{*******************************************************}
{ }
{ RadStudio Debugger Visualizer Sample }
{ Copyright(c) 2009-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit StdStringVisualizer;
interface
procedure Register;
implementation
uses
Classes, Forms, SysUtils, ToolsAPI;
resourcestring
sStdStringVisualizerName = 'std::string and std::wstring Visualizer for C++';
sStdStringVisualizerDescription = 'Displays the actual string value for std::string and std::wstring instances';
type
TStdStringTimeVisualizer = class(TInterfacedObject, IOTADebuggerVisualizer,
IOTADebuggerVisualizerValueReplacer, IOTAThreadNotifier, IOTAThreadNotifier160)
private
FNotifierIndex: Integer;
FCompleted: Boolean;
FDeferredResult: string;
public
{ IOTADebuggerVisualizer }
function GetSupportedTypeCount: Integer;
procedure GetSupportedType(Index: Integer; var TypeName: string;
var AllDescendants: Boolean);
function GetVisualizerIdentifier: string;
function GetVisualizerName: string;
function GetVisualizerDescription: string;
{ IOTADebuggerVisualizerValueReplacer }
function GetReplacementValue(const Expression, TypeName, EvalResult: string): string;
{ IOTAThreadNotifier }
procedure EvaluteComplete(const ExprStr: string; const ResultStr: string;
CanModify: Boolean; ResultAddress: Cardinal; ResultSize: Cardinal;
ReturnCode: Integer);
procedure ModifyComplete(const ExprStr: string; const ResultStr: string;
ReturnCode: Integer);
procedure ThreadNotify(Reason: TOTANotifyReason);
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
{ IOTAThreadNotifier160 }
procedure EvaluateComplete(const ExprStr: string; const ResultStr: string;
CanModify: Boolean; ResultAddress: TOTAAddress; ResultSize: LongWord;
ReturnCode: Integer);
end;
const
StdStringVisualizerTypes: array[0..3] of string =
(
'std::basic_string<char, std::char_traits<char>, std::allocator<char> >',
'std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >',
'std::string',
'std::wstring'
);
{ TStdStringTimeVisualizer }
procedure TStdStringTimeVisualizer.AfterSave;
begin
// don't care about this notification
end;
procedure TStdStringTimeVisualizer.BeforeSave;
begin
// don't care about this notification
end;
procedure TStdStringTimeVisualizer.Destroyed;
begin
// don't care about this notification
end;
procedure TStdStringTimeVisualizer.Modified;
begin
// don't care about this notification
end;
procedure TStdStringTimeVisualizer.ModifyComplete(const ExprStr,
ResultStr: string; ReturnCode: Integer);
begin
// don't care about this notification
end;
procedure TStdStringTimeVisualizer.EvaluteComplete(const ExprStr,
ResultStr: string; CanModify: Boolean; ResultAddress, ResultSize: Cardinal;
ReturnCode: Integer);
begin
EvaluateComplete(ExprStr, ResultStr, CanModify, TOTAAddress(ResultAddress),
LongWord(ResultSize), ReturnCode);
end;
procedure TStdStringTimeVisualizer.EvaluateComplete(const ExprStr,
ResultStr: string; CanModify: Boolean; ResultAddress: TOTAAddress; ResultSize: LongWord;
ReturnCode: Integer);
begin
FCompleted := True;
if ReturnCode = 0 then
FDeferredResult := ResultStr;
end;
procedure TStdStringTimeVisualizer.ThreadNotify(Reason: TOTANotifyReason);
begin
// don't care about this notification
end;
function TStdStringTimeVisualizer.GetReplacementValue(
const Expression, TypeName, EvalResult: string): string;
var
CurProcess: IOTAProcess;
CurThread: IOTAThread;
ResultStr: array[0..4095] of Char;
CanModify: Boolean;
Done: Boolean;
ResultAddr, ResultSize, ResultVal: LongWord;
EvalRes: TOTAEvaluateResult;
DebugSvcs: IOTADebuggerServices;
begin
begin
Result := EvalResult;
if Supports(BorlandIDEServices, IOTADebuggerServices, DebugSvcs) then
CurProcess := DebugSvcs.CurrentProcess;
if (CurProcess <> nil) and (CurProcess.GetProcessType <> optOSX32) and (CurProcess.GetProcessType <> optOSX64) then
begin
CurThread := CurProcess.CurrentThread;
if CurThread <> nil then
begin
repeat
begin
Done := True;
EvalRes := CurThread.Evaluate(Expression+'.c_str()', @ResultStr, Length(ResultStr),
CanModify, eseAll, '', ResultAddr, ResultSize, ResultVal, '', 0);
case EvalRes of
erOK: Result := ResultStr;
erDeferred:
begin
FCompleted := False;
FDeferredResult := '';
FNotifierIndex := CurThread.AddNotifier(Self);
while not FCompleted do
DebugSvcs.ProcessDebugEvents;
CurThread.RemoveNotifier(FNotifierIndex);
FNotifierIndex := -1;
if FDeferredResult <> '' then
Result := FDeferredResult
else
Result := EvalResult;
end;
erBusy:
begin
DebugSvcs.ProcessDebugEvents;
Done := False;
end;
end;
end
until Done = True;
end;
end;
end;
end;
function TStdStringTimeVisualizer.GetSupportedTypeCount: Integer;
begin
Result := Length(StdStringVisualizerTypes);
end;
procedure TStdStringTimeVisualizer.GetSupportedType(Index: Integer; var TypeName: string;
var AllDescendants: Boolean);
begin
AllDescendants := False;
TypeName := StdStringVisualizerTypes[Index];
end;
function TStdStringTimeVisualizer.GetVisualizerDescription: string;
begin
Result := sStdStringVisualizerDescription;
end;
function TStdStringTimeVisualizer.GetVisualizerIdentifier: string;
begin
Result := ClassName;
end;
function TStdStringTimeVisualizer.GetVisualizerName: string;
begin
Result := sStdStringVisualizerName;
end;
var
StdStringVis: IOTADebuggerVisualizer;
procedure Register;
begin
StdStringVis := TStdStringTimeVisualizer.Create;
(BorlandIDEServices as IOTADebuggerServices).RegisterDebugVisualizer(StdStringVis);
end;
procedure RemoveVisualizer;
var
DebuggerServices: IOTADebuggerServices;
begin
if Supports(BorlandIDEServices, IOTADebuggerServices, DebuggerServices) then
begin
DebuggerServices.UnregisterDebugVisualizer(StdStringVis);
StdStringVis := nil;
end;
end;
initialization
finalization
RemoveVisualizer;
end.
|
unit ServerMethodsServer;
interface
uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, DBXPlatform;
type
{$METHODINFO ON}
TServerMethods1 = class(TComponent)
private
{ Private declarations }
public
{ Public declarations }
function updateEmpresa(ID: Integer): string;
function Empresa: string;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
end;
{$METHODINFO OFF}
implementation
uses System.StrUtils, Redis.Client, Vcl.Dialogs, uSession, Web.HTTPApp,
Datasnap.DSHTTPWebBroker, uRedisConfig, Redis.Values, REST.Json;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
function TServerMethods1.Empresa: string;
var
AModule: TWebModule;
ASession: TSession;
AAuth: string;
begin
AModule := GetDataSnapWebModule;
AAuth := AModule.Request.Authorization;
ASession := TSessionManager.GetInstance(AAuth);
try
Result := ASession.empresa.ToString;
finally
ASession.Free;
end;
end;
function TServerMethods1.updateEmpresa(ID: Integer): string;
var
AModule: TWebModule;
ARedisConfig: TRedisConfig;
ARedis: TRedisClient;
AValue: TRedisString;
ASession: TSession;
AAuth: string;
begin
AModule := GetDataSnapWebModule;
AAuth := AModule.Request.Authorization;
ARedisConfig := TRedisConfig.Create;
try
ARedis := TRedisClient.Create(ARedisConfig.Host, ARedisConfig.Port);
try
ARedis.Connect;
AValue := ARedis.GET(AAuth);
if not AValue.IsNull then
ASession := TJson.JsonToObject<TSession>(AValue.Value)
else
ASession := TSession.Create;
try
ASession.empresa := ID;
ARedis.&SET(AAuth, TJson.ObjectToJsonString(ASession));
finally
ASession.Free;
end;
finally
ARedis.Free;
end;
finally
ARedisConfig.Free;
end;
result := 'empresa alterada para ' + ID.ToString;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUICheckListBox.pas
// Creator : Shen Min
// Date : 2002-09-07 V1-V3
// 2003-07-15 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUICheckListBox;
interface
{$I SUIPack.inc}
uses Windows, Messages, CheckLst, Graphics, Forms, Classes, Controls, SysUtils,
SUIScrollBar, SUIThemes, SUIMgr;
type
TsuiCheckListBox = class(TCheckListBox)
private
m_BorderColor : TColor;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
// scroll bar
m_VScrollBar : TsuiScrollBar;
m_HScrollBar : TsuiScrollBar;
m_MouseDown : Boolean;
m_SelfChanging : Boolean;
procedure SetVScrollBar(const Value: TsuiScrollBar);
procedure SetHScrollBar(const Value: TsuiScrollBar);
procedure OnVScrollBarChange(Sender : TObject);
procedure OnHScrollBarChange(Sender : TObject);
procedure UpdateScrollBars();
procedure UpdateScrollBarsPos();
procedure CMEnabledChanged(var Msg : TMessage); message CM_ENABLEDCHANGED;
procedure CMVisibleChanged(var Msg : TMEssage); message CM_VISIBLECHANGED;
procedure WMSIZE(var Msg : TMessage); message WM_SIZE;
procedure WMMOVE(var Msg : TMessage); message WM_MOVE;
procedure WMMOUSEWHEEL(var Message: TMessage); message WM_MOUSEWHEEL;
procedure WMLBUTTONDOWN(var Message: TMessage); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Message: TMessage); message WM_LBUTTONUP;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure LBADDSTRING(var Msg : TMessage); message LB_ADDSTRING;
procedure LBDELETESTRING(var Msg : TMessage); message LB_DELETESTRING;
procedure LBINSERTSTRING(var Msg : TMessage); message LB_INSERTSTRING;
procedure LBSETCOUNT(var Msg : TMessage); message LB_SETCOUNT;
procedure LBNSELCHANGE(var Msg : TMessage); message LBN_SELCHANGE;
procedure LBNSETFOCUS(var Msg : TMessage); message LBN_SETFOCUS;
procedure WMDELETEITEM(var Msg : TMessage); message WM_DELETEITEM;
procedure WMMOUSEMOVE(var Message: TMessage); message WM_MOUSEMOVE;
procedure WMVSCROLL(var Message: TWMVScroll); message WM_VSCROLL;
procedure WMHSCROLL(var Message: TWMHScroll); message WM_HSCROLL;
procedure SetBorderColor(const Value: TColor);
procedure WMPAINT(var Msg : TMessage); message WM_PAINT;
procedure WMEARSEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
function GetBorderStyle() : TBorderStyle;
procedure SetBorderStyle(const Value : TBorderStyle);
function GetBorderWidth: TBorderWidth;
procedure SetBorderWidth(const Value: TBorderWidth);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetFileTheme(const Value: TsuiFileTheme);
private
FSelectedTextColor: TColor;
FSelectedColor: TColor;
FDisabledTextColor: TColor;
procedure SetSelectedColor(const Value: TColor);
procedure SetSelectedTextColor(const Value: TColor);
procedure SetDisabledTextColor(const Value: TColor);
procedure CNDrawItem(var Msg: TWMDrawItem); message CN_DRAWITEM;
protected
procedure DrawItem(Index: Integer; Rect: TRect;State: TOwnerDrawState); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
published
property SelectedColor: TColor read FSelectedColor write SetSelectedColor;
property SelectedTextColor: TColor read FSelectedTextColor write SetSelectedTextColor;
property DisabledTextColor: TColor read FDisabledTextColor write SetDisabledTextColor;
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property BorderStyle : TBorderStyle read GetBorderStyle write SetBorderStyle;
property BorderWidth : TBorderWidth read GetBorderWidth write SetBorderWidth;
// scroll bar
property VScrollBar : TsuiScrollBar read m_VScrollBar write SetVScrollBar;
property HScrollBar : TsuiScrollBar read m_HScrollBar write SetHScrollBar;
end;
implementation
uses SUIPublic, SUIProgressBar;
procedure DrawBorder(WinControl : TWinControl; BorderColor, Color : TColor);
var
DC : HDC;
Brush : HBRUSH;
R: TRect;
begin
DC := GetWindowDC(WinControl.Handle);
GetWindowRect(WinControl.Handle, R);
OffsetRect(R, -R.Left, -R.Top);
Brush := CreateSolidBrush(ColorToRGB(BorderColor));
FrameRect(DC, R, Brush);
DeleteObject(Brush);
ReleaseDC(WinControl.Handle, DC);
end;
{ TsuiCheckListBox }
procedure TsuiCheckListBox.CMEnabledChanged(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.CMVisibleChanged(var Msg: TMEssage);
begin
inherited;
if not Visible then
begin
if m_VScrollBar <> nil then
m_VScrollBar.Visible := Visible;
if m_HScrollBar <> nil then
m_HScrollBar.Visible := Visible;
end
else
UpdateScrollBarsPos();
end;
procedure TsuiCheckListBox.CNDrawItem(var Msg: TWMDrawItem);
var
State: TOwnerDrawState;
begin
inherited;
with Msg.DrawItemStruct^ do
begin
State := TOwnerDrawState(LongRec(itemState).Lo);
Canvas.Handle := hDC;
Canvas.Font := Font;
Canvas.Brush := Brush;
if Integer(itemID) >= 0 then
begin
if odSelected in State then
begin
Canvas.Brush.Color := FSelectedColor;
Canvas.Font.Color := FSelectedTextColor;
end;
if (([odDisabled, odGrayed] * State) <> []) or not Enabled then
Canvas.Font.Color := FDisabledTextColor;
end;
if Integer(itemID) >= 0 then
DrawItem(itemID, rcItem, State)
else
begin
Canvas.FillRect(rcItem);
if odFocused in State then
DrawFocusRect(hDC, rcItem);
end;
Canvas.Handle := 0;
end;
end;
constructor TsuiCheckListBox.Create(AOwner: TComponent);
begin
inherited;
Flat := True;
inherited BorderStyle := bsNone;
BorderWidth := 2;
m_SelfChanging := false;
m_MouseDown := false;
UIStyle := GetSUIFormStyle(AOwner);
FSelectedColor := clHighlight;
FSelectedTextColor := clHighlightText;
FDisabledTextColor := clGrayText;
end;
procedure TsuiCheckListBox.DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState);
var
Bitmap : TBitmap;
bChecked : Boolean;
nIndex : Integer;
OutUIStyle : TsuiUIStyle;
begin
bChecked := Checked[Index];
inherited;
Bitmap := TBitmap.Create();
if Enabled then
begin
if bChecked then
nIndex := 1
else
nIndex := 2
end
else
begin
if bChecked then
nIndex := 3
else
nIndex := 4;
end;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_FileTheme.GetBitmap(SUI_THEME_CHECKLISTBOX_IMAGE, Bitmap, 4, nIndex)
else
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_CHECKLISTBOX_IMAGE, Bitmap, 4, nIndex);
if Canvas.TextHeight('W') < 12 then
Rect.Bottom := Rect.Bottom + 1;
Canvas.Draw(Rect.Left - 13, Rect.Top + (Rect.Bottom - Rect.Top - 11) div 2, Bitmap);
Bitmap.Free();
end;
function TsuiCheckListBox.GetBorderStyle: TBorderStyle;
begin
Result := bsSingle;
end;
function TsuiCheckListBox.GetBorderWidth: TBorderWidth;
begin
Result := 1;
end;
procedure TsuiCheckListBox.LBADDSTRING(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.LBDELETESTRING(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.LBINSERTSTRING(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.LBNSELCHANGE(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.LBNSETFOCUS(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.LBSETCOUNT(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if AComponent = nil then
Exit;
if (
(Operation = opRemove) and
(AComponent = m_VScrollBar)
)then
m_VScrollBar := nil;
if (
(Operation = opRemove) and
(AComponent = m_HScrollBar)
)then
m_HScrollBar := nil;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiCheckListBox.OnHScrollBarChange(Sender: TObject);
begin
if m_SelfChanging then
Exit;
SendMessage(Handle, WM_HSCROLL, MakeWParam(SB_THUMBPOSITION, m_HScrollBar.Position), 0);
Invalidate;
end;
procedure TsuiCheckListBox.OnVScrollBarChange(Sender: TObject);
begin
if m_SelfChanging then
Exit;
SendMessage(Handle, WM_VSCROLL, MakeWParam(SB_THUMBPOSITION, m_VScrollBar.Position), 0);
Invalidate;
end;
procedure TsuiCheckListBox.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
Repaint();
end;
procedure TsuiCheckListBox.SetBorderStyle(const Value: TBorderStyle);
begin
inherited BorderStyle := bsNone;
end;
procedure TsuiCheckListBox.SetBorderWidth(const Value: TBorderWidth);
begin
inherited BorderWidth := 1;
end;
procedure TsuiCheckListBox.SetDisabledTextColor(const Value: TColor);
begin
if FDisabledTextColor <> Value then
begin
FDisabledTextColor := Value;
Invalidate;
end;
end;
procedure TsuiCheckListBox.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
if m_VScrollBar <> nil then
m_VScrollBar.FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiCheckListBox.SetHScrollBar(const Value: TsuiScrollBar);
begin
if m_HScrollBar = Value then
Exit;
if m_HScrollBar <> nil then
begin
m_HScrollBar.OnChange := nil;
m_HScrollBar.LineButton := 0;
m_HScrollBar.Max := 100;
m_HScrollBar.Enabled := true;
end;
m_HScrollBar := Value;
if m_HScrollBar = nil then
Exit;
m_HScrollBar.Orientation := suiHorizontal;
m_HScrollBar.OnChange := OnHScrollBArChange;
m_HScrollBar.BringToFront();
UpdateScrollBarsPos();
end;
procedure TsuiCheckListBox.SetSelectedColor(const Value: TColor);
begin
if FSelectedColor <> Value then
begin
FSelectedColor := Value;
Invalidate;
end;
end;
procedure TsuiCheckListBox.SetSelectedTextColor(const Value: TColor);
begin
if FSelectedTextColor <> Value then
begin
FSelectedTextColor := Value;
Invalidate;
end;
end;
procedure TsuiCheckListBox.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR)
else
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
if m_VScrollBar <> nil then
m_VScrollBar.UIStyle := OutUIStyle;
if m_HScrollBar <> nil then
m_HScrollBar.UIStyle := OutUIStyle;
Repaint();
end;
procedure TsuiCheckListBox.SetVScrollBar(const Value: TsuiScrollBar);
begin
if m_VScrollBar = Value then
Exit;
if m_VScrollBar <> nil then
begin
m_VScrollBar.OnChange := nil;
m_VScrollBar.LineButton := 0;
m_VScrollBar.Max := 100;
m_VScrollBar.Enabled := true;
end;
m_VScrollBar := Value;
if m_VScrollBar = nil then
Exit;
m_VScrollBar.Orientation := suiVertical;
m_VScrollBar.OnChange := OnVScrollBArChange;
m_VScrollBar.BringToFront();
UpdateScrollBarsPos();
end;
procedure TsuiCheckListBox.UpdateScrollBars;
var
info : tagScrollInfo;
barinfo : tagScrollBarInfo;
R : Boolean;
begin
m_SelfChanging := true;
if m_VScrollBar <> nil then
begin
barinfo.cbSize := SizeOf(barinfo);
R := SUIGetScrollBarInfo(Handle, Integer(OBJID_VSCROLL), barinfo);
if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or
(barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or
(not R) then
begin
m_VScrollBar.LineButton := 0;
m_VScrollBar.Enabled := false;
m_VScrollBar.Visible := false;
end
else if not Enabled then
m_VScrollBar.Enabled := false
else
begin
m_VScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop);
m_VScrollBar.Enabled := true;
m_VScrollBar.Visible := true;
end;
info.cbSize := SizeOf(info);
info.fMask := SIF_ALL;
GetScrollInfo(Handle, SB_VERT, info);
m_VScrollBar.Max := info.nMax - Integer(info.nPage) + 1;
m_VScrollBar.Min := info.nMin;
m_VScrollBar.Position := info.nPos;
end;
if m_HScrollBar <> nil then
begin
barinfo.cbSize := SizeOf(barinfo);
R := SUIGetScrollBarInfo(Handle, Integer(OBJID_HSCROLL), barinfo);
if (barinfo.rgstate[0] = STATE_SYSTEM_INVISIBLE) or
(barinfo.rgstate[0] = STATE_SYSTEM_UNAVAILABLE) or
(not R) then
begin
m_HScrollBar.LineButton := 0;
m_HScrollBar.Enabled := false;
m_HScrollBar.Visible := false;
end
else if not Enabled then
m_HScrollBar.Enabled := false
else
begin
m_HScrollBar.LineButton := abs(barinfo.xyThumbBottom - barinfo.xyThumbTop);
m_HScrollBar.Enabled := true;
m_HScrollBar.Visible := true;
end;
info.cbSize := SizeOf(info);
info.fMask := SIF_ALL;
GetScrollInfo(Handle, SB_HORZ, info);
m_HScrollBar.Max := info.nMax - Integer(info.nPage) + 1;
m_HScrollBar.Min := info.nMin;
m_HScrollBar.Position := info.nPos;
end;
m_SelfChanging := false;
end;
procedure TsuiCheckListBox.UpdateScrollBarsPos;
begin
if m_HScrollBar <> nil then
begin
if m_HScrollBar.Height > Height then
m_HScrollBar.Top := Top
else
begin
m_HScrollBar.Left := Left + 1;
m_HScrollBar.Top := Top + Height - m_HScrollBar.Height - 1;
if m_VScrollBar <> nil then
begin
if m_VScrollBar.Visible then
m_HScrollBar.Width := Width - 2 - m_VScrollBar.Width
else
m_HScrollBar.Width := Width - 2
end
else
m_HScrollBar.Width := Width - 2
end;
end;
if m_VScrollBar <> nil then
begin
if m_VScrollBar.Width > Width then
m_VScrollBar.Left := Left
else
begin
m_VScrollBar.Left := Left + Width - m_VScrollBar.Width - 1;
m_VScrollBar.Top := Top + 1;
if m_HScrollBar <> nil then
begin
if m_HScrollBar.Visible then
m_VScrollBar.Height := Height - 2 - m_HScrollBar.Height
else
m_VScrollBar.Height := Height - 2;
end
else
m_VScrollBar.Height := Height - 2;
end;
end;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMDELETEITEM(var Msg: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMEARSEBKGND(var Msg: TMessage);
begin
inherited;
DrawBorder(self, m_BorderColor, Color);
end;
procedure TsuiCheckListBox.WMHSCROLL(var Message: TWMHScroll);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMKeyDown(var Message: TWMKeyDown);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMLBUTTONDOWN(var Message: TMessage);
begin
inherited;
m_MouseDown := true;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMLButtonUp(var Message: TMessage);
begin
inherited;
m_MouseDown := false;
end;
procedure TsuiCheckListBox.WMMOUSEMOVE(var Message: TMessage);
begin
inherited;
if m_MouseDown then UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMMOUSEWHEEL(var Message: TMessage);
begin
inherited;
UpdateScrollBars();
end;
procedure TsuiCheckListBox.WMMOVE(var Msg: TMessage);
begin
inherited;
UpdateScrollBarsPos();
end;
procedure TsuiCheckListBox.WMPAINT(var Msg: TMessage);
begin
inherited;
DrawBorder(self, m_BorderColor, Color);
end;
procedure TsuiCheckListBox.WMSIZE(var Msg: TMessage);
begin
inherited;
UpdateScrollBarsPos();
end;
procedure TsuiCheckListBox.WMVSCROLL(var Message: TWMVScroll);
begin
inherited;
UpdateScrollBars();
end;
end.
|
unit adot.JSON.JBuilder;
interface
uses
Adot.Collections,
System.Classes,
System.SysUtils,
System.JSON.Types,
System.JSON.Writers,
System.Generics.Collections;
type
(*
Delphi has 3 frameworks for JSON:
1. Objects
+ max flexibility
- lot of variables, code is not as readable as it can be
2. Readers and Writers (TJSonWriter)
+ almost as powerful/flexible as object model
+ cleaner code than in object model
- adding of items to object (map) requires two commands
- not as readable as builder
3. Builder (TJSONObjectBuilder)
+ great for simple structures / very readable
- recursive syntax
- when some parts should be generated in cycles/by ext routines,
it became tricky & code is not as readable as it should
In TJBuilder we tried to collect the best from all:
- simple & readable
- flexible as writer
- as it is a record type, no need to use Try-Finally & free manually
Example:
var
B: TJBuilder;
begin
B.Init;
B.BeginObject;
B.BeginArray('Transaction');
B.BeginObject;
B.Add('id', 662713);
B.Add('firstName', 'John');
B.Add('lastName', 'Doe');
B.Add('price', 2.1);
B.AddNull('parent_id');
B.Add('validated', true);
B.EndObject;
B.BeginObject;
B.AddArray('A', [1,2,3]);
B.AddArray('B', ['Ver','2.2.1']);
B.EndObject;
B.EndArray;
B.EndObject;
Result := B.ToString;
end;
*)
TJBuilder = record
private
FJsonWriter: TJsonTextWriter;
FTextWriter: TTextWriter;
FAutoFreeCollection: TAutoFreeCollection;
public
procedure Init; overload;
procedure Init(const TextWriter: TTextWriter; TakeOwnership: boolean = False); overload;
class function Create: TJBuilder; overload; static;
class function Create(const TextWriter: TTextWriter; TakeOwnership: boolean = False): TJBuilder; overload; static;
{ add value }
procedure BeginObject; overload;
procedure BeginArray; overload;
procedure AddNull; overload;
procedure Add(const Value: string); overload;
procedure Add(Value: Integer); overload;
procedure Add(Value: UInt32); overload;
procedure Add(Value: Int64); overload;
procedure Add(Value: UInt64); overload;
procedure Add(Value: Single); overload;
procedure Add(Value: Double); overload;
procedure Add(Value: Extended); overload;
procedure Add(Value: Boolean); overload;
procedure Add(Value: Char); overload;
procedure Add(Value: Byte); overload;
procedure Add(Value: TDateTime); overload;
procedure Add(const Value: TGUID); overload;
procedure Add(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); overload;
procedure Add(const Value: TJsonOid); overload;
procedure Add(const Value: TJsonRegEx); overload;
procedure Add(const Value: TJsonDBRef); overload;
procedure Add(const Value: TJsonCodeWScope); overload;
{ add to object }
procedure BeginObject(const Name: string); overload;
procedure BeginArray(const Name: string); overload;
procedure AddNull(const Name: string); overload;
procedure Add(const Name: string; const Value: string); overload;
procedure Add(const Name: string; Value: Integer); overload;
procedure Add(const Name: string; Value: UInt32); overload;
procedure Add(const Name: string; Value: Int64); overload;
procedure Add(const Name: string; Value: UInt64); overload;
procedure Add(const Name: string; Value: Single); overload;
procedure Add(const Name: string; Value: Double); overload;
procedure Add(const Name: string; Value: Extended); overload;
procedure Add(const Name: string; Value: Boolean); overload;
procedure Add(const Name: string; Value: Char); overload;
procedure Add(const Name: string; Value: Byte); overload;
procedure Add(const Name: string; Value: TDateTime); overload;
procedure Add(const Name: string; const Value: TGUID); overload;
procedure Add(const Name: string; const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); overload;
procedure Add(const Name: string; const Value: TJsonOid); overload;
procedure Add(const Name: string; const Value: TJsonRegEx); overload;
procedure Add(const Name: string; const Value: TJsonDBRef); overload;
procedure Add(const Name: string; const Value: TJsonCodeWScope); overload;
procedure EndObject; overload;
procedure EndArray; overload;
{ higher level }
{ add array }
procedure AddArray(const Values: TEnumerable<Integer>); overload;
procedure AddArray(const Values: TEnumerable<Double>); overload;
procedure AddArray(const Values: TEnumerable<String>); overload;
procedure AddArray(const Values: TArray<Integer>); overload;
procedure AddArray(const Values: TArray<Double>); overload;
procedure AddArray(const Values: TArray<String>); overload;
procedure AddArray(const Name: string; const Values: TEnumerable<Integer>); overload;
procedure AddArray(const Name: string; const Values: TEnumerable<Double>); overload;
procedure AddArray(const Name: string; const Values: TEnumerable<String>); overload;
procedure AddArray(const Name: string; const Values: TArray<Integer>); overload;
procedure AddArray(const Name: string; const Values: TArray<Double>); overload;
procedure AddArray(const Name: string; const Values: TArray<String>); overload;
{ add object }
procedure AddObject(const Values: TEnumerable<TPair<String,Integer>>); overload;
procedure AddObject(const Values: TEnumerable<TPair<String,Double>>); overload;
procedure AddObject(const Values: TEnumerable<TPair<String,String>>); overload;
procedure AddObject(const Name: string; const Values: TEnumerable<TPair<String,Integer>>); overload;
procedure AddObject(const Name: string; const Values: TEnumerable<TPair<String,Double>>); overload;
procedure AddObject(const Name: string; const Values: TEnumerable<TPair<String,String>>); overload;
function ToString: string;
class operator Implicit(const B: TJBuilder): string;
class operator Explicit(const B: TJBuilder): string;
property JsonWriter: TJsonTextWriter read FJsonWriter;
end;
implementation
{ TJBuilder }
procedure TJBuilder.Init;
begin
Init(TStringWriter.Create, True);
end;
procedure TJBuilder.Init(const TextWriter: TTextWriter; TakeOwnership: boolean);
begin
{ destroy old instance }
Self := Default(TJBuilder);
{ create new instance }
if TakeOwnership
then FTextWriter := FAutoFreeCollection.Add( TextWriter )
else FTextWriter := TextWriter;
FJsonWriter := FAutoFreeCollection.Add( TJsonTextWriter.Create(FTextWriter) );
end;
class function TJBuilder.Create: TJBuilder;
begin
result.Init;
end;
class function TJBuilder.Create(const TextWriter: TTextWriter; TakeOwnership: boolean): TJBuilder;
begin
result.Init(TextWriter, TakeOwnership);
end;
procedure TJBuilder.EndArray;
begin
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.EndObject;
begin
FJsonWriter.WriteEndObject;
end;
class operator TJBuilder.Explicit(const B: TJBuilder): string;
begin
result := B.ToString;
end;
class operator TJBuilder.Implicit(const B: TJBuilder): string;
begin
result := B.ToString;
end;
function TJBuilder.ToString: string;
begin
FJsonWriter.Flush;
FTextWriter.Flush;
result := FTextWriter.ToString;
end;
procedure TJBuilder.BeginArray;
begin
FJsonWriter.WriteStartArray;
end;
procedure TJBuilder.BeginObject(const Name: string);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteStartObject;
end;
procedure TJBuilder.BeginArray(const Name: string);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteStartArray;
end;
procedure TJBuilder.BeginObject;
begin
FJsonWriter.WriteStartObject;
end;
procedure TJBuilder.Add(const Name: string; Value: Single);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: UInt64);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Extended);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Double);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Integer);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name, Value: string);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Int64);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: UInt32);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Boolean);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; const Value: TJsonRegEx);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; const Value: TJsonOid);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.AddNull(const Name: string);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteNull;
end;
procedure TJBuilder.Add(const Name: string; const Value: TJsonCodeWScope);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; const Value: TJsonDBRef);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; const Value: TBytes; BinaryType: TJsonBinaryType);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Byte);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: Char);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; const Value: TGUID);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Name: string; Value: TDateTime);
begin
FJsonWriter.WritePropertyName(Name);
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Double);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Single);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Boolean);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Extended);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: UInt64);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Integer);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: string);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Int64);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: UInt32);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Char);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: TJsonRegEx);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: TJsonOid);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: TJsonCodeWScope);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: TJsonDBRef);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: TDateTime);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(Value: Byte);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: TBytes; BinaryType: TJsonBinaryType);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.Add(const Value: TGUID);
begin
FJsonWriter.WriteValue(Value);
end;
procedure TJBuilder.AddNull;
begin
FJsonWriter.WriteNull;
end;
procedure TJBuilder.AddArray(const Values: TEnumerable<String>);
var
Value: String;
begin
FJsonWriter.WriteStartArray;
for Value in Values do
FJsonWriter.WriteValue(Value);
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.AddArray(const Values: TEnumerable<Double>);
var
Value: Double;
begin
FJsonWriter.WriteStartArray;
for Value in Values do
FJsonWriter.WriteValue(Value);
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.AddArray(const Values: TEnumerable<Integer>);
var
Value: Integer;
begin
FJsonWriter.WriteStartArray;
for Value in Values do
FJsonWriter.WriteValue(Value);
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.AddArray(const Values: TArray<Integer>);
var
Value: Integer;
begin
FJsonWriter.WriteStartArray;
for Value in Values do
FJsonWriter.WriteValue(Value);
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.AddArray(const Values: TArray<Double>);
var
Value: Double;
begin
FJsonWriter.WriteStartArray;
for Value in Values do
FJsonWriter.WriteValue(Value);
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.AddArray(const Values: TArray<String>);
var
Value: String;
begin
FJsonWriter.WriteStartArray;
for Value in Values do
FJsonWriter.WriteValue(Value);
FJsonWriter.WriteEndArray;
end;
procedure TJBuilder.AddArray(const Name: string; const Values: TEnumerable<Integer>);
begin
FJsonWriter.WritePropertyName(Name);
AddArray(Values);
end;
procedure TJBuilder.AddArray(const Name: string; const Values: TEnumerable<Double>);
begin
FJsonWriter.WritePropertyName(Name);
AddArray(Values);
end;
procedure TJBuilder.AddArray(const Name: string; const Values: TEnumerable<String>);
begin
FJsonWriter.WritePropertyName(Name);
AddArray(Values);
end;
procedure TJBuilder.AddArray(const Name: string; const Values: TArray<Integer>);
begin
FJsonWriter.WritePropertyName(Name);
AddArray(Values);
end;
procedure TJBuilder.AddArray(const Name: string; const Values: TArray<Double>);
begin
FJsonWriter.WritePropertyName(Name);
AddArray(Values);
end;
procedure TJBuilder.AddArray(const Name: string; const Values: TArray<String>);
begin
FJsonWriter.WritePropertyName(Name);
AddArray(Values);
end;
procedure TJBuilder.AddObject(const Values: TEnumerable<TPair<String, String>>);
var
Value: TPair<String, String>;
begin
FJsonWriter.WriteStartObject;
for Value in Values do
begin
FJsonWriter.WritePropertyName(Value.Key);
FJsonWriter.WriteValue(Value.Value);
end;
FJsonWriter.WriteEndObject;
end;
procedure TJBuilder.AddObject(const Values: TEnumerable<TPair<String, Double>>);
var
Value: TPair<String, Double>;
begin
FJsonWriter.WriteStartObject;
for Value in Values do
begin
FJsonWriter.WritePropertyName(Value.Key);
FJsonWriter.WriteValue(Value.Value);
end;
FJsonWriter.WriteEndObject;
end;
procedure TJBuilder.AddObject(const Values: TEnumerable<TPair<String, Integer>>);
var
Value: TPair<String, Integer>;
begin
FJsonWriter.WriteStartObject;
for Value in Values do
begin
FJsonWriter.WritePropertyName(Value.Key);
FJsonWriter.WriteValue(Value.Value);
end;
FJsonWriter.WriteEndObject;
end;
procedure TJBuilder.AddObject(const Name: string; const Values: TEnumerable<TPair<String, Integer>>);
begin
FJsonWriter.WritePropertyName(Name);
AddObject(Values);
end;
procedure TJBuilder.AddObject(const Name: string; const Values: TEnumerable<TPair<String, Double>>);
begin
FJsonWriter.WritePropertyName(Name);
AddObject(Values);
end;
procedure TJBuilder.AddObject(const Name: string; const Values: TEnumerable<TPair<String, String>>);
begin
FJsonWriter.WritePropertyName(Name);
AddObject(Values);
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUISkinControl.pas
// Creator : Shen Min
// Date : 2002-09-16
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUISkinControl;
interface
{$I SUIPack.inc}
uses Windows, Messages, SysUtils, Classes, Controls, Graphics;
type
TsuiSkinControl = class(TComponent)
private
m_Control : TWinControl;
m_Glyph : TBitmap;
m_Color : TColor;
m_OnRegionChanged : TNotifyEvent;
procedure SetColor(const Value: TColor);
procedure SetControl(const Value: TWinControl);
procedure SetPicture(const Value: TBitmap);
procedure ReSetWndRgn();
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy(); override;
published
property Control : TWinControl read m_Control write SetControl;
property Glyph : TBitmap read m_Glyph write SetPicture;
property TransparentColor : TColor read m_Color write SetColor;
property OnRegionChanged : TNotifyEvent read m_OnRegionChanged write m_OnRegionChanged;
end;
implementation
uses SUIPublic;
{ TsuiSkinControl }
constructor TsuiSkinControl.Create(AOwner: TComponent);
begin
inherited;
m_Glyph := TBitmap.Create();
m_Color := clFuchsia;
m_Control := nil;
end;
destructor TsuiSkinControl.Destroy;
begin
m_Glyph.Free();
m_Glyph := nil;
inherited;
end;
procedure TsuiSkinControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_Control)
)then
m_Control := nil;
end;
procedure TsuiSkinControl.ReSetWndRgn;
begin
if (
(m_Glyph.Empty) or
(not Assigned(m_Control))
) then
Exit;
SetBitmapWindow(m_Control.Handle, m_Glyph, m_Color);
if (
(m_Glyph.Height <> 0) and
(m_Glyph.Width <> 0)
) then
begin
m_Control.Height := m_Glyph.Height;
m_Control.Width := m_Glyph.Width;
end;
if Assigned(m_OnRegionChanged) then
m_OnRegionChanged(self);
end;
procedure TsuiSkinControl.SetColor(const Value: TColor);
begin
m_Color := Value;
ReSetWndRgn();
end;
procedure TsuiSkinControl.SetControl(const Value: TWinControl);
begin
m_Control := Value;
ReSetWndRgn();
end;
procedure TsuiSkinControl.SetPicture(const Value: TBitmap);
begin
m_Glyph.Assign(Value);
ReSetWndRgn();
end;
end.
|
unit SHA384;
{SHA384 - 384 bit Secure Hash Function}
interface
(*************************************************************************
DESCRIPTION : SHA384 - 384 bit Secure Hash Function
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : - Latest specification of Secure Hash Standard:
http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
- Test vectors and intermediate values:
http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 21.11.02 W.Ehrhardt Initial version
0.11 21.11.02 we BugFix SHA384File
3.00 01.12.03 we Common version 3.0
3.01 05.03.04 we Update fips180-2 URL
3.02 26.02.05 we With {$ifdef StrictLong}
3.03 05.05.05 we $R- for StrictLong, D9: errors if $R+ even if warnings off
3.04 17.12.05 we Force $I- in SHA384File
3.05 15.01.06 we uses Hash unit and THashDesc
3.06 18.01.06 we Descriptor fields HAlgNum, HSig
3.07 22.01.06 we Removed HSelfTest from descriptor
3.08 11.02.06 we Descriptor as typed const
3.09 07.08.06 we $ifdef BIT32: (const fname: shortstring...)
3.10 22.02.07 we values for OID vector
3.11 30.06.07 we Use conditional define FPC_ProcVar
3.12 03.05.08 we Bit-API: SHA384FinalBits/Ex
3.13 05.05.08 we THashDesc constant with HFinalBit field
3.14 12.11.08 we Uses BTypes, Ptr2Inc and/or Str255/Str127
3.15 11.03.12 we Updated references
3.16 16.08.15 we Removed $ifdef DLL / stdcall
3.17 15.05.17 we adjust OID to new MaxOIDLen
3.18 29.11.17 we SHA384File - fname: string
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2002-2017 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
uses
BTypes,Hash,SHA512;
procedure SHA384Init(var Context: THashContext);
{-initialize context}
procedure SHA384Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
procedure SHA384UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
procedure SHA384Final(var Context: THashContext; var Digest: TSHA384Digest);
{-finalize SHA384 calculation, clear context}
procedure SHA384FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize SHA384 calculation, clear context}
procedure SHA384FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize SHA384 calculation with bitlen bits from BData (big-endian), clear context}
procedure SHA384FinalBits(var Context: THashContext; var Digest: TSHA384Digest; BData: byte; bitlen: integer);
{-finalize SHA384 calculation with bitlen bits from BData (big-endian), clear context}
function SHA384SelfTest: boolean;
{-self test for string from SHA384 document}
procedure SHA384Full(var Digest: TSHA384Digest; Msg: pointer; Len: word);
{-SHA384 of Msg with init/update/final}
procedure SHA384FullXL(var Digest: TSHA384Digest; Msg: pointer; Len: longint);
{-SHA384 of Msg with init/update/final}
procedure SHA384File({$ifdef CONST} const {$endif} fname: string;
var Digest: TSHA384Digest; var buf; bsize: word; var Err: word);
{-SHA384 of file, buf: buffer with at least bsize bytes}
implementation
const
SHA384_BlockLen = 128;
{2.16.840.1.101.3.4.2.2}
{joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) hashAlgs(2) sha384(2)}
const
SHA384_OID : TOID_Vec = (2,16,840,1,101,3,4,2,2,-1,-1); {Len=9}
{$ifndef VER5X}
const
SHA384_Desc: THashDesc = (
HSig : C_HashSig;
HDSize : sizeof(THashDesc);
HDVersion : C_HashVers;
HBlockLen : SHA384_BlockLen;
HDigestlen: sizeof(TSHA384Digest);
{$ifdef FPC_ProcVar}
HInit : @SHA384Init;
HFinal : @SHA384FinalEx;
HUpdateXL : @SHA384UpdateXL;
{$else}
HInit : SHA384Init;
HFinal : SHA384FinalEx;
HUpdateXL : SHA384UpdateXL;
{$endif}
HAlgNum : longint(_SHA384);
HName : 'SHA384';
HPtrOID : @SHA384_OID;
HLenOID : 9;
HFill : 0;
{$ifdef FPC_ProcVar}
HFinalBit : @SHA384FinalBitsEx;
{$else}
HFinalBit : SHA384FinalBitsEx;
{$endif}
HReserved : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
);
{$else}
var
SHA384_Desc: THashDesc;
{$endif}
{$ifdef BIT16}
{$F-}
{$endif}
{---------------------------------------------------------------------------}
procedure SHA384Init(var Context: THashContext);
{-initialize context}
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9 errors!}
{$endif}
const
SIV: THashState = ($c1059ed8, $cbbb9d5d, $367cd507, $629a292a,
$3070dd17, $9159015a, $f70e5939, $152fecd8,
$ffc00b31, $67332667, $68581511, $8eb44a87,
$64f98fa7, $db0c2e0d, $befa4fa4, $47b5481d);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
begin
{Clear context}
fillchar(Context,sizeof(Context),0);
Context.Hash := SIV;
end;
{---------------------------------------------------------------------------}
procedure SHA384UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
begin
SHA512UpdateXL(THashContext(Context), Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA384Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
begin
SHA512UpdateXL(THashContext(Context), Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA384FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize SHA384 calculation with bitlen bits from BData (big-endian), clear context}
begin
SHA512FinalBitsEx(Context, Digest, BData, bitlen);
end;
{---------------------------------------------------------------------------}
procedure SHA384FinalBits(var Context: THashContext; var Digest: TSHA384Digest; BData: byte; bitlen: integer);
{-finalize SHA384 calculation with bitlen bits from BData (big-endian), clear context}
var
tmp: THashDigest;
begin
SHA512FinalBitsEx(Context, tmp, BData, bitlen);
move(tmp, Digest, sizeof(Digest));
end;
{---------------------------------------------------------------------------}
procedure SHA384FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize SHA384 calculation, clear context}
begin
SHA512FinalBitsEx(Context, Digest,0,0);
end;
{---------------------------------------------------------------------------}
procedure SHA384Final(var Context: THashContext; var Digest: TSHA384Digest);
{-finalize SHA384 calculation, clear context}
var
tmp: THashDigest;
begin
SHA512FinalBitsEx(Context, tmp, 0, 0);
move(tmp, Digest, sizeof(Digest));
end;
{---------------------------------------------------------------------------}
function SHA384SelfTest: boolean;
{-self test for string from SHA384 document}
const
s1: string[3] = 'abc';
s2: string[112] = 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn'
+'hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu';
D1: TSHA384Digest = ($cb, $00, $75, $3f, $45, $a3, $5e, $8b,
$b5, $a0, $3d, $69, $9a, $c6, $50, $07,
$27, $2c, $32, $ab, $0e, $de, $d1, $63,
$1a, $8b, $60, $5a, $43, $ff, $5b, $ed,
$80, $86, $07, $2b, $a1, $e7, $cc, $23,
$58, $ba, $ec, $a1, $34, $c8, $25, $a7);
D2: TSHA384Digest = ($09, $33, $0c, $33, $f7, $11, $47, $e8,
$3d, $19, $2f, $c7, $82, $cd, $1b, $47,
$53, $11, $1b, $17, $3b, $3b, $05, $d2,
$2f, $a0, $80, $86, $e3, $b0, $f7, $12,
$fc, $c7, $c7, $1a, $55, $7e, $2d, $b9,
$66, $c3, $e9, $fa, $91, $74, $60, $39);
D3: TSHA384Digest = ($63, $4a, $a6, $30, $38, $a1, $64, $ae,
$6c, $7d, $48, $b3, $19, $f2, $ac, $a0,
$a1, $07, $90, $8e, $54, $85, $19, $20,
$4c, $6d, $72, $db, $ea, $c0, $fd, $c3,
$c9, $24, $66, $74, $f9, $8e, $8f, $d3,
$02, $21, $ba, $98, $6e, $73, $7d, $61);
D4: TSHA384Digest = ($e7, $9b, $94, $65, $32, $fa, $5c, $f7,
$22, $33, $ae, $1c, $bb, $a8, $6e, $21,
$9e, $1a, $3d, $35, $49, $a3, $44, $4f,
$2e, $a3, $fc, $db, $ce, $0f, $ab, $58,
$aa, $56, $70, $ab, $d1, $98, $ba, $a8,
$dc, $fb, $cb, $e9, $4e, $8e, $b8, $07);
var
Context: THashContext;
Digest : TSHA384Digest;
function SingleTest(s: Str127; TDig: TSHA384Digest): boolean;
{-do a single test, const not allowed for VER<7}
{ Two sub tests: 1. whole string, 2. one update per char}
var
i: integer;
begin
SingleTest := false;
{1. Hash complete string}
SHA384Full(Digest, @s[1],length(s));
{Compare with known value}
if not HashSameDigest(@SHA384_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
{2. one update call for all chars}
SHA384Init(Context);
for i:=1 to length(s) do SHA384Update(Context,@s[i],1);
SHA384Final(Context,Digest);
{Compare with known value}
if not HashSameDigest(@SHA384_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
SingleTest := true;
end;
begin
SHA384SelfTest := false;
{1 Zero bit from NESSIE test vectors}
SHA384Init(Context);
SHA384FinalBits(Context,Digest,0,1);
if not HashSameDigest(@SHA384_Desc, PHashDigest(@Digest), PHashDigest(@D3)) then exit;
{4 hightest bits of $50, D4 calculated with program shatest from RFC 4634}
SHA384Init(Context);
SHA384FinalBits(Context,Digest,$50,4);
if not HashSameDigest(@SHA384_Desc, PHashDigest(@Digest), PHashDigest(@D4)) then exit;
{strings from SHA384 document}
SHA384SelfTest := SingleTest(s1, D1) and SingleTest(s2, D2)
end;
{---------------------------------------------------------------------------}
procedure SHA384FullXL(var Digest: TSHA384Digest; Msg: pointer; Len: longint);
{-SHA384 of Msg with init/update/final}
var
Context: THashContext;
begin
SHA384Init(Context);
SHA384UpdateXL(Context, Msg, Len);
SHA384Final(Context, Digest);
end;
{---------------------------------------------------------------------------}
procedure SHA384Full(var Digest: TSHA384Digest; Msg: pointer; Len: word);
{-SHA384 of Msg with init/update/final}
begin
SHA384FullXL(Digest, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA384File({$ifdef CONST} const {$endif} fname: string;
var Digest: TSHA384Digest; var buf; bsize: word; var Err: word);
{-SHA384 of file, buf: buffer with at least bsize bytes}
var
tmp: THashDigest;
begin
HashFile(fname, @SHA384_Desc, tmp, buf, bsize, Err);
move(tmp, Digest, sizeof(Digest));
end;
begin
{$ifdef VER5X}
fillchar(SHA384_Desc, sizeof(SHA384_Desc), 0);
with SHA384_Desc do begin
HSig := C_HashSig;
HDSize := sizeof(THashDesc);
HDVersion := C_HashVers;
HBlockLen := SHA384_BlockLen;
HDigestlen:= sizeof(TSHA384Digest);
HInit := SHA384Init;
HFinal := SHA384FinalEx;
HUpdateXL := SHA384UpdateXL;
HAlgNum := longint(_SHA384);
HName := 'SHA384';
HPtrOID := @SHA384_OID;
HLenOID := 9;
HFinalBit := SHA384FinalBitsEx;
end;
{$endif}
RegisterHash(_SHA384, @SHA384_Desc);
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriUndo;
interface
uses
SysUtils, Classes;
type
TOriUndoCommand = class;
TOriCommandGroup = class;
TUndoRedoEvent = procedure (Sender: TObject; CmdUndo, CmdRedo: TOriUndoCommand) of object;
TUndoneEvent = procedure (Sender: TObject; Cmd: TOriUndoCommand) of object;
// Command history
TOriHistory = class
private
FLockCount: Integer;
FItems: TList; // command stack
FUndoIndex: Integer; // top command to Undo, all upped - Redo
FLimit: Integer; // maximal count of command to undo
FOnChanged: TUndoRedoEvent; // event on command stack was changed
FOnUndone: TUndoneEvent; // event after undo
FOnRedone: TUndoneEvent; // event after redo
FGroup: TOriCommandGroup; // temporary pointer to a group action
function GetGroupped: Boolean;
function GetUndoCmd: TOriUndoCommand;
function GetRedoCmd: TOriUndoCommand;
procedure ClearTo(Index: Integer);
procedure ClearFirst;
procedure DoChanged;
procedure DoUndone(Cmd: TOriUndoCommand);
procedure DoRedone(Cmd: TOriUndoCommand);
public
constructor Create;
destructor Destroy; override;
procedure Undo;
procedure Redo;
function RedoCount: Integer;
function UndoCount: Integer;
property UndoCmd: TOriUndoCommand read GetUndoCmd;
property RedoCmd: TOriUndoCommand read GetRedoCmd;
procedure Append(Command: TOriUndoCommand);
procedure Clear;
procedure Lock;
procedure Unlock;
procedure BeginGroup(const ATitle: String);
procedure EndGroup;
property Groupped: Boolean read GetGroupped;
property Limit: Integer read FLimit write FLimit;
property OnChanged: TUndoRedoEvent read FOnChanged write FOnChanged;
property OnUndone: TUndoneEvent read FOnUndone write FOnUndone;
property OnRedone: TUndoneEvent read FOnRedone write FOnRedone;
end;
// Undoable command is an item of command history. Command must contain
// all the information required to do an action and do it back.
TOriUndoCommand = class
protected
FTitle: String;
protected
procedure Swap; virtual;
public
procedure Undo; virtual;
procedure Redo; virtual;
property Title: String read FTitle;
end;
// List of commands to undo is presented in history as single command.
// It can be useful for group operations, for example deletion of some elements.
// It is convenient if we already have a command to undo deletion of single element
// and we are too lazy to implement a new command to undo deletion of several.
TOriCommandGroup = class(TOriUndoCommand)
private
FItems: TList; // commands stack
public
constructor Create(const ATitle: String);
destructor Destroy; override;
procedure Append(Command: TOriUndoCommand);
procedure Undo; override;
procedure Redo; override;
end;
// Global command history.
// It must be initialized (HistoryInit) anywhere in program before first usage.
var History: TOriHistory;
// Procedures to working with global command history.
procedure HistoryAppend(Command: TOriUndoCommand);
procedure HistoryUndo;
procedure HistoryRedo;
procedure HistoryInit;
implementation
const
HistoryLimit = 100;
{%region Global History}
procedure HistoryInit;
begin
History := TOriHistory.Create;
end;
procedure HistoryAppend(Command: TOriUndoCommand);
begin
if Assigned(History) then History.Append(Command);
end;
procedure HistoryUndo;
begin
if Assigned(History) then History.Undo;
end;
procedure HistoryRedo;
begin
if Assigned(History) then History.Redo;
end;
{%endregion}
{%region TOriHistory}
constructor TOriHistory.Create;
begin
FItems := TList.Create;
FLimit := HistoryLimit;
FLockCount := 0;
FUndoIndex := -1;
end;
destructor TOriHistory.Destroy;
begin
ClearTo(0);
FItems.Free;
inherited;
end;
procedure TOriHistory.Clear;
begin
ClearTo(0);
FUndoIndex := -1;
DoChanged;
end;
function TOriHistory.RedoCount: Integer;
begin
Result := FItems.Count - FUndoIndex - 1;
end;
function TOriHistory.UndoCount: Integer;
begin
Result := FUndoIndex+1;
end;
procedure TOriHistory.Lock;
begin
Inc(FLockCount);
end;
procedure TOriHistory.Unlock;
begin
if FLockCount > 0 then Dec(FLockCount);
end;
procedure TOriHistory.Append(Command: TOriUndoCommand);
begin
if FLockCount = 0 then
if FGroup = nil then
begin
ClearTo(FUndoIndex+1);
FItems.Add(Command);
if FItems.Count = FLimit
then ClearFirst
else Inc(FUndoIndex);
DoChanged;
end
else FGroup.Append(Command);
end;
procedure TOriHistory.ClearTo(Index: Integer);
var
I: Integer;
begin
for I := FItems.Count-1 downto Index do
begin
TOriUndoCommand(FItems[I]).Free;
FItems.Delete(I);
end;
end;
procedure TOriHistory.ClearFirst;
begin
if FItems.Count = 0 then Exit;
TOriUndoCommand(FItems[0]).Free;
FItems.Delete(0);
end;
procedure TOriHistory.DoChanged;
begin
if Assigned(FOnChanged) then FOnChanged(Self, UndoCmd, RedoCmd);
end;
procedure TOriHistory.DoUndone(Cmd: TOriUndoCommand);
begin
if Assigned(FOnUndone) then FOnUndone(Self, Cmd);
end;
procedure TOriHistory.DoRedone(Cmd: TOriUndoCommand);
begin
if Assigned(FOnRedone) then FOnRedone(Self, Cmd);
end;
function TOriHistory.GetUndoCmd: TOriUndoCommand;
begin
if FUndoIndex > -1
then Result := TOriUndoCommand(FItems[FUndoIndex])
else Result := nil;
end;
function TOriHistory.GetRedoCmd: TOriUndoCommand;
begin
if FUndoIndex+1 < FItems.Count
then Result := TOriUndoCommand(FItems[FUndoIndex+1])
else Result := nil;
end;
procedure TOriHistory.Undo;
var
Cmd: TOriUndoCommand;
begin
if FUndoIndex > -1 then
begin
Cmd := TOriUndoCommand(FItems[FUndoIndex]);
Cmd.Undo;
Dec(FUndoIndex);
DoUndone(Cmd);
DoChanged;
end;
end;
procedure TOriHistory.Redo;
var
Cmd: TOriUndoCommand;
begin
if FUndoIndex+1 < FItems.Count then
begin
Cmd := TOriUndoCommand(FItems[FUndoIndex+1]);
Cmd.Redo;
Inc(FUndoIndex);
DoRedone(Cmd);
DoChanged;
end;
end;
procedure TOriHistory.BeginGroup(const ATitle: String);
begin
if FLockCount > 0 then exit;
// If FGroup is assigned, it may be there was an exception between
// BeginGroup and EndGroup. This group is not needed anymore.
if Assigned(FGroup) and (FItems.IndexOf(FGroup) = -1) then FreeAndNil(FGroup);
FGroup := TOriCommandGroup.Create(ATitle);
end;
procedure TOriHistory.EndGroup;
var
Tmp: TOriCommandGroup;
begin
if Assigned(FGroup) then
begin
Tmp := FGroup;
FGroup := nil;
Append(Tmp);
end;
end;
function TOriHistory.GetGroupped: Boolean;
begin
Result := Assigned(FGroup);
end;
{%endregion TOriHistory}
{%region TOriCommandGroup}
constructor TOriCommandGroup.Create(const ATitle: String);
begin
FTitle := ATitle;
FItems := TList.Create;
end;
destructor TOriCommandGroup.Destroy;
var i: Integer;
begin
for i := FItems.Count-1 downto 0 do
TOriUndoCommand(FItems[i]).Free;
FItems.Free;
inherited;
end;
procedure TOriCommandGroup.Append(Command: TOriUndoCommand);
begin
FItems.Add(Command);
end;
procedure TOriCommandGroup.Undo;
var i: Integer;
begin
for i := FItems.Count-1 downto 0 do
TOriUndoCommand(FItems[i]).Undo;
end;
procedure TOriCommandGroup.Redo;
var i: Integer;
begin
for i := 0 to FItems.Count-1 do
TOriUndoCommand(FItems[i]).Redo;
end;
{%endregion TOriCommandGroup}
{%region TOriUndoCommand}
procedure TOriUndoCommand.Swap;
begin
// do nothing
end;
procedure TOriUndoCommand.Undo;
begin
Swap;
end;
procedure TOriUndoCommand.Redo;
begin
Swap;
end;
{%endregion}
initialization
finalization
History.Free;
end.
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit cis_list;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, JSONObjects, AbstractSerializationObjects;
type
{ TCISItem }
TCISItem = class(TJSONSerializationObject)
private
FAgentName: string;
FBrand: string;
FChildren: TXSDStringArray;
FCIS: string;
FCountChildren: Integer;
FEmissionDate: Int64;
FGTIN: string;
FIntroducedDate: Int64;
FLastDocId: string;
FLastStatusChangeDate: string;
FNextCises: string;
FOwnerInn: string;
FOwnerName: string;
FPackageType: string;
FParent: string;
FPrevCises: string;
FProducedDate: Int64;
FProducerName: string;
FProductGroup: string;
FProductName: string;
FStatus: string;
FStatusEx: string;
FTNVED10: string;
procedure SetAgentName(AValue: string);
procedure SetBrand(AValue: string);
procedure SetChildren(AValue: TXSDStringArray);
procedure SetCIS(AValue: string);
procedure SetCountChildren(AValue: Integer);
procedure SetEmissionDate(AValue: Int64);
procedure SetGTIN(AValue: string);
procedure SetIntroducedDate(AValue: Int64);
procedure SetLastDocId(AValue: string);
procedure SetLastStatusChangeDate(AValue: string);
procedure SetNextCises(AValue: string);
procedure SetOwnerInn(AValue: string);
procedure SetOwnerName(AValue: string);
procedure SetPackageType(AValue: string);
procedure SetParent(AValue: string);
procedure SetPrevCises(AValue: string);
procedure SetProducedDate(AValue: Int64);
procedure SetProducerName(AValue: string);
procedure SetProductGroup(AValue: string);
procedure SetProductName(AValue: string);
procedure SetStatus(AValue: string);
procedure SetStatusEx(AValue: string);
procedure SetTNVED10(AValue: string);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create; override;
destructor Destroy; override;
published
property CIS:string read FCIS write SetCIS;
property GTIN:string read FGTIN write SetGTIN;
property ProducerName:string read FProducerName write SetProducerName;
property Status:string read FStatus write SetStatus;
property StatusEx:string read FStatusEx write SetStatusEx;
property EmissionDate:Int64 read FEmissionDate write SetEmissionDate;
property PackageType:string read FPackageType write SetPackageType;
property OwnerName:string read FOwnerName write SetOwnerName;
property OwnerInn:string read FOwnerInn write SetOwnerInn;
property ProductName:string read FProductName write SetProductName;
property Brand:string read FBrand write SetBrand;
property PrevCises:string read FPrevCises write SetPrevCises;
property NextCises:string read FNextCises write SetNextCises;
property CountChildren:Integer read FCountChildren write SetCountChildren;
property LastDocId:string read FLastDocId write SetLastDocId;
property IntroducedDate:Int64 read FIntroducedDate write SetIntroducedDate;
property AgentName:string read FAgentName write SetAgentName;
property LastStatusChangeDate:string read FLastStatusChangeDate write SetLastStatusChangeDate;
property ProductGroup:string read FProductGroup write SetProductGroup;
property ProducedDate:Int64 read FProducedDate write SetProducedDate;
property Children:TXSDStringArray read FChildren write SetChildren;
property TNVED10:string read FTNVED10 write SetTNVED10;
property Parent:string read FParent write SetParent;
end;
TCISItemList = specialize GXMLSerializationObjectList<TCISItem>;
{ TCISItems }
TCISItems = class(TJSONSerializationObject)
private
FItems: TCISItemList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create; override;
destructor Destroy; override;
published
property Items:TCISItemList read FItems;
end;
implementation
{ TCISItems }
procedure TCISItems.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('Items', 'Items', [xsaDefault], '', -1, -1);
end;
procedure TCISItems.InternalInitChilds;
begin
inherited InternalInitChilds;
FItems:=TCISItemList.Create;
end;
constructor TCISItems.Create;
begin
inherited Create;
FIgnoreReadUndefProps:=true;
end;
destructor TCISItems.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
{ TCISItem }
procedure TCISItem.SetAgentName(AValue: string);
begin
if FAgentName=AValue then Exit;
FAgentName:=AValue;
ModifiedProperty('AgentName');
end;
procedure TCISItem.SetBrand(AValue: string);
begin
if FBrand=AValue then Exit;
FBrand:=AValue;
ModifiedProperty('Brand');
end;
procedure TCISItem.SetChildren(AValue: TXSDStringArray);
begin
if FChildren=AValue then Exit;
FChildren:=AValue;
ModifiedProperty('Children');
end;
procedure TCISItem.SetCIS(AValue: string);
begin
if FCIS=AValue then Exit;
FCIS:=AValue;
ModifiedProperty('CIS');
end;
procedure TCISItem.SetCountChildren(AValue: Integer);
begin
if FCountChildren=AValue then Exit;
FCountChildren:=AValue;
ModifiedProperty('CountChildren');
end;
procedure TCISItem.SetEmissionDate(AValue: Int64);
begin
if FEmissionDate=AValue then Exit;
FEmissionDate:=AValue;
ModifiedProperty('EmissionDate');
end;
procedure TCISItem.SetGTIN(AValue: string);
begin
if FGTIN=AValue then Exit;
FGTIN:=AValue;
ModifiedProperty('GTIN');
end;
procedure TCISItem.SetIntroducedDate(AValue: Int64);
begin
if FIntroducedDate=AValue then Exit;
FIntroducedDate:=AValue;
ModifiedProperty('IntroducedDate');
end;
procedure TCISItem.SetLastDocId(AValue: string);
begin
if FLastDocId=AValue then Exit;
FLastDocId:=AValue;
ModifiedProperty('LastDocId');
end;
procedure TCISItem.SetLastStatusChangeDate(AValue: string);
begin
if FLastStatusChangeDate=AValue then Exit;
FLastStatusChangeDate:=AValue;
ModifiedProperty('LastStatusChangeDate');
end;
procedure TCISItem.SetNextCises(AValue: string);
begin
if FNextCises=AValue then Exit;
FNextCises:=AValue;
ModifiedProperty('NextCises');
end;
procedure TCISItem.SetOwnerInn(AValue: string);
begin
if FOwnerInn=AValue then Exit;
FOwnerInn:=AValue;
ModifiedProperty('OwnerInn');
end;
procedure TCISItem.SetOwnerName(AValue: string);
begin
if FOwnerName=AValue then Exit;
FOwnerName:=AValue;
ModifiedProperty('OwnerName');
end;
procedure TCISItem.SetPackageType(AValue: string);
begin
if FPackageType=AValue then Exit;
FPackageType:=AValue;
ModifiedProperty('PackageType');
end;
procedure TCISItem.SetParent(AValue: string);
begin
if FParent=AValue then Exit;
FParent:=AValue;
ModifiedProperty('Parent');
end;
procedure TCISItem.SetPrevCises(AValue: string);
begin
if FPrevCises=AValue then Exit;
FPrevCises:=AValue;
ModifiedProperty('PrevCises');
end;
procedure TCISItem.SetProducedDate(AValue: Int64);
begin
if FProducedDate=AValue then Exit;
FProducedDate:=AValue;
ModifiedProperty('ProducedDate');
end;
procedure TCISItem.SetProducerName(AValue: string);
begin
if FProducerName=AValue then Exit;
FProducerName:=AValue;
ModifiedProperty('ProducerName');
end;
procedure TCISItem.SetProductGroup(AValue: string);
begin
if FProductGroup=AValue then Exit;
FProductGroup:=AValue;
ModifiedProperty('ProductGroup');
end;
procedure TCISItem.SetProductName(AValue: string);
begin
if FProductName=AValue then Exit;
FProductName:=AValue;
ModifiedProperty('ProductName');
end;
procedure TCISItem.SetStatus(AValue: string);
begin
if FStatus=AValue then Exit;
FStatus:=AValue;
ModifiedProperty('Status');
end;
procedure TCISItem.SetStatusEx(AValue: string);
begin
if FStatusEx=AValue then Exit;
FStatusEx:=AValue;
ModifiedProperty('StatusEx');
end;
procedure TCISItem.SetTNVED10(AValue: string);
begin
if FTNVED10=AValue then Exit;
FTNVED10:=AValue;
ModifiedProperty('TNVED10');
end;
procedure TCISItem.InternalRegisterPropertys;
begin
inherited InternalRegisterPropertys;
RegisterProperty('CIS', 'cis', [], '', -1, -1);
RegisterProperty('GTIN', 'gtin', [], '', -1, -1);
RegisterProperty('ProducerName', 'producerName', [], '', -1, -1);
RegisterProperty('Status', 'status', [], '', -1, -1);
RegisterProperty('StatusEx', 'statusEx', [], '', -1, -1);
RegisterProperty('EmissionDate', 'emissionDate', [], '', -1, -1);
RegisterProperty('PackageType', 'packageType', [], '', -1, -1);
RegisterProperty('OwnerName', 'ownerName', [], '', -1, -1);
RegisterProperty('OwnerInn', 'ownerInn', [], '', -1, -1);
RegisterProperty('ProductName', 'productName', [], '', -1, -1);
RegisterProperty('Brand', 'brand', [], '', -1, -1);
RegisterProperty('PrevCises', 'prevCises', [], '', -1, -1);
RegisterProperty('NextCises', 'nextCises', [], '', -1, -1);
RegisterProperty('CountChildren', 'countChildren', [], '', -1, -1);
RegisterProperty('LastDocId', 'lastDocId', [], '', -1, -1);
RegisterProperty('IntroducedDate', 'introducedDate', [], '', -1, -1);
RegisterProperty('AgentName', 'agentName', [], '', -1, -1);
RegisterProperty('LastStatusChangeDate', 'lastStatusChangeDate', [], '', -1, -1);
RegisterProperty('ProductGroup', 'productGroup', [], '', -1, -1);
RegisterProperty('ProducedDate', 'producedDate', [], '', -1, -1);
RegisterProperty('Children', 'children', [], '', -1, -1);
RegisterProperty('TNVED10', 'tnVed10', [], '', -1, -1);
RegisterProperty('Parent', 'parent', [], '', -1, -1);
end;
procedure TCISItem.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
constructor TCISItem.Create;
begin
inherited Create;
FIgnoreReadUndefProps:=true;
end;
destructor TCISItem.Destroy;
begin
inherited Destroy;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.EdgeHTTPListener;
{$HPPEMIT LINKUNIT}
interface
uses EMSHosting.EdgeService, EMSHosting.EdgeHTTPServer,
System.Classes, System.JSON;
type
TCustomEMSEdgeHTTPListener = class(TEMSEdgeListener)
public type
TCreateModuleEvent = reference to function: TEMSEdgeListener.TModule;
private
FServer: TEMSEdgeHTTPServer;
FHost: string;
FModule: TEMSEdgeListener.TModule;
function Getport: Cardinal;
procedure Setport(const Value: Cardinal);
protected
function GetActive: Boolean; override;
procedure SetActive(const Value: Boolean); override;
function GetModule: TEMSEdgeListener.TModule; override;
procedure AddProtocolProps(const AProtocolProps: TJSONObject); override;
property Server: TEMSEdgeHTTPServer read FServer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Host: string read FHost write FHost;
property Port: Cardinal read Getport write Setport;
end;
TEMSEdgeHTTPListener = class(TCustomEMSEdgeHTTPListener)
published
property Port;
property Host;
end;
TCustomEMSEdgeHTTPSListener = class(TCustomEMSEdgeHTTPListener)
public type
TGetPasswordEvent = procedure(Sender: TObject; var APassword: string) of object;
private
FOnGetKeyPassword: TGetPasswordEvent;
function GetCertFile: string;
function GetKeyFile: string;
function GetRootCertFile: string;
procedure SetCertFile(const Value: string);
procedure SetKeyFile(const Value: string);
procedure SetRootCertFile(const Value: string);
protected
procedure DoGetKeyPassword(var APassword: string); virtual;
public
constructor Create(AOwner: TComponent); override;
/// <summary>File of the X.509 certificate</summary>
property CertFile: string read GetCertFile write SetCertFile;
/// <summary>File of the X.509 private key</summary>
property KeyFile: string read GetKeyFile write SetKeyFile;
/// <summary>File of the X.509 root certificate</summary>
property RootCertFile: string read GetRootCertFile write SetRootCertFile;
/// <summary>Event handler to provide the string used to encrypt the private key in KeyFile</summary>
property OnGetKeyPassword: TGetPasswordEvent read FOnGetKeyPassword write FOnGetKeyPassword;
end;
TEMSEdgeHTTPSListener = class(TCustomEMSEdgeHTTPSListener)
published
property Port;
property Host;
property CertFile;
property KeyFile;
property OnGetKeyPassword;
property RootCertFile;
end;
implementation
uses EMSHosting.EdgeListeners, System.SysUtils;
{ TCustomEMSEdgHTTPListenerFactory }
type
TCustomEMSEdgHTTPListenerFactory = class(TEMSEdgeListenerFactory)
protected
function DoCreateListener(const AOwner: TComponent; const AProtocolName: string): TEMSEdgeListener; override;
end;
TCustomEMSEdgHTTPSListenerFactory = class(TEMSEdgeListenerFactory)
protected
function DoCreateListener(const AOwner: TComponent; const AProtocolName: string): TEMSEdgeListener; override;
end;
const
sHttp = 'http';
sHttps = 'https';
sPort = 'port';
sHost = 'host';
{ TCustomEMSEdgeHTTPListener }
constructor TCustomEMSEdgeHTTPListener.Create(AOwner: TComponent);
begin
inherited;
FServer := TEMSEdgeHTTPServer.Create;
end;
destructor TCustomEMSEdgeHTTPListener.Destroy;
begin
FServer.Free;
inherited;
end;
function TCustomEMSEdgeHTTPListener.GetActive: Boolean;
begin
Result := FServer.Active;
end;
function TCustomEMSEdgeHTTPListener.GetModule: TEMSEdgeListener.TModule;
begin
if FModule = nil then
FModule := CreateModule;
Result := FModule;
end;
function TCustomEMSEdgeHTTPListener.Getport: Cardinal;
begin
Result := FServer.Port;
end;
procedure TCustomEMSEdgeHTTPListener.AddProtocolProps(const AProtocolProps: TJSONObject);
begin
AProtocolProps.AddPair(sPort, TJSONNumber.Create(Port));
AProtocolProps.AddPair(sHost, TJSONString.Create(Host));
end;
procedure TCustomEMSEdgeHTTPListener.SetActive(const Value: Boolean);
begin
if FServer.Active <> Value then
begin
FServer.Module := nil;
FreeAndNil(FModule);
if Value then
FServer.Module := Module;
FServer.Active := Value;
end;
end;
procedure TCustomEMSEdgeHTTPListener.Setport(const Value: Cardinal);
begin
FServer.Port := Value;
end;
{ TCustomEMSEdgHTTPListenerFactory }
function TCustomEMSEdgHTTPListenerFactory.DoCreateListener(
const AOwner: TComponent; const AProtocolName: string): TEMSEdgeListener;
begin
Result := TEMSEdgeHTTPListener.Create(AOwner);
end;
{ TCustomEMSEdgHTTPSListenerFactory }
function TCustomEMSEdgHTTPSListenerFactory.DoCreateListener(
const AOwner: TComponent; const AProtocolName: string): TEMSEdgeListener;
begin
Result := TEMSEdgeHTTPSListener.Create(AOwner);
end;
const
sUnit = 'EMSHosting.EdgeHTTPListener';
{ TCustomEMSEdgeHTTPSListener }
constructor TCustomEMSEdgeHTTPSListener.Create(AOwner: TComponent);
begin
inherited;
Server.OnGetSSLPassword := DoGetKeyPassword;
Server.HTTPS := True;
end;
procedure TCustomEMSEdgeHTTPSListener.DoGetKeyPassword(var APassword: string);
begin
if Assigned(FOnGetKeyPassword) then
FOnGetKeyPassword(Self, APassword);
end;
function TCustomEMSEdgeHTTPSListener.GetCertFile: string;
begin
Result := FServer.CertFile;
end;
function TCustomEMSEdgeHTTPSListener.GetKeyFile: string;
begin
Result := FServer.KeyFile;
end;
function TCustomEMSEdgeHTTPSListener.GetRootCertFile: string;
begin
Result := FServer.RootCertFile;
end;
procedure TCustomEMSEdgeHTTPSListener.SetCertFile(const Value: string);
begin
FServer.CertFile := Value;
end;
procedure TCustomEMSEdgeHTTPSListener.SetKeyFile(const Value: string);
begin
FServer.KeyFile := Value;
end;
procedure TCustomEMSEdgeHTTPSListener.SetRootCertFile(const Value: string);
begin
FServer.RootCertFile := Value;
end;
initialization
TEMSEdgeListenerFactories.Instance.Add(sHttp, sUnit, // Do not localize
TCustomEMSEdgHTTPListenerFactory.Create);
TEMSEdgeListenerFactories.Instance.Add(sHttps, sUnit, // Do not localize
TCustomEMSEdgHTTPSListenerFactory.Create);
finalization
TEMSEdgeListenerFactories.Instance.Remove(sHttp);
end.
|
unit IdTCPClient;
interface
uses
Classes, IdStack,
IdException, IdGlobal, IdTCPConnection;
const
BoundPortDefault = 0;
type
TIdTCPClient = class(TIdTCPConnection)
protected
FBoundIP: string;
FBoundPort: Integer;
FBoundPortMax: Integer;
FBoundPortMin: Integer;
FHost: string;
FOnConnected: TNotifyEvent;
FPassword: string;
FPort: integer;
FUsername: string;
//
procedure SetHost(const Value: string); virtual;
procedure SetPort(const Value: integer); virtual;
procedure DoOnConnected; virtual;
//
property Username: string read FUsername write FUsername;
property Password: string read FPassword write FPassword;
public
procedure Connect(const ATimeout: Integer = IdTimeoutDefault); virtual;
function ConnectAndGetAll: string; virtual;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//
property BoundPortMax: Integer read FBoundPortMax write FBoundPortMax;
property BoundPortMin: Integer read FBoundPortMin write FBoundPortMin;
published
property BoundIP: string read FBoundIP write FBoundIP;
property BoundPort: Integer read FBoundPort write FBoundPort default BoundPortDefault;
property Host: string read FHost write SetHost;
property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
property Port: integer read FPort write SetPort;
end;
implementation
uses
IdComponent, IdIOHandlerSocket, IdResourceStrings,
SysUtils;
{ TIdTCPClient }
procedure TIdTCPClient.Connect(const ATimeout: Integer = IdTimeoutDefault);
begin
// Do not call Connected here, it will call CheckDisconnect
if IOHandler <> nil then begin
if IOHandler.Connected then begin
raise EIdAlreadyConnected.Create(RSAlreadyConnected);
end;
end else begin
IOHandler := TIdIOHandlerSocket.Create(Self);
IOHandler.OnStatus := OnStatus;
FFreeIOHandlerOnDisconnect := True;
end;
try
IOHandler.Open;
ResetConnection;
// Socks support
IOHandler.ConnectClient(Host, Port, BoundIP, BoundPort, BoundPortMin, BoundPortMax, ATimeout);
if Assigned(Intercept) then begin
Intercept.Connect(Self);
end;
DoStatus(hsConnected, [Host]);
DoOnConnected;
except
// This will free IOHandler
DisconnectSocket;
raise;
end;
end;
function TIdTCPClient.ConnectAndGetAll: string;
begin
Connect; try
Result := AllData;
finally Disconnect; end;
end;
constructor TIdTCPClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBoundPort := BoundPortDefault;
end;
destructor TIdTCPClient.Destroy;
begin
inherited Destroy;
end;
procedure TIdTCPClient.DoOnConnected;
begin
if Assigned(OnConnected) then begin
OnConnected(Self);
end;
end;
procedure TIdTCPClient.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure TIdTCPClient.SetPort(const Value: integer);
begin
FPort := Value;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ TStrings property editor dialog }
{ }
{ Copyright (c) 1999 Borland International }
{ }
{*******************************************************}
unit StrEdit;
interface
uses Windows, Classes, Graphics, Forms, Controls, Buttons, Dialogs, DsgnIntf,
StdCtrls, ExtCtrls, ComCtrls, Menus;
type
TStrEditDlg = class(TForm)
LineCount: TLabel;
CodeWndBtn: TButton;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
HelpButton: TButton;
OKButton: TButton;
CancelButton: TButton;
Memo: TRichEdit;
StringEditorMenu: TPopupMenu;
LoadItem: TMenuItem;
SaveItem: TMenuItem;
CodeEditorItem: TMenuItem;
procedure FileOpen(Sender: TObject);
procedure FileSave(Sender: TObject);
procedure UpdateStatus(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure HelpButtonClick(Sender: TObject);
procedure CodeWndBtnClick(Sender: TObject);
private
SingleLine: string;
MultipleLines: string;
FModified: Boolean;
end;
type
TStringListProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
implementation
{$R *.DFM}
uses ActiveX, SysUtils, DesignConst, LibHelp, ToolsAPI, IStreams, StFilSys,
TypInfo;
type
TStringsModuleCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator)
private
FFileName: string;
FStream: TStringStream;
FAge: TDateTime;
public
constructor Create(const FileName: string; Stream: TStringStream; Age: TDateTime);
destructor Destroy; override;
{ IOTACreator }
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
TOTAFile = class(TInterfacedObject, IOTAFile)
private
FSource: string;
FAge: TDateTime;
public
constructor Create(const ASource: string; AAge: TDateTime);
{ IOTAFile }
function GetSource: string;
function GetAge: TDateTime;
end;
{ TOTAFile }
constructor TOTAFile.Create(const ASource: string; AAge: TDateTime);
begin
inherited Create;
FSource := ASource;
FAge := AAge;
end;
function TOTAFile.GetAge: TDateTime;
begin
Result := FAge;
end;
function TOTAFile.GetSource: string;
begin
Result := FSource;
end;
{ TStringsModuleCreator }
constructor TStringsModuleCreator.Create(const FileName: string; Stream: TStringStream;
Age: TDateTime);
begin
inherited Create;
FFileName := FileName;
FStream := Stream;
FAge := Age;
end;
destructor TStringsModuleCreator.Destroy;
begin
FStream.Free;
inherited;
end;
procedure TStringsModuleCreator.FormCreated(const FormEditor: IOTAFormEditor);
begin
{ Nothing to do }
end;
function TStringsModuleCreator.GetAncestorName: string;
begin
Result := '';
end;
function TStringsModuleCreator.GetCreatorType: string;
begin
Result := sText;
end;
function TStringsModuleCreator.GetExisting: Boolean;
begin
Result := False;
end;
function TStringsModuleCreator.GetFileSystem: string;
begin
Result := sTStringsFileSystem;
end;
function TStringsModuleCreator.GetFormName: string;
begin
Result := '';
end;
function TStringsModuleCreator.GetImplFileName: string;
begin
Result := FFileName;
end;
function TStringsModuleCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TStringsModuleCreator.GetMainForm: Boolean;
begin
Result := False;
end;
function TStringsModuleCreator.GetOwner: IOTAModule;
begin
Result := nil;
end;
function TStringsModuleCreator.GetShowForm: Boolean;
begin
Result := False;
end;
function TStringsModuleCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TStringsModuleCreator.GetUnnamed: Boolean;
begin
Result := False;
end;
function TStringsModuleCreator.NewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TStringsModuleCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := TOTAFile.Create(FStream.DataString, FAge);
end;
function TStringsModuleCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
{ TStrEditDlg }
procedure TStrEditDlg.FileOpen(Sender: TObject);
begin
with OpenDialog do
if Execute then Memo.Lines.LoadFromFile(FileName);
end;
procedure TStrEditDlg.FileSave(Sender: TObject);
begin
SaveDialog.FileName := OpenDialog.FileName;
with SaveDialog do
if Execute then Memo.Lines.SaveToFile(FileName);
end;
procedure TStrEditDlg.UpdateStatus(Sender: TObject);
var
Count: Integer;
LineText: string;
begin
if Sender = Memo then FModified := True;
Count := Memo.Lines.Count;
if Count = 1 then LineText := SingleLine
else LineText := MultipleLines;
LineCount.Caption := Format('%d %s', [Count, LineText]);
end;
{ TStringListProperty }
function TStringListProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
procedure TStringListProperty.Edit;
var
Ident: string;
Component: TComponent;
Module: IOTAModule;
Editor: IOTAEditor;
ModuleServices: IOTAModuleServices;
Stream: TStringStream;
Age: TDateTime;
begin
Component := TComponent(GetComponent(0));
ModuleServices := BorlandIDEServices as IOTAModuleServices;
if (TObject(Component) is TComponent) and
(Component.Owner = Self.Designer.GetRoot) then
begin
Ident := Self.Designer.GetRoot.Name + DotSep +
Component.Name + DotSep + GetName;
Module := ModuleServices.FindModule(Ident);
end else Module := nil;
if (Module <> nil) and (Module.GetModuleFileCount > 0) then
Module.GetModuleFileEditor(0).Show
else with TStrEditDlg.Create(Application) do
try
Memo.Lines := TStrings(GetOrdValue);
UpdateStatus(nil);
FModified := False;
ActiveControl := Memo;
CodeEditorItem.Enabled := Ident <> '';
CodeWndBtn.Enabled := Ident <> '';
case ShowModal of
mrOk: SetOrdValue(Longint(Memo.Lines));
mrYes:
begin
Stream := TStringStream.Create('');
Memo.Lines.SaveToStream(Stream);
Stream.Position := 0;
Age := Now;
Module := ModuleServices.CreateModule(
TStringsModuleCreator.Create(Ident, Stream, Age));
if Module <> nil then
begin
with StringsFileSystem.GetTStringsProperty(Ident, Component, GetName) do
DiskAge := DateTimeToFileDate(Age);
Editor := Module.GetModuleFileEditor(0);
if FModified then
Editor.MarkModified;
Editor.Show;
end;
end;
end;
finally
Free;
end;
end;
procedure TStrEditDlg.FormCreate(Sender: TObject);
begin
HelpContext := hcDStringListEditor;
OpenDialog.HelpContext := hcDStringListLoad;
SaveDialog.HelpContext := hcDStringListSave;
SingleLine := srLine;
MultipleLines := srLines;
end;
procedure TStrEditDlg.Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then CancelButton.Click;
end;
procedure TStrEditDlg.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TStrEditDlg.CodeWndBtnClick(Sender: TObject);
begin
ModalResult := mrYes;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ASADef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf;
type
// TFDPhysASAConnectionDefParams
// Generated for: FireDAC ASA driver
/// <summary> TFDPhysASAConnectionDefParams class implements FireDAC ASA driver specific connection definition class. </summary>
TFDPhysASAConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetODBCAdvanced: String;
procedure SetODBCAdvanced(const AValue: String);
function GetLoginTimeout: Integer;
procedure SetLoginTimeout(const AValue: Integer);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetDatabaseFile: TFileName;
procedure SetDatabaseFile(const AValue: TFileName);
function GetOSAuthent: Boolean;
procedure SetOSAuthent(const AValue: Boolean);
function GetCompress: Boolean;
procedure SetCompress(const AValue: Boolean);
function GetEncrypt: String;
procedure SetEncrypt(const AValue: String);
function GetApplicationName: String;
procedure SetApplicationName(const AValue: String);
function GetMetaDefCatalog: String;
procedure SetMetaDefCatalog(const AValue: String);
function GetMetaDefSchema: String;
procedure SetMetaDefSchema(const AValue: String);
function GetMetaCurCatalog: String;
procedure SetMetaCurCatalog(const AValue: String);
function GetMetaCurSchema: String;
procedure SetMetaCurSchema(const AValue: String);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property ODBCAdvanced: String read GetODBCAdvanced write SetODBCAdvanced stored False;
property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False;
property Server: String read GetServer write SetServer stored False;
property DatabaseFile: TFileName read GetDatabaseFile write SetDatabaseFile stored False;
property OSAuthent: Boolean read GetOSAuthent write SetOSAuthent stored False;
property Compress: Boolean read GetCompress write SetCompress stored False;
property Encrypt: String read GetEncrypt write SetEncrypt stored False;
property ApplicationName: String read GetApplicationName write SetApplicationName stored False;
property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False;
property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False;
property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False;
property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysASAConnectionDefParams
// Generated for: FireDAC ASA driver
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetODBCAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetODBCAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetLoginTimeout: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetLoginTimeout(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetDatabaseFile: TFileName;
begin
Result := FDef.AsString[S_FD_ConnParam_ASA_DatabaseFile];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetDatabaseFile(const AValue: TFileName);
begin
FDef.AsString[S_FD_ConnParam_ASA_DatabaseFile] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetOSAuthent: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetOSAuthent(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetCompress: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_ASA_Compress];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetCompress(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_ASA_Compress] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetEncrypt: String;
begin
Result := FDef.AsString[S_FD_ConnParam_ASA_Encrypt];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetEncrypt(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_ASA_Encrypt] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetApplicationName: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_ApplicationName];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetApplicationName(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_ApplicationName] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetMetaDefCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetMetaDefCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetMetaDefSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetMetaDefSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetMetaCurCatalog: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetMetaCurCatalog(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysASAConnectionDefParams.GetMetaCurSchema: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysASAConnectionDefParams.SetMetaCurSchema(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue;
end;
end.
|
unit tsUtils;
interface
uses
Controls, SysUtils, DateUtils, Dialogs;
const
eps = 0.01; // если цена меньше этой величины, то она равнозначна нулю
// функции обработки целочисленного времени и даты
function IntToDate(ADate: integer): TDate;
function DateToInt(ADate: TDate): integer;
function IntToTime(ATime: integer): TTime;
function TimeToInt(ATime: TTime): integer;
function IntToDateTime(ADate, ATime: integer): TDateTime;
procedure DateTimeToInt(ADateTime: TDateTime; var ADate, ATime: integer);
function IntTimeToSec(ATime: integer): integer;
function SecToIntTime(ASeconds: integer): integer;
function IntSecondsBetween(ANowTime, AThenTime: integer): integer;
// конвертеры
function fts(Value: real): string;
// функции для работы с указателями
function addp(p: Pointer; increment: integer = 1): Pointer; overload;
function addp(p: Pointer; increment: pointer): Pointer; overload;
function subp(p: Pointer; decrement: integer = 1): Pointer; overload;
function subp(p: Pointer; decrement: pointer): Pointer; overload;
type
TComplPrice = record
Date: integer;
Time: integer;
Price1: real;
Price2: real;
end;
TComplPriceCollector = object
Count: integer;
Prices: array of TComplPrice;
procedure AddPrices(ADate, ATime: integer; APrice1, APrice2: real);
procedure AddPrice1(ADate, ATime: integer; APrice: real);
procedure AddPrice2(ADate, ATime: integer; APrice: real);
procedure Clear;
procedure Sort;
procedure ReplaceZeros;
end;
TPriceQueue = object
fLength: integer;
fData: array of real;
fPointer: integer;
procedure Init(aLength: integer; aPrice: real);
function appPrice(aPrice: real): real;
end;
TTimePriceQueue = object
private
fLength: integer;
fData: array of real;
fPointer: integer;
fLastTime: integer;
public
Round: boolean;
property Pointer: integer read fPointer;
procedure Init(aLength: integer; aPrice: real; ATime: integer = 0);
function appPrice(aPrice: real; ATime: integer = 0): real;
end;
TPriceType = (ptNone, ptAction, ptFutures, ptBoth, ptJointFile);
TPriceData = class
private
fPriceType: TPriceType;
fData: TComplPriceCollector;
fLastDate: integer;
fFile: TextFile;
aFile: TextFile;
aFileName: TFileName;
fFileName: TFileName;
fNextIndex: integer;
function ReadNextDay: integer;
public
procedure Start(ActionFile, FuturesFile: TFileName);overload;
procedure Start(ADate: integer; ActionFile, FuturesFile: TFileName);overload;
procedure Start(ActionFuturesFile: TFileName);overload;
procedure Start(Adate: integer; ActionFuturesFile: TFileName);overload;
function GetNext(var ADate, ATime: integer; var ActionPrice, FuturesPrice: real): integer;overload;
function GetNext(var ADate, ATime: integer; var APrice: real):integer;overload;
procedure Stop;
end;
var
PriceData: TPriceData;
implementation
uses LogThread;
function IntToDate(ADate: integer): TDate;
begin
try
result := EncodeDate(ADate div 10000, ADate div 100 mod 100, ADate mod 100);
except
Log.AddEvent('Ошибка конвертации даты');
end;
end;
function DateToInt(ADate: TDate): integer;
var
y, m, d: word;
begin
try
DecodeDate(ADate, y, m, d);
except
y:=0;
m := 0;
d := 0;
Log.AddEvent('Ошибка конвертации даты');
end;
result := (y*100 + m)*100 + d;
end;
function IntToTime(ATime: integer): TTime;
begin
try
result := EncodeTime(ATime div 10000, ATime div 100 mod 100, ATime mod 100, 0);
except
// ShowMessage(inttostr(ATime))
Log.AddEvent('Ошибка конвертации времени');
end;
end;
function TimeToInt(ATime: TTime): integer;
var
h, m, s, t: word;
begin
try
DecodeTime(ATime, h, m, s, t);
except
h := 0;
m := 0;
s := 0;
Log.AddEvent('Ошибка конвертации времени');
end;
result := (h*100 + m)*100 + s
end;
function IntToDateTime(ADate, ATime: integer): TDateTime;
begin
result := IntToDate(ADate) + IntToTime(ATime)
end;
procedure DateTimeToInt(ADateTime: TDateTime; var ADate, ATime: integer);
begin
ADate := DateToInt(ADateTime);
ATime := TimeToInt(ADateTime);
end;
function inttimetosec(ATime: integer): integer;
begin
result := (ATime mod 100) + ((ATime div 100) mod 100)*60 + (ATime div 10000)*3600;
end;
function sectointtime(ASeconds: integer): integer;
begin
result := (ASeconds mod 60) + (ASeconds mod 3600 div 60)*100 + (ASeconds div 3600)*10000
end;
function IntSecondsBetween(ANowTime, AThenTime: integer): integer;
begin
result := IntTimeToSec(ANowTime) - IntTimeToSec(AThenTime);
end;
function fts(Value: real): string;
begin
result := FloatToStrF(Value, ffFixed, 25, 2)
end;
function addp(p: Pointer; increment: integer = 1): Pointer; overload;
begin
result := Pointer(Integer(p) + increment);
end;
function addp(p: Pointer; increment: pointer): Pointer; overload;
begin
result := Pointer(Integer(p) + Integer(increment));
end;
function subp(p: Pointer; decrement: integer = 1): Pointer; overload;
begin
result := Pointer(Integer(p) - decrement);
end;
function subp(p: Pointer; decrement: pointer): Pointer; overload;
begin
result := Pointer(Integer(p) - Integer(decrement));
end;
//----------TComplPriceCollector--------
procedure TComplPriceCollector.Clear;
begin
Count := 0;
SetLength(Prices, Count);
end;
procedure TComplPriceCollector.AddPrices(ADate, ATime: integer; APrice1, APrice2: real);
var
i: integer;
new: boolean;
begin
new := true;
For i := 0 to Count - 1 do
If (Prices[i].Date = ADate) and (Prices[i].Time = ATime) then
begin
new := false;
If APrice1 <> 0 then
Prices[i].Price1 := APrice1;
If APrice2 <> 0 then
Prices[i].Price2 := APrice2;
Break
end;
If new then
begin
SetLength(Prices, Count+1);
Prices[Count].Date := ADate;
Prices[Count].Time := ATime;
Prices[Count].Price1 := APrice1;
Prices[Count].Price2 := APrice2;
inc(Count);
end;
end;
procedure TComplPriceCollector.AddPrice1(ADate, ATime: integer; APrice: real);
begin
AddPrices(ADate, ATime, APrice, 0);
end;
procedure TComplPriceCollector.AddPrice2(ADate, ATime: integer; APrice: real);
begin
AddPrices(ADate, ATime, 0, APrice);
end;
procedure TComplPriceCollector.Sort;
var
i: integer;
tmp: TComplPrice;
done: boolean;
begin
Repeat
done := true;
For i := 0 to Count - 2 do
// елси текущая дата больше следующей или дата равна, а время больше, то меняем местами
If (Prices[i].Date > Prices[i+1].Date) or ((Prices[i].Date = Prices[i+1].Date) and (Prices[i].Time > Prices[i+1].Time)) then
begin
tmp := Prices[i];
Prices[i] := Prices[i+1];
Prices[i+1] := tmp;
done := false
end;
Until done;
end;
procedure TComplPriceCollector.ReplaceZeros;
var
i, n: integer;
begin
Sort;
For i := 1 to Count - 1 do
With Prices[i] do
begin
If Price1 = 0 then Price1 := Prices[i-1].Price1;
If Price2 = 0 then Price2 := Prices[i-1].Price2;
end;
n := 0;
While (Prices[n].Price1 = 0) or (Prices[n].Price2 = 0) do
inc(n); // подсчет нулей в начале списка
If n > 0 then
For i := n to Count - 1 do
Prices[i - n] := Prices[i];
Count := Count - n;
SetLength(Prices, Count);
end;
//--------------------------------------
//----------TPriceQueue----------
procedure TPriceQueue.Init;
var
i: integer;
begin
fLength := aLength;
SetLength(fData, fLength);
fPointer := 0;
For i := 0 to fLength - 1 do
fData[i] := aPrice;
end;
function TPriceQueue.appPrice;
var
i: integer;
sum: real;
begin
fData[fPointer] := aPrice;
inc(fPointer);
If fPointer >= fLength then fPointer := 0;
sum := 0;
For i := 0 to fLength - 1 do
sum := sum + fData[i];
result := sum / fLength
end;
//--------------------------------------
//----------TTimePriceQueue----------
procedure TTimePriceQueue.Init;
var
i: integer;
begin
fLength := aLength;
SetLength(fData, fLength);
fPointer := 0;
For i := 0 to fLength - 1 do
fData[i] := aPrice;
If ATime = 0 then
ATime := timetoint(Now);
fLastTime := ATime;
Round := false;
end;
function TTimePriceQueue.appPrice;
var
i, t: integer;
sum: real;
begin
If ATime = 0 then
ATime := TimeToInt(Now);
t := intSecondsBetween(ATime, fLastTime);
If t = 0 then
fData[fPointer] := (fData[fPointer] + aPrice)/2
else
For i := 1 to t do
begin
fData[fPointer] := aPrice;
inc(fPointer);
If fPointer >= fLength then
begin
fPointer := 0;
round := true;
end;
end;
fLastTime := ATime;
sum := 0;
For i := 0 to fLength - 1 do
sum := sum + fData[i];
result := sum / fLength
end;
//--------------------------------------
//----------TPriceData------------------
function TPriceData.ReadNextDay: integer;
var
fDate, fTime, hDate: integer;
fPrice: real;
begin
result := -1;
fData.Clear;
If fPriceType in [ptAction, ptBoth] then // читаем акции
begin
If eof(aFile) then Exit;
// reset(aFile);
Repeat // проматываем, то что уже было обработано раньше
Readln(aFile, fDate, fTime, fPrice)
Until eof(aFile) or (fDate = fLastDate) or (fLastDate = 0);
If not eof(aFile) then
begin
hDate := fDate;
Repeat
fData.AddPrice1(fDate, fTime, fPrice);
Readln(aFile, fDate, fTime, fPrice);
Until eof(aFile) or (fDate > hDate);
fData.AddPrice1(fDate, fTime, fPrice);
end;
// closefile(aFile);
end;
If fPriceType in [ptFutures, ptBoth] then // читаем фьючи
begin
If eof(fFile) then Exit;
// reset(fFile);
Repeat // проматываем, то что уже было обработано раньше
Readln(fFile, fDate, fTime, fPrice)
Until eof(fFile) or (fDate = fLastDate) or (fLastDate = 0);
If not eof(fFile) then
begin
hDate := fDate;
Repeat
fData.AddPrice2(fDate, fTime, fPrice);
Readln(fFile, fDate, fTime, fPrice);
Until eof(fFile) or (fDate > hDate);
fData.AddPrice2(fDate, fTime, fPrice);
end;
// closefile(fFile);
end;
fData.Sort;
// fData.ReplaceZeros;
fLastDate := fDate;
fNextIndex := 0;
result := fData.Count;
end;
procedure TPriceData.Start(ADate: integer; ActionFile, FuturesFile: TFileName);
var
i: integer;
begin
i := 0;
If FileExists(ActionFile) then
begin
aFileName := ActionFile;
assignfile(aFile, ActionFile);
reset(aFile);
inc(i);
end;
If FileExists(FuturesFile) then
begin
fFileName := FuturesFile;
assignfile(fFile, FuturesFile);
reset(fFile);
inc(i, 2);
end;
fPriceType := TPriceType(i);
fLastDate := ADate;
ReadNextDay;
end;
procedure TPriceData.Start(ActionFile, FuturesFile: TFileName);
begin
Start(0, ActionFile, FuturesFile);
end;
procedure TPriceData.Start(ADate: integer; ActionFuturesFile: TFileName);
var
fDate, fTime, hDate: integer;
fAPrice, fFPrice: real;
begin
If FileExists(ActionFuturesFile) then
begin
assignfile(aFile, ActionFuturesFile);
reset(aFile);
fPriceType := ptJointFile;
end;
Repeat
readln(aFile, fDate, fTime, fAPrice, fFPrice);
Until eof(aFile) or (fDate >= ADate) or (ADate = 0);
end;
procedure TPriceData.Start(ActionFuturesFile: TFileName);
begin
Start(0, ActionFuturesFile);
end;
procedure TPriceData.Stop;
begin
try
closefile(aFile);
except end;
try
closefile(fFile);
except end;
fLastDate := 0;
fPriceType := ptNone;;
fData.Clear;
end;
function TPriceData.GetNext(var ADate, ATime: integer; var ActionPrice, FuturesPrice: real): integer;
begin
If fPriceType = ptNone then
begin
result := -1;
Exit;
end;
If fPriceType = ptJointFile then
begin
result := 0;
If eof(aFile) then
result := -1
else
Readln(AFile, ADate, ATime, ActionPrice, FuturesPrice);
Exit;
end;
If fNextIndex >= fData.Count then // если буфер исчерпан, то обновляем буфер
ReadNextDay;
If fData.Count > 0 then
begin
ADate := fData.Prices[fNextIndex].Date;
ATime := fData.Prices[fNextIndex].Time;
ActionPrice := fData.Prices[fNextIndex].Price1;
FuturesPrice := fData.Prices[fNextIndex].Price2;
inc(fNextIndex);
result := 0;
end
else
result := -1;
end;
function TPriceData.GetNext(var ADate, ATime: integer; var APrice: real):integer;
var
dum: real;
begin
Case fPriceType of
ptAction : result := GetNext(ADate, ATime, APrice, dum);
ptFutures: result := GetNext(ADate, ATime, dum, APrice);
else result := -1;
end;
end;
//--------------------------------------
Initialization
PriceData := TPriceData.Create;
Finalization
// PriceData.Stop;
PriceData.Free;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit OCXReg;
interface
uses Winapi.Windows, Winapi.ActiveX, System.SysUtils, System.Variants, System.Win.ComObj, System.Classes, Vcl.Graphics, Vcl.Controls,
Vcl.Forms, Vcl.Dialogs, System.TypInfo, DesignIntf, DesignEditors, Vcl.OleCtrls;
type
{ TOleControlEditor }
TOleControlEditor = class(TDefaultEditor)
private
FVerbs: TStringList;
protected
property Verbs: TStringList read FVerbs;
procedure DoVerb(Verb: Integer); virtual;
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
destructor Destroy; override;
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TOleObjectEditor = class
private
FPropertyEditor: TPropertyEditor;
public
constructor Create(PropertyEditor: TPropertyEditor); virtual;
function Edit(OleObject: Variant): Variant; virtual;
property PropertyEditor: TPropertyEditor read FPropertyEditor;
end;
TOleFontEditor = class(TOleObjectEditor)
function Edit(OleObject: Variant): Variant; override;
end;
TOleObjectProperty = class(TVariantProperty)
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
end;
TOleCustomProperty = class(TPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
TOlePropPageProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TOleEnumProperty = class(TOrdinalProperty)
private
FEnumPropDesc: TEnumPropDesc;
protected
property EnumPropDesc: TEnumPropDesc read FEnumPropDesc;
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure Initialize; override;
procedure SetValue(const Value: string); override;
end;
TOleObjectEditorClass = class of TOleObjectEditor;
procedure RegisterOleObjectEditor(const IID: TIID; const ClassName: string;
EditorClass: TOleObjectEditorClass);
procedure Register;
implementation
uses DesignConst, VCLEditors;
type
POleObjectClassRec = ^TOleObjectClassRec;
TOleObjectClassRec = record
Next: POleObjectClassRec;
IID: TIID;
ClassName: string;
EditorClass: TOleObjectEditorClass;
end;
var
OleObjectClassList: POleObjectClassRec = nil;
function GetOleObjectClassRec(OleObject: Variant): POleObjectClassRec;
var
Dispatch: IDispatch;
Unknown: IUnknown;
begin
if VarType(OleObject) = varDispatch then
begin
Dispatch := IUnknown(OleObject) as IDispatch;
if Dispatch <> nil then
begin
Result := OleObjectClassList;
while Result <> nil do
begin
if Dispatch.QueryInterface(Result^.IID, Unknown) = 0 then Exit;
Result := Result^.Next;
end;
end;
end;
Result := nil;
end;
{ TOleControlEditor }
constructor TOleControlEditor.Create(AComponent: TComponent;
ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FVerbs := TStringList.Create;
end;
destructor TOleControlEditor.Destroy;
begin
FVerbs.Free;
inherited Destroy;
end;
procedure TOleControlEditor.DoVerb(Verb: Integer);
begin
try
if Verb = -65536 then
TOleControl(Component).ShowAboutBox
else
TOleControl(Component).DoObjectVerb(Verb);
except
// Rather than raising exceptions here (which is what we were doing)
// just use MessageDlg to display a bit friendlier dialog to the user.
case Verb of
-65536: MessageDlg(SNoAboutBoxAvailable, mtInformation, [mbOk], 0);
OLEIVERB_PROPERTIES: MessageDlg(SNoPropertyPageAvailable, mtInformation, [mbOk], 0);
else
raise;
end;
end;
end;
procedure TOleControlEditor.Edit;
begin
DoVerb(OLEIVERB_PROPERTIES);
end;
procedure TOleControlEditor.ExecuteVerb(Index: Integer);
begin
DoVerb(Integer(FVerbs.Objects[Index]));
end;
function TOleControlEditor.GetVerb(Index: Integer): string;
begin
Result := FVerbs[Index];
end;
function TOleControlEditor.GetVerbCount: Integer;
var
TI: ITypeInfo;
W: WideString;
N: Integer;
begin
TOleControl(Component).GetObjectVerbs(FVerbs);
if ((IUnknown(TOleControl(Component).OleObject) as IDispatch).GetTypeInfo(0,0,TI) = S_OK) and
(TI.GetNames(DISPID_ABOUTBOX, @W, 1, N) = S_OK) and
(FVerbs.IndexOf(SAboutVerb) = -1) and
(FVerbs.IndexOfObject(TObject(-65536)) = -1) then
FVerbs.AddObject(SAboutVerb, TObject(-65536));
Result := FVerbs.Count;
end;
function MapOleCustomProperty(Obj: TPersistent;
PropInfo: PPropInfo): TPropertyEditorClass;
begin
Result := nil;
if (DWORD(PropInfo^.Index) <> $80000000) and (Obj is TOleControl) then
begin
if TOleControl(Obj).IsPropPageProperty(PropInfo^.Index) then
Result := TOlePropPageProperty
else if TOleControl(Obj).IsCustomProperty(PropInfo^.Index) then
Result := TOleCustomProperty;
end;
end;
{ TOleCustomProperty }
function TOleCustomProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
function TOleCustomProperty.GetValue: string;
begin
Result := TOleControl(GetComponent(0)).GetPropDisplayString(
GetPropInfo^.Index);
end;
procedure TOleCustomProperty.GetValues(Proc: TGetStrProc);
var
Values: TStringList;
I: Integer;
begin
Values := TStringList.Create;
try
TOleControl(GetComponent(0)).GetPropDisplayStrings(
GetPropInfo^.Index, Values);
for I := 0 to Values.Count - 1 do Proc(Values[I]);
finally
Values.Free;
end;
end;
procedure TOleCustomProperty.SetValue(const Value: string);
begin
TOleControl(GetComponent(0)).SetPropDisplayString(
GetPropInfo^.Index, Value);
end;
{ TOlePropPageProperty }
function TOlePropPageProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect];
end;
procedure TOlePropPageProperty.Edit;
var
PPID: TCLSID;
OleCtl: TOleControl;
OleCtls: array of IDispatch;
Params: TOCPFIParams;
Caption: WideString;
I, DispID: Integer;
begin
SetLength(OleCtls, PropCount);
for I := 0 to PropCount - 1 do
begin
OleCtls[I] := TOleControl(GetComponent(0)).DefaultDispatch;
if Caption <> '' then Caption := Caption + ', ';
Caption := Caption + TOleControl(GetComponent(0)).Name;
end;
OleCtl := TOleControl(GetComponent(0));
if OleCtl.PerPropBrowsing <> nil then
begin
DispID := GetPropInfo^.Index;
OleCtl.PerPropBrowsing.MapPropertyToPage(DispID, PPID);
if not IsEqualCLSID(PPID, GUID_NULL) then
begin
with Params do
begin
cbStructSize := SizeOf(Params);
hWndOwner := GetActiveWindow;
x := 16;
y := 16;
lpszCaption := PWideChar(Caption);
cObjects := PropCount;
pObjects := @OleCtls[0];
cPages := 1;
pPages := @PPID;
lcid := GetUserDefaultLCID;
dispidInitialProperty := DispID;
end;
OleCreatePropertyFrameIndirect(Params);
end;
end;
end;
{ TOleEnumProperty }
function TOleEnumProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList];
end;
function TOleEnumProperty.GetValue: string;
begin
if FEnumPropDesc <> nil then
Result := FEnumPropDesc.ValueToString(GetOrdValue)
else
Result := IntToStr(GetOrdValue);
end;
procedure TOleEnumProperty.GetValues(Proc: TGetStrProc);
begin
if FEnumPropDesc <> nil then FEnumPropDesc.GetStrings(Proc);
end;
procedure TOleEnumProperty.Initialize;
begin
FEnumPropDesc := TOleControl(GetComponent(0)).GetEnumPropDesc(
GetPropInfo^.Index);
end;
procedure TOleEnumProperty.SetValue(const Value: string);
begin
if FEnumPropDesc <> nil then
SetOrdValue(FEnumPropDesc.StringToValue(Value))
else
SetOrdValue(StrToInt(Value));
end;
{ TOleObjectEditor }
constructor TOleObjectEditor.Create(PropertyEditor: TPropertyEditor);
begin
FPropertyEditor := PropertyEditor;
end;
function TOleObjectEditor.Edit(OleObject: Variant): Variant;
begin
VarClear(Result);
end;
{ TOleFontEditor }
function TOleFontEditor.Edit(OleObject: Variant): Variant;
begin
VarClear(Result);
with TFontDialog.Create(Application) do
try
OleFontToFont(OleObject, Font);
Options := Options + [fdForceFontExist];
if Execute then Result := FontToOleFont(Font);
finally
Free;
end;
end;
{ TOleObjectProperty }
procedure TOleObjectProperty.Edit;
var
P: POleObjectClassRec;
Value: Variant;
Editor: TOleObjectEditor;
begin
Value := GetVarValue;
P := GetOleObjectClassRec(Value);
if P <> nil then
begin
Editor := P^.EditorClass.Create(Self);
try
Value := Editor.Edit(Value);
finally
Editor.Free;
end;
if VarType(Value) = varDispatch then
SetVarValue(Value);
end;
end;
function TOleObjectProperty.GetAttributes: TPropertyAttributes;
var
Value: Variant;
begin
Result := inherited GetAttributes;
try
Value := GetVarValue;
except
Value := Null;
end;
if GetOleObjectClassRec(Value) <> nil then
Result := Result + [paReadOnly, paDialog];
end;
function TOleObjectProperty.GetValue: string;
function GetVariantStr(const Value: Variant): string;
begin
case VarType(Value) of
varEmpty: Result := '';
varNull: Result := SNull;
varBoolean:
if Value then
Result := BooleanIdents[True]
else
Result := BooleanIdents[False];
varCurrency:
Result := CurrToStr(Value);
else
Result := string(Value);
end;
end;
var
P: POleObjectClassRec;
Value: Variant;
begin
Value := GetVarValue;
if VarType(Value) <> varDispatch then
Result := inherited GetValue
else
begin
P := GetOleObjectClassRec(Value);
if P <> nil then
Result := '(' + P^.ClassName + ')'
else
Result := '(OleObject)';
end
end;
procedure RegisterOleObjectEditor(const IID: TIID; const ClassName: string;
EditorClass: TOleObjectEditorClass);
var
P: POleObjectClassRec;
begin
New(P);
P^.Next := OleObjectClassList;
P^.IID := IID;
P^.ClassName := ClassName;
P^.EditorClass := EditorClass;
OleObjectClassList := P;
end;
{ Registration }
procedure Register;
begin
RegisterComponentEditor(TOleControl, TOleControlEditor);
RegisterPropertyMapper(MapOleCustomProperty);
RegisterPropertyEditor(TypeInfo(TOleEnum), TOleControl, '', TOleEnumProperty);
RegisterPropertyEditor(TypeInfo(Variant), nil, '', TOleObjectProperty);
RegisterPropertyEditor(TypeInfo(SmallInt), TOleControl, 'Cursor', TCursorProperty);
RegisterOleObjectEditor(IFontDisp, 'OleFont', TOleFontEditor);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.