text stringlengths 14 6.51M |
|---|
program test16;
(* Test static scoping *)
var
a, b, c: real;
procedure display(a, b, c: real);
begin
a := a / 10;
b := b / 10;
c := c / 10;
writeln(a, b, c);
end;
function displayFunc(a, b, c: real): real;
begin
a := a / 100;
b := b / 100;
c := c / 100;
writeln(a, b, c);
displayFunc := c;
end;
begin
a:= 100;
b:= 200;
c:= a + b;
writeln(a, b, c);
display(a, b, c);
displayFunc(a, b, c);
c := displayFunc(a, b, c);
writeln(a, b, c);
end.
(*
Expected output:
100.0 200.0 300.0
10.0 20.0 30.0
1.0 2.0 3.0
1.0 2.0 3.0
100.0 200.0 3.0
*) |
{ *************************************************************************** }
{ }
{ Audio Tools Library (Freeware) }
{ Class TID3v1 - for manipulating with ID3v1 tags }
{ }
{ Copyright (c) 2001,2002 by Jurgen Faul }
{ E-mail: jfaul@gmx.de }
{ http://jfaul.de/atl }
{ }
{ Version 1.0 (25 July 2001) }
{ - Reading & writing support for ID3v1.x tags }
{ - Tag info: title, artist, album, track, year, genre, comment }
{ }
{ *************************************************************************** }
unit ID3v1;
interface
uses
Classes, SysUtils;
const
MAX_MUSIC_GENRES = 148; { Max. number of music genres }
DEFAULT_GENRE = 255; { Index for default genre }
{ Used with VersionID property }
TAG_VERSION_1_0 = 1; { Index for ID3v1.0 tag }
TAG_VERSION_1_1 = 2; { Index for ID3v1.1 tag }
var
MusicGenre: array [0..MAX_MUSIC_GENRES - 1] of string; { Genre names }
type
{ Used in TID3v1 class }
String04 = string[4]; { String with max. 4 symbols }
String30 = string[30]; { String with max. 30 symbols }
{ Class TID3v1 }
TID3v1 = class(TObject)
private
{ Private declarations }
FExists: Boolean;
FVersionID: Byte;
FTitle: String30;
FArtist: String30;
FAlbum: String30;
FYear: String04;
FComment: String30;
FTrack: Byte;
FGenreID: Byte;
procedure FSetTitle(const NewTitle: String30);
procedure FSetArtist(const NewArtist: String30);
procedure FSetAlbum(const NewAlbum: String30);
procedure FSetYear(const NewYear: String04);
procedure FSetComment(const NewComment: String30);
procedure FSetTrack(const NewTrack: Byte);
procedure FSetGenreID(const NewGenreID: Byte);
function FGetGenre: string;
public
{ Public declarations }
constructor Create; { Create object }
procedure ResetData; { Reset all data }
function ReadFromFile(const FileName: string): Boolean; { Load tag }
function RemoveFromFile(const FileName: string): Boolean; { Delete tag }
function SaveToFile(const FileName: string): Boolean; { Save tag }
property Exists: Boolean read FExists; { True if tag found }
property VersionID: Byte read FVersionID; { Version code }
property Title: String30 read FTitle write FSetTitle; { Song title }
property Artist: String30 read FArtist write FSetArtist; { Artist name }
property Album: String30 read FAlbum write FSetAlbum; { Album name }
property Year: String04 read FYear write FSetYear; { Year }
property Comment: String30 read FComment write FSetComment; { Comment }
property Track: Byte read FTrack write FSetTrack; { Track number }
property GenreID: Byte read FGenreID write FSetGenreID; { Genre code }
property Genre: string read FGetGenre; { Genre name }
end;
implementation
type
{ Real structure of ID3v1 tag }
TagRecord = record
Header: array [1..3] of Char; { Tag header - must be "TAG" }
Title: array [1..30] of Char; { Title data }
Artist: array [1..30] of Char; { Artist data }
Album: array [1..30] of Char; { Album data }
Year: array [1..4] of Char; { Year data }
Comment: array [1..30] of Char; { Comment data }
Genre: Byte; { Genre data }
end;
{ ********************* Auxiliary functions & procedures ******************** }
function ReadTag(const FileName: string; var TagData: TagRecord): Boolean;
var
SourceFile: file;
begin
try
Result := true;
{ Set read-access and open file }
AssignFile(SourceFile, FileName);
FileMode := 0;
Reset(SourceFile, 1);
{ Read tag }
Seek(SourceFile, FileSize(SourceFile) - 128);
BlockRead(SourceFile, TagData, 128);
CloseFile(SourceFile);
except
{ Error }
Result := false;
end;
end;
{ --------------------------------------------------------------------------- }
function RemoveTag(const FileName: string): Boolean;
var
SourceFile: file;
begin
try
Result := true;
{ Allow write-access and open file }
FileSetAttr(FileName, 0);
AssignFile(SourceFile, FileName);
FileMode := 2;
Reset(SourceFile, 1);
{ Delete tag }
Seek(SourceFile, FileSize(SourceFile) - 128);
Truncate(SourceFile);
CloseFile(SourceFile);
except
{ Error }
Result := false;
end;
end;
{ --------------------------------------------------------------------------- }
function SaveTag(const FileName: string; TagData: TagRecord): Boolean;
var
SourceFile: file;
begin
try
Result := true;
{ Allow write-access and open file }
FileSetAttr(FileName, 0);
AssignFile(SourceFile, FileName);
FileMode := 2;
Reset(SourceFile, 1);
{ Write tag }
Seek(SourceFile, FileSize(SourceFile));
BlockWrite(SourceFile, TagData, SizeOf(TagData));
CloseFile(SourceFile);
except
{ Error }
Result := false;
end;
end;
{ --------------------------------------------------------------------------- }
function GetTagVersion(const TagData: TagRecord): Byte;
begin
Result := TAG_VERSION_1_0;
{ Terms for ID3v1.1 }
if ((TagData.Comment[29] = #0) and (TagData.Comment[30] <> #0)) or
((TagData.Comment[29] = #32) and (TagData.Comment[30] <> #32)) then
Result := TAG_VERSION_1_1;
end;
{ ********************** Private functions & procedures ********************* }
procedure TID3v1.FSetTitle(const NewTitle: String30);
begin
FTitle := TrimRight(NewTitle);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetArtist(const NewArtist: String30);
begin
FArtist := TrimRight(NewArtist);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetAlbum(const NewAlbum: String30);
begin
FAlbum := TrimRight(NewAlbum);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetYear(const NewYear: String04);
begin
FYear := TrimRight(NewYear);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetComment(const NewComment: String30);
begin
FComment := TrimRight(NewComment);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetTrack(const NewTrack: Byte);
begin
FTrack := NewTrack;
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetGenreID(const NewGenreID: Byte);
begin
FGenreID := NewGenreID;
end;
{ --------------------------------------------------------------------------- }
function TID3v1.FGetGenre: string;
begin
Result := '';
{ Return an empty string if the current GenreID is not valid }
if FGenreID in [0..MAX_MUSIC_GENRES - 1] then Result := MusicGenre[FGenreID];
end;
{ ********************** Public functions & procedures ********************** }
constructor TID3v1.Create;
begin
inherited;
ResetData;
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.ResetData;
begin
FExists := false;
FVersionID := TAG_VERSION_1_0;
FTitle := '';
FArtist := '';
FAlbum := '';
FYear := '';
FComment := '';
FTrack := 0;
FGenreID := DEFAULT_GENRE;
end;
{ --------------------------------------------------------------------------- }
function TID3v1.ReadFromFile(const FileName: string): Boolean;
var
TagData: TagRecord;
begin
{ Reset and load tag data from file to variable }
ResetData;
Result := ReadTag(FileName, TagData);
{ Process data if loaded and tag header OK }
if (Result) and (TagData.Header = 'TAG') then
begin
FExists := true;
FVersionID := GetTagVersion(TagData);
{ Fill properties with tag data }
FTitle := TrimRight(TagData.Title);
FArtist := TrimRight(TagData.Artist);
FAlbum := TrimRight(TagData.Album);
FYear := TrimRight(TagData.Year);
if FVersionID = TAG_VERSION_1_0 then
FComment := TrimRight(TagData.Comment)
else
begin
FComment := TrimRight(Copy(TagData.Comment, 1, 28));
FTrack := Ord(TagData.Comment[30]);
end;
FGenreID := TagData.Genre;
end;
end;
{ --------------------------------------------------------------------------- }
function TID3v1.RemoveFromFile(const FileName: string): Boolean;
var
TagData: TagRecord;
begin
{ Find tag }
Result := ReadTag(FileName, TagData);
{ Delete tag if loaded and tag header OK }
if (Result) and (TagData.Header = 'TAG') then Result := RemoveTag(FileName);
end;
{ --------------------------------------------------------------------------- }
function TID3v1.SaveToFile(const FileName: string): Boolean;
var
TagData: TagRecord;
begin
{ Prepare tag record }
FillChar(TagData, SizeOf(TagData), 0);
TagData.Header := 'TAG';
Move(FTitle[1], TagData.Title, Length(FTitle));
Move(FArtist[1], TagData.Artist, Length(FArtist));
Move(FAlbum[1], TagData.Album, Length(FAlbum));
Move(FYear[1], TagData.Year, Length(FYear));
Move(FComment[1], TagData.Comment, Length(FComment));
if FTrack > 0 then
begin
TagData.Comment[29] := #0;
TagData.Comment[30] := Chr(FTrack);
end;
TagData.Genre := FGenreID;
{ Delete old tag and write new tag }
Result := (RemoveFromFile(FileName)) and (SaveTag(FileName, TagData));
end;
{ ************************** Initialize music genres ************************ }
initialization
begin
{ Standard genres }
MusicGenre[0] := 'Blues';
MusicGenre[1] := 'Classic Rock';
MusicGenre[2] := 'Country';
MusicGenre[3] := 'Dance';
MusicGenre[4] := 'Disco';
MusicGenre[5] := 'Funk';
MusicGenre[6] := 'Grunge';
MusicGenre[7] := 'Hip-Hop';
MusicGenre[8] := 'Jazz';
MusicGenre[9] := 'Metal';
MusicGenre[10] := 'New Age';
MusicGenre[11] := 'Oldies';
MusicGenre[12] := 'Other';
MusicGenre[13] := 'Pop';
MusicGenre[14] := 'R&B';
MusicGenre[15] := 'Rap';
MusicGenre[16] := 'Reggae';
MusicGenre[17] := 'Rock';
MusicGenre[18] := 'Techno';
MusicGenre[19] := 'Industrial';
MusicGenre[20] := 'Alternative';
MusicGenre[21] := 'Ska';
MusicGenre[22] := 'Death Metal';
MusicGenre[23] := 'Pranks';
MusicGenre[24] := 'Soundtrack';
MusicGenre[25] := 'Euro-Techno';
MusicGenre[26] := 'Ambient';
MusicGenre[27] := 'Trip-Hop';
MusicGenre[28] := 'Vocal';
MusicGenre[29] := 'Jazz+Funk';
MusicGenre[30] := 'Fusion';
MusicGenre[31] := 'Trance';
MusicGenre[32] := 'Classical';
MusicGenre[33] := 'Instrumental';
MusicGenre[34] := 'Acid';
MusicGenre[35] := 'House';
MusicGenre[36] := 'Game';
MusicGenre[37] := 'Sound Clip';
MusicGenre[38] := 'Gospel';
MusicGenre[39] := 'Noise';
MusicGenre[40] := 'AlternRock';
MusicGenre[41] := 'Bass';
MusicGenre[42] := 'Soul';
MusicGenre[43] := 'Punk';
MusicGenre[44] := 'Space';
MusicGenre[45] := 'Meditative';
MusicGenre[46] := 'Instrumental Pop';
MusicGenre[47] := 'Instrumental Rock';
MusicGenre[48] := 'Ethnic';
MusicGenre[49] := 'Gothic';
MusicGenre[50] := 'Darkwave';
MusicGenre[51] := 'Techno-Industrial';
MusicGenre[52] := 'Electronic';
MusicGenre[53] := 'Pop-Folk';
MusicGenre[54] := 'Eurodance';
MusicGenre[55] := 'Dream';
MusicGenre[56] := 'Southern Rock';
MusicGenre[57] := 'Comedy';
MusicGenre[58] := 'Cult';
MusicGenre[59] := 'Gangsta';
MusicGenre[60] := 'Top 40';
MusicGenre[61] := 'Christian Rap';
MusicGenre[62] := 'Pop/Funk';
MusicGenre[63] := 'Jungle';
MusicGenre[64] := 'Native American';
MusicGenre[65] := 'Cabaret';
MusicGenre[66] := 'New Wave';
MusicGenre[67] := 'Psychadelic';
MusicGenre[68] := 'Rave';
MusicGenre[69] := 'Showtunes';
MusicGenre[70] := 'Trailer';
MusicGenre[71] := 'Lo-Fi';
MusicGenre[72] := 'Tribal';
MusicGenre[73] := 'Acid Punk';
MusicGenre[74] := 'Acid Jazz';
MusicGenre[75] := 'Polka';
MusicGenre[76] := 'Retro';
MusicGenre[77] := 'Musical';
MusicGenre[78] := 'Rock & Roll';
MusicGenre[79] := 'Hard Rock';
{ Extended genres }
MusicGenre[80] := 'Folk';
MusicGenre[81] := 'Folk-Rock';
MusicGenre[82] := 'National Folk';
MusicGenre[83] := 'Swing';
MusicGenre[84] := 'Fast Fusion';
MusicGenre[85] := 'Bebob';
MusicGenre[86] := 'Latin';
MusicGenre[87] := 'Revival';
MusicGenre[88] := 'Celtic';
MusicGenre[89] := 'Bluegrass';
MusicGenre[90] := 'Avantgarde';
MusicGenre[91] := 'Gothic Rock';
MusicGenre[92] := 'Progessive Rock';
MusicGenre[93] := 'Psychedelic Rock';
MusicGenre[94] := 'Symphonic Rock';
MusicGenre[95] := 'Slow Rock';
MusicGenre[96] := 'Big Band';
MusicGenre[97] := 'Chorus';
MusicGenre[98] := 'Easy Listening';
MusicGenre[99] := 'Acoustic';
MusicGenre[100]:= 'Humour';
MusicGenre[101]:= 'Speech';
MusicGenre[102]:= 'Chanson';
MusicGenre[103]:= 'Opera';
MusicGenre[104]:= 'Chamber Music';
MusicGenre[105]:= 'Sonata';
MusicGenre[106]:= 'Symphony';
MusicGenre[107]:= 'Booty Bass';
MusicGenre[108]:= 'Primus';
MusicGenre[109]:= 'Porn Groove';
MusicGenre[110]:= 'Satire';
MusicGenre[111]:= 'Slow Jam';
MusicGenre[112]:= 'Club';
MusicGenre[113]:= 'Tango';
MusicGenre[114]:= 'Samba';
MusicGenre[115]:= 'Folklore';
MusicGenre[116]:= 'Ballad';
MusicGenre[117]:= 'Power Ballad';
MusicGenre[118]:= 'Rhythmic Soul';
MusicGenre[119]:= 'Freestyle';
MusicGenre[120]:= 'Duet';
MusicGenre[121]:= 'Punk Rock';
MusicGenre[122]:= 'Drum Solo';
MusicGenre[123]:= 'A capella';
MusicGenre[124]:= 'Euro-House';
MusicGenre[125]:= 'Dance Hall';
MusicGenre[126]:= 'Goa';
MusicGenre[127]:= 'Drum & Bass';
MusicGenre[128]:= 'Club-House';
MusicGenre[129]:= 'Hardcore';
MusicGenre[130]:= 'Terror';
MusicGenre[131]:= 'Indie';
MusicGenre[132]:= 'BritPop';
MusicGenre[133]:= 'Negerpunk';
MusicGenre[134]:= 'Polsk Punk';
MusicGenre[135]:= 'Beat';
MusicGenre[136]:= 'Christian Gangsta Rap';
MusicGenre[137]:= 'Heavy Metal';
MusicGenre[138]:= 'Black Metal';
MusicGenre[139]:= 'Crossover';
MusicGenre[140]:= 'Contemporary Christian';
MusicGenre[141]:= 'Christian Rock';
MusicGenre[142]:= 'Merengue';
MusicGenre[143]:= 'Salsa';
MusicGenre[144]:= 'Trash Metal';
MusicGenre[145]:= 'Anime';
MusicGenre[146]:= 'JPop';
MusicGenre[147]:= 'Synthpop';
end;
end.
|
unit ClassCities;
interface
uses ExtCtrls, ClassPlayer;
type TCities = class
private
NaTahu : integer;
Koniec : boolean;
Human, Computer : TPlayer;
Table : TTable;
Image : TImage;
FFinish : boolean;
procedure ClearTable;
procedure PaintTable;
procedure PaintGame;
procedure ProcessMove( Move : TPos );
procedure FillCity( X, Y : integer );
procedure SetFinish( Value : boolean );
public
constructor Create( iHuman, iComputer : TPlayer; iImage : TImage );
destructor Destroy; override;
procedure NewGame;
property Finish : boolean read FFinish write SetFinish;
end;
var Cities : TCities;
implementation
uses Windows, Graphics;
//******************************************************************************
// Constructor
//******************************************************************************
constructor TCities.Create( iHuman, iComputer : TPlayer; iImage : TImage );
begin
Human := iHuman;
Computer := iComputer;
Image := iImage;
end;
//******************************************************************************
// Destructor
//******************************************************************************
destructor TCities.Destroy;
begin
Human.Free;
Computer.Free;
end;
//******************************************************************************
// Properties
//******************************************************************************
procedure TCities.SetFinish( Value : boolean );
begin
if (Value = FFinish) then
exit;
FFinish := Value;
Koniec := Value;
Human.Finish := True;
end;
//******************************************************************************
// Game management
//******************************************************************************
procedure TCities.ClearTable;
var I, J : integer;
begin
for I := 1 to XMAX do
for J := 1 to YMAX do
Table[I,J] := -1;
end;
procedure TCities.PaintTable;
var I : integer;
d : double;
begin
with Image.Canvas do
begin
Pen.Color := clGray;
Brush.Color := clBlack;
FillRect( Image.ClientRect );
Rectangle( Image.ClientRect );
d := Image.Width / XMAX;
for I := 1 to XMAX-1 do
begin
MoveTo( Round( d * I ) , 0 );
LineTo( Round( d * I ) , Image.Height );
end;
d := Image.Height / YMAX;
for I := 1 to YMAX-1 do
begin
MoveTo( 0 , Round( d * I ) );
LineTo( Image.Width , Round( d * I ) );
end;
end;
end;
procedure TCities.PaintGame;
var I, J : integer;
d, b : double;
Color : TColor;
begin
d := Image.Height / YMAX;
b := Image.Width / XMAX;
for I := 1 to XMAX do
for J := 1 to YMAX do
begin
case Table[I,J] of
0 : Color := clBlue;
1 : Color := clRed;
2 : Color := clLtGray;
else Color := clBlack;
end;
Image.Canvas.Brush.Color := Color;
if (Table[I,J] < 2) then
Image.Canvas.FloodFill( Round( b * (I-1) ) + 1 , Round( d * (J-1) ) + 1 , clGray , fsBorder )
else
Image.Canvas.Ellipse( Round( b * (I-1) ) + 1 , Round( d * (J-1) ) + 1 ,
Round( b * I ) , Round( d * J ) );
end;
end;
procedure TCities.FillCity( X, Y : integer );
begin
if (Table[X,Y] = 2) then
exit;
if (Table[X,Y] = -1) then
Table[X,Y] := 2;
if (Table[X,Y] = 1-NaTahu) then
Table[X,Y] := NaTahu;
{dole}
if (Y < YMAX) and
(Table[X,Y+1] <> NaTahu) then
FillCity( X , Y+1 );
{hore}
if (Y > 1) and
(Table[X,Y-1] <> NaTahu) then
FillCity( X , Y-1 );
{doprava}
if (X < XMAX) and
(Table[X+1,Y] <> NaTahu) then
FillCity( X+1 , Y );
{dolava}
if (X > 1) and
(Table[X-1,Y] <> NaTahu) then
FillCity( X-1 , Y );
end;
procedure TCities.ProcessMove( Move : TPos );
var I, J : integer;
Backup : TTable;
City : boolean;
procedure FloodFill( X, Y : integer );
begin
Backup[X,Y] := 3;
{dole}
if (Y = YMAX) then
City := False
else
if (Backup[X,Y+1] <> NaTahu) and
(Backup[X,Y+1] <> 3) then
FloodFill( X , Y+1 );
{hore}
if (Y = 1) then
City := False
else
if (Backup[X,Y-1] <> NaTahu) and
(Backup[X,Y-1] <> 3) then
FloodFill( X , Y-1 );
{doprava}
if (X = XMAX) then
City := False
else
if (Backup[X+1,Y] <> NaTahu) and
(Backup[X+1,Y] <> 3) then
FloodFill( X+1 , Y );
{dolava}
if (X = 1) then
City := False
else
if (Backup[X-1,Y] <> NaTahu) and
(Backup[X-1,Y] <> 3) then
FloodFill( X-1 , Y );
end;
begin
if (Koniec) then
exit;
Table[Move.X,Move.Y] := NaTahu;
Backup := Table;
for I := -1 to 1 do
for J := -1 to 1 do
if (Move.X+I >= 1) and
(Move.X+I <= XMAX) and
(Move.Y+J >= 1) and
(Move.Y+J <= YMAX) and
(Backup[Move.X+I,Move.Y+J] <> NaTahu) and
(Backup[Move.X+I,Move.Y+J] < 2) then
begin
City := True;
FloodFill( Move.X+I , Move.Y+J );
if (City) then
FillCity( Move.X+I , Move.Y+J );
end;
PaintGame;
Koniec := True;
for I := 1 to XMAX do
for J := 1 to YMAX do
if (Table[I,J] = -1) then
begin
Koniec := False;
exit;
end;
end;
//******************************************************************************
// INTERFACE
//******************************************************************************
procedure TCities.NewGame;
var Tah : TPos;
begin
ClearTable;
PaintTable;
NaTahu := 1;
Koniec := False;
repeat
case NaTahu of
0 : Tah := Human.MakeMove( Table );
1 : Tah := Computer.MakeMove( Table );
end;
ProcessMove( Tah );
NaTahu := 1 - NaTahu;
until Koniec;
end;
end.
|
PROGRAM segiempat;
(* File : segiempat.pas *)
(* membentuk segiempat dengan besar n, rusuk c1, dan isi c2 *)
// KAMUS
VAR
n, i, j : INTEGER;
c1, c2 : CHAR;
outputLine : STRING;
// ALGORITMA
BEGIN
ReadLn (n, c1, c1, c2, c2);
IF ((n <= 0) OR (c1 = c2)) THEN BEGIN
WriteLn('Masukan tidak valid');
END ELSE {-(N > 0) AND (C1 != C2)-} BEGIN
// Top-most line
outputLine := '';
FOR i := 1 TO n DO BEGIN
outputLine += C1;
END;
WriteLn(outputLine);
// Middle lines
FOR i := 2 TO (n-1) DO BEGIN
outputLine := C1;
FOR j := 2 TO (n-1) DO BEGIN
outputLine += C2;
END;
outputLine += C1;
WriteLn(outputLine);
END;
// Bottom=most line
outputLine := '';
IF (n <> 1) THEN BEGIN
FOR i := 1 TO n DO BEGIN
outputLine += C1;
END;
WriteLn(outputLine);
END;
END;
END.
|
unit ScratchPad;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls,
Math,
SudokuType, DigitSetEditor;
type
{ TScratchForm }
TCopyValuesEvent = procedure(Sender: TObject; Values: TValues) of Object;
TCopyRawDataEvent = procedure(Sender: TObject; RawData: TRawGrid) of Object;
TScratchForm = class(TForm)
btnCopy: TButton;
btnCopyRaw: TButton;
ScratchGrid: TStringGrid;
procedure btnCopyClick(Sender: TObject);
procedure btnCopyRawClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ScratchGridClick(Sender: TObject);
procedure ScratchGridPrepareCanvas(sender: TObject; aCol, aRow: Integer;
{%H-}aState: TGridDrawState);
private
FRawData: TRawGrid;
FOnCopyValues: TCopyValuesEvent;
FOnCopyRawData: TCopyRawDataEvent;
procedure GridToRawData(out RawData: TRawGrid);
procedure SetRawData(Data: TRawGrid);
procedure GridToValues(out Values: TValues);
procedure KeepInView;
procedure EditCell(ACol, ARow: Integer);
public
property RawData: TRawGrid write SetRawData;
property OnCopyValues: TCopyValuesEvent read FOnCopyValues write FOnCopyValues;
property OnCopyRawData: TCopyRawDataEvent read FOnCopyRawData write FOnCopyRawData;
end;
var
ScratchForm: TScratchForm;
implementation
{$R *.lfm}
function DigitSetToStr(ASet: TDigitSet): String;
function Get(D: Integer): Char;
begin
if (D in ASet) then
Result := Char(Ord('0') + D)
else
Result := #32;//'x'
end;
begin
Result := Format('%s %s %s'+LineEnding+'%s %s %s'+LineEnding+'%s %s %s',[Get(1),Get(2),Get(3),Get(4),Get(5),Get(6),Get(7),Get(8),Get(9)]);
end;
function StrToDigitSet(const S: String): TDigitSet;
var
Ch: Char;
begin
Result := [];
for Ch in S do
if (Ch in ['1'..'9']) then
Include(Result, Ord(Ch) - Ord('0'));
end;
{
}
function TryCellTextToDigit(const AText: String; out Value: TDigits): Boolean;
var
Ch: Char;
S: String;
begin
Result := False;
S := '';
for Ch in AText do
if (Ch in ['1'..'9']) then S := S + Ch;
if (Length(S) = 1) then
begin
Ch := S[1];
if (Ch in ['1'..'9']) then
begin
Value := Ord(Ch) - Ord('0');
Result := True;
end;
end;
end;
{ TScratchForm }
procedure TScratchForm.FormActivate(Sender: TObject);
begin
Self.OnActivate := nil;
ScratchGrid.ClientWidth := 9 * ScratchGrid.DefaultColWidth;
ScratchGrid.ClientHeight := 9 * ScratchGrid.DefaultRowHeight;
//writeln(format('ScratchGrid: %d x %d',[ScratchGrid.ClientWidth,ScratchGrid.ClientHeight]));
ClientWidth := 2 * ScratchGrid.Left + ScratchGrid.Width;
//writeln(format('btnCopy.Top: %d, btnCopy.Height: %d',[btnCopy.Top,btnCopy.Height]));
Self.ReAlign;
//ClientHeight := btnCopy.Top + btnCopy.Height + 10;
//Above doesn't work: at this time btnCopy.Top still holds designtime value, even when it's top is anchored to the grid
ClientHeight := ScratchGrid.Top + ScratchGrid.Height + 10 + btnCopy.Height + 10 + btnCopyRaw.Height + 10;
btnCopy.AutoSize := False;
btnCopy.Width := btnCopyRaw.Width;
//writeln(format('ClientHeight: %d',[ClientHeight]));
KeepInView;
end;
procedure TScratchForm.btnCopyClick(Sender: TObject);
var
Values: TValues;
begin
if Assigned(FOnCopyValues) then
begin
GridToValues(Values);
FOnCopyValues(Self, Values);
ModalResult := mrOk;
//Close;
end;
end;
procedure TScratchForm.btnCopyRawClick(Sender: TObject);
var
ARawData: TRawGrid;
begin
if Assigned(FOnCopyRawData) then
begin
GridToRawData(ARawData);
FOnCopyRawData(Self, ARawData);
ModalResult := mrOk;
//Close;
end;
end;
procedure TScratchForm.FormCreate(Sender: TObject);
var
DefWH: Integer;
begin
DefWH := Max(ScratchGrid.Canvas.TextWidth(' 8-8-8 '), 3 * ScratchGrid.Canvas.TextHeight('8')) + 10;
ScratchGrid.DefaultColWidth := DefWH;
ScratchGrid.DefaultRowHeight := DefWH;
end;
procedure TScratchForm.ScratchGridClick(Sender: TObject);
var
Col, Row: Integer;
begin
Col := ScratchGrid.Col;
Row := ScratchGrid.Row;
if not FRawData[Col+1,Row+1].Locked then
EditCell(Col, Row);
end;
procedure TScratchForm.ScratchGridPrepareCanvas(sender: TObject; aCol, aRow: Integer; aState: TGridDrawState);
var
NeedsColor: Boolean;
GridTextStyle: TTextStyle;
begin
GridTextStyle := (Sender as TStringGrid).Canvas.TextStyle;
GridTextStyle.Alignment := taCenter;
GridTextStyle.Layout := tlCenter;
GridTextStyle.SingleLine := False;
(Sender as TStringGrid).Canvas.TextStyle := GridTextStyle;
NeedsColor := False;
if aCol in [0..2, 6..8] then
begin
if aRow in [0..2, 6..8] then
NeedsColor := True;
end
else
begin
if aRow in [3..5] then
NeedsColor := True;
end;
if NeedsColor then
(Sender as TStringGrid).Canvas.Brush.Color := $00EEEEEE;
//if (aRow=0) and (aCol=0) then
if FRawData[aCol+1, aRow+1].Locked then
begin
(Sender as TStringGrid).Canvas.Brush.Color := $00F8E3CB; // $00F1CEA3;
(Sender as TStringGrid).Canvas.Font.Color := clRed;
(Sender as TStringGrid).Canvas.Font.Style := [fsBold]
end;
end;
procedure TScratchForm.SetRawData(Data: TRawGrid);
var
Row, Col: Integer;
S: String;
begin
FRawData := Data;
for Col := 1 to 9 do
begin
for Row := 1 to 9 do
begin
//writeln('Col: ',Col,', Row: ',Row,', Square: ',DbgS(Data[Col,Row]));
if Data[Col,Row].Locked then
S := IntToStr(Data[Col,Row].Value)
else
//S := DbgS(Data[Col,Row].DigitsPossible);
S := DigitSetToStr(Data[Col,Row].DigitsPossible);
ScratchGrid.Cells[Col-1,Row-1] := S;
end;
end;
end;
procedure TScratchForm.GridToRawData(out RawData: TRawGrid);
var
Col, Row: Integer;
ADigit: TDigits;
DigitSet: TDigitSet;
S: String;
begin
for Col := 0 to 8 do
begin
for Row := 0 to 8 do
begin
S := ScratchGrid.Cells[Col, Row];
if TryCellTextToDigit(S, ADigit) then
begin
RawData[Col+1,Row+1].Value := ADigit;
RawData[Col+1,Row+1].DigitsPossible := [];
RawData[Col+1,Row+1].Locked := True;
end
else
begin
DigitSet := StrToDigitSet(S);
RawData[Col+1,Row+1].Value := 0;
RawData[Col+1,Row+1].DigitsPossible := DigitSet;
RawData[Col+1,Row+1].Locked := False;
end;
end;
end;
end;
procedure TScratchForm.GridToValues(out Values: TValues);
var
Col, Row: Integer;
AValue: TDigits;
S: String;
begin
Values := Default(TValues);
for Col := 0 to 8 do
begin
for Row := 0 to 8 do
begin
S := ScratchGrid.Cells[Col, Row];
//DigitSet := StrToDigitSet(S);
if Length(S) >= 1 then
begin
if TryCellTextToDigit(S, AValue) then
Values[Col + 1, Row + 1] := AValue;
end;
end;
end;
end;
procedure TScratchForm.KeepInView;
var
SW, FR, Diff, FL: Integer;
begin
SW := Screen.Width;
FR := Left + Width + 8;
FL := Left;
Diff := FR - SW;
if (Diff > 0) then FL := Left - Diff;
if (FL < 0) then FL := 0;
Left := FL;
end;
procedure TScratchForm.EditCell(ACol, ARow: Integer);
var
S: String;
CurrentDigitSet: TDigitSet;
begin
S := ScratchGrid.Cells[ACol, ARow];
CurrentDigitSet := StrToDigitSet(S);
DigitSetEditorForm.OriginalDigitsPossible := FRawData[ACol+1,ARow+1].DigitsPossible; //always set this first
DigitSetEditorForm.CurrentDigitSet := CurrentDigitSet;
DigitSetEditorForm.Top := Top;
DigitSetEditorForm.PreferredRight := Left;
if (DigitSetEditorForm.ShowModal = mrOK) then
begin
S := DigitSetToStr(DigitSetEditorForm.CurrentDigitSet);
ScratchGrid.Cells[ACol, ARow] := S;
end;
end;
end.
|
program EnclosureInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
procedure GetEnclosureInfo;
Var
SMBios: TSMBios;
LEnclosure: TEnclosureInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Enclosure Information');
if SMBios.HasEnclosureInfo then
for LEnclosure in SMBios.EnclosureInfo do
begin
WriteLn('Manufacter '+LEnclosure.ManufacturerStr);
WriteLn('Version '+LEnclosure.VersionStr);
WriteLn('Serial Number '+LEnclosure.SerialNumberStr);
WriteLn('Asset Tag Number '+LEnclosure.AssetTagNumberStr);
WriteLn('Type '+LEnclosure.TypeStr);
WriteLn('Power Supply State '+LEnclosure.PowerSupplyStateStr);
WriteLn('BootUp State '+LEnclosure.BootUpStateStr);
WriteLn;
end
else
Writeln('No Enclosure Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetEnclosureInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
unit Unit1;
interface
uses
{do exemplo}
REST.JSON, System.IOUtils, System.SysUtils, uValidation,
{do form}
System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Ani,
FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls, FMX.Layouts;
type
TSettings = class
private
FServer: string;
FPort: Integer;
FDatabaseName: string;
FUser: string;
FPassword: string;
public
[MandatoryAttribute, IPAddressAttribute]
property Server: string read FServer write FServer;
[RangeAttribute(1024, 32000)]
property Port: Integer read FPort write FPort;
[MandatoryAttribute]
property DatabaseName: string read FDatabaseName write FDatabaseName;
[MandatoryAttribute]
property User: string read FUser write FUser;
[MandatoryAttribute, EncryptedAttribute]
property Password: string read FPassword write FPassword;
procedure Save;
class function Load: TSettings;
class function NewObject: TSettings;
end;
TForm1 = class(TForm)
Memo1: TMemo;
FloatAnimation1: TFloatAnimation;
glayBotos: TGridLayout;
btnTestar: TButton;
procedure btnTestarClick(Sender: TObject);
private
{ Private declarations }
protected
procedure Test01;
procedure Test02;
procedure Test03;
procedure Test04;
public
{ Public declarations }
procedure Test;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{ TSettings }
class function TSettings.Load: TSettings;
var
LConfFile, LJsonStr: string;
begin
{ recupera o nome do arquivo de backup do objeto }
LConfFile := ChangeFileExt(ParamStr(0), '.conf');
{ verifica se o arquivo existe }
if TFile.Exists(LConfFile) then
begin
{ recupera o texto do arquivo }
LJsonStr := TFile.ReadAllText(LConfFile);
{ instacia um objeto com os valores guardados no arquivo }
Result := TJson.JsonToObject<TSettings>(LJsonStr);
end
else
begin
{ ou, devolve um objeto limpo }
Result := TSettings.NewObject;
end;
end;
class function TSettings.NewObject: TSettings;
begin
{ ou, devolve um objeto limpo }
Result := TSettings.Create;
end;
procedure TSettings.Save;
begin
{ salva no arquivo as informações do objeto em formato Json }
TFile.WriteAllText(ChangeFileExt(ParamStr(0), '.conf'),
TJson.Format(TJson.ObjectToJsonObject(Self)));
end;
{ TForm1 }
procedure TForm1.btnTestarClick(Sender: TObject);
begin
Self.Test;
end;
procedure TForm1.Test;
procedure LAdicionarLinha;
begin
Memo1.Lines.Add('');
Memo1.Lines.Add('=================================================');
Memo1.Lines.Add('');
end;
begin
// Self.Test01;
// LAdicionarLinha;
// Self.Test02;
// LAdicionarLinha;
Self.Test03;
LAdicionarLinha;
Self.Test04;
LAdicionarLinha;
end;
procedure TForm1.Test01;
var
LSettings: TSettings;
begin
{ recupera um objeto novo }
LSettings := TSettings.NewObject;
try
{ exibe os dados }
Memo1.Lines.Add(TJson.Format(TJson.ObjectToJsonObject(LSettings)));
{ valida os dados antes de salvar }
if not TValidateObject.TryValidate(LSettings) then
begin
Memo1.Lines.Add('Objeto não é válido.');
end
else
begin
Memo1.Lines.Add('Objeto passou na validação!!!');
end;
{ salva os dados }
LSettings.Save;
finally
LSettings.Free;
end;
end;
procedure TForm1.Test02;
var
LSettings: TSettings;
begin
{ recupera o objeto salvo }
LSettings := TSettings.Load;
try
{ adiciona o dado }
LSettings.Server := 'Meu servidor';
{ exibe os dados }
Memo1.Lines.Add(TJson.Format(TJson.ObjectToJsonObject(LSettings)));
{ valida os dados antes de salvar }
if not TValidateObject.TryValidate(LSettings) then
begin
Memo1.Lines.Add('Objeto não é válido.');
end
else
begin
Memo1.Lines.Add('Objeto passou na validação!!!');
end;
{ salva os dados }
LSettings.Save;
finally
LSettings.Free;
end;
end;
procedure TForm1.Test03;
var
LSettings: TSettings;
LResult: TStrings;
begin
{ recupera o objeto salvo }
LSettings := TSettings.Load;
try
{ adiciona o dado }
LSettings.Server := '192.168.0.1';
{ exibe os dados }
Memo1.Lines.Add(TJson.Format(TJson.ObjectToJsonObject(LSettings)));
LResult := TStringList.Create;
try
{ valida os dados antes de salvar }
if not TValidateObject.TryValidate(LSettings, LResult) then
begin
Memo1.Lines.Add('Objeto não é válido.' + sLineBreak + LResult.Text);
end
else
begin
Memo1.Lines.Add('Objeto passou na validação!!!');
end;
finally
LResult.Free;
end;
{ salva os dados }
LSettings.Save;
finally
LSettings.Free;
end;
end;
procedure TForm1.Test04;
var
LSettings: TSettings;
begin
{ recupera o objeto salvo }
LSettings := TSettings.Load;
try
{ adiciona o dado }
LSettings.Server := '192.168.0.1';
LSettings.Password := 'admin8900*';
{ exibe os dados }
Memo1.Lines.Add(TJson.Format(TJson.ObjectToJsonObject(LSettings)));
{ encripta }
TValidateObject.TryTransform(LSettings, tdForward, '87654kdjj');
{ exibe os dados }
Memo1.Lines.Add(TJson.Format(TJson.ObjectToJsonObject(LSettings)));
{ desencripta }
TValidateObject.TryTransform(LSettings, tdBackward, '87654kdjj');
{ exibe os dados }
Memo1.Lines.Add(TJson.Format(TJson.ObjectToJsonObject(LSettings)));
{ salva os dados }
LSettings.Save;
finally
LSettings.Free;
end;
end;
end.
|
unit uGitCalls;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, process, StrUtils;
function GitRootPath: string;
function GitBranch: string;
function GitHash: string;
function GitIsModified: boolean;
function GitSvnLatest: string;
implementation
var
fGitRootPath: String;
fGitBranch: string;
fGitHash: string;
fGitModified: integer = -1;
fGitSvnLatest: string;
function RunGit(SubCmd: array of String; out output: string): boolean;
begin
Result:= RunCommand('git', SubCmd, output);
if Result then
output:= Trim(output);
end;
function GitRootPath: string;
begin
if fGitRootPath = '' then begin
if RunGit(['rev-parse', '--show-cdup'], fGitRootPath) then begin
fGitRootPath:= ExpandFileName(ConcatPaths([GetCurrentDir, fGitRootPath]));
end;
end;
Result:= fGitRootPath;
end;
function GitBranch: string;
begin
if fGitBranch = '' then begin
if not RunGit(['describe','--all','HEAD'], fGitBranch) then
fGitBranch:= '';
end;
Result:= fGitBranch;
end;
function GitHash: string;
begin
if fGitHash = '' then begin
if not RunGit(['rev-parse','HEAD'], fGitHash) then
fGitHash:= '';
end;
Result:= fGitHash;
end;
function GitIsModified: boolean;
var
cmdres: string;
st: TStringList;
begin
if fGitModified = -1 then begin
if RunGit(['status','--short','-uno'], cmdres) then begin
st:= TStringList.Create;
try
st.Text:= cmdres;
fGitModified:= st.Count;
finally
FreeAndNil(st);
end;
end;
end;
Result:= fGitModified > 0;
end;
function GitSvnLatest: string;
const
STARTMARK = 'git-svn-id: http';
function ExtractSvnRev(A: String): string;
var
i: integer;
spl: TStringArray;
begin
Result:= '';
i:= LastDelimiter(#13#10, A);
if i = 0 then Exit;
Delete(A, 1, i);
A:= Trim(A);
i:= Pos(STARTMARK, A);
if i <> 1 then Exit;
spl:= A.Split([' '], TStringSplitOptions.None);
if Length(spl) <> 3 then Exit;
spl:= spl[1].Split('@', TStringSplitOptions.None);
if Length(spl) <> 2 then Exit;
Result:= spl[1];
end;
var
tmp: string;
begin
if fGitSvnLatest = '' then begin
if RunGit(['log','--grep='+STARTMARK,'-F','--topo-order','-n1'], tmp) then begin
fGitSvnLatest:= ExtractSvnRev(tmp);
end;
end;
Result:= fGitSvnLatest;
end;
end.
|
{ **************************************************************
Package: XWB - Kernel RPCBroker
Date Created: Sept 18, 1997 (Version 1.1)
Site Name: Oakland, OI Field Office, Dept of Veteran Affairs
Developers: Joel Ivey, Brian Juergensmeyer
Description: Contains TRPCBroker and related components.
Unit: fRPCBErrMsg Error Display to permit application control
over bringing it to the front.
Current Release: Version 1.1 Patch 50
*************************************************************** }
{ **************************************************
Changes in v1.1.65 (HGW 10/06/2016) XWB*1.1*65
1. Resolved CPRS Defect 329516 for 508 compliance (code submitted
by Brian Juergensmeyer). Replaced MessageDlg (not 508 compliant)
with MessageBox (508 compliant).
Changes in v1.1.60 (HGW 12/16/2013) XWB*1.1*60
1. None.
Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50
1. None.
************************************************** }
unit fRPCBErrMsg;
interface
uses
{System}
SysUtils, Classes,
{WinApi}
Windows, Messages,
{Vcl}
Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TfrmErrMsg = class(TForm)
Button1: TButton;
mmoErrorMessage: TMemo;
private
{ Private declarations }
public
{ Public declarations }
class procedure RPCBShowException(Sender: TObject; E: Exception);
end;
procedure RPCBShowErrMsg(ErrorText: String);
var
frmErrMsg: TfrmErrMsg;
implementation
{$R *.DFM}
procedure RPCBShowErrMsg(ErrorText: String);
begin
{
blj 6 Oct 2016 - Jazz item 329516
Removing full form. Simply use MessageBox for better 508 compliance.
}
MessageBox(0, PWideChar(ErrorText), nil, MB_ICONERROR or MB_OK);
// frmErrMsg := TfrmErrMsg.Create(Application);
// frmErrMsg.mmoErrorMessage.Lines.Add(ErrorText);
// frmErrMsg.ShowModal;
// frmErrMsg.Free;
end;
class procedure TfrmErrMsg.RPCBShowException(Sender: TObject; E: Exception);
begin
{
blj 6 Oct 2016 - Jazz item 329516
Removing full form. Simply use MessageBox for better 508 compliance.
}
MessageBox(0, PWideChar(E.Message), nil, MB_ICONERROR or MB_OK);
// frmErrMsg := TfrmErrMsg.Create(Application);
// frmErrMsg.mmoErrorMessage.Lines.Add(ErrorText);
// frmErrMsg.ShowModal;
// frmErrMsg.Free;
end;
end.
|
unit vr_xml_utils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, math, vr_utils, vr_classes, vr_intfs,
RegExpr, laz2_XMLRead, Laz2_DOM, LConvEncoding;
type
TDomElementArray = array of TDOMElement;
function TryReadXMLFile(out ADoc: TXMLDocument; const AFilename: String;
AFlags: TXMLReaderFlags = []; AIsShowError: Boolean = False): Boolean;
function xml_GetChildrenByTagName(const AParent: TDOMElement; const AName: DOMString;
out arr: TDomElementArray): Boolean;
function xml_GetElementByTagAndAttrValue(const AParent: TDOMElement;
const ATag, Attr, AValue: DOMString; out AResult: TDOMElement;
const ACheckChild: Boolean = False): Boolean;
function xml_GetElementByPathAndAttrValue(const AParent: TDOMElement;
const APath, Attr, AValue: DOMString; out AResult: TDOMElement;
const ACheckChild: Boolean = False): Boolean;
function xml_FindNode(const AParent: TDOMNode; const AName: string; out ANode: TDOMNode): Boolean;
function xml_HasElement(const AParent: TDOMNode; const AName: string): Boolean;
function xml_FindElement(const AParent: TDOMNode; const AName: string; out AElement: TDOMElement): Boolean;
function xml_GetAttr(const ANode: TDOMElement; const Atrr: string; out AValue: string): Boolean;
function xml_AttrDef(const ANode: TDOMElement; const Atrr: string; const ADefault: string = ''): string;
function xml_AttrAsInt(const ANode: TDOMElement; const Atrr: string; const ADefault: Integer = 0): Integer;
function xml_AttrAsDouble(const ANode: TDOMElement; const Atrr: string; const ADefault: Double = 0): Double;
function xml_GetAllAttrValues(const AName: string; out AValues: IFPStringList;
const AParent: TDOMElement): Boolean;
function xml_ChildText(const AParent: TDOMNode; const AName: string; out AValue: string): Boolean;
function xml_ChildTextDef(const AParent: TDOMNode; const AName: string; const ADefault: string = ''): string;
function xml_ChildTextAsInt(const AParent: TDOMNode; const AName: string; const ADefault: Integer = 0): Integer;
function xml_ChildAttr(const AParent: TDOMElement; const AName, Attr: string; out AValue: string): Boolean;
function xml_ChildAttrDef(const AParent: TDOMElement; const AName, Attr: string; const ADefault: string = ''): string;
function xml_ChildAttrAsInt(const AParent: TDOMElement; const AName, Attr: string; const ADefault: Integer = 0): Integer;
function xml_PathNode(const AParent: TDOMNode; const APath: string; out ANode: TDOMNode): Boolean;
function xml_PathElement(const AParent: TDOMNode; const APath: string; out AElement: TDOMElement): Boolean;
function xml_PathText(const AParent: TDOMElement; const APath: string; out AValue: string): Boolean;
function xml_PathTextDef(const AParent: TDOMElement; const APath: string;
const ADefault: string = ''): string;
function xml_PathInt(const AParent: TDOMElement; const APath: string; out AValue: Integer): Boolean;
function xml_PathTextAsInt(const AParent: TDOMElement; const APath: string;
const ADefault: Integer = 0): Integer;
function xml_PathAttr(const AParent: TDOMElement; const APath, Attr: string; out AValue: string): Boolean;
function xml_PathAttrDef(const AParent: TDOMElement; const APath, Attr: string;
const ADefault: string = ''): string;
function xml_PathAttrAsInt(const AParent: TDOMElement; const APath, Attr: string;
const ADefault: Integer = 0): Integer;
function xml_PathAttrAsDouble(const AParent: TDOMElement; const APath, Attr: string;
const ADefault: Double = 0): Double;
function xml_AddTag(const AParent: TDOMElement; const ATag: string;
const Attrs: array of string; const AValues: array of string): TDOMElement;
procedure xml_Clear(const AParent: TDOMElement);
implementation
var
XmlFormatSettings: TFormatSettings;
function TryReadXMLFile(out ADoc: TXMLDocument; const AFilename: String;
AFlags: TXMLReaderFlags; AIsShowError: Boolean): Boolean;
var
S, sEncoding: String;
st: TStringStreamUTF8 = nil;
procedure _ReplaceEncoding; //<?xml version="1.0" encoding="UTF-16"?>
var
I: SizeInt;
S1: RegExprString;
begin
I := Pos('?>', S);
if I = 0 then Exit;
S1 := ReplaceRegExpr('encoding.*=.*".*"', Copy(S, 1, I - 1), 'encoding="utf-8"', False);
S := S1 + Copy(S, I, MaxInt);
end;
begin
try
try
//ReadXMLFile(ADoc, AFilename, AFlags);
sEncoding := '';
S := str_LoadFromFileEx(sEncoding, AFilename, False);
if sEncoding <> EncodingUTF8 then
_ReplaceEncoding;
st := TStringStreamUTF8.Create(S);
ReadXMLFile(ADoc, st, AFlags);
Result := ADoc <> nil;
except
on E: Exception do
begin
Result := False;
if AIsShowError then
ShowExceptionMsg(E);
end;
end;
finally
st.Free;
end;
end;
function xml_GetChildrenByTagName(const AParent: TDOMElement;
const AName: DOMString; out arr: TDomElementArray): Boolean;
var
el: TDOMElement;
Len: Integer;
begin
SetLength(arr, AParent.ChildNodes.Count);
Len := 0;
el := TDOMElement(AParent.FirstChild);
while el <> nil do
begin
if (el is TDOMElement) and
(el.CompareName(AName) = 0) then
begin
arr[Len] := el;
Inc(Len);
end;
el := TDOMElement(el.NextSibling);
end;
SetLength(arr, Len);
Result := Len > 0;
end;
function xml_GetElementByTagAndAttrValue(const AParent: TDOMElement;
const ATag, Attr, AValue: DOMString; out AResult: TDOMElement;
const ACheckChild: Boolean): Boolean;
var
el: TDOMElement;
begin
AResult := TDOMElement(AParent.FirstChild);
while AResult <> nil do
begin
if (AResult is TDOMElement) and
(AResult.CompareName(ATag) = 0) and
SameStr(AResult.GetAttribute(Attr), AValue) then
begin
Exit(True);
end;
if ACheckChild and (AResult.FirstChild is TDOMElement) then
begin
Result := xml_GetElementByTagAndAttrValue(AResult,
ATag, Attr, AValue, el, ACheckChild);
if Result then
begin
AResult := el;
Exit(True);
end;
end;
AResult := TDOMElement(AResult.NextSibling);
end;
Result := False;
AResult := nil;
end;
function xml_GetElementByPathAndAttrValue(const AParent: TDOMElement;
const APath, Attr, AValue: DOMString; out AResult: TDOMElement;
const ACheckChild: Boolean): Boolean;
var
sPath, sTag: string;
Node: TDOMNode;
begin
NameValueOfString(APath, sPath{%H-}, sTag{%H-}, '/', True);
if sTag = '' then
begin
Node := AParent;
sTag := sPath;
end
else if not xml_PathNode(AParent, sPath, Node) or not (Node is TDOMElement) then
Exit(False);
Result := xml_GetElementByTagAndAttrValue(TDOMElement(Node), sTag, Attr, AValue, AResult, ACheckChild);
end;
function xml_FindNode(const AParent: TDOMNode; const AName: string; out
ANode: TDOMNode): Boolean;
begin
if AParent = nil then
begin
ANode := nil;
Exit(False);
end
else
begin
ANode := AParent.FindNode(AName);
Result := ANode <> nil;
end;
end;
function xml_HasElement(const AParent: TDOMNode; const AName: string): Boolean;
var
el: TDOMElement;
begin
Result := xml_FindElement(AParent, AName, el);
end;
function xml_FindElement(const AParent: TDOMNode; const AName: string; out
AElement: TDOMElement): Boolean;
begin
TDOMNode(AElement) := AParent.FindNode(AName);
Result := (AElement is TDOMElement);
if not Result then
AElement := nil;
end;
function xml_GetAttr(const ANode: TDOMElement; const Atrr: string; out
AValue: string): Boolean;
var
AttrNode: TDOMAttr;
begin
AttrNode := ANode.GetAttributeNode(Atrr);
Result := Assigned(AttrNode);
if Result then
AValue := AttrNode.Value
else
AValue := '';
end;
function xml_AttrDef(const ANode: TDOMElement; const Atrr: string;
const ADefault: string): string;
var
AttrNode: TDOMAttr;
begin
AttrNode := ANode.GetAttributeNode(Atrr);
if Assigned(AttrNode) then
Result := AttrNode.Value
else
Result := ADefault;
end;
function xml_AttrAsInt(const ANode: TDOMElement; const Atrr: string;
const ADefault: Integer): Integer;
var
AttrNode: TDOMAttr;
begin
AttrNode := ANode.GetAttributeNode(Atrr);
if Assigned(AttrNode) then
Result := StrToIntDef(AttrNode.Value, ADefault)
else
Result := ADefault;
end;
function xml_AttrAsDouble(const ANode: TDOMElement; const Atrr: string;
const ADefault: Double): Double;
var
AttrNode: TDOMAttr;
begin
AttrNode := ANode.GetAttributeNode(Atrr);
if Assigned(AttrNode) then
Result := StrToFloatDef(AttrNode.Value, ADefault, XmlFormatSettings)
else
Result := ADefault;
end;
function xml_GetAllAttrValues(const AName: string; out AValues: IFPStringList;
const AParent: TDOMElement): Boolean;
procedure _CheckAttr(const AElement: TDOMElement);
var
sValue: DOMString;
begin
sValue := AElement.GetAttribute(AName);
if sValue <> '' then
AValues.Add(sValue);
end;
procedure _Do(const AElement: TDOMElement);
var
el: TDOMElement;
begin
_CheckAttr(AElement);
el := TDOMElement(AElement.FirstChild);
while el <> nil do
begin
if (el is TDOMElement) then
begin
_CheckAttr(el);
_Do(el);
end;
el := TDOMElement(el.NextSibling);
end;
end;
begin
AValues := new_StringList(True);
_Do(AParent);
Result := AValues.Count > 0;
if not Result then
AValues := nil;
end;
function xml_ChildText(const AParent: TDOMNode; const AName: string; out
AValue: string): Boolean;
var
Node: TDOMNode;
begin
Node := AParent.FindNode(AName);
Result := (Node <> nil);
if Result then
AValue := Node.TextContent;
end;
function xml_ChildTextDef(const AParent: TDOMNode; const AName: string;
const ADefault: string): string;
begin
if not xml_ChildText(AParent, AName, Result) then
Result := ADefault;
end;
function xml_ChildTextAsInt(const AParent: TDOMNode; const AName: string;
const ADefault: Integer): Integer;
var
S: string;
begin
if xml_ChildText(AParent, AName, S) then
Result := StrToIntDef(S, ADefault)
else
Result := ADefault;
end;
function xml_ChildAttr(const AParent: TDOMElement; const AName, Attr: string; out
AValue: string): Boolean;
var
Node: TDOMNode;
begin
Result := xml_FindNode(AParent, AName, Node) and (Node is TDOMElement);
if Result then
begin
AValue := TDOMElement(Node).GetAttribute(Attr);
Result := AValue <> '';
end;
end;
function xml_ChildAttrDef(const AParent: TDOMElement; const AName, Attr: string;
const ADefault: string): string;
begin
if not xml_ChildAttr(AParent, AName, Attr, Result) then
Result := ADefault;
end;
function xml_ChildAttrAsInt(const AParent: TDOMElement; const AName,
Attr: string; const ADefault: Integer): Integer;
var
S: string;
begin
if xml_ChildAttr(AParent, AName, Attr, S) then
Result := StrToIntDef(S, ADefault)
else
Result := ADefault;
end;
function xml_PathNode(const AParent: TDOMNode; const APath: string; out
ANode: TDOMNode): Boolean;
var
ns: INextDelimStringGetter;
S: string;
begin
Result := False;
if APath = '' then Exit;
ANode := AParent;
ns := New_NextDelimStringGetter(APath, '/', []);
while ns.Next(S) do
begin
ANode := ANode.FindNode(S);
if ANode = nil then Exit;
end;
Result := True;
end;
function xml_PathElement(const AParent: TDOMNode; const APath: string; out
AElement: TDOMElement): Boolean;
begin
Result := xml_PathNode(AParent, APath, TDOMNode(AElement)) and (AElement is TDOMElement);
end;
function xml_PathText(const AParent: TDOMElement; const APath: string; out AValue: string): Boolean;
var
Node: TDOMNode;
begin
Result := xml_PathNode(AParent, APath, Node) and (Node is TDOMElement);
if Result then
begin
AValue := TDOMElement(Node).TextContent;
Result := AValue <> '';
end;
end;
function xml_PathTextDef(const AParent: TDOMElement; const APath: string;
const ADefault: string): string;
begin
if not xml_PathText(AParent, APath, Result) then
Result := ADefault;
end;
function xml_PathInt(const AParent: TDOMElement; const APath: string; out
AValue: Integer): Boolean;
var
S: string;
begin
Result := xml_PathText(AParent, APath, S) and TryStrToInt(S, AValue);
if not Result then
AValue := 0;
end;
function xml_PathTextAsInt(const AParent: TDOMElement; const APath: string;
const ADefault: Integer): Integer;
begin
Result := StrToIntDef(xml_PathTextDef(AParent, APath), ADefault);
end;
function xml_PathAttr(const AParent: TDOMElement; const APath, Attr: string;
out AValue: string): Boolean;
var
Node: TDOMNode;
begin
Result := xml_PathNode(AParent, APath, Node) and (Node is TDOMElement);
if Result then
begin
AValue := TDOMElement(Node).GetAttribute(Attr);
Result := AValue <> '';
end;
end;
function xml_PathAttrDef(const AParent: TDOMElement; const APath, Attr: string;
const ADefault: string): string;
begin
if not xml_PathAttr(AParent, APath, Attr, Result) then
Result := ADefault;
end;
function xml_PathAttrAsInt(const AParent: TDOMElement; const APath,
Attr: string; const ADefault: Integer): Integer;
var
S: string;
begin
if xml_PathAttr(AParent, APath, Attr, S) then
Result := StrToIntDef(S, ADefault)
else
Result := ADefault;
end;
function xml_PathAttrAsDouble(const AParent: TDOMElement; const APath,
Attr: string; const ADefault: Double): Double;
var
S: string;
begin
if xml_PathAttr(AParent, APath, Attr, S) then
Result := StrToFloatDef(S, ADefault, XmlFormatSettings)
else
Result := ADefault;
end;
function xml_AddTag(const AParent: TDOMElement; const ATag: string;
const Attrs: array of string; const AValues: array of string): TDOMElement;
var
i: Integer;
sValue: String;
begin
Result := AParent.OwnerDocument.CreateElement(ATag);
AParent.AppendChild(Result);
for i := 0 to Min(Length(Attrs), Length(AValues)) - 1 do
begin
sValue := AValues[i];
if sValue <> '' then
Result.SetAttribute(Attrs[i], sValue);
end;
end;
procedure xml_Clear(const AParent: TDOMElement);
var
NextNode, Node: TDOMNode;
begin
NextNode := AParent.FirstChild;
while NextNode <> nil do
begin
Node := NextNode;
NextNode := NextNode.NextSibling;
AParent.RemoveChild(Node);
end;
end;
initialization
XmlFormatSettings := DefaultFormatSettings;
XmlFormatSettings.DecimalSeparator := '.';
end.
|
{*******************************************************}
{ }
{ DelphiWebMVC }
{ }
{ °æÈ¨ËùÓÐ (C) 2019 ËÕÐËÓ(PRSoft) }
{ }
{*******************************************************}
unit DBOracle;
interface
uses
System.SysUtils, FireDAC.Comp.Client, superobject, DBBase;
type
TDBOracle = class(TDBBase)
public
function FindFirst(tablename: string; where: string = ''): ISuperObject; overload; override;
function QueryPage(var count: Integer; select, from, order: string; pageindex, pagesize: Integer): ISuperObject; override;
end;
implementation
{ TDBOracle }
function TDBOracle.FindFirst(tablename: string; where: string = ''): ISuperObject;
var
sql: string;
begin
Result := nil;
if (Trim(tablename) = '') then
Exit;
if Fields = '' then
Fields := '*';
sql := 'select ' + Fields + ' from ' + tablename + ' where 1=1 ' + where;
sql := 'select * from (' + sql + ') where rownum=1';
Result := QueryFirst(sql);
end;
function TDBOracle.QueryPage(var count: Integer; select, from, order: string; pageindex, pagesize: Integer): ISuperObject;
var
CDS: TFDQuery;
sql: string;
begin
Result := nil;
if (not TryConnDB) or (Trim(select) = '') or (Trim(from) = '') then
Exit;
if Fields = '' then
Fields := '*';
if Trim(order) <> '' then
order := 'order by ' + Trim(order);
CDS := TFDQuery.Create(nil);
try
try
CDS.Connection := condb;
sql := 'select count(1) as N from ' + from;
sql:=filterSQL(sql);
CDS.Open(sql);
count := CDS.FieldByName('N').AsInteger;
CDS.Close;
sql := 'select A.*,rownum rn from(select ' + Fields + ' from ' + from + ')';
sql := 'select * from (' + sql + ') where rn between ' + IntToStr(pagesize * pageindex) + ' and ' + IntToStr(pagesize);
Result := Query(sql);
except
on e: Exception do
begin
DBlog(e.ToString);
Result := nil;
end;
end;
finally
FreeAndNil(CDS);
end;
end;
end.
|
unit pviewfrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
QRPrntr, Quickrpt, ToolWin, ComCtrls, StdCtrls;
type
TPreviewForm = class(TForm)
QRPreview: TQRPreview;
barTool: TToolBar;
btnPrint: TToolButton;
btnPrinter: TToolButton;
edtZoom: TComboBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure btnPrinterClick(Sender: TObject);
private
rep:TQuickRep;
public
procedure Execute(rep:TQuickRep);
end;
var
PreviewForm: TPreviewForm;
implementation
{$R *.DFM}
procedure TPreviewForm.FormCreate(Sender: TObject);
begin
QRPreview.ZoomToWidth;
end;
procedure TPreviewForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TPreviewForm.FormDestroy(Sender: TObject);
begin
if rep<>nil then begin
rep.QRPrinter.Free;
rep.Free;
end;
end;
procedure TPreviewForm.Execute(rep:TQuickRep);
begin
self.rep:=rep;
Show;
rep.Prepare;
QRPreview.QRPrinter:=rep.QRPrinter;
end;
procedure TPreviewForm.btnPrintClick(Sender: TObject);
begin
rep.QRPrinter.Print;
end;
procedure TPreviewForm.btnPrinterClick(Sender: TObject);
begin
rep.QRPrinter.PrintSetup;
end;
end.
|
unit Form.MainView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseForm, dxSkinsCore,
dxSkinMetropolis, System.ImageList, Vcl.ImgList, cxGraphics, cxClasses,
cxLookAndFeels, dxSkinsForm, cxControls, cxLookAndFeelPainters, cxCustomData,
cxStyles, cxTL, cxMaskEdit, cxTLdxBarBuiltInMenu, dxSkinscxPCPainter,
cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGridCustomView, cxGrid, cxSplitter, cxInplaceContainer, cxDBTL, cxTLData,
Vcl.ComCtrls, Vcl.ToolWin, Vcl.ExtCtrls, dxActivityIndicator,
System.Generics.Collections, Uni,
ConnectionModule,
cxContainer, cxTextEdit, Vcl.StdCtrls, System.Actions, Vcl.ActnList, cxMemo;
type
TfrmLibraryView = class(TfrmBase)
pnlLeft: TPanel;
tbCategoryEdit: TToolBar;
btnAddCategory: TToolButton;
btnEditCategory: TToolButton;
btnDelCategory: TToolButton;
btnRefresh: TToolButton;
lstCategories: TcxDBTreeList;
lstCategoriesCategoryID: TcxDBTreeListColumn;
lstCategoriesCategoryName: TcxDBTreeListColumn;
MainSplitter: TcxSplitter;
pnlRight: TPanel;
grdBooks: TcxGrid;
grdBooksView: TcxGridDBTableView;
grdBooksViewID: TcxGridDBColumn;
grdBooksViewBOOK_NAME: TcxGridDBColumn;
grdBooksViewFILE_LINK: TcxGridDBColumn;
grdBooksLevel: TcxGridLevel;
tbBookEdit: TToolBar;
btnAddBook: TToolButton;
btnEditBook: TToolButton;
btnDelBook: TToolButton;
btnRefreshBook: TToolButton;
btnRun: TToolButton;
lstCategoriesCntBook: TcxDBTreeListColumn;
procedure btnAddCategoryClick(Sender: TObject);
procedure btnEditCategoryClick(Sender: TObject);
procedure btnDelCategoryClick(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure btnAddBookClick(Sender: TObject);
procedure btnEditBookClick(Sender: TObject);
procedure btnRefreshBookClick(Sender: TObject);
procedure btnDelBookClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnRunClick(Sender: TObject);
procedure grdBooksViewCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure FormCreate(Sender: TObject);
procedure lstCategoriesCustomDrawDataCell(Sender: TcxCustomTreeList;
ACanvas: TcxCanvas; AViewInfo: TcxTreeListEditCellViewInfo;
var ADone: Boolean);
private
FBookID: Integer;
private
function GetBookCount: Integer;
procedure BooksChange(Sender: TObject);
public
procedure LoadData;
public
property BookCount: Integer read GetBookCount;
end;
var
frmLibraryView: TfrmLibraryView;
implementation
uses
Common.Utils,
Common.DatabaseUtils,
Form.EditCategory,
Form.EditBook,
System.IniFiles,
Vcl.FileCtrl;
{$R *.dfm}
resourcestring
rsConfirmDeleteRecord = 'Вы действительно хотите удалить %s "%s"?';
rsErrorDeleteRecord = 'Не удалось удалить запись "%s"';
{ TfrmLibraryView }
procedure TfrmLibraryView.btnRunClick(Sender: TObject);
var
FileName: string;
begin
// вызов программы-читалки
if not btnRun.Enabled then Exit;
with dm do begin
FileName := qryBooks.FieldByName('BookLink').AsString;
if FileName.IsEmpty then Exit;
end;
ShellExecute(0, '', FileName);
end;
procedure TfrmLibraryView.BooksChange(Sender: TObject);
var
BookLink: string;
begin
if not Assigned(Sender) then Exit;
BookLink := DM.qryBooks.FieldByName('BookLink').AsString;
btnRun.Enabled := FileExists(BookLink);
btnDelBook.Enabled := btnRun.Enabled;
end;
procedure TfrmLibraryView.btnAddBookClick(Sender: TObject);
begin
DM.qryBooks.Append;
TfrmEditBook.Edit(emAppend);
end;
procedure TfrmLibraryView.btnAddCategoryClick(Sender: TObject);
begin
with DM.qryCategories do begin
Append;
// генерим новый ID
FieldByName('Id').AsInteger := GetFieldValue(['max(Id)+1', 'Categories', 'Id < 1000']);
// по умолчанию категория 1
FieldByName('Parent_Id').AsInteger := 1;
end;
TfrmEditCategory.Edit(emAppend);
end;
procedure TfrmLibraryView.btnDelBookClick(Sender: TObject);
var
BookName, BookLink: string;
begin
if not btnDelBook.Enabled then Exit;
BookName := DM.qryBooks.FieldByName('BookName').asString;
BookLink := DM.qryBooks.FieldByName('BookLink').AsString;
if ShowConfirmFmt(rsConfirmDeleteRecord, ['книгу', BookName]) then begin
DM.conn.StartTransaction;
try
DM.qryBooks.Delete;
if FileExists(BookLink) then begin
if ShowConfirm('Удалить файл с диска ?') then begin
if not DeleteFile(BookLink) then begin
raise Exception.CreateFmt('Не удалось удалить книгу. Код ошибки', [ GetLastError ]);
end;
end;
end;
DM.conn.Commit;
except
DM.conn.Rollback;
ShowErrorFmt(rsErrorDeleteRecord, [BookName]);
end;
end;
end;
procedure TfrmLibraryView.btnDelCategoryClick(Sender: TObject);
var
CategoryName: string;
begin
CategoryName := DM.qryCategories.FieldByName('CategoryName').asString;
if ShowConfirmFmt(rsConfirmDeleteRecord, ['категорию', CategoryName]) then
begin
try
DM.qryCategories.Delete;
except
ShowErrorFmt(rsErrorDeleteRecord, [CategoryName]);
end;
end;
end;
procedure TfrmLibraryView.btnEditBookClick(Sender: TObject);
begin
DM.qryBooks.Edit;
TfrmEditBook.Edit(emEdit);
btnRefreshClick(nil);
end;
procedure TfrmLibraryView.btnEditCategoryClick(Sender: TObject);
begin
DM.qryCategories.Edit;
TfrmEditCategory.Edit(emEdit);
btnRefreshClick(nil);
end;
procedure TfrmLibraryView.btnRefreshBookClick(Sender: TObject);
begin
btnRefreshClick(nil);
end;
procedure TfrmLibraryView.btnRefreshClick(Sender: TObject);
var
CategoryBookmark, Bookmark: TBookmark;
begin
with DM do begin
if qryCategories.Active then
CategoryBookmark := qryCategories.GetBookmark;
if qryBooks.Active then
Bookmark := qryBooks.GetBookmark;
LoadData;
qryCategories.GotoBookmark(CategoryBookmark);
qryBooks.GotoBookmark(Bookmark);
end;
end;
procedure TfrmLibraryView.FormCreate(Sender: TObject);
begin
DM.RegChangeNotifier(BooksChange);
end;
procedure TfrmLibraryView.FormDestroy(Sender: TObject);
begin
with dm do begin
UnregChangeNotifier(BooksChange);
qryCategories.Close;
qryBooks.Close;
end;
end;
procedure TfrmLibraryView.FormShow(Sender: TObject);
begin
inherited;
LoadData;
end;
function TfrmLibraryView.GetBookCount: Integer;
begin
with TUniQuery.Create(nil) do try
Connection := DM.conn;
SQL.Text := 'select count(*) as Cnt from Books';
Open;
if not IsEmpty then
Result := FieldByName('Cnt').AsInteger;
Close;
finally
Free;
end;
end;
procedure TfrmLibraryView.grdBooksViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
Var
lTextToDraw: string;
lColFont: TFont;
begin
lColFont := ACanvas.Font; //сохраняем настройки шрифта по умолчанию для текущей ячейки
lTextToDraw := trim(AViewInfo.GridRecord.DisplayTexts[ 2 ]); //считываем содержимое 2ого столбца
if ( not lTextToDraw.IsEmpty ) and ( not FileExists( lTextToDraw ) ) then begin
lColFont.Style := [ fsStrikeOut, fsItalic ];
lColFont.Color := clRed;
end;
ACanvas.Font := lColFont; //устанавливаем получившиеся выделение для всей строки
end;
procedure TfrmLibraryView.LoadData;
begin
with DM do begin
if qryBooks.Active then
qryBooks.Close;
if qryCategories.Active then
qryCategories.Close;
qryCategories.Open;
qryBooks.Open;
end;
lstCategories.FullExpand;
end;
procedure TfrmLibraryView.lstCategoriesCustomDrawDataCell(
Sender: TcxCustomTreeList; ACanvas: TcxCanvas;
AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean);
var
lColFont: TFont;
begin
lColFont := ACanvas.Font;
if AViewInfo.Column.ItemIndex = 2 then begin
lColFont.Color := clRed;
lColFont.Style := [ fsBold ];
end;
ACanvas.Font := lColFont;
end;
end.
|
inherited dataTeste: TdataTeste
inherited qrySel: TUniQuery
SQLInsert.Strings = (
'INSERT INTO CLIENTES'
' (CODIGO, NOME, FONE)'
'VALUES'
' (:CODIGO, :NOME, :FONE)')
SQLDelete.Strings = (
'DELETE FROM CLIENTES'
'WHERE'
' CODIGO = :Old_CODIGO')
SQLUpdate.Strings = (
'UPDATE CLIENTES'
'SET'
' CODIGO = :CODIGO, NOME = :NOME, FONE = :FONE'
'WHERE'
' CODIGO = :Old_CODIGO')
SQLLock.Strings = (
'SELECT NULL FROM CLIENTES'
'WHERE'
'CODIGO = :Old_CODIGO'
'FOR UPDATE WITH LOCK')
SQLRefresh.Strings = (
'SELECT CODIGO, NOME, FONE FROM CLIENTES'
'WHERE'
' CODIGO = :CODIGO')
SQL.Strings = (
'SELECT'
' CODIGO,'
' NOME,'
' FONE'
'FROM '
' CLIENTES')
object qrySelCODIGO: TIntegerField
DisplayLabel = 'C'#243'd.Cliente'
FieldName = 'CODIGO'
Required = True
end
object qrySelNOME: TStringField
DisplayLabel = 'Nome'
FieldName = 'NOME'
Required = True
FixedChar = True
Size = 40
end
object qrySelFONE: TStringField
DisplayLabel = 'Telefone'
FieldName = 'FONE'
FixedChar = True
end
end
inherited qryCad: TUniQuery
SQLInsert.Strings = (
'INSERT INTO CLIENTES'
' (CODIGO, PESSOAFISICA, RAZAOSOCIAL, NOME, DATANASC, NATURALIDA' +
'DE, SEXO, ESTADOCIVIL, RG, CPF, CGC, IE, PAI, MAE, LOGRADOURO, N' +
'UMERO, COMPLEMENTO, BAIRRO, CIDADE, ESTADO, CEP, MUNIBGE, FONE, ' +
'FAX, EMAIL, HOMEPAGE, CELULAR, DATACADAST, OBSERVACOES, CONTATO,' +
' DATAFUND, PROFISSAO, EQUIPAMENTO, SALARIO, ORGAOEXP, SOUNDBYTES' +
', PROTESTO, SPC, SERASA, IMOVEL, PROTESTO_DATA, SPC_DATA, SERASA' +
'_DATA, PROTESTO_USER, SPC_USER, SERASA_USER, IMOVEL_TIPO, CODEMP' +
'REEND, PROCESSO_OK, FGTS, PIS, VALOR_FGTS, CONTRATO, KMS, COMISS' +
'IONADO, NOMEUSER, DESCONTO, FINANCEIRO, ESTORNO, CODEMPRESA, TRO' +
'CAVENDEDOR, INTERNET, MUDAEMPRESA, COMISSAO, TIPO, CODFORNECEDOR' +
', CODTRANSPORTADOR, CODASSOCIADO, NOME_FAMILIA, RECEBIMENTO, CUS' +
'TO, SEQUENCIAS, RECALCULO, COMPRAS, TRANSFERENCIA, RELATORIOS, L' +
'IMITECREDITO, TIPO_BLOQUEIO, TIPO_IMPEDIMENTO, OCULTO, VENDADIRE' +
'TA, TECNICOLOGIN, FECHAMENTO, LOG_USUARIO, LOG_TIPO, LOG_MAQUINA' +
', LOG_DATAREMOTO, SENHAWEB, PERCCOMIS_PROD, PERCCOMIS_PECA, PERC' +
'COMIS_SERV, PERCCOMIS_CALCULO, CODLINHA, CODCENTRO, CODPLANO, CA' +
'LC_BASEICMS, CAIXA, OCULTOS, ANALISES, LOGS, ENTREGA1, ENTREGA2,' +
' RESIDENCIA_TEMPO, ALUGUEL, ALUGUEL_VALOR, TRAB_SALARIO, CONJ_SA' +
'LARIO, TRAB_EMPRESA, TRAB_ADMISSAO, TRAB_ENDERECO, TRAB_CIDADE, ' +
'TRAB_FONE, TRAB_CARGO, CONJ_NOME, CONJ_DATANASC, CONJ_RG, CONJ_C' +
'PF, CONJ_CARTEIRA, CONJ_EMPRESA, CONJ_ADMISSAO, CONJ_CARGO, CONJ' +
'_ENDERECO, CONJ_FONE, CARTEIRA, REFERENCIA1, REFERENCIA2, REFERE' +
'NCIA3, VALOR_CONTRATO, IM, CNAE)'
'VALUES'
' (:CODIGO, :PESSOAFISICA, :RAZAOSOCIAL, :NOME, :DATANASC, :NATU' +
'RALIDADE, :SEXO, :ESTADOCIVIL, :RG, :CPF, :CGC, :IE, :PAI, :MAE,' +
' :LOGRADOURO, :NUMERO, :COMPLEMENTO, :BAIRRO, :CIDADE, :ESTADO, ' +
':CEP, :MUNIBGE, :FONE, :FAX, :EMAIL, :HOMEPAGE, :CELULAR, :DATAC' +
'ADAST, :OBSERVACOES, :CONTATO, :DATAFUND, :PROFISSAO, :EQUIPAMEN' +
'TO, :SALARIO, :ORGAOEXP, :SOUNDBYTES, :PROTESTO, :SPC, :SERASA, ' +
':IMOVEL, :PROTESTO_DATA, :SPC_DATA, :SERASA_DATA, :PROTESTO_USER' +
', :SPC_USER, :SERASA_USER, :IMOVEL_TIPO, :CODEMPREEND, :PROCESSO' +
'_OK, :FGTS, :PIS, :VALOR_FGTS, :CONTRATO, :KMS, :COMISSIONADO, :' +
'NOMEUSER, :DESCONTO, :FINANCEIRO, :ESTORNO, :CODEMPRESA, :TROCAV' +
'ENDEDOR, :INTERNET, :MUDAEMPRESA, :COMISSAO, :TIPO, :CODFORNECED' +
'OR, :CODTRANSPORTADOR, :CODASSOCIADO, :NOME_FAMILIA, :RECEBIMENT' +
'O, :CUSTO, :SEQUENCIAS, :RECALCULO, :COMPRAS, :TRANSFERENCIA, :R' +
'ELATORIOS, :LIMITECREDITO, :TIPO_BLOQUEIO, :TIPO_IMPEDIMENTO, :O' +
'CULTO, :VENDADIRETA, :TECNICOLOGIN, :FECHAMENTO, :LOG_USUARIO, :' +
'LOG_TIPO, :LOG_MAQUINA, :LOG_DATAREMOTO, :SENHAWEB, :PERCCOMIS_P' +
'ROD, :PERCCOMIS_PECA, :PERCCOMIS_SERV, :PERCCOMIS_CALCULO, :CODL' +
'INHA, :CODCENTRO, :CODPLANO, :CALC_BASEICMS, :CAIXA, :OCULTOS, :' +
'ANALISES, :LOGS, :ENTREGA1, :ENTREGA2, :RESIDENCIA_TEMPO, :ALUGU' +
'EL, :ALUGUEL_VALOR, :TRAB_SALARIO, :CONJ_SALARIO, :TRAB_EMPRESA,' +
' :TRAB_ADMISSAO, :TRAB_ENDERECO, :TRAB_CIDADE, :TRAB_FONE, :TRAB' +
'_CARGO, :CONJ_NOME, :CONJ_DATANASC, :CONJ_RG, :CONJ_CPF, :CONJ_C' +
'ARTEIRA, :CONJ_EMPRESA, :CONJ_ADMISSAO, :CONJ_CARGO, :CONJ_ENDER' +
'ECO, :CONJ_FONE, :CARTEIRA, :REFERENCIA1, :REFERENCIA2, :REFEREN' +
'CIA3, :VALOR_CONTRATO, :IM, :CNAE)')
SQLDelete.Strings = (
'DELETE FROM CLIENTES'
'WHERE'
' CODIGO = :Old_CODIGO')
SQLUpdate.Strings = (
'UPDATE CLIENTES'
'SET'
' CODIGO = :CODIGO, PESSOAFISICA = :PESSOAFISICA, RAZAOSOCIAL = ' +
':RAZAOSOCIAL, NOME = :NOME, DATANASC = :DATANASC, NATURALIDADE =' +
' :NATURALIDADE, SEXO = :SEXO, ESTADOCIVIL = :ESTADOCIVIL, RG = :' +
'RG, CPF = :CPF, CGC = :CGC, IE = :IE, PAI = :PAI, MAE = :MAE, LO' +
'GRADOURO = :LOGRADOURO, NUMERO = :NUMERO, COMPLEMENTO = :COMPLEM' +
'ENTO, BAIRRO = :BAIRRO, CIDADE = :CIDADE, ESTADO = :ESTADO, CEP ' +
'= :CEP, MUNIBGE = :MUNIBGE, FONE = :FONE, FAX = :FAX, EMAIL = :E' +
'MAIL, HOMEPAGE = :HOMEPAGE, CELULAR = :CELULAR, DATACADAST = :DA' +
'TACADAST, OBSERVACOES = :OBSERVACOES, CONTATO = :CONTATO, DATAFU' +
'ND = :DATAFUND, PROFISSAO = :PROFISSAO, EQUIPAMENTO = :EQUIPAMEN' +
'TO, SALARIO = :SALARIO, ORGAOEXP = :ORGAOEXP, SOUNDBYTES = :SOUN' +
'DBYTES, PROTESTO = :PROTESTO, SPC = :SPC, SERASA = :SERASA, IMOV' +
'EL = :IMOVEL, PROTESTO_DATA = :PROTESTO_DATA, SPC_DATA = :SPC_DA' +
'TA, SERASA_DATA = :SERASA_DATA, PROTESTO_USER = :PROTESTO_USER, ' +
'SPC_USER = :SPC_USER, SERASA_USER = :SERASA_USER, IMOVEL_TIPO = ' +
':IMOVEL_TIPO, CODEMPREEND = :CODEMPREEND, PROCESSO_OK = :PROCESS' +
'O_OK, FGTS = :FGTS, PIS = :PIS, VALOR_FGTS = :VALOR_FGTS, CONTRA' +
'TO = :CONTRATO, KMS = :KMS, COMISSIONADO = :COMISSIONADO, NOMEUS' +
'ER = :NOMEUSER, DESCONTO = :DESCONTO, FINANCEIRO = :FINANCEIRO, ' +
'ESTORNO = :ESTORNO, CODEMPRESA = :CODEMPRESA, TROCAVENDEDOR = :T' +
'ROCAVENDEDOR, INTERNET = :INTERNET, MUDAEMPRESA = :MUDAEMPRESA, ' +
'COMISSAO = :COMISSAO, TIPO = :TIPO, CODFORNECEDOR = :CODFORNECED' +
'OR, CODTRANSPORTADOR = :CODTRANSPORTADOR, CODASSOCIADO = :CODASS' +
'OCIADO, NOME_FAMILIA = :NOME_FAMILIA, RECEBIMENTO = :RECEBIMENTO' +
', CUSTO = :CUSTO, SEQUENCIAS = :SEQUENCIAS, RECALCULO = :RECALCU' +
'LO, COMPRAS = :COMPRAS, TRANSFERENCIA = :TRANSFERENCIA, RELATORI' +
'OS = :RELATORIOS, LIMITECREDITO = :LIMITECREDITO, TIPO_BLOQUEIO ' +
'= :TIPO_BLOQUEIO, TIPO_IMPEDIMENTO = :TIPO_IMPEDIMENTO, OCULTO =' +
' :OCULTO, VENDADIRETA = :VENDADIRETA, TECNICOLOGIN = :TECNICOLOG' +
'IN, FECHAMENTO = :FECHAMENTO, LOG_USUARIO = :LOG_USUARIO, LOG_TI' +
'PO = :LOG_TIPO, LOG_MAQUINA = :LOG_MAQUINA, LOG_DATAREMOTO = :LO' +
'G_DATAREMOTO, SENHAWEB = :SENHAWEB, PERCCOMIS_PROD = :PERCCOMIS_' +
'PROD, PERCCOMIS_PECA = :PERCCOMIS_PECA, PERCCOMIS_SERV = :PERCCO' +
'MIS_SERV, PERCCOMIS_CALCULO = :PERCCOMIS_CALCULO, CODLINHA = :CO' +
'DLINHA, CODCENTRO = :CODCENTRO, CODPLANO = :CODPLANO, CALC_BASEI' +
'CMS = :CALC_BASEICMS, CAIXA = :CAIXA, OCULTOS = :OCULTOS, ANALIS' +
'ES = :ANALISES, LOGS = :LOGS, ENTREGA1 = :ENTREGA1, ENTREGA2 = :' +
'ENTREGA2, RESIDENCIA_TEMPO = :RESIDENCIA_TEMPO, ALUGUEL = :ALUGU' +
'EL, ALUGUEL_VALOR = :ALUGUEL_VALOR, TRAB_SALARIO = :TRAB_SALARIO' +
', CONJ_SALARIO = :CONJ_SALARIO, TRAB_EMPRESA = :TRAB_EMPRESA, TR' +
'AB_ADMISSAO = :TRAB_ADMISSAO, TRAB_ENDERECO = :TRAB_ENDERECO, TR' +
'AB_CIDADE = :TRAB_CIDADE, TRAB_FONE = :TRAB_FONE, TRAB_CARGO = :' +
'TRAB_CARGO, CONJ_NOME = :CONJ_NOME, CONJ_DATANASC = :CONJ_DATANA' +
'SC, CONJ_RG = :CONJ_RG, CONJ_CPF = :CONJ_CPF, CONJ_CARTEIRA = :C' +
'ONJ_CARTEIRA, CONJ_EMPRESA = :CONJ_EMPRESA, CONJ_ADMISSAO = :CON' +
'J_ADMISSAO, CONJ_CARGO = :CONJ_CARGO, CONJ_ENDERECO = :CONJ_ENDE' +
'RECO, CONJ_FONE = :CONJ_FONE, CARTEIRA = :CARTEIRA, REFERENCIA1 ' +
'= :REFERENCIA1, REFERENCIA2 = :REFERENCIA2, REFERENCIA3 = :REFER' +
'ENCIA3, VALOR_CONTRATO = :VALOR_CONTRATO, IM = :IM, CNAE = :CNAE'
'WHERE'
' CODIGO = :Old_CODIGO')
SQLLock.Strings = (
'SELECT NULL FROM CLIENTES'
'WHERE'
'CODIGO = :Old_CODIGO'
'FOR UPDATE WITH LOCK')
SQLRefresh.Strings = (
'SELECT CODIGO, PESSOAFISICA, RAZAOSOCIAL, NOME, DATANASC, NATURA' +
'LIDADE, SEXO, ESTADOCIVIL, RG, CPF, CGC, IE, PAI, MAE, LOGRADOUR' +
'O, NUMERO, COMPLEMENTO, BAIRRO, CIDADE, ESTADO, CEP, MUNIBGE, FO' +
'NE, FAX, EMAIL, HOMEPAGE, CELULAR, DATACADAST, OBSERVACOES, CONT' +
'ATO, DATAFUND, PROFISSAO, EQUIPAMENTO, SALARIO, ORGAOEXP, SOUNDB' +
'YTES, PROTESTO, SPC, SERASA, IMOVEL, PROTESTO_DATA, SPC_DATA, SE' +
'RASA_DATA, PROTESTO_USER, SPC_USER, SERASA_USER, IMOVEL_TIPO, CO' +
'DEMPREEND, PROCESSO_OK, FGTS, PIS, VALOR_FGTS, CONTRATO, KMS, CO' +
'MISSIONADO, NOMEUSER, DESCONTO, FINANCEIRO, ESTORNO, CODEMPRESA,' +
' TROCAVENDEDOR, INTERNET, MUDAEMPRESA, COMISSAO, TIPO, CODFORNEC' +
'EDOR, CODTRANSPORTADOR, CODASSOCIADO, NOME_FAMILIA, RECEBIMENTO,' +
' CUSTO, SEQUENCIAS, RECALCULO, COMPRAS, TRANSFERENCIA, RELATORIO' +
'S, LIMITECREDITO, TIPO_BLOQUEIO, TIPO_IMPEDIMENTO, OCULTO, VENDA' +
'DIRETA, TECNICOLOGIN, FECHAMENTO, LOG_USUARIO, LOG_TIPO, LOG_MAQ' +
'UINA, LOG_DATAREMOTO, SENHAWEB, PERCCOMIS_PROD, PERCCOMIS_PECA, ' +
'PERCCOMIS_SERV, PERCCOMIS_CALCULO, CODLINHA, CODCENTRO, CODPLANO' +
', CALC_BASEICMS, CAIXA, OCULTOS, ANALISES, LOGS, ENTREGA1, ENTRE' +
'GA2, RESIDENCIA_TEMPO, ALUGUEL, ALUGUEL_VALOR, TRAB_SALARIO, CON' +
'J_SALARIO, TRAB_EMPRESA, TRAB_ADMISSAO, TRAB_ENDERECO, TRAB_CIDA' +
'DE, TRAB_FONE, TRAB_CARGO, CONJ_NOME, CONJ_DATANASC, CONJ_RG, CO' +
'NJ_CPF, CONJ_CARTEIRA, CONJ_EMPRESA, CONJ_ADMISSAO, CONJ_CARGO, ' +
'CONJ_ENDERECO, CONJ_FONE, CARTEIRA, REFERENCIA1, REFERENCIA2, RE' +
'FERENCIA3, VALOR_CONTRATO, IM, CNAE FROM CLIENTES'
'WHERE'
' CODIGO = :CODIGO')
SQL.Strings = (
'SELECT * FROM CLIENTES WHERE CODIGO = :CODIGO')
ParamData = <
item
DataType = ftLargeint
Name = 'CODIGO'
ParamType = ptInput
end>
object qryCadCODIGO: TIntegerField
DisplayLabel = 'C'#243'd.Cliente'
FieldName = 'CODIGO'
Required = True
end
object qryCadPESSOAFISICA: TStringField
FieldName = 'PESSOAFISICA'
Required = True
FixedChar = True
Size = 1
end
object qryCadRAZAOSOCIAL: TStringField
FieldName = 'RAZAOSOCIAL'
FixedChar = True
Size = 50
end
object qryCadNOME: TStringField
DisplayLabel = 'Nome'
FieldName = 'NOME'
Required = True
FixedChar = True
Size = 40
end
object qryCadDATANASC: TDateTimeField
DisplayLabel = 'Data Nasc.'
FieldName = 'DATANASC'
end
object qryCadNATURALIDADE: TStringField
FieldName = 'NATURALIDADE'
FixedChar = True
Size = 40
end
object qryCadSEXO: TStringField
FieldName = 'SEXO'
FixedChar = True
end
object qryCadESTADOCIVIL: TStringField
FieldName = 'ESTADOCIVIL'
FixedChar = True
end
object qryCadRG: TStringField
FieldName = 'RG'
FixedChar = True
end
object qryCadCPF: TStringField
FieldName = 'CPF'
FixedChar = True
end
object qryCadCGC: TStringField
FieldName = 'CGC'
FixedChar = True
end
object qryCadIE: TStringField
FieldName = 'IE'
FixedChar = True
end
object qryCadPAI: TStringField
FieldName = 'PAI'
FixedChar = True
Size = 40
end
object qryCadMAE: TStringField
FieldName = 'MAE'
FixedChar = True
Size = 40
end
object qryCadLOGRADOURO: TStringField
FieldName = 'LOGRADOURO'
FixedChar = True
Size = 60
end
object qryCadNUMERO: TIntegerField
FieldName = 'NUMERO'
end
object qryCadCOMPLEMENTO: TStringField
FieldName = 'COMPLEMENTO'
FixedChar = True
Size = 40
end
object qryCadBAIRRO: TStringField
FieldName = 'BAIRRO'
FixedChar = True
Size = 60
end
object qryCadCIDADE: TStringField
FieldName = 'CIDADE'
FixedChar = True
Size = 60
end
object qryCadESTADO: TStringField
FieldName = 'ESTADO'
Required = True
FixedChar = True
Size = 2
end
object qryCadCEP: TStringField
FieldName = 'CEP'
FixedChar = True
Size = 10
end
object qryCadMUNIBGE: TStringField
FieldName = 'MUNIBGE'
FixedChar = True
Size = 10
end
object qryCadFONE: TStringField
DisplayLabel = 'Telefone'
FieldName = 'FONE'
FixedChar = True
end
object qryCadFAX: TStringField
FieldName = 'FAX'
FixedChar = True
end
object qryCadEMAIL: TStringField
FieldName = 'EMAIL'
FixedChar = True
Size = 50
end
object qryCadHOMEPAGE: TStringField
FieldName = 'HOMEPAGE'
FixedChar = True
Size = 60
end
object qryCadCELULAR: TStringField
FieldName = 'CELULAR'
FixedChar = True
end
object qryCadDATACADAST: TDateTimeField
FieldName = 'DATACADAST'
Required = True
end
object qryCadOBSERVACOES: TStringField
FieldName = 'OBSERVACOES'
Size = 2048
end
object qryCadCONTATO: TStringField
FieldName = 'CONTATO'
FixedChar = True
Size = 40
end
object qryCadDATAFUND: TDateTimeField
FieldName = 'DATAFUND'
end
object qryCadPROFISSAO: TStringField
FieldName = 'PROFISSAO'
FixedChar = True
Size = 30
end
object qryCadEQUIPAMENTO: TStringField
FieldName = 'EQUIPAMENTO'
Size = 1024
end
object qryCadSALARIO: TFloatField
FieldName = 'SALARIO'
end
object qryCadORGAOEXP: TStringField
FieldName = 'ORGAOEXP'
FixedChar = True
Size = 6
end
object qryCadSOUNDBYTES: TIntegerField
FieldName = 'SOUNDBYTES'
Required = True
end
object qryCadPROTESTO: TStringField
FieldName = 'PROTESTO'
Required = True
FixedChar = True
Size = 1
end
object qryCadSPC: TStringField
FieldName = 'SPC'
Required = True
FixedChar = True
Size = 1
end
object qryCadSERASA: TStringField
FieldName = 'SERASA'
Required = True
FixedChar = True
Size = 1
end
object qryCadIMOVEL: TStringField
FieldName = 'IMOVEL'
Required = True
FixedChar = True
Size = 1
end
object qryCadPROTESTO_DATA: TDateTimeField
FieldName = 'PROTESTO_DATA'
end
object qryCadSPC_DATA: TDateTimeField
FieldName = 'SPC_DATA'
end
object qryCadSERASA_DATA: TDateTimeField
FieldName = 'SERASA_DATA'
end
object qryCadPROTESTO_USER: TStringField
FieldName = 'PROTESTO_USER'
FixedChar = True
end
object qryCadSPC_USER: TStringField
FieldName = 'SPC_USER'
FixedChar = True
end
object qryCadSERASA_USER: TStringField
FieldName = 'SERASA_USER'
FixedChar = True
end
object qryCadIMOVEL_TIPO: TStringField
FieldName = 'IMOVEL_TIPO'
FixedChar = True
end
object qryCadCODEMPREEND: TIntegerField
FieldName = 'CODEMPREEND'
end
object qryCadPROCESSO_OK: TStringField
FieldName = 'PROCESSO_OK'
Required = True
FixedChar = True
Size = 1
end
object qryCadFGTS: TStringField
FieldName = 'FGTS'
Required = True
FixedChar = True
Size = 1
end
object qryCadPIS: TStringField
FieldName = 'PIS'
FixedChar = True
end
object qryCadVALOR_FGTS: TFloatField
FieldName = 'VALOR_FGTS'
end
object qryCadCONTRATO: TStringField
FieldName = 'CONTRATO'
Required = True
FixedChar = True
Size = 1
end
object qryCadKMS: TIntegerField
FieldName = 'KMS'
end
object qryCadCOMISSIONADO: TStringField
FieldName = 'COMISSIONADO'
Required = True
FixedChar = True
Size = 1
end
object qryCadNOMEUSER: TStringField
FieldName = 'NOMEUSER'
Required = True
FixedChar = True
Size = 30
end
object qryCadDESCONTO: TFloatField
FieldName = 'DESCONTO'
end
object qryCadFINANCEIRO: TStringField
FieldName = 'FINANCEIRO'
Required = True
FixedChar = True
Size = 1
end
object qryCadESTORNO: TStringField
FieldName = 'ESTORNO'
Required = True
FixedChar = True
Size = 1
end
object qryCadCODEMPRESA: TIntegerField
FieldName = 'CODEMPRESA'
Required = True
end
object qryCadTROCAVENDEDOR: TStringField
FieldName = 'TROCAVENDEDOR'
Required = True
FixedChar = True
Size = 1
end
object qryCadINTERNET: TStringField
FieldName = 'INTERNET'
Required = True
FixedChar = True
Size = 1
end
object qryCadMUDAEMPRESA: TStringField
FieldName = 'MUDAEMPRESA'
Required = True
FixedChar = True
Size = 1
end
object qryCadCOMISSAO: TFloatField
FieldName = 'COMISSAO'
end
object qryCadTIPO: TStringField
FieldName = 'TIPO'
Required = True
FixedChar = True
Size = 1
end
object qryCadCODFORNECEDOR: TIntegerField
FieldName = 'CODFORNECEDOR'
end
object qryCadCODTRANSPORTADOR: TIntegerField
FieldName = 'CODTRANSPORTADOR'
end
object qryCadCODASSOCIADO: TIntegerField
FieldName = 'CODASSOCIADO'
end
object qryCadNOME_FAMILIA: TStringField
FieldName = 'NOME_FAMILIA'
FixedChar = True
Size = 50
end
object qryCadRECEBIMENTO: TStringField
FieldName = 'RECEBIMENTO'
Required = True
FixedChar = True
Size = 1
end
object qryCadCUSTO: TStringField
FieldName = 'CUSTO'
Required = True
FixedChar = True
Size = 1
end
object qryCadSEQUENCIAS: TStringField
FieldName = 'SEQUENCIAS'
Required = True
FixedChar = True
Size = 1
end
object qryCadRECALCULO: TStringField
FieldName = 'RECALCULO'
Required = True
FixedChar = True
Size = 1
end
object qryCadCOMPRAS: TStringField
FieldName = 'COMPRAS'
Required = True
FixedChar = True
Size = 1
end
object qryCadTRANSFERENCIA: TStringField
FieldName = 'TRANSFERENCIA'
Required = True
FixedChar = True
Size = 1
end
object qryCadRELATORIOS: TStringField
FieldName = 'RELATORIOS'
Required = True
FixedChar = True
Size = 1
end
object qryCadLIMITECREDITO: TFloatField
FieldName = 'LIMITECREDITO'
end
object qryCadTIPO_BLOQUEIO: TStringField
FieldName = 'TIPO_BLOQUEIO'
Required = True
FixedChar = True
Size = 1
end
object qryCadTIPO_IMPEDIMENTO: TStringField
FieldName = 'TIPO_IMPEDIMENTO'
Required = True
FixedChar = True
Size = 1
end
object qryCadOCULTO: TStringField
FieldName = 'OCULTO'
Required = True
FixedChar = True
Size = 1
end
object qryCadVENDADIRETA: TStringField
FieldName = 'VENDADIRETA'
Required = True
FixedChar = True
Size = 1
end
object qryCadTECNICOLOGIN: TStringField
FieldName = 'TECNICOLOGIN'
Required = True
FixedChar = True
Size = 1
end
object qryCadFECHAMENTO: TStringField
FieldName = 'FECHAMENTO'
Required = True
FixedChar = True
Size = 1
end
object qryCadLOG_USUARIO: TStringField
FieldName = 'LOG_USUARIO'
FixedChar = True
Size = 30
end
object qryCadLOG_TIPO: TStringField
FieldName = 'LOG_TIPO'
FixedChar = True
Size = 10
end
object qryCadLOG_MAQUINA: TStringField
FieldName = 'LOG_MAQUINA'
FixedChar = True
Size = 30
end
object qryCadLOG_DATAREMOTO: TDateTimeField
FieldName = 'LOG_DATAREMOTO'
end
object qryCadSENHAWEB: TStringField
FieldName = 'SENHAWEB'
FixedChar = True
Size = 10
end
object qryCadPERCCOMIS_PROD: TFloatField
FieldName = 'PERCCOMIS_PROD'
end
object qryCadPERCCOMIS_PECA: TFloatField
FieldName = 'PERCCOMIS_PECA'
end
object qryCadPERCCOMIS_SERV: TFloatField
FieldName = 'PERCCOMIS_SERV'
end
object qryCadPERCCOMIS_CALCULO: TStringField
FieldName = 'PERCCOMIS_CALCULO'
Required = True
FixedChar = True
Size = 1
end
object qryCadCODLINHA: TIntegerField
FieldName = 'CODLINHA'
end
object qryCadCODCENTRO: TIntegerField
FieldName = 'CODCENTRO'
end
object qryCadCODPLANO: TIntegerField
FieldName = 'CODPLANO'
end
object qryCadCALC_BASEICMS: TStringField
FieldName = 'CALC_BASEICMS'
Required = True
FixedChar = True
Size = 1
end
object qryCadCAIXA: TStringField
FieldName = 'CAIXA'
Required = True
FixedChar = True
Size = 1
end
object qryCadOCULTOS: TStringField
FieldName = 'OCULTOS'
Required = True
FixedChar = True
Size = 1
end
object qryCadANALISES: TStringField
FieldName = 'ANALISES'
Required = True
FixedChar = True
Size = 1
end
object qryCadLOGS: TStringField
FieldName = 'LOGS'
Required = True
FixedChar = True
Size = 1
end
object qryCadENTREGA1: TStringField
FieldName = 'ENTREGA1'
FixedChar = True
Size = 60
end
object qryCadENTREGA2: TStringField
FieldName = 'ENTREGA2'
FixedChar = True
Size = 60
end
object qryCadRESIDENCIA_TEMPO: TStringField
FieldName = 'RESIDENCIA_TEMPO'
FixedChar = True
end
object qryCadALUGUEL: TStringField
FieldName = 'ALUGUEL'
Required = True
FixedChar = True
Size = 1
end
object qryCadALUGUEL_VALOR: TFloatField
FieldName = 'ALUGUEL_VALOR'
end
object qryCadTRAB_SALARIO: TFloatField
FieldName = 'TRAB_SALARIO'
end
object qryCadCONJ_SALARIO: TFloatField
FieldName = 'CONJ_SALARIO'
end
object qryCadTRAB_EMPRESA: TStringField
FieldName = 'TRAB_EMPRESA'
FixedChar = True
Size = 60
end
object qryCadTRAB_ADMISSAO: TDateField
FieldName = 'TRAB_ADMISSAO'
end
object qryCadTRAB_ENDERECO: TStringField
FieldName = 'TRAB_ENDERECO'
FixedChar = True
Size = 60
end
object qryCadTRAB_CIDADE: TStringField
FieldName = 'TRAB_CIDADE'
FixedChar = True
Size = 40
end
object qryCadTRAB_FONE: TStringField
FieldName = 'TRAB_FONE'
FixedChar = True
end
object qryCadTRAB_CARGO: TStringField
FieldName = 'TRAB_CARGO'
FixedChar = True
end
object qryCadCONJ_NOME: TStringField
FieldName = 'CONJ_NOME'
FixedChar = True
Size = 60
end
object qryCadCONJ_DATANASC: TDateField
FieldName = 'CONJ_DATANASC'
end
object qryCadCONJ_RG: TStringField
FieldName = 'CONJ_RG'
FixedChar = True
Size = 30
end
object qryCadCONJ_CPF: TStringField
FieldName = 'CONJ_CPF'
FixedChar = True
end
object qryCadCONJ_CARTEIRA: TStringField
FieldName = 'CONJ_CARTEIRA'
FixedChar = True
end
object qryCadCONJ_EMPRESA: TStringField
FieldName = 'CONJ_EMPRESA'
FixedChar = True
Size = 60
end
object qryCadCONJ_ADMISSAO: TDateField
FieldName = 'CONJ_ADMISSAO'
end
object qryCadCONJ_CARGO: TStringField
FieldName = 'CONJ_CARGO'
FixedChar = True
end
object qryCadCONJ_ENDERECO: TStringField
FieldName = 'CONJ_ENDERECO'
FixedChar = True
Size = 60
end
object qryCadCONJ_FONE: TStringField
FieldName = 'CONJ_FONE'
FixedChar = True
end
object qryCadCARTEIRA: TStringField
FieldName = 'CARTEIRA'
FixedChar = True
end
object qryCadREFERENCIA1: TStringField
FieldName = 'REFERENCIA1'
FixedChar = True
Size = 60
end
object qryCadREFERENCIA2: TStringField
FieldName = 'REFERENCIA2'
FixedChar = True
Size = 60
end
object qryCadREFERENCIA3: TStringField
FieldName = 'REFERENCIA3'
FixedChar = True
Size = 60
end
object qryCadVALOR_CONTRATO: TFloatField
FieldName = 'VALOR_CONTRATO'
end
object qryCadIM: TStringField
FieldName = 'IM'
FixedChar = True
end
object qryCadCNAE: TStringField
FieldName = 'CNAE'
FixedChar = True
Size = 10
end
end
end
|
unit ExtensionTypeManager;
interface
uses sysUtils,
Extensions,
ExtensionTypes,
RegExpressions;
type TExtensionTypeManager = class
private
fExtensions : TExtensions;
fExtensionTypes : TExtensionTypes;
fRegExpressions : TRegExpression;
fExceptAndIncludeExpr : TRegExpression;
public
constructor Create();
destructor Destroy; override;
procedure AddExtensionType(ExtType : String);
procedure AddExtension(Ext : String; ExtType : String);
function GetExtensionType (S : String) : String;
function IsPathExcluded(Gname : String; Path: string) : Boolean;
procedure DumpExtensions();
procedure AddIncExclPathRegExp(RegExpLabel : String; ExtRegExp : String);
property Extensions: TExtensions read FExtensions;
property ExtensionTypes: TExtensionTypes read FExtensionTypes;
property RegExpressions: TRegExpression read FRegExpressions write FRegExpressions;
property ExceptAndIncludeExpr: TRegExpression read fExceptAndIncludeExpr write fExceptAndIncludeExpr;
end;
EExtensionsTypeNotSet = class(Exception);
EExtensionsExceptRuleExists = class(Exception);
EExtensionsIsNotRegExp = class(Exception);
implementation
uses
InternalTypes;
constructor TExtensionTypeManager.Create();
begin
fExtensions := TExtensions.Create();
fExtensionTypes := TExtensionTypes.Create();
fRegExpressions := TRegExpression.Create();
fExceptAndIncludeExpr := TRegExpression.Create();
fExceptAndIncludeExpr.Sorted := False;
end;
destructor TExtensionTypeManager.Destroy;
begin
fExtensions.free;
fExtensionTypes.free;
fRegExpressions.free;
fExceptAndIncludeExpr.free;
inherited Destroy;
end;
function TExtensionTypeManager.GetExtensionType (S : String) : String;
var Ext : string;
var i : integer;
begin
Ext := ExtractFileExt(S);
Result := Extensions.ExtensionType[Ext];
if Result='' then
begin
for i:= 0 to pred(RegExpressions.count) do
begin
// Writeln(i,': fic:',S,'/',RegExpressions.names[i],' - ',RegExpressions.TypeExtension[i]);
Result := GetExtensionTypeFromRegExp(RegExpressions.names[i],S,RegExpressions.TypeExtension[i]);
if Result <> '' then
begin
// writeln('TROUVE ! donne ', Result);
break;
end;
end;
end ;
if (Result='') and (Length(Ext)>4) then
begin
// Writeln('fic:',S);
// writeln('Extension longue (' + IntToStr(Length(Ext))+ ') et pas de RegularExpression : [' + Ext + ']');
end;
end;
procedure TExtensionTypeManager.AddExtensionType(ExtType : String);
begin
ExtensionTypes.AddUnique(ExtType);
end;
procedure TExtensionTypeManager.AddIncExclPathRegExp(RegExpLabel : String; ExtRegExp : String);
begin
// writeln(RegExpLabel+' ajoute à la liste avec RegExp '+ExtRegExp+', IndexOf:'+IntToStr(ExceptAndIncludeExpr.Indexof(RegExpLabel)));
if ExceptAndIncludeExpr.Indexof(RegExpLabel)=-1 then
begin
if RegularExpression(ExtRegExp) then
begin
Writeln('ajoute ExceptInclude ExpReg ',ExtRegExp);
ExceptAndIncludeExpr.addRegExpression(RegExpLabel,ExtRegExp);
end
else
raise EExtensionsIsNotRegExp.create('['+RegExpLabel+'] ExceptInclude rule is not RegExp : '+ExtRegExp);
end
else
raise EExtensionsExceptRuleExists.create('['+RegExpLabel+'] ExceptInclude rule already set.');
end;
function TExtensionTypeManager.IsPathExcluded(GName : String; Path: string) : Boolean;
var i : Integer;
var Exclude, Found : Boolean;
var DumpIt : Boolean;
begin
Result := false;
DumpIt := false;
for i := 0 to pred(ExceptAndIncludeExpr.count) do
with ExceptAndIncludeExpr do
begin
Exclude := Names[i][1] = '-';
Found := GetExtensionTypeFromRegExp(ValueFromIndex[i],Path,GName)<>'';
// DumpIt := DumpIt or Found;
If Found then
Result := Exclude;
// Writeln(ValueFromIndex[i]:60,cTrueFalse[Found]:8, cTrueFalse[Exclude]:8);
end;
if DumpIt then
begin
Writeln(Path:60 , 'Found':8, 'Exclude':8);
for i := 0 to pred(ExceptAndIncludeExpr.count) do
with ExceptAndIncludeExpr do
begin
Exclude := Names[i][1] = '-';
Found := GetExtensionTypeFromRegExp(ValueFromIndex[i],Path,Gname)<>'';
Writeln(ValueFromIndex[i]:60,cTrueFalse[Found]:8, cTrueFalse[Exclude]:8);
end
end;
end;
procedure TExtensionTypeManager.AddExtension(Ext : String; ExtType : String);
begin
if ExtensionTypes.Indexof(ExtType)<>-1 then
begin
if RegularExpression(Ext) then
begin
// Writeln('ajoute ExpReg ',Ext,' sur ',ExtType);
RegExpressions.addRegExpression(Ext,ExtType);
end
else
Extensions.AddExtensionType(Ext,ExtType);
end
else
raise EExtensionsTypeNotSet.create('['+ExtType+'] not set.');
end;
procedure TExtensionTypeManager.DumpExtensions();
var i : Integer;
begin
Writeln;
Writeln('Value:':25 , '':3, 'Name:':25);
for i := 0 to pred(Extensions.count) do
with Extensions do
Writeln(ValueFromIndex[i]:25,' = ':3, Names[i]:25);
end;
end.
|
unit uServer;
interface
uses System.Classes, uSharedMemoryPoint;
type
TSharedMemoryServer = class(TSharedMemoryPoint)
private
type
TServerThread = class(TThread)
private
type
TServerThreadEvent = procedure of object;
var
OnReceive_,
OnCallback_ : TServerThreadEvent;
public
constructor Create(OnReceive, OnCallback: TServerThreadEvent);
procedure Execute(); override;
end;
var
Thread: TServerThread;
hRead,
hWrite: THandle;
Callback_: TSharedMemoryServer.TProcessCallBack;
DirName_,
Msg: String;
FileName: WideString;
PrevPercents,
Percents,
Attempts: Integer;
IsError,
IsReception: Boolean;
ReceptionSize,
FileSize: Int64;
Stream: TFileStream;
function GetTempFileName(): String;
procedure ThreadReceive(); // Процедура получения данных
procedure ThreadCallBack(); // Процедура обратного вызова
procedure CompleteReceive(SaveFile: Boolean = True);
protected
procedure Start(Callback: TSharedMemoryServer.TProcessCallBack); override;
public
constructor Create(Callback: TSharedMemoryServer.TProcessCallBack);
destructor Destroy(); override;
procedure Terminated(); override;
property DirName: String read DirName_;
end;
implementation
uses Vcl.Forms, Winapi.Windows, System.SysUtils, System.StrUtils,
System.IniFiles, System.Math, uCommon;
constructor
TSharedMemoryServer.Create(Callback: TSharedMemoryServer.TProcessCallBack);
procedure LoadSettings();
var
Settings: TIniFile;
AppDirName: String;
begin
AppDirName := ExtractFilePath(Application.ExeName);
try
Settings := TIniFile.Create(Format('%s\server.ini', [AppDirName]));
try
DirName_ := Settings.ReadString('Server', 'DirName', AppDirName);
finally
FreeAndNil(Settings);
end;
except
end;
if DirName_ = '' then
DirName_ := AppDirName;
if not DirectoryExists(DirName_) then
raise Exception.Create(Format('Указанный путь (%s) не существует',
[DirName_]));
end;
begin
try
LoadSettings();
inherited Create();
Start(Callback);
except
on E: EGetSharedMemoryName do
raise Exception.Create('Не удалось подключиться к COM-серверу!');
on E: EExistSharedMemoryPoint do
raise Exception.Create(Format('Сервер для объекта "%s" уже запущен!',
[SharedMemoryName]));
on E: Exception do
raise Exception.Create(Format('Не удалось запустить сервер: "%s"!',
[E.Message]));
end;
end;
destructor TSharedMemoryServer.Destroy();
begin
if Assigned(Thread) then
begin
Thread.Terminate();
Thread.WaitFor();
FreeAndNil(Thread);
end;
if hWrite <> 0 then
CloseHandle(hWrite);
if hRead <> 0 then
CloseHandle(hRead);
CompleteReceive(False);
inherited Destroy();
end;
procedure TSharedMemoryServer.Terminated();
begin
if Assigned(Thread) then
Thread.Terminate();
end;
procedure
TSharedMemoryServer.Start(Callback: TSharedMemoryServer.TProcessCallBack);
begin
if Assigned(Callback) then
begin
CallBack_ := CallBack;
hRead := CreateEvent(NIL, False, False, PChar(Format('%s.read',
[SharedMemoryName])));
hWrite := CreateEvent(NIL, False, True, PChar(Format('%s.write',
[SharedMemoryName])));
Thread := TServerThread.Create(ThreadReceive, ThreadCallBack);
end;
end;
function TSharedMemoryServer.GetTempFileName(): String;
begin
Result := Format('%s\%s.temp', [DirName_, SharedMemoryName]);
end;
procedure TSharedMemoryServer.ThreadReceive();
procedure ReadMetaData();
var
Memory: TMemoryStream;
FileNameLength: Integer;
begin
Memory := TMemoryStream.Create();
try
Memory.WriteBuffer(DataPointer, POINT_DATA_SIZE);
Memory.Position := 0;
Memory.ReadBuffer(FileSize, SizeOf(FileSize));
Memory.ReadBuffer(FileNameLength, SizeOf(FileNameLength));
SetLength(FileName, FileNameLength);
Memory.ReadBuffer(FileName[1], FileNameLength*SizeOf(WideChar));
finally
FreeAndNil(Memory);
end;
end;
procedure ReadData();
var
Memory: TMemoryStream;
DataSize: Integer;
begin
if Assigned(Stream) then
begin
Memory := TMemoryStream.Create();
try
Memory.WriteBuffer(DataPointer, POINT_DATA_SIZE);
Memory.Position := 0;
Memory.ReadBuffer(DataSize, SizeOf(DataSize));
try
Stream.CopyFrom(Memory, DataSize);
except
on E: EWriteError do
raise Exception.Create('Не удалось сохранить данные!');
end;
Inc(ReceptionSize, DataSize);
finally
FreeAndNil(Memory);
end;
end;
end;
procedure CreateEmptyFile();
var
EmptyFile: TextFile;
begin
AssignFile(EmptyFile, GetTempFileName());
try
Rewrite(EmptyFile);
finally
Close(EmptyFile);
end;
end;
begin
try
case WaitForSingleObject(hRead, POINT_WAIT_TIMEOUT) of
WAIT_TIMEOUT:
begin
if IsReception then
begin
Inc(Attempts);
if Attempts >= POINT_ATTEPMTS_COUNT then
begin
CompleteReceive(False);
SetEvent(hWrite);
Msg := 'Клиент не доступен!';
end;
end;
end;
WAIT_OBJECT_0:
begin
if not IsReception then
begin
ReadMetaData();
if FileSize = 0 then
begin
CreateEmptyFile();
CompleteReceive();
Msg := Format('Принят файл нулевого размера' +
' (Сохранён как: "%s")', [FileName]);
end else
begin
IsReception := True;
Stream := TFileStream.Create(GetTempFileName(),
fmCreate or fmShareDenyNone);
Msg := Format('Начат прием файла (Файл: "%s", Размер: %s)',
[FileName, FileSizeToStr(FileSize)]);
end;
end else
begin
Attempts := 0;
ReadData();
if ReceptionSize = FileSize then
begin
CompleteReceive();
Msg := Format('Завершён прием файла (Сохранён как: "%s")',
[FileName]);
FileName := '';
end;
end;
SetEvent(hWrite);
end;
else
raise Exception.Create(SysErrorMessage(GetLastError()));
end;
except
on E: Exception do
begin
CompleteReceive(False);
Msg := E.Message;
IsError := True;
end;
end;
end;
procedure TSharedMemoryServer.ThreadCallBack();
begin
try
if FileSize <> 0 then
Percents := Floor(100*ReceptionSize/FileSize);
if (Msg <> '') or (PrevPercents <> Percents) then
begin
CallBack_(Msg, Percents, IsError);
PrevPercents := Percents;
end;
except
end;
Msg := '';
IsError := False;
end;
procedure TSharedMemoryServer.CompleteReceive(SaveFile: Boolean);
var
FileIndex: Integer;
FileNameToSave: String;
begin
PrevPercents := 0;
Percents := 0;
Attempts := 0;
IsReception := False;
ReceptionSize := 0;
FileSize := 0;
if Assigned(Stream) then
FreeAndNil(Stream);
if not SaveFile then
DeleteFile(GetTempFileName())
else
begin
FileIndex := 1;
FileNameToSave := FileName;
while FileExists(Format('%s\%s', [DirName_, FileNameToSave])) do
begin
FileNameToSave := Format('%s (%d)%s', [ChangeFileExt(FileName, ''),
FileIndex,
ExtractFileExt(FileName)]);
Inc(FileIndex)
end;
FileName := FileNameToSave;
if not RenameFile(Format('%s', [GetTempFileName()]),
Format('%s\%s', [DirName_, FileName])) then
raise Exception.Create('Не удалось переименовать файл!');
end;
end;
constructor TSharedMemoryServer.TServerThread.Create(OnReceive,
OnCallback: TServerThreadEvent);
begin
OnReceive_ := OnReceive;
OnCallBack_ := OnCallback;
inherited Create();
end;
procedure TSharedMemoryServer.TServerThread.Execute();
begin
while not Terminated do
begin
OnReceive_();
Synchronize(OnCallBack_);
end;
end;
end.
|
unit ufTarefa1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, uGeraSql_Controller;
type
TfTarefa1 = class(TForm)
memColunas: TMemo;
memTabelas: TMemo;
memCondicoes: TMemo;
btnGeraSql: TBitBtn;
memSqlGerado: TMemo;
lblColunas: TLabel;
lblTabelas: TLabel;
lblCondicoes: TLabel;
lblSqlGerado: TLabel;
btnLimpar: TBitBtn;
procedure btnGeraSqlClick(Sender: TObject);
procedure btnLimparClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
function geraSQL : TStringList;
procedure limparCampos;
public
{ Public declarations }
end;
var
fTarefa1: TfTarefa1;
implementation
{$R *.dfm}
procedure TfTarefa1.btnGeraSqlClick(Sender: TObject);
begin
memSqlGerado.Clear;
memSqlGerado.lines := geraSQL;
end;
procedure TfTarefa1.btnLimparClick(Sender: TObject);
begin
limparCampos;
end;
procedure TfTarefa1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
function TfTarefa1.geraSQL: TStringList;
var
g : TGeraSql;
begin
g := TGeraSql.Create;
try
g.SetColunas(memColunas);
g.SetTabela(memTabelas);
g.SetCondicoes(memCondicoes);
Result := g.GeraSQL;
finally
g.Destroy;
end;
end;
procedure TfTarefa1.limparCampos;
begin
memColunas.Clear;
memTabelas.Clear;
memCondicoes.Clear;
memSqlGerado.Clear;
end;
end.
|
PROGRAM Stat(INPUT, OUTPUT);
VAR
Number, Average, Min, Max, NumbersAmount, Sum: INTEGER;
OverFlow: BOOLEAN;
PROCEDURE ReadDigit(VAR InFile: TEXT; VAR Digit: INTEGER);
VAR
Ch: CHAR;
BEGIN{ReadDigit}
Digit := -1;
IF NOT EOLN(InFile)
THEN
BEGIN
READ(InFile ,Ch);
IF Ch = '0' THEN Digit := 0;
IF Ch = '1' THEN Digit := 1;
IF Ch = '2' THEN Digit := 2;
IF Ch = '3' THEN Digit := 3;
IF Ch = '4' THEN Digit := 4;
IF Ch = '5' THEN Digit := 5;
IF Ch = '6' THEN Digit := 6;
IF Ch = '7' THEN Digit := 7;
IF Ch = '8' THEN Digit := 8;
IF Ch = '9' THEN Digit := 9
END
END;{ReadDigit}
PROCEDURE ReadNumber(VAR InFile: TEXT; VAR Number: INTEGER);
VAR
Digit: INTEGER;
BEGIN{ReadNumber}
Number := 0;
ReadDigit(InFile, Digit);
WHILE (Digit <> -1 ) AND ( Number <> -1)
DO
BEGIN
IF (MAXINT DIV 10 < Number) OR (MAXINT DIV 10 = Number) AND (MAXINT MOD 10 < Digit)
THEN
Number := -1
ELSE
BEGIN
Number := Number * 10;
Number := Number + Digit
END;
ReadDigit(InFile, Digit)
END;
END;{ReadNumber}
BEGIN{Stat}
ReadNumber(INPUT, Number);
IF Number <> -1
THEN
BEGIN
Sum := Number;
Min := Number;
Max := Number;
OverFlow := FALSE;
NumbersAmount := 1;
WHILE (NOT EOF(INPUT)) AND (OverFlow = FALSE)
DO
BEGIN
ReadNumber(INPUT, Number);
IF (Number <= (MAXINT - Sum)) AND (Number <> -1)
THEN
BEGIN
Sum := Sum + Number;
NumbersAmount := NumbersAmount + 1;
IF Number < Min
THEN
Min := Number;
IF Number > Max
THEN
Max := Number
END
ELSE
OverFlow := TRUE
END;
IF NOT OverFlow
THEN
BEGIN
IF NumbersAmount <> 0
THEN
BEGIN
WRITELN('Min: ', Min);
WRITELN('Max: ', Max);
WRITE('Average: ');
WRITELN(Sum DIV NumbersAmount, '.', Sum MOD NumbersAmount * 100 DIV NumbersAmount)
END
ELSE
WRITELN('Empty File');
END
ELSE
WRITELN('Overflow')
END
ELSE
WRITELN('Overflow')
END.{Stat}
|
unit LoginatorUnit;
interface
uses SysUtils;
type
TLoginator = class(TObject)
private
target_file : string;
handle : TextFile;
protected
public
constructor Create(file_name:string);
destructor Destroy; override;
procedure Log(logline:string);
published
property FileName : string
read target_file;
end;
implementation
constructor TLoginator.Create(file_name:string);
begin
file_name := file_name + '.log';
self.target_file := file_name;
AssignFile(handle, file_name);
if FileExists(file_name) then
Append(handle)
else
ReWrite(handle);
end;
procedure TLoginator.Log(logline:string);
var tab:char;
begin
tab := chr(9);
WriteLn(self.handle, FormatDateTime('ddddd hh:mm:ss.zzz',Now) + tab + tab + logline);
Flush(self.handle);
end;
destructor TLoginator.Destroy;
begin
CloseFile(self.handle);
end;
end.
|
unit TypePrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh,
DB, ComCtrls, ToolWin;
type
TTypePriceForm = class(TForm)
Panel1: TPanel;
CancelButton: TButton;
OKButton: TButton;
DBGridEh1: TDBGridEh;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
InsertButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure InsertButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
TypePriceForm: TTypePriceForm;
implementation
uses StoreDM, TypePriceItem;
{$R *.dfm}
procedure TTypePriceForm.FormCreate(Sender: TObject);
begin
StoreDataModule.TypePriceDataSet.Locate('PriceID', StoreDataModule.PriceDataSet['PriceID'], []);
Caption := 'Справочник Типов Цен';
end;
procedure TTypePriceForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrOk then
begin
CurPriceID := StoreDataModule.TypePriceDataSet['PriceID'];
CurPriceName := StoreDataModule.TypePriceDataSet['PriceName'];
CurPriceMarkup := StoreDataModule.TypePriceDataSet['Markup'];
end;
with StoreDataModule.TypePriceDataSet do
begin
Close;
SelectSQL.Strings[3] := '';
Open;
end;
Release;
end;
procedure TTypePriceForm.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TTypePriceForm.OKButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TTypePriceForm.Edit1Change(Sender: TObject);
var
Find : String;
begin
Find := AnsiUpperCase(Edit1.Text);
with StoreDataModule.TypePriceDataSet do
begin
Close;
SelectSQL.Strings[3] := 'AND UPPER("PriceName") LIKE ''%' + Find + '%''';
Open;
end;
// StoreDataModule.CustomerSelectQuery.Locate('CustomerName', Edit1.Text, [loCaseInsensitive, loPartialKey]);
end;
procedure TTypePriceForm.InsertButtonClick(Sender: TObject);
begin
StoreDataModule.TypePriceDataSet.Append;
TypePriceItemForm := TTypePriceItemForm.Create(Self);
TypePriceItemForm.ShowModal;
end;
procedure TTypePriceForm.EditButtonClick(Sender: TObject);
begin
StoreDataModule.TypePriceDataSet.Edit;
TypePriceItemForm := TTypePriceItemForm.Create(Self);
TypePriceItemForm.ShowModal;
end;
procedure TTypePriceForm.DeleteButtonClick(Sender: TObject);
var
PriceStr : String;
begin
PriceStr := StoreDataModule.TypePriceDataSet['PriceName'];
if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' +
PriceStr + '"?'),
'Удаление записи',
mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then
try
StoreDataModule.TypePriceDataSet.Delete;
except
Application.MessageBox(PChar('Запись "' + PriceStr + '" удалять нельзя.'),
'Ошибка удаления', mb_IconStop);
end;
end;
procedure TTypePriceForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_RETURN : OKButton.Click;
VK_F2 : InsertButton.Click;
VK_F3 : EditButton.Click;
VK_F8 : DeleteButton.Click;
VK_F4 : Edit1.SetFocus;
end;
end;
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeSelectList;
{$I TeeDefs.inc}
interface
uses {$IFDEF CLR}
Classes,
Borland.VCL.Controls,
Borland.VCL.Forms,
Borland.VCL.StdCtrls,
Borland.VCL.ExtCtrls,
Borland.VCL.Buttons,
{$ELSE}
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls,
{$ENDIF}
{$ENDIF}
TeeProcs;
type
TSelectListForm = class(TForm)
FromList: TListBox;
ToList: TListBox;
Panel1: TPanel;
BMoveUP: TSpeedButton;
BMoveDown: TSpeedButton;
Panel2: TPanel;
L22: TLabel;
L24: TLabel;
Panel3: TPanel;
BRightOne: TButton;
BRightAll: TButton;
BLeftOne: TButton;
BLeftAll: TButton;
procedure FormCreate(Sender: TObject);
procedure BMoveUPClick(Sender: TObject);
procedure ToListDblClick(Sender: TObject);
procedure FromListDblClick(Sender: TObject);
procedure BLeftAllClick(Sender: TObject);
procedure BRightAllClick(Sender: TObject);
procedure BLeftOneClick(Sender: TObject);
procedure BRightOneClick(Sender: TObject);
procedure ToListClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure Changed;
public
{ Public declarations }
OnChange : TNotifyEvent;
procedure EnableButtons;
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeePenDlg;
procedure TSelectListForm.FormCreate(Sender: TObject);
begin
Align:=alClient;
TeeLoadArrowBitmaps(BMoveUp.Glyph,BMoveDown.Glyph);
end;
procedure TSelectListForm.Changed;
begin
EnableButtons;
if Assigned(OnChange) then OnChange(Self);
end;
procedure TSelectListForm.BMoveUPClick(Sender: TObject);
var tmp : Integer;
tmp2 : Integer;
begin
if Sender=BMoveUp then tmp:=-1 else tmp:=1;
with ToList do
begin
tmp2:=ItemIndex;
Items.Exchange(ItemIndex,ItemIndex+tmp);
ItemIndex:=tmp2+tmp; { 5.03 }
end;
ToList.SetFocus;
Changed;
end;
procedure TSelectListForm.ToListDblClick(Sender: TObject);
begin
BLeftOneClick(Self);
end;
procedure TSelectListForm.FromListDblClick(Sender: TObject);
begin
BRightOneClick(Self);
ToList.ItemIndex:=ToList.Items.Count-1;
EnableButtons;
end;
procedure TSelectListForm.BLeftAllClick(Sender: TObject);
begin
MoveListAll(ToList.Items,FromList.Items);
Changed;
end;
procedure TSelectListForm.BRightAllClick(Sender: TObject);
begin
MoveListAll(FromList.Items,ToList.Items);
Changed;
end;
procedure TSelectListForm.BLeftOneClick(Sender: TObject);
begin
MoveList(ToList,FromList);
Changed;
end;
procedure TSelectListForm.BRightOneClick(Sender: TObject);
begin
MoveList(FromList,ToList);
Changed;
if FromList.Items.Count=0 then ToList.SetFocus;
end;
procedure TSelectListForm.ToListClick(Sender: TObject);
begin
EnableButtons;
end;
procedure TSelectListForm.EnableButtons;
begin
BRightOne.Enabled:=FromList.Items.Count>0;
BRightAll.Enabled:=BRightOne.Enabled;
BLeftOne.Enabled :=ToList.Items.Count>0;
BLeftAll.Enabled :=BLeftOne.Enabled;
BMoveUp.Enabled :=ToList.ItemIndex>0;
BMoveDown.Enabled:=(ToList.ItemIndex>-1) and (ToList.ItemIndex<ToList.Items.Count-1);
end;
procedure TSelectListForm.FormShow(Sender: TObject);
begin
EnableButtons;
if FromList.Items.Count>0 then FromList.SetFocus
else ToList.SetFocus;
end;
end.
|
unit AnalogQueryes;
interface
uses
CategoryParametersGroupUnit2, DBRecordHolder,
FireDAC.Comp.Client, QueryGroupUnit2, System.Classes,
UniqueParameterValuesQuery, Data.DB, System.Generics.Collections,
TableWithProgress, DSWrap;
type
TParameterValuesTableW = class(TDSWrap)
private
FID: TFieldWrap;
FValue: TFieldWrap;
FChecked: TFieldWrap;
FDefaultCheckedValues: string;
procedure CheckNearNumerical;
procedure CheckNearSubStr;
procedure FilterChecked;
public
constructor Create(AOwner: TComponent); override;
procedure AppendRec(const AID: Integer; const AValue: string);
procedure CheckDefault;
procedure CheckNear(AParameterKindID: Integer);
procedure CheckRecord(const AChecked: Boolean);
procedure CheckRecords(const AValues: string);
function GetCheckedValues(const ADelimiter: string;
const AQuote: Char): String;
procedure SetAsDefaultValues;
procedure UncheckAll;
property ID: TFieldWrap read FID;
property Value: TFieldWrap read FValue;
property Checked: TFieldWrap read FChecked;
property DefaultCheckedValues: string read FDefaultCheckedValues
write FDefaultCheckedValues;
end;
TParameterValuesTable = class(TTableWithProgress)
private
FW: TParameterValuesTableW;
public
constructor Create(AOwner: TComponent); override;
property W: TParameterValuesTableW read FW;
end;
TParamValues = class(TObject)
private
FParamSubParamID: Integer;
FParameterKindID: Integer;
FTable: TParameterValuesTable;
public
constructor Create(AParamSubParamID, AParameterKindID: Integer);
destructor Destroy; override;
property ParamSubParamID: Integer read FParamSubParamID;
property ParameterKindID: Integer read FParameterKindID
write FParameterKindID;
property Table: TParameterValuesTable read FTable;
end;
TParamValuesList = class(TList<TParamValues>)
public
function FindByParamSubParamID(AParamSubParamID: Integer): TParamValues;
end;
type
TAnalogGroup = class(TQueryGroup2)
private
FAllParameterFields: TDictionary<Integer, String>;
FCatParamsGroup: TCategoryParametersGroup2;
FFDMemTable: TFDMemTable;
FParamSubParamIDDic: TDictionary<String, Integer>;
FParamValuesList: TParamValuesList;
FProductCategoryID: Integer;
FqUniqueParameterValues: TQueryUniqueParameterValues;
FTempTableName: String;
FW: TDSWrap;
const
FFieldPrefix: string = 'Field';
{ Private declarations }
protected
property FDMemTable: TFDMemTable read FFDMemTable;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ApplyFilter;
procedure CheckDefault;
procedure CheckNear;
procedure Clear(AParamSubParamID: Integer);
function GetParamSubParamIDByFieldName(const AFieldName: String): Integer;
function Load(AProductCategoryID: Integer; ARecHolder: TRecordHolder;
AAllParameterFields: TDictionary<Integer, String>): Boolean;
procedure SetAsDefaultValues;
procedure UpdateParameterValues(AParamSubParamID: Integer);
property AllParameterFields: TDictionary<Integer, String>
read FAllParameterFields;
property CatParamsGroup: TCategoryParametersGroup2 read FCatParamsGroup;
property ParamValuesList: TParamValuesList read FParamValuesList;
property qUniqueParameterValues: TQueryUniqueParameterValues
read FqUniqueParameterValues;
property TempTableName: String read FTempTableName;
property W: TDSWrap read FW;
{ Public declarations }
end;
implementation
uses
ParameterKindEnum, System.SysUtils, SearchProductByParamValuesQuery,
System.Variants, NaturalSort, System.Math, System.StrUtils;
function TParamValuesList.FindByParamSubParamID(AParamSubParamID: Integer)
: TParamValues;
begin
for Result in Self do
begin
if Result.ParamSubParamID = AParamSubParamID then
Exit;
end;
Result := nil;
end;
constructor TParamValues.Create(AParamSubParamID, AParameterKindID: Integer);
begin
// Assert(not ACaption.IsEmpty);
Assert(AParamSubParamID > 0);
Assert(AParameterKindID >= Integer(Неиспользуется));
Assert(AParameterKindID <= Integer(Строковый_частичный));
FParamSubParamID := AParamSubParamID;
// FCaption := ACaption;
FParameterKindID := AParameterKindID;
FTable := TParameterValuesTable.Create(nil);
end;
destructor TParamValues.Destroy;
begin
FreeAndNil(FTable);
inherited;
end;
constructor TAnalogGroup.Create(AOwner: TComponent);
begin
inherited;
FCatParamsGroup := TCategoryParametersGroup2.Create(Self);
FqUniqueParameterValues := TQueryUniqueParameterValues.Create(Self);
FParamValuesList := TParamValuesList.Create;
FFDMemTable := TFDMemTable.Create(Self);
FAllParameterFields := TDictionary<Integer, String>.Create;
FParamSubParamIDDic := TDictionary<String, Integer>.Create;
FTempTableName := 'search_analog_temp_table';
FW := TDSWrap.Create(FDMemTable);
end;
destructor TAnalogGroup.Destroy;
begin
FreeAndNil(FAllParameterFields);
FreeAndNil(FParamValuesList);
FreeAndNil(FParamSubParamIDDic);
inherited;
end;
procedure TAnalogGroup.ApplyFilter;
var
ACheckedValues: String;
AParamValues: TParamValues;
ASQL: string;
Q: TqSearchProductByParamValues;
S: string;
begin
ASQL := '';
Q := TqSearchProductByParamValues.Create(nil);
// Цикл по всем отфильтрованным значениям параметров
for AParamValues in ParamValuesList do
begin
ACheckedValues := AParamValues.Table.W.GetCheckedValues(',', '''');
// Если по этому параметру не надо фильтровать
if ACheckedValues.IsEmpty then
Continue;
S := Q.GetSQL(AParamValues.ParamSubParamID,
AParamValues.Table.W.GetCheckedValues(',', ''''));
if not ASQL.IsEmpty then
ASQL := ASQL + #13#10'intersect'#13#10;
ASQL := ASQL + S;
end;
Assert(not FTempTableName.IsEmpty);
// Сначала пытаемся удалить все записи
Q.FDQuery.Connection.ExecSQL(Format('DELETE FROM %s', [FTempTableName]));
Q.FDQuery.Connection.Commit;
// Если хоть один фильтр надо наложить
if not ASQL.IsEmpty then
begin
Q.FDQuery.SQL.Text := Format('INSERT INTO %s '#13#10'%s',
[FTempTableName, ASQL]);
Q.Execute(FProductCategoryID);
Q.FDQuery.Connection.Commit;
end;
// Заполняем таблицу аналогов семейств
Q.FDQuery.Connection.ExecSQL('DELETE FROM FamilyAnalog');
Q.FDQuery.Connection.ExecSQL
(Format('INSERT INTO FamilyAnalog SELECT DISTINCT FamilyID FROM %s',
[FTempTableName]));
Q.FDQuery.Connection.Commit;
// Заполняем таблицу аналогов компонент
Q.FDQuery.Connection.ExecSQL('DELETE FROM ProductsAnalog');
Q.FDQuery.Connection.ExecSQL
(Format('INSERT INTO ProductsAnalog SELECT DISTINCT ProductID FROM %s',
[FTempTableName]));
Q.FDQuery.Connection.Commit;
end;
procedure TAnalogGroup.CheckDefault;
var
AParamValues: TParamValues;
begin
// Цикл по всем значениям параметров
for AParamValues in ParamValuesList do
begin
AParamValues.Table.W.CheckDefault;
UpdateParameterValues(AParamValues.ParamSubParamID);
end;
end;
procedure TAnalogGroup.CheckNear;
var
AParamValues: TParamValues;
begin
// Цикл по всем значениям параметров
for AParamValues in ParamValuesList do
begin
AParamValues.Table.W.CheckNear(AParamValues.ParameterKindID);
UpdateParameterValues(AParamValues.ParamSubParamID);
end;
end;
procedure TAnalogGroup.Clear(AParamSubParamID: Integer);
var
AParamValues: TParamValues;
begin
Assert(AParamSubParamID > 0);
AParamValues := ParamValuesList.FindByParamSubParamID(AParamSubParamID);
Assert(AParamValues <> nil);
AParamValues.Table.W.UncheckAll;
Assert(AllParameterFields.ContainsKey(AParamSubParamID));
FDMemTable.Edit;
FDMemTable.FieldByName(AllParameterFields[AParamSubParamID]).Value := null;
FDMemTable.Post;
end;
function TAnalogGroup.GetParamSubParamIDByFieldName(const AFieldName
: String): Integer;
begin
Assert(not AFieldName.IsEmpty);
Assert(FParamSubParamIDDic.ContainsKey(AFieldName));
Result := FParamSubParamIDDic[AFieldName];
end;
function TAnalogGroup.Load(AProductCategoryID: Integer;
ARecHolder: TRecordHolder;
AAllParameterFields: TDictionary<Integer, String>): Boolean;
var
AFieldList: TList<String>;
AFieldName: string;
AIDParameterKind: Integer;
AParamSubParamID: Integer;
AParamValues: TParamValues;
ASortList: TList<String>;
F: TField;
i: Integer;
S: string;
begin
Result := False;
Assert(ARecHolder <> nil);
FAllParameterFields.Clear;
FParamSubParamIDDic.Clear;
FProductCategoryID := AProductCategoryID;
AFieldList := TList<String>.Create;
ASortList := TList<String>.Create;
try
// Ищем параметры используемые для поиска аналога
CatParamsGroup.qCategoryParameters.SearchAnalog(AProductCategoryID);
CatParamsGroup.qCategoryParameters.FDQuery.First;
while not CatParamsGroup.qCategoryParameters.FDQuery.Eof do
begin
AParamSubParamID := CatParamsGroup.qCategoryParameters.W.ParamSubParamID.
F.AsInteger;
AIDParameterKind := CatParamsGroup.qCategoryParameters.W.IDParameterKind.
F.AsInteger;
// Имя поля в таблице определяющей выбранные значения для поиска аналога
Assert(AAllParameterFields.ContainsKey(AParamSubParamID));
AFieldName := AAllParameterFields[AParamSubParamID];
// Добавляем очередное поле
AFieldList.Add(AFieldName);
// Заполняем словари id->поле и поле->id
FAllParameterFields.Add(AParamSubParamID, AFieldName);
FParamSubParamIDDic.Add(AFieldName, AParamSubParamID);
// Создаём список значений параметра
AParamValues := TParamValues.Create(AParamSubParamID, AIDParameterKind);
// Выбираем значения из БД
FqUniqueParameterValues.SearchEx(AProductCategoryID, AParamSubParamID);
ASortList.Clear;
while not FqUniqueParameterValues.FDQuery.Eof do
begin
ASortList.Add(FqUniqueParameterValues.W.Value.F.AsString);
FqUniqueParameterValues.FDQuery.Next;
end;
// Сортируем
ASortList.Sort(TNaturalStringComparer.Create);
for i := 0 to ASortList.Count - 1 do
begin
AParamValues.Table.W.AppendRec(i, ASortList[i]);
end;
ParamValuesList.Add(AParamValues);
CatParamsGroup.qCategoryParameters.FDQuery.Next;
end;
// Если не найдено ни одного поля, по которому можно искать аналог
if AFieldList.Count = 0 then
Exit;
FFDMemTable.Close;
FFDMemTable.FieldDefs.Clear;
FFDMemTable.Name := 'asdsad';
// Создаём набор данныых в памяти
for S in AFieldList do
begin
FFDMemTable.FieldDefs.Add(S, ftString, 200);
end;
FDMemTable.CreateDataSet;
// Добавляем в него одну запись
FDMemTable.Append;
for i := 0 to ARecHolder.Count - 1 do
begin
F := FDMemTable.FindField(ARecHolder.Items[i].FieldName);
if F = nil then
Continue;
F.Value := ARecHolder.Items[i].Value;
AParamSubParamID := GetParamSubParamIDByFieldName(F.FieldName);
AParamValues := ParamValuesList.FindByParamSubParamID(AParamSubParamID);
AParamValues.Table.W.CheckRecords(F.Value);
// Запоминаем эти значения для поиска полного аналога
AParamValues.Table.W.DefaultCheckedValues := F.Value;
end;
FDMemTable.Post;
Result := True;
finally
FreeAndNil(ASortList);
FreeAndNil(AFieldList);
end;
end;
procedure TAnalogGroup.SetAsDefaultValues;
var
AParamValues: TParamValues;
begin
// Цикл по всем значениям параметров
for AParamValues in ParamValuesList do
begin
AParamValues.Table.W.SetAsDefaultValues;
end;
end;
procedure TAnalogGroup.UpdateParameterValues(AParamSubParamID: Integer);
var
AParamValues: TParamValues;
AValues: String;
begin
Assert(AParamSubParamID > 0);
AParamValues := ParamValuesList.FindByParamSubParamID(AParamSubParamID);
Assert(AParamValues <> nil);
AValues := AParamValues.Table.W.GetCheckedValues(#13#10, #0);
Assert(AllParameterFields.ContainsKey(AParamSubParamID));
FDMemTable.Edit;
FDMemTable.FieldByName(AllParameterFields[AParamSubParamID]).Value := AValues;
FDMemTable.Post;
end;
constructor TParameterValuesTable.Create(AOwner: TComponent);
begin
inherited;
FW := TParameterValuesTableW.Create(Self);
FieldDefs.Add(W.ID.FieldName, ftInteger, 0, True);
FieldDefs.Add(W.Checked.FieldName, ftInteger, 0, True);
FieldDefs.Add(W.Value.FieldName, ftWideString, 200, True);
CreateDataSet;
end;
constructor TParameterValuesTableW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FValue := TFieldWrap.Create(Self, 'Value', 'Значение');
FChecked := TFieldWrap.Create(Self, 'Checked', 'X');
end;
procedure TParameterValuesTableW.AppendRec(const AID: Integer;
const AValue: string);
begin
Assert(not AValue.IsEmpty);
TryAppend;
ID.F.AsInteger := AID;
Checked.F.AsInteger := 0;
Value.F.AsString := AValue;
TryPost;
end;
procedure TParameterValuesTableW.CheckDefault;
begin
UncheckAll;
CheckRecords(FDefaultCheckedValues);
end;
procedure TParameterValuesTableW.CheckNear(AParameterKindID: Integer);
begin
Assert(AParameterKindID > Integer(Неиспользуется));
Assert(AParameterKindID <= Integer(Строковый_частичный));
case AParameterKindID of
Integer(Числовой):
CheckNearNumerical;
Integer(Строковый_точный):
; // нет ближайшего аналога
Integer(Строковый_частичный):
CheckNearSubStr;
else
Assert(False);
end;
end;
procedure TParameterValuesTableW.CheckNearNumerical;
var
AID: Integer;
i: Integer;
begin
// Выделяет галочками ближайшие значения
DataSet.DisableControls;
try
CheckDefault;
AID := 0;
i := 0;
while i < RecordCount do
begin
// Переходим к следующей записи
Inc(i);
DataSet.RecNo := i;
if Checked.F.AsInteger = 0 then
Continue;
// Отмечаем предшествующую запись
if i > 1 then
begin
DataSet.RecNo := i - 1;
CheckRecord(True);
end;
// Отмечаем следующую запись
if i < RecordCount then
begin
DataSet.RecNo := i + 1;
CheckRecord(True);
end;
AID := ID.F.AsInteger;
// Пропускаем одну запись
Inc(i);
end;
// Переходим на последнюю отмеченную запись
if AID > 0 then
ID.Locate(AID, [])
finally
DataSet.EnableControls;
end;
end;
procedure TParameterValuesTableW.CheckNearSubStr;
var
i: Integer;
m: TArray<string>;
S: string;
V: string;
begin
if FDefaultCheckedValues.IsEmpty then
Exit;
m := FDefaultCheckedValues.Split([#13]);
// Выделяет галочками строки содержащие выбранные
DataSet.DisableControls;
try
CheckDefault;
DataSet.First;
while not DataSet.Eof do
begin
if Checked.F.AsInteger = 0 then
begin
// Цикл по всем подстрокам
for i := Low(m) to High(m) do
begin
S := m[i].Trim([#10, ' ']).ToUpperInvariant;
V := Value.F.AsString.ToUpperInvariant;
// Нашли подстроку
if V.IndexOf(S) >= 0 then
CheckRecord(True);
end;
end;
DataSet.Next;
end;
finally
DataSet.EnableControls;
end;
end;
procedure TParameterValuesTableW.CheckRecord(const AChecked: Boolean);
begin
TryEdit;
Checked.F.AsInteger := IfThen(AChecked, 1, 0);
TryPost;
end;
procedure TParameterValuesTableW.CheckRecords(const AValues: string);
var
i: Integer;
m: TArray<String>;
S: string;
begin
DataSet.DisableControls;
try
m := AValues.Split([#13, #10]);
for i := Low(m) to High(m) do
begin
S := m[i].Trim([#13, #10, ' ']);
if S.IsEmpty then
Continue;
Value.Locate(S, [], True);
CheckRecord(True);
end;
finally
DataSet.EnableControls;
end;
end;
procedure TParameterValuesTableW.FilterChecked;
begin
DataSet.Filter := Format('%s = 1', [Checked.FieldName]);
DataSet.Filtered := True;
end;
function TParameterValuesTableW.GetCheckedValues(const ADelimiter: string;
const AQuote: Char): String;
var
AClone: TFDMemTable;
ACloneWrap: TParameterValuesTableW;
AQuoteStr: string;
begin
Assert(not ADelimiter.IsEmpty);
TryPost;
AQuoteStr := IfThen(AQuote = #0, '', AQuote);
AClone := AddClone('');
try
ACloneWrap := TParameterValuesTableW.Create(AClone);
ACloneWrap.FilterChecked;
Result := '';
while not AClone.Eof do
begin
Result := Result + IfThen(Result.IsEmpty, '', ADelimiter);
Result := Format('%s%s%s%s', [Result, AQuoteStr,
ACloneWrap.Value.F.AsString, AQuoteStr]);
AClone.Next;
end;
finally
DropClone(AClone);
end;
end;
procedure TParameterValuesTableW.SetAsDefaultValues;
begin
// Делаем выбранные сейчас значения - значениями по умолчанию
FDefaultCheckedValues := GetCheckedValues(#13#10, #0)
end;
procedure TParameterValuesTableW.UncheckAll;
begin
DataSet.DisableControls;
try
DataSet.First;
while not DataSet.Eof do
begin
if Checked.F.AsInteger = 1 then
CheckRecord(False);
DataSet.Next;
end;
finally
DataSet.EnableControls;
end;
end;
end.
|
{**********************************************}
{ TBar3DSeries Component }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit Bar3D;
{$I TeeDefs.inc}
{ This Series component is derived from TBarSeries.
It has a new property: OffsetValues
This new property allows to specify a different ORIGIN value
for EACH bar point.
This can be used with standard TBarSeries components to
make a "Stacked-3D" chart type.
}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs,
{$ELSE}
Graphics, Controls, Forms, Dialogs,
{$ENDIF}
TeEngine, Series;
type
TBar3DSeries = class(TBarSeries)
private
{ Private declarations }
FOffsetValues : TChartValueList;
protected
{ Protected declarations }
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override;
Procedure SetOffsetValues(Value:TChartValueList);
class Function SubGalleryStack:Boolean; override; { 5.01 }
public
{ Public declarations }
Constructor Create(AOwner: TComponent); override;
Function AddBar( Const AX,AY,AOffset:Double;
Const AXLabel:String='';
AColor:TColor=clTeeColor):Integer;
Function GetOriginValue(ValueIndex:Integer):Double; override;
Function MaxYValue:Double; override;
Function MinYValue:Double; override;
Function PointOrigin(ValueIndex:Integer; SumAll:Boolean):Double; override;
published
{ Published declarations }
property OffsetValues:TChartValueList read FOffsetValues
write SetOffsetValues;
end;
implementation
Uses {$IFDEF CLR}
{$ELSE}
Math,
{$ENDIF}
Chart, TeeProcs, TeCanvas, TeeProCo;
{ TBar3DSeries }
Constructor TBar3DSeries.Create(AOwner: TComponent);
begin
inherited;
FOffsetValues:=TChartValueList.Create(Self,TeeMsg_ValuesOffset); { <-- "offset" storage }
end;
Procedure TBar3DSeries.SetOffsetValues(Value:TChartValueList);
begin
SetChartValueList(FOffsetValues,Value); { standard method }
end;
{ calculate maximum Y value }
Function TBar3DSeries.MaxYValue:Double;
begin
result:=inherited MaxYValue;
if (MultiBar=mbNone) or (MultiBar=mbSide) then
result:=Math.Max(result,FOffsetValues.MaxValue);
end;
{ calculate minimum Y value ( YValues and negative Offsets supported ) }
Function TBar3DSeries.MinYValue:Double;
var t : Integer;
begin
result:=inherited MinYValue;
if (MultiBar=mbNone) or (MultiBar=mbSide) then
for t:=0 to Count-1 do
if FOffsetValues.Value[t]<0 then
result:=Math.Min(result,YValues.Value[t]+FOffsetValues.Value[t]);
end;
Function TBar3DSeries.AddBar( Const AX,AY,AOffset:Double;
Const AXLabel:String='';
AColor:TColor=clTeeColor):Integer;
begin
FOffsetValues.TempValue:=AOffset;
result:=AddXY(AX,AY,AXLabel,AColor);
// AddValue(result);
end;
Procedure TBar3DSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);
Var t : Integer;
s : TSeriesRandomBounds;
Begin
s:=RandomBounds(NumValues);
with s do
for t:=1 to NumValues do { some sample values to see something in design mode }
Begin
tmpY:=RandomValue(Round(DifY));
AddBar( tmpX,
10+Abs(tmpY),
Abs(DifY/(1+RandomValue(5))));
tmpX:=tmpX+StepX;
end;
end;
{ this overrides default bottom origin calculation }
Function TBar3DSeries.PointOrigin(ValueIndex:Integer; SumAll:Boolean):Double;
begin
result:=FOffsetValues.Value[ValueIndex];
end;
{ this makes this bar heigth to be: "offset" + "height" }
Function TBar3DSeries.GetOriginValue(ValueIndex:Integer):Double;
begin
result:=inherited GetOriginValue(ValueIndex)+FOffsetValues.Value[ValueIndex];
end;
class function TBar3DSeries.SubGalleryStack: Boolean;
begin
result:=False; { 5.01 } { Do not show stacked styles at sub-gallery }
end;
// Register the Series at Chart gallery
initialization
RegisterTeeSeries( TBar3DSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryBar3D,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySamples, 1 );
finalization
UnRegisterTeeSeries([TBar3DSeries]);
end.
|
unit TelaDeSelecao;
interface
uses
System.SysUtils;
type
TTelaDeSelecao = class
public
procedure Tela;
end;
implementation
{ TTelaDeSelecao }
procedure TTelaDeSelecao.Tela;
const
Tela ='-----------------'+ #13#10 +
'Selecione a Loja:' + #13#10 +
'1 - Esfiharia Edmoto' + #13#10 +
'2 - Pizzaria Jamal' + #13#10 +
'3 - Sair' + #13#10 +
'--------------------' + #13#10;
begin
Writeln(Tela);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC TFDUpdateSQL editor form }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.VCLUI.USEdit;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls,
FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Comp.Client,
FireDAC.VCLUI.OptsBase, FireDAC.VCLUI.UpdateOptions, FireDAC.VCLUI.Controls,
FireDAC.VCLUI.Memo;
type
TfrmFDGUIxFormsUSEdit = class(TfrmFDGUIxFormsOptsBase)
pcMain: TPageControl;
tsGenerate: TTabSheet;
Label1: TLabel;
cbxTableName: TComboBox;
btnDSDefaults: TButton;
btnGenSQL: TButton;
btnServerInfo: TButton;
GroupBox2: TLabel;
lbKeyFields: TListBox;
GroupBox3: TLabel;
lbUpdateFields: TListBox;
GroupBox4: TLabel;
lbRefetchFields: TListBox;
tsSQL: TTabSheet;
tsOptions: TTabSheet;
ptreeOptions: TFDGUIxFormsPanelTree;
GroupBox5: TPanel;
cbQuoteTabName: TCheckBox;
cbQuoteColName: TCheckBox;
frmUpdateOptions: TfrmFDGUIxFormsUpdateOptions;
Bevel4: TBevel;
Bevel1: TBevel;
Bevel5: TBevel;
pcSQL: TPageControl;
tsInsert: TTabSheet;
tsModify: TTabSheet;
tsDelete: TTabSheet;
tsLock: TTabSheet;
tsUnlock: TTabSheet;
tsFetchRow: TTabSheet;
procedure cbxTableNameDropDown(Sender: TObject);
procedure btnServerInfoClick(Sender: TObject);
procedure btnDSDefaultsClick(Sender: TObject);
procedure btnGenSQLClick(Sender: TObject);
procedure cbxTableNameExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure mmSQLExit(Sender: TObject);
procedure mmSQLKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cbxTableNameChange(Sender: TObject);
procedure cbxTableNameClick(Sender: TObject);
private
FConnection: TFDCustomConnection;
FDataSet: TFDAdaptedDataSet;
FUpdateSQL: TFDUpdateSQL;
FOpts: IFDStanOptions;
procedure UpdateExistSQLs;
procedure GenCommands;
function GetSQL(AIndex: Integer): TFDGUIxFormsMemo;
function ExecuteBase(AUpdSQL: TFDUpdateSQL; const ACaption: String): Boolean;
function UseField(const AFieldName: String): Boolean;
public
class function Execute(AUpdSQL: TFDUpdateSQL; const ACaption: String): Boolean;
end;
var
frmFDGUIxFormsUSEdit: TfrmFDGUIxFormsUSEdit;
implementation
{$R *.dfm}
uses
System.UITypes,
Vcl.Dialogs, Data.DB,
FireDAC.Stan.ResStrs, FireDAC.Stan.Util,
FireDAC.DatS,
FireDAC.Phys.Intf;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.FormCreate(Sender: TObject);
var
i: Integer;
oSQL: TFDGUIxFormsMemo;
begin
for i := 0 to 5 do begin
oSQL := TFDGUIxFormsMemo.Create(Self);
oSQL.Parent := pcSQL.Pages[i];
oSQL.Left := 5;
oSQL.Top := 5;
oSQL.Width := oSQL.Parent.ClientWidth - 12;
oSQL.Height := oSQL.Parent.ClientHeight - 12;
oSQL.Anchors := [akLeft, akTop, akRight, akBottom];
oSQL.Align := alNone;
oSQL.Visible := True;
oSQL.OnExit := mmSQLExit;
oSQL.OnKeyDown := mmSQLKeyDown;
end;
end;
{ --------------------------------------------------------------------------- }
function TfrmFDGUIxFormsUSEdit.GetSQL(AIndex: Integer): TFDGUIxFormsMemo;
begin
Result := pcSQL.Pages[AIndex].Controls[0] as TFDGUIxFormsMemo;
end;
{ --------------------------------------------------------------------------- }
function TfrmFDGUIxFormsUSEdit.UseField(const AFieldName: String): Boolean;
begin
Result := (FDataSet = nil) or (FDataSet.FieldCount = 0) or
(FDataSet.FindField(AFieldName) <> nil);
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.cbxTableNameDropDown(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
cbxTableName.Perform(CB_SETDROPPEDWIDTH, Width div 2, 0);
{$ENDIF}
if cbxTableName.Items.Count = 0 then
try
FConnection.GetTableNames('', '', '', cbxTableName.Items, [osMy]);
except
cbxTableName.DroppedDown := False;
raise;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.cbxTableNameChange(Sender: TObject);
begin
btnGenSQL.Enabled := (cbxTableName.Text <> '');
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.cbxTableNameClick(Sender: TObject);
begin
if cbxTableName.Text <> '' then begin
btnServerInfoClick(nil);
btnDSDefaultsClick(nil);
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.cbxTableNameExit(Sender: TObject);
begin
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.btnServerInfoClick(Sender: TObject);
var
oConnMeta: IFDPhysConnectionMetadata;
oView: TFDDatSView;
sName: String;
eAttrs: TFDDataAttributes;
i, j: Integer;
begin
FConnection.ConnectionIntf.CreateMetadata(oConnMeta);
oView := oConnMeta.GetTableFields('', '', cbxTableName.Text, '');
try
lbKeyFields.Items.Clear;
lbUpdateFields.Items.Clear;
lbRefetchFields.Items.Clear;
for i := 0 to oView.Rows.Count - 1 do begin
sName := oView.Rows[i].GetData('COLUMN_NAME');
if sName = '' then
sName := '_' + IntToStr(lbKeyFields.Items.Count);
lbKeyFields.Items.Add(sName);
lbUpdateFields.Items.Add(sName);
lbRefetchFields.Items.Add(sName);
end;
for i := 0 to oView.Rows.Count - 1 do begin
sName := oView.Rows[i].GetData('COLUMN_NAME');
if UseField(sName) then begin
j := oView.Rows[i].GetData('COLUMN_ATTRIBUTES');
eAttrs := TFDDataAttributes(Pointer(@J)^);
if (sName <> '') and (eAttrs * [caCalculated, caInternal, caUnnamed] = []) then
lbUpdateFields.Selected[i] := True;
if eAttrs * [caAutoInc, caROWID, caDefault, caRowVersion, caCalculated, caVolatile] <> [] then
lbRefetchFields.Selected[i] := True;
end;
end;
finally
FDFree(oView);
end;
oView := oConnMeta.GetTablePrimaryKeyFields('', '', cbxTableName.Text, '');
try
for i := 0 to oView.Rows.Count - 1 do begin
sName := oConnMeta.UnQuoteObjName(oView.Rows[i].GetData('COLUMN_NAME'));
if UseField(sName) then begin
j := lbKeyFields.Items.IndexOf(sName);
if j <> -1 then
lbKeyFields.Selected[j] := True;
end;
end;
finally
FDFree(oView);
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.btnDSDefaultsClick(Sender: TObject);
var
oConnMeta: IFDPhysConnectionMetadata;
i, j: Integer;
oFld: TField;
sFldName: String;
begin
if FDataSet = nil then
Exit;
if (FConnection <> nil) and (FConnection.ConnectionIntf <> nil) then
FConnection.ConnectionIntf.CreateMetadata(oConnMeta)
else
oConnMeta := nil;
if FDataSet.FieldCount <> 0 then begin
for i := 0 to lbKeyFields.Items.Count - 1 do
lbKeyFields.Selected[i] := False;
for i := 0 to lbUpdateFields.Items.Count - 1 do
lbUpdateFields.Selected[i] := False;
for i := 0 to lbRefetchFields.Items.Count - 1 do
lbRefetchFields.Selected[i] := False;
for i := 0 to FDataSet.FieldCount - 1 do begin
oFld := FDataSet.Fields[i];
if oFld.Origin = '' then
sFldName := oFld.FieldName
else
sFldName := oFld.Origin;
if oConnMeta <> nil then
sFldName := oConnMeta.UnQuoteObjName(sFldName);
j := lbKeyFields.Items.IndexOf(sFldName);
if j <> -1 then begin
lbKeyFields.Selected[j] := pfInKey in oFld.ProviderFlags;
lbUpdateFields.Selected[j] := pfInUpdate in oFld.ProviderFlags;
lbRefetchFields.Selected[j] := (oFld.AutoGenerateValue <> TAutoRefreshFlag.arNone);
end;
end;
end;
if FDataSet.Adapter <> nil then begin
FOpts.UpdateOptions.RestoreDefaults;
frmUpdateOptions.LoadFrom(FOpts.UpdateOptions);
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.btnGenSQLClick(Sender: TObject);
begin
frmUpdateOptions.SaveTo(FOpts.UpdateOptions);
GenCommands;
UpdateExistSQLs;
pcMain.ActivePage := tsSQL;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.mmSQLExit(Sender: TObject);
begin
UpdateExistSQLs;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.mmSQLKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and ((Key = Ord('A')) or (Key = Ord('a'))) then begin
TFDGUIxFormsMemo(Sender).SelectAll;
Key := 0;
end
else if Key = VK_ESCAPE then begin
ModalResult := mrCancel;
Key := 0;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.UpdateExistSQLs;
var
i: Integer;
s: String;
begin
for i := 0 to 5 do begin
s := pcSQL.Pages[i].Caption;
if GetSQL(i).Lines.Count > 0 then begin
if Pos('*', s) = 0 then
s := s + ' *';
end
else begin
if Pos('*', s) <> 0 then
s := Copy(s, 1, Pos('*', s) - 1);
end;
pcSQL.Pages[i].Caption := s;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsUSEdit.GenCommands;
var
i, j: Integer;
oCmdGen: IFDPhysCommandGenerator;
oTab: TFDDatSTable;
oCol: TFDDatSColumn;
oFld: TField;
sFldName: String;
oCmd: IFDPhysCommand;
oOpts: IFDStanOptions;
begin
oTab := TFDDatSTable.Create;
FConnection.ConnectionIntf.CreateCommand(oCmd);
try
oOpts := oCmd.Options;
oOpts.UpdateOptions.Assign(FOpts.UpdateOptions);
oOpts.FetchOptions.RowsetSize := 0;
oOpts.FetchOptions.Mode := fmManual;
oOpts.FetchOptions.Items := oOpts.FetchOptions.Items + [fiMeta];
// define table
oCmd.Prepare('select * from ' + cbxTableName.Text);
oCmd.Define(oTab);
oTab.SourceName := cbxTableName.Text;
// Include into Where only fields existing in dataset and
// having pfInWhere in ProviderFlags
if FDataSet <> nil then
for i := 0 to oTab.Columns.Count - 1 do begin
oCol := oTab.Columns[i];
if coInWhere in oCol.Options then begin
oCol.Options := oCol.Options - [coInWhere];
for j := 0 to FDataSet.FieldCount - 1 do begin
oFld := FDataSet.Fields[j];
if oFld.Origin = '' then
sFldName := oFld.FieldName
else
sFldName := oFld.Origin;
if (AnsiCompareText(oCol.Name, sFldName) = 0) and
(pfInWhere in oFld.ProviderFlags) then
oCol.Options := oCol.Options + [coInWhere];
end;
end;
end;
// Include into where selected Key fields
for i := 0 to lbKeyFields.Items.Count - 1 do begin
oCol := oTab.Columns.ColumnByName(lbKeyFields.Items[i]);
if lbKeyFields.Selected[i] then
oCol.Options := oCol.Options + [coInKey, coInWhere]
else
oCol.Options := oCol.Options - [coInKey, coInWhere];
end;
// Include into update selected Updating fields
for i := 0 to lbUpdateFields.Items.Count - 1 do begin
oCol := oTab.Columns.ColumnByName(lbUpdateFields.Items[i]);
if lbUpdateFields.Selected[i] then
oCol.Options := oCol.Options + [coInUpdate, coInWhere]
else
oCol.Options := oCol.Options - [coInUpdate, coInWhere];
end;
// Include into refetch selected Refreshing fields
for i := 0 to lbRefetchFields.Items.Count - 1 do begin
oCol := oTab.Columns.ColumnByName(lbRefetchFields.Items[i]);
if lbRefetchFields.Selected[i] then
oCol.Options := oCol.Options + [coAfterInsChanged, coAfterUpdChanged]
else
oCol.Options := oCol.Options - [coAfterInsChanged, coAfterUpdChanged];
end;
// Setup SQL generator
FConnection.ConnectionIntf.CreateCommandGenerator(oCmdGen, oCmd);
oCmdGen.FillRowOptions := [foData, foBlobs, foDetails, foClear] +
FDGetFillRowOptions(oOpts.FetchOptions);
oCmdGen.GenOptions := [goBeautify];
if cbQuoteColName.Checked then
oCmdGen.GenOptions := oCmdGen.GenOptions + [goForceQuoteCol]
else
oCmdGen.GenOptions := oCmdGen.GenOptions + [goForceNoQuoteCol];
if cbQuoteTabName.Checked then
oCmdGen.GenOptions := oCmdGen.GenOptions + [goForceQuoteTab]
else
oCmdGen.GenOptions := oCmdGen.GenOptions + [goForceNoQuoteTab];
oCmdGen.Options := oOpts;
oCmdGen.Table := oTab;
// Generate commands
if FOpts.UpdateOptions.EnableInsert then
GetSQL(0).Lines.Text := oCmdGen.GenerateInsert;
if FOpts.UpdateOptions.EnableUpdate then
GetSQL(1).Lines.Text := oCmdGen.GenerateUpdate;
if FOpts.UpdateOptions.EnableDelete then
GetSQL(2).Lines.Text := oCmdGen.GenerateDelete;
if FOpts.UpdateOptions.LockMode <> lmNone then begin
GetSQL(3).Lines.Text := oCmdGen.GenerateLock;
GetSQL(4).Lines.Text := oCmdGen.GenerateUnLock;
end;
GetSQL(5).Lines.Text := oCmdGen.GenerateSelect(False);
finally
FDFree(oTab);
oCmdGen := nil;
oCmd := nil;
end;
end;
{ --------------------------------------------------------------------------- }
function TfrmFDGUIxFormsUSEdit.ExecuteBase(AUpdSQL: TFDUpdateSQL; const ACaption: String): Boolean;
var
oTestCmd: TFDCustomCommand;
i: Integer;
function GetConnection: TFDCustomConnection;
begin
if FUpdateSQL.ConnectionName <> '' then
Result := FDManager.AcquireConnection(FUpdateSQL.ConnectionName, FUpdateSQL.Name)
else begin
if FUpdateSQL.Connection <> nil then
Result := FUpdateSQL.Connection
else if (FDataSet <> nil) and (FDataSet.PointedConnection <> nil) then
Result := FDataSet.PointedConnection
else
Result := oTestCmd.GetConnection(False);
if Result = nil then
raise Exception.Create(S_FD_USEditCantEdit);
Result := FDManager.AcquireConnection(Result, FUpdateSQL.Name);
end;
end;
function GetParentObject: TPersistent;
begin
if FDataSet <> nil then
Result := FDataSet
else
Result := oTestCmd;
end;
function GetUpdateOptions: TFDBottomUpdateOptions;
begin
if FDataSet <> nil then
Result := FDataSet.OptionsIntf.UpdateOptions as TFDBottomUpdateOptions
else
Result := oTestCmd.UpdateOptions;
end;
begin
LoadState;
FUpdateSQL := AUpdSQL;
FDataSet := FUpdateSQL.DataSet;
oTestCmd := FUpdateSQL.Commands[arInsert];
FConnection := GetConnection;
try
FConnection.CheckActive;
if (FDataSet <> nil) and not FDataSet.Active and
(FDataSet.Command <> nil) and (Trim(FDataSet.Command.CommandText.Text) <> '') and
(MessageDlg(S_FD_USEditOpenDS, mtConfirmation, [mbYes, mbNo], -1) = mrYes) then
FDataSet.Open;
FOpts := TFDOptionsContainer.Create(GetParentObject, TFDFetchOptions,
TFDUpdateOptions, TFDTopResourceOptions, nil);
FOpts.ParentOptions := GetUpdateOptions.Container as IFDStanOptions;
FOpts.UpdateOptions.Assign(GetUpdateOptions);
Caption := Format(S_FD_USEditCaption, [ACaption]);
btnDSDefaults.Enabled := (FDataSet <> nil);
btnGenSQL.Enabled := False;
pcMain.ActivePage := tsGenerate;
ActiveControl := cbxTableName;
frmUpdateOptions.LoadFrom(FOpts.UpdateOptions);
frmUpdateOptions.SQLGenerator := True;
cbxTableName.Text := GetUpdateOptions.UpdateTableName;
if (cbxTableName.Text = '') and (FDataSet <> nil) and (FDataSet.Table <> nil) then
cbxTableName.Text := FDataSet.Table.ActualOriginName;
if cbxTableName.Text <> '' then begin
cbxTableNameChange(cbxTableName);
cbxTableNameClick(cbxTableName);
end;
if btnDSDefaults.Enabled then
btnDSDefaultsClick(nil);
for i := 0 to 5 do
GetSQL(i).RDBMSKind := FConnection.RDBMSKind;
GetSQL(0).Lines.SetStrings(AUpdSQL.InsertSQL);
GetSQL(1).Lines.SetStrings(AUpdSQL.ModifySQL);
GetSQL(2).Lines.SetStrings(AUpdSQL.DeleteSQL);
GetSQL(3).Lines.SetStrings(AUpdSQL.LockSQL);
GetSQL(4).Lines.SetStrings(AUpdSQL.UnlockSQL);
GetSQL(5).Lines.SetStrings(AUpdSQL.FetchRowSQL);
UpdateExistSQLs;
Result := (ShowModal = mrOK);
finally
FDManager.ReleaseConnection(FConnection);
end;
if Result then begin
AUpdSQL.InsertSQL.SetStrings(GetSQL(0).Lines);
AUpdSQL.ModifySQL.SetStrings(GetSQL(1).Lines);
AUpdSQL.DeleteSQL.SetStrings(GetSQL(2).Lines);
AUpdSQL.LockSQL.SetStrings(GetSQL(3).Lines);
AUpdSQL.UnlockSQL.SetStrings(GetSQL(4).Lines);
AUpdSQL.FetchRowSQL.SetStrings(GetSQL(5).Lines);
end;
SaveState;
end;
{ --------------------------------------------------------------------------- }
class function TfrmFDGUIxFormsUSEdit.Execute(AUpdSQL: TFDUpdateSQL; const ACaption: String): Boolean;
var
oFrm: TfrmFDGUIxFormsUSEdit;
begin
oFrm := TfrmFDGUIxFormsUSEdit.Create(nil);
try
Result := oFrm.ExecuteBase(AUpdSQL, ACaption);
finally
FDFree(oFrm);
end;
end;
end.
|
unit uEmpresa;
interface
// O Modelo não precisa conhecer ninguem
// Ai esta o interessante do MVC.
// Desta forma o modelo fica desacoplado e podendo ser utilizado por vários controles
uses
Contnrs, // <-- Nesta Unit está implementado TObjectList
MVCInterfaces,uRegistro,uContador;
type
TEmpresa = class(TRegistro)
private
fID : Integer; // Toda chave primaria nossa no banco dentro do objeto vai chamar ID
fNome : String;
fContador : TContador;
FOnModeloMudou: TModeloMudou;
fCNPJ: String;
procedure SetContador(const Value: Tcontador);
procedure SetID(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetOnModeloMudou(const Value: TModeloMudou);
procedure SetCNPJ(const Value: String);
public
property ID : Integer read fID write SetID;
property Nome : String read fNome write SetNome;
property CNPJ : String read fCNPJ write SetCNPJ;
property Contador : Tcontador read fContador write SetContador;
//property OnModeloMudou: TModeloMudou read GetOnModeloMudou write SetOnModeloMudou; // Precisa ver se assim funciona em versões mais novas de Delphi
property OnModeloMudou: TModeloMudou read FOnModeloMudou write SetOnModeloMudou; // Assim funcionou em Delphi 7
function Todos : TObjectList;
class function GetEmpresa() : TEmpresa;
constructor create();
end;
implementation
uses
UEmpresaBD;
{ TEmpresa }
var
fEmpresa:TEmpresa = nil;
constructor TEmpresa.create;
begin
fContador := TContador.create;
end;
class function TEmpresa.GetEmpresa: TEmpresa;
begin
if (not Assigned(fEmpresa)) then begin
fEmpresa := create();
end;
result := fEmpresa;
end;
procedure TEmpresa.SetCNPJ(const Value: String);
begin
fCNPJ := Value;
end;
procedure TEmpresa.SetContador(const Value: Tcontador);
begin
fContador := Value;
end;
procedure TEmpresa.SetID(const Value: Integer);
begin
fID := Value;
end;
procedure TEmpresa.SetNome(const Value: String);
begin
fNome := Value;
end;
procedure TEmpresa.SetOnModeloMudou(const Value: TModeloMudou);
begin
FOnModeloMudou := Value;
end;
function TEmpresa.Todos: TObjectList;
var
lEmpresaBD : TEmpresaBD;
begin
lEmpresaBD := TEmpresaBD.Create;
result := lEmpresaBD.Todos();
end;
end.
|
{$MODE OBJFPC}
program SlidingWindows;
const
InputFile = 'SWINDOW.INP';
OutputFile = 'SWINDOW.OUT';
max = 1000000;
var
n, m, k: Integer;
P, T: AnsiString;
Pie: array[1..max] of Integer;
CurrentWindowPos: Integer;
Count: Integer;
procedure Enter;
var
f: TextFile;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, T);
ReadLn(f, P);
ReadLn(f, k);
m := Length(P);
n := Length(T);
finally
CloseFile(f);
end;
end;
procedure Init;
begin
Count := 0;
CurrentWindowPos := k - 1;
end;
procedure ComputePrefixFunction;
var
k, q: Integer;
begin
Pie[1] := 0;
k := 0;
for q := 2 to m do
begin
while (k > 0) and (P[k + 1] <> P[q]) do
k := Pie[k];
if P[k + 1] = P[q] then
Inc(k);
Pie[q] := k;
end;
end;
procedure KnuttMorrisPrattStrMatching;
var
i, q: Integer;
wbegin, wend: Integer;
begin
if k < m then Exit;
q := 0;
for i := 1 to n do
begin
while (q > 0) and (P[q + 1] <> T[i]) do
q := Pie[q];
if P[q + 1] = T[i] then
begin
Inc(q);
if q = m then
begin
wbegin := i - 1; //position before the match
wend := i + k - m;
if wbegin < CurrentWindowPos then
wbegin := CurrentWindowPos;
if wend > n then
wend := n;
Count := Count + wend - wbegin;
CurrentWindowPos := wend;
q := Pie[q];
end;
end;
end;
end;
procedure PrintResult;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
Write(f, Count);
finally
CloseFile(f);
end;
end;
begin
Enter;
Init;
ComputePrefixFunction;
KnuttMorrisPrattStrMatching;
PrintResult;
end.
this is the first task.
is
4
ababababa
aba
5
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
program TEXFILT;
{
Strip non-printable chars from text file. Leaves TAB.
Alters a text file <file>.<ext>. The original remains as
<file>.BAK. Type TEXFILT. You will be prompted for the file
name.
}
uses
CRT, Graph;
CONST
{ set of chars TEXFILT will pass }
PassableChars = [Chr(9),Chr(10),Chr(12),Chr(13),' '..'~'];
type AnyStr = string[80];
delimters = (LF,CR,NONE,GOOD);
var FileToRead, OutFile : text;
NameOfFile : anystr;
currfile : integer;
function Exist(name: anystr):Boolean;
var
Fil: file;
begin
Assign(Fil,name);
{$I-}
Reset(Fil);
Close(Fil);
{$I+}
Exist := (IOresult = 0);
{! 1. IOResult^ now returns different values corresponding to DOS error codes.}
end; {exist}
Procedure ChooseFile(currentfile : integer);
begin
GotoXY(1,1);
if currentfile = 0 then begin
Writeln ('Name of file (include extension)?');ClrEol;
Readln(NameOfFile);ClrEol;
end
else begin
NameOfFile := paramstr(currentfile);
GotoXY(1,3);
end;
if Exist(NameOfFile) then begin
Assign(FileToRead,NameOfFile);
Assign(OutFile,'text.tmp');
Reset(FileToRead);
Rewrite(Outfile);
end
else begin
writeln('File ',NameOfFile,' does not exist here.');ClrEol;
writeln('Choose again or <Ctrl><Break> to exit.');ClrEol;
writeln;
Choosefile(0);
end;
end; {choosefile}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure Swapfile;
{leave unaltered file with a '.BAK' extension
Rename TEMP file as old file name.}
var temp : anystr;
tempfile : text;
begin
if pos('.',nameOfFile)<>0 then
temp := copy(NameofFile,1,pos('.',nameOfFile)-1)+ '.BAK'
else
temp := nameOfFile + '.BAK';
if Exist(temp) then
begin
Assign(tempfile,temp);
Erase(tempfile);
{ Close(tempfile); }
end;
Rename(FileToRead,temp);
Rename(OutFile,NameOfFile);
end; {swapfile}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function ChangeLines : boolean;
var chrA : char;
begin { CHANGELINES }
while not eof(FileToRead) do
begin
read(FileToRead,ChrA);
if chrA IN PassableChars then
write(Outfile,chrA);
end;
close(fileToRead);
close(OutFile);
ChangeLines := TRUE;
end; {changeLines}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
{MAIN PROGRAM}
BEGIN
ClrScr;
if paramcount = 0 then
begin
ChooseFile(0);
if ChangeLines then SwapFile;
end
else
for currfile := 1 to paramcount do
begin
ChooseFile(currfile);
if ChangeLines then SwapFile;
end;
END.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfKeyStreams;
interface
{$I TFL.inc}
uses tfTypes, tfUtils{, tfCipherServ};
type
PStreamCipherInstance = ^TStreamCipherInstance;
TStreamCipherInstance = record
private type
TBlock = array[0..TF_MAX_CIPHER_BLOCK_SIZE - 1] of Byte;
private
{$HINTS OFF}
FVTable: Pointer;
FRefCount: Integer;
{$HINTS ON}
FCipher: ICipher;
FBlockSize: Cardinal;
// don't assume that FBlockNo is the rightmost 8 bytes of a block cipher's IV
// FBlockNo: UInt64;
FPos: Cardinal; // 0 .. FBlockSize - 1
FBlock: TBlock; // var len
public
class function GetInstance(var Inst: PStreamCipherInstance; Alg: ICipher): TF_RESULT; static;
class procedure Burn(Inst: PStreamCipherInstance);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Duplicate(Inst: PStreamCipherInstance; var NewInst: PStreamCipherInstance): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function ExpandKey(Inst: PStreamCipherInstance;
Key: PByte; KeySize: Cardinal; Nonce: UInt64): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Read(Inst: PStreamCipherInstance; Data: PByte; DataSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Skip(Inst: PStreamCipherInstance; Dist: Int64): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Crypt(Inst: PStreamCipherInstance; Data: PByte; DataSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function SetNonce(Inst: PStreamCipherInstance; Nonce: UInt64): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetNonce(Inst: PStreamCipherInstance; var Nonce: UInt64): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
//function GetKeyStreamByAlgID(AlgID: UInt32; var A: PKeyStreamEngine): TF_RESULT;
implementation
uses tfRecords;
const
VTable: array[0..10] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
// @TKeyStreamInstance.Release,
@TStreamCipherInstance.Burn,
@TStreamCipherInstance.Duplicate,
@TStreamCipherInstance.ExpandKey,
@TStreamCipherInstance.SetNonce,
@TStreamCipherInstance.GetNonce,
@TStreamCipherInstance.Skip,
@TStreamCipherInstance.Read,
@TStreamCipherInstance.Crypt
);
(*
function GetKeyStreamByAlgID(AlgID: UInt32; var A: PKeyStreamEngine): TF_RESULT;
var
Server: ICipherServer;
Alg: ICipherAlgorithm;
BlockSize: Cardinal;
Tmp: PKeyStreamEngine;
begin
Result:= GetCipherServer(Server);
if Result <> TF_S_OK then Exit;
Result:= Server.GetByAlgID(AlgID, Alg);
if Result <> TF_S_OK then Exit;
BlockSize:= Alg.GetBlockSize;
if (BlockSize = 0) or (BlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin
Result:= TF_E_UNEXPECTED;
Exit;
end;
try
Tmp:= AllocMem(SizeOf(TKeyStreamEngine) + BlockSize);
Tmp^.FVTable:= @EngVTable;
Tmp^.FRefCount:= 1;
Tmp^.FCipher:= Alg;
Tmp^.FBlockSize:= BlockSize;
if A <> nil then TKeyStreamEngine.Release(A);
A:= Tmp;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
*)
{ TKeyStreamInstance }
(*
procedure Burn(Inst: PKeyStreamEngine); inline;
var
BurnSize: Integer;
begin
BurnSize:= SizeOf(TKeyStreamEngine) - Integer(@PKeyStreamEngine(nil)^.FBlockNo);
FillChar(Inst.FBlockNo, BurnSize, 0);
end;
*)
procedure BurnMem(Inst: PStreamCipherInstance); inline;
var
BurnSize: Integer;
begin
BurnSize:= SizeOf(TStreamCipherInstance) - SizeOf(TStreamCipherInstance.TBlock)
+ Integer(Inst.FBlockSize) - Integer(@PStreamCipherInstance(nil)^.FCipher);
FillChar(Inst.FCipher, BurnSize, 0);
end;
class procedure TStreamCipherInstance.Burn(Inst: PStreamCipherInstance);
begin
// Inst.FCipher.BurnKey;
// tfFreeInstance(Inst.FCipher);
Inst.FCipher:= nil;
BurnMem(Inst);
end;
{
class function TKeyStreamInstance.Release(Inst: PKeyStreamInstance): Integer;
begin
if Inst.FRefCount > 0 then begin
Result:= tfDecrement(Inst.FRefCount);
if Result = 0 then begin
Inst.FCipher.BurnKey;
Inst.FCipher:= nil;
Burn(Inst);
FreeMem(Inst);
end;
end
else
Result:= Inst.FRefCount;
end;
}
class function TStreamCipherInstance.ExpandKey(Inst: PStreamCipherInstance;
Key: PByte; KeySize: Cardinal; Nonce: UInt64): TF_RESULT;
var
Flags: UInt32;
begin
// for block ciphers; stream ciphers will return error code which is ignored
Flags:= CTR_ENCRYPT;
Inst.FCipher.SetKeyParam(TF_KP_FLAGS, @Flags, SizeOf(Flags));
// Inst.FBlockNo:= 0;
Inst.FPos:= 0;
Result:= Inst.FCipher.ExpandKey(Key, KeySize);
if Result = TF_S_OK then
Result:= Inst.FCipher.SetKeyParam(TF_KP_NONCE, @Nonce, SizeOf(Nonce));
end;
class function TStreamCipherInstance.GetInstance(var Inst: PStreamCipherInstance;
Alg: ICipher): TF_RESULT;
var
BlockSize: Cardinal;
Tmp: PStreamCipherInstance;
begin
BlockSize:= Alg.GetBlockSize;
if (BlockSize = 0) or (BlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin
Result:= TF_E_UNEXPECTED;
Exit;
end;
try
Tmp:= AllocMem(SizeOf(TStreamCipherInstance) + BlockSize);
Tmp^.FVTable:= @VTable;
Tmp^.FRefCount:= 1;
Tmp^.FCipher:= Alg;
Tmp^.FBlockSize:= BlockSize;
// Result^.FPos:= 0;
tfFreeInstance(Inst); // if Inst <> nil then TKeyStreamInstance.Release(Inst);
Inst:= Tmp;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
(*
class function TKeyStreamEngine.NewInstance(Alg: ICipherAlgorithm;
BlockSize: Cardinal): PKeyStreamEngine;
begin
Result:= AllocMem(SizeOf(TKeyStreamEngine) + BlockSize);
Result^.FVTable:= @EngVTable;
Result^.FRefCount:= 1;
Result^.FCipher:= Alg;
Result^.FBlockSize:= BlockSize;
// Result^.FPos:= 0;
end;
*)
(*
class function TKeyStreamEngine.Read(Inst: PKeyStreamEngine; Data: PByte;
DataSize: Cardinal): TF_RESULT;
var
LBlockSize: Cardinal;
LDataSize: Cardinal;
LPos: Cardinal;
LBlockNo: UInt64;
begin
// check arguments
LBlockSize:= Inst.FBlockSize;
LBlockNo:= Inst.FBlockNo + DataSize div LBlockSize + 1;
if LBlockNo < Inst.FBlockNo then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
// read current block's tail
if Inst.FPos > 0 then begin
LDataSize:= Inst.FBlockSize - Inst.FPos;
if LDataSize > DataSize
then LDataSize:= DataSize;
LPos:= Inst.FPos + LDataSize;
if LPos = Inst.FBlockSize then begin
LPos:= 0;
LBlockNo:= Inst.FBlockNo + 1;
if LBlockNo = 0 then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
end;
Move(PByte(@Inst.FBlock)[Inst.FPos], Data^, LDataSize);
Inst.FPos:= LPos;
Inst.FBlockNo:= LBlockNo;
if LDataSize = DataSize then begin
Result:= TF_S_OK;
Exit;
end;
Inc(Data, LDataSize);
Dec(DataSize, LDataSize);
end;
// read full blocks
if DataSize >= Inst.FBlockSize then begin
LDataSize:= DataSize and not (Inst.FBlockSize - 1);
Result:= Inst.FCipher.GetKeyStream(Data, LDataSize);
if Result <> TF_S_OK then Exit;
Inc(Data, LDataSize);
Dec(DataSize, LDataSize);
// Inst.FBlockNo:= Inst.FBlockNo + LDataSize div Inst.FBlockSize;
end;
if DataSize > 0 then begin
Result:= Inst.FCipher.GetKeyStream(@Inst.FBlock, Inst.FBlockSize);
if Result <> TF_S_OK then Exit;
Move(PByte(@Inst.FBlock)^, Data^, DataSize);
Inst.FPos:= DataSize;
// Inst.FBlockNo:= Inst.FBlockNo + 1;
end;
end;
*)
class function TStreamCipherInstance.Read(Inst: PStreamCipherInstance; Data: PByte;
DataSize: Cardinal): TF_RESULT;
var
LDataSize: Cardinal;
NBlocks: Cardinal;
begin
// read current block's tail
if Inst.FPos > 0 then begin
NBlocks:= 1;
Result:= Inst.FCipher.SetKeyParam(TF_KP_DECNO, @NBlocks, SizeOf(NBlocks));
if Result <> TF_S_OK then Exit;
Result:= Inst.FCipher.GetKeyStream(@Inst.FBlock, Inst.FBlockSize);
if Result <> TF_S_OK then Exit;
LDataSize:= Inst.FBlockSize - Inst.FPos;
if LDataSize > DataSize
then LDataSize:= DataSize;
Move(PByte(@Inst.FBlock)[Inst.FPos], Data^, LDataSize);
Inst.FPos:= Inst.FPos + LDataSize;
if Inst.FPos = Inst.FBlockSize then Inst.FPos:= 0;
if LDataSize = DataSize then begin
Result:= TF_S_OK;
Exit;
end;
Inc(Data, LDataSize);
Dec(DataSize, LDataSize);
end;
// read full blocks
if DataSize >= Inst.FBlockSize then begin
LDataSize:= DataSize and not (Inst.FBlockSize - 1);
Result:= Inst.FCipher.GetKeyStream(Data, LDataSize);
if Result <> TF_S_OK then Exit;
Inc(Data, LDataSize);
Dec(DataSize, LDataSize);
end;
// read last incomplete block
if DataSize > 0 then begin
Result:= Inst.FCipher.GetKeyStream(@Inst.FBlock, Inst.FBlockSize);
if Result <> TF_S_OK then Exit;
Move(PByte(@Inst.FBlock)^, Data^, DataSize);
Inst.FPos:= DataSize;
end;
Result:= TF_S_OK;
end;
class function TStreamCipherInstance.Crypt(Inst: PStreamCipherInstance; Data: PByte;
DataSize: Cardinal): TF_RESULT;
var
LDataSize: Cardinal;
NBlocks: Cardinal;
begin
// read current block's tail
if Inst.FPos > 0 then begin
NBlocks:= 1;
Result:= Inst.FCipher.SetKeyParam(TF_KP_DECNO, @NBlocks, SizeOf(NBlocks));
if Result <> TF_S_OK then Exit;
Result:= Inst.FCipher.GetKeyStream(@Inst.FBlock, Inst.FBlockSize);
if Result <> TF_S_OK then Exit;
LDataSize:= Inst.FBlockSize - Inst.FPos;
if LDataSize > DataSize
then LDataSize:= DataSize;
MoveXor(PByte(@Inst.FBlock)[Inst.FPos], Data^, LDataSize);
Inst.FPos:= Inst.FPos + LDataSize;
if Inst.FPos = Inst.FBlockSize then Inst.FPos:= 0;
if LDataSize = DataSize then begin
Result:= TF_S_OK;
Exit;
end;
Inc(Data, LDataSize);
Dec(DataSize, LDataSize);
end;
// read full blocks
if DataSize >= Inst.FBlockSize then begin
LDataSize:= DataSize and not (Inst.FBlockSize - 1);
Result:= Inst.FCipher.KeyCrypt(Data, LDataSize, False);
if Result <> TF_S_OK then Exit;
Inc(Data, LDataSize);
Dec(DataSize, LDataSize);
end;
// read last incomplete block
if DataSize > 0 then begin
// Result:= Inst.FCipher.KeyCrypt(@Inst.FBlock, Inst.FBlockSize, False);
Result:= Inst.FCipher.GetKeyStream(@Inst.FBlock, Inst.FBlockSize);
if Result <> TF_S_OK then Exit;
MoveXor(PByte(@Inst.FBlock)^, Data^, DataSize);
Inst.FPos:= DataSize;
end;
Result:= TF_S_OK;
end;
class function TStreamCipherInstance.Duplicate(Inst: PStreamCipherInstance;
var NewInst: PStreamCipherInstance): TF_RESULT;
var
CipherInst: ICipher;
TmpInst: PStreamCipherInstance;
begin
Result:= Inst.FCipher.Duplicate(CipherInst);
if Result = TF_S_OK then begin
TmpInst:= nil;
Result:= GetInstance(TmpInst, CipherInst);
if Result = TF_S_OK then begin
TmpInst.FBlockSize:= Inst.FBlockSize;
TmpInst.FPos:= Inst.FPos;
Move(Inst.FBlock, TmpInst.FBlock, Inst.FBlockSize);
tfFreeInstance(NewInst);
NewInst:= TmpInst;
end
else
CipherInst:= nil;
end;
end;
class function TStreamCipherInstance.SetNonce(Inst: PStreamCipherInstance;
Nonce: UInt64): TF_RESULT;
begin
Result:= Inst.FCipher.SetKeyParam(TF_KP_NONCE, @Nonce, SizeOf(Nonce));
end;
class function TStreamCipherInstance.GetNonce(Inst: PStreamCipherInstance;
var Nonce: UInt64): TF_RESULT;
var
L: Cardinal;
begin
L:= SizeOf(Nonce);
Result:= Inst.FCipher.GetKeyParam(TF_KP_NONCE, @Nonce, L);
end;
class function TStreamCipherInstance.Skip(Inst: PStreamCipherInstance; Dist: Int64): TF_RESULT;
var
NBlocks: UInt64;
NBytes: Cardinal;
Tail: Cardinal;
ZeroIn, ZeroOut: Boolean;
begin
if Dist >= 0 then begin
Tail:= Inst.FBlockSize - Inst.FPos;
NBlocks:= UInt64(Dist) div Inst.FBlockSize;
NBytes:= UInt64(Dist) mod Inst.FBlockSize;
ZeroIn:= Inst.FPos = 0;
Inc(Inst.FPos, NBytes);
if Inst.FPos >= Inst.FBlockSize then begin
Inc(NBlocks);
Dec(Inst.FPos, Inst.FBlockSize);
end;
ZeroOut:= Inst.FPos = 0;
if ZeroIn <> ZeroOut then begin
if ZeroIn then Inc(NBlocks)
else Dec(NBlocks);
end;
if NBlocks = 0 then Result:= TF_S_OK
else
Result:= Inst.FCipher.SetKeyParam(TF_KP_INCNO, @NBlocks, SizeOf(NBlocks));
end
else begin
Dist:= -Dist;
NBlocks:= UInt64(Dist) div Inst.FBlockSize;
NBytes:= UInt64(Dist) mod Inst.FBlockSize;
ZeroIn:= Inst.FPos = 0;
if NBytes > Inst.FPos then begin
Inc(NBlocks);
Inst.FPos:= Inst.FPos + Inst.FBlockSize;
end;
Dec(Inst.FPos, NBytes);
ZeroOut:= Inst.FPos = 0;
if ZeroIn <> ZeroOut then begin
if ZeroIn then Dec(NBlocks)
else Inc(NBlocks);
end;
if NBlocks = 0 then Result:= TF_S_OK
else
Result:= Inst.FCipher.SetKeyParam(TF_KP_DECNO, @NBlocks, SizeOf(NBlocks));
end;
end;
end.
|
PROGRAM AverageScore(INPUT, OUTPUT);
CONST
NumberOfScores = 4;
ClassSize = 4;
TYPE
Score = 0 .. 100;
VAR
WhichScore: 1 .. NumberOfScores;
Student: 1 .. ClassSize;
NextScore: Score;
Ave, TotalScore, ClassTotal: INTEGER;
SecondName: TEXT;
Ch: CHAR;
BEGIN {AverageScore}
ClassTotal := 0;
WRITELN('Student averages:');
Student := 1;
WHILE Student <= ClassSize
DO
BEGIN
TotalScore := 0;
WhichScore := 1;
REWRITE(SecondName);
IF NOT EOLN(INPUT)
THEN
BEGIN
READ(INPUT, Ch);
WRITE(SecondName, Ch)
END;
WHILE (Ch <> ' ') AND (NOT EOLN(INPUT))
DO
BEGIN
READ(INPUT, Ch);
WRITE(SecondName, Ch);
END;
WHILE WhichScore <= NumberOfScores
DO
BEGIN
READ(NextScore);
IF (NextScore <= 100) AND (NextScore >= 0)
THEN
BEGIN
TotalScore := TotalScore + NextScore;
WhichScore := WhichScore + 1
END
ELSE
BEGIN
WRITE('Введеное число не входит в диапазон от 0 до 100');
EXIT
END;
END;
READLN;
TotalScore := TotalScore * 10;
Ave := TotalScore DIV NumberOfScores;
RESET(SecondName);
BEGIN
Student := Student + 1;
WHILE NOT EOLN(SecondName)
DO
BEGIN
READ(SecondName, Ch);
WRITE(OUTPUT, Ch);
END;
END;
IF Ave MOD 10 >= 5
THEN
WRITELN(Ave DIV 10 + 1)
ELSE
WRITELN(Ave DIV 10);
ClassTotal := ClassTotal + TotalScore;
END;
WRITELN;
WRITELN ('Class average:');
ClassTotal := ClassTotal DIV (ClassSize *NumberOfScores);
WRITELN(ClassTotal DIV 10, '.', ClassTotal MOD 10)
END. {AverageScore}
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, System.Rtti,
FMX.Grid.Style, FMX.Grid, FMX.ScrollBox, FMX.ListBox, FMX.Layouts, FMX.ComboEdit, FMX.SpinBox, FMX.EditBox, FMX.NumberBox;
type
TForm1 = class(TForm)
Edit1: TEdit;
CornerButton1: TCornerButton;
Label1: TLabel;
PasswordEditButton1: TPasswordEditButton;
StringGrid1: TStringGrid;
Column1: TColumn;
ProgressColumn1: TProgressColumn;
CheckColumn1: TCheckColumn;
DateColumn1: TDateColumn;
TimeColumn1: TTimeColumn;
PopupColumn1: TPopupColumn;
CurrencyColumn1: TCurrencyColumn;
FloatColumn1: TFloatColumn;
IntegerColumn1: TIntegerColumn;
GlyphColumn1: TGlyphColumn;
Grid1: TGrid;
ListBox1: TListBox;
ListBoxGroupHeader1: TListBoxGroupHeader;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ComboEdit1: TComboEdit;
ListBoxHeader1: TListBoxHeader;
ListBoxGroupHeader2: TListBoxGroupHeader;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
ComboBox1: TComboBox;
ListBoxGroupHeader3: TListBoxGroupHeader;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxGroupHeader4: TListBoxGroupHeader;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
CheckBox1: TCheckBox;
Switch1: TSwitch;
NumberBox1: TNumberBox;
SpinBox1: TSpinBox;
AniIndicator1: TAniIndicator;
procedure CornerButton1Click(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{$R *.Windows.fmx MSWINDOWS}
{$R *.LgXhdpiPh.fmx ANDROID}
{$R *.NmXhdpiPh.fmx ANDROID}
{$R *.SmXhdpiPh.fmx ANDROID}
{$R *.LgXhdpiTb.fmx ANDROID}
procedure TForm1.CornerButton1Click(Sender: TObject);
begin
ShowMessage(Edit1.Text);
end;
end.
|
unit uFastParser;
{$I ..\Include\IntXLib.inc}
interface
uses
{$IFDEF DELPHI}
Generics.Collections,
{$ENDIF DELPHI}
uParserBase,
uDigitOpHelper,
uIMultiplier,
uMultiplyManager,
uIParser,
uConstants,
uXBits,
uStrRepHelper,
uDigitHelper,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Fast parsing algorithm using divide-by-two (O[n*{log n}^2]).
/// </summary>
TFastParser = class sealed(TParserBase)
private
/// <summary>
/// Classic Parser Instance
/// </summary>
F_classicParser: IIParser;
public
/// <summary>
/// Creates new <see cref="FastParser" /> instance.
/// </summary>
/// <param name="pow2Parser">Parser for pow2 case.</param>
/// <param name="classicParser">Classic parser.</param>
constructor Create(pow2Parser: IIParser; classicParser: IIParser);
/// <summary>
/// Parses provided string representation of <see cref="TIntX" /> object.
/// </summary>
/// <param name="value">Number as string.</param>
/// <param name="startIndex">Index inside string from which to start.</param>
/// <param name="endIndex">Index inside string on which to end.</param>
/// <param name="numberBase">Number base.</param>
/// <param name="charToDigits">Char->digit dictionary.</param>
/// <param name="digitsRes">Resulting digits.</param>
/// <returns>Parsed integer length.</returns>
function Parse(const value: String; startIndex: Integer; endIndex: Integer;
numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>;
digitsRes: TIntXLibUInt32Array): UInt32; override;
end;
implementation
constructor TFastParser.Create(pow2Parser: IIParser; classicParser: IIParser);
begin
Inherited Create(pow2Parser);
F_classicParser := classicParser;
end;
function TFastParser.Parse(const value: String; startIndex: Integer;
endIndex: Integer; numberBase: UInt32;
charToDigits: TDictionary<Char, UInt32>;
digitsRes: TIntXLibUInt32Array): UInt32;
var
newLength, initialLength, valueLength, digitsLength, loLength, hiLength,
innerStep, outerStep, realLength: UInt32;
valueDigits, valueDigits2, tempDigits: TIntXLibUInt32Array;
valueDigitsStartPtr, valueDigitsStartPtr2, valueDigitsPtr, valueDigitsPtr2,
tempPtr, ptr1, ptr2, valueDigitsPtrEnd, baseDigitsPtr: PCardinal;
valueStartPtr, valuePtr, valueEndPtr: PChar;
multiplier: IIMultiplier;
baseInt: TIntX;
begin
newLength := Inherited Parse(value, startIndex, endIndex, numberBase,
charToDigits, digitsRes);
// Maybe base method already parsed this number
if (newLength <> 0) then
begin
result := newLength;
Exit;
end;
// Check length - maybe use classic parser instead
initialLength := UInt32(Length(digitsRes));
if (initialLength < TConstants.FastParseLengthLowerBound) then
begin
result := F_classicParser.Parse(value, startIndex, endIndex, numberBase,
charToDigits, digitsRes);
Exit;
end;
valueLength := UInt32(endIndex - startIndex + 1);
digitsLength := UInt32(1) shl TBits.CeilLog2(valueLength);
// Prepare array for digits in other base
SetLength(valueDigits, digitsLength);
// This second array will store integer lengths initially
SetLength(valueDigits2, digitsLength);
valueDigitsStartPtr := @valueDigits[0];
valueDigitsStartPtr2 := @valueDigits2[0];
// In the string first digit means last in digits array
valueDigitsPtr := valueDigitsStartPtr + valueLength - 1;
valueDigitsPtr2 := valueDigitsStartPtr2 + valueLength - 1;
// Reverse copy characters into digits
valueStartPtr := PChar(value);
// for Zero-Based Strings Language, Remove the '-1' .
valuePtr := valueStartPtr + startIndex - 1;
valueEndPtr := valuePtr + valueLength - 1;
// for Zero-Based Strings Language, Remove the '=' .
while valuePtr <= (valueEndPtr) do
begin
// Get digit itself - this call will throw an exception if char is invalid
valueDigitsPtr^ := TStrRepHelper.GetDigit(charToDigits, valuePtr^,
numberBase);
// Set length of this digit (zero for zero)
if valueDigitsPtr^ = UInt32(0) then
valueDigitsPtr2^ := UInt32(0)
else
begin
valueDigitsPtr2^ := UInt32(1);
end;
Inc(valuePtr);
Dec(valueDigitsPtr);
Dec(valueDigitsPtr2);
end;
// lengths array needs to be cleared before using
TDigitHelper.SetBlockDigits(valueDigitsStartPtr2 + valueLength,
digitsLength - valueLength, 0);
// Now start from the digit arrays beginning
valueDigitsPtr := valueDigitsStartPtr;
valueDigitsPtr2 := valueDigitsStartPtr2;
// Current multiplier (classic or fast) will be used
multiplier := TMultiplyManager.GetCurrentMultiplier();
// Here base in needed power will be stored
baseInt := Default (TIntX);
innerStep := 1;
outerStep := 2;
while innerStep < (digitsLength) do
begin
if baseInt = Default (TIntX) then
begin
baseInt := numberBase
end
else
begin
baseInt := baseInt * baseInt;
end;
baseDigitsPtr := @baseInt._digits[0];
// Start from arrays beginning
ptr1 := valueDigitsPtr;
ptr2 := valueDigitsPtr2;
// vauleDigits array end
valueDigitsPtrEnd := valueDigitsPtr + digitsLength;
// Cycle through all digits and their lengths
while ptr1 < (valueDigitsPtrEnd) do
begin
// Get lengths of "lower" and "higher" value parts
loLength := ptr2^;
hiLength := (ptr2 + innerStep)^;
if (hiLength <> 0) then
begin
// We always must clear an array before multiply
TDigitHelper.SetBlockDigits(ptr2, outerStep, UInt32(0));
// Multiply per baseInt
hiLength := multiplier.Multiply(baseDigitsPtr, baseInt._length,
ptr1 + innerStep, hiLength, ptr2);
end;
// Sum results
if ((hiLength <> 0) or (loLength <> 0)) then
begin
ptr1^ := TDigitOpHelper.Add(ptr2, hiLength, ptr1, loLength, ptr2);
end
else
begin
ptr1^ := UInt32(0);
end;
ptr1 := ptr1 + outerStep;
ptr2 := ptr2 + outerStep;
end;
// After inner cycle valueDigits will contain lengths and valueDigits2 will contain actual values
// so we need to swap them here
tempDigits := valueDigits;
valueDigits := valueDigits2;
valueDigits2 := tempDigits;
tempPtr := valueDigitsPtr;
valueDigitsPtr := valueDigitsPtr2;
valueDigitsPtr2 := tempPtr;
innerStep := innerStep shl 1;
outerStep := outerStep shl 1;
end;
// Determine real length of converted number
realLength := valueDigits2[0];
// Copy to result
Move(valueDigits[0], digitsRes[0], realLength * SizeOf(UInt32));
result := realLength;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Spin, Buttons;
type
{ TForm1 }
TForm1 = class(TForm)
bmbReset: TBitBtn;
btnDivideIntMod: TButton;
btnAddInt: TButton;
btnSubtractInt: TButton;
btnMultiplyInt: TButton;
btnDivideIntDiv: TButton;
btnAddReal: TButton;
btnSubtractReal: TButton;
btnMultiplyReal: TButton;
btnDivideReal: TButton;
edtFirst: TEdit;
edtSecond: TEdit;
edtResult: TEdit;
lblIntegerValues: TLabel;
lblStringValues: TLabel;
lblFirstValue: TLabel;
lblSecondValue: TLabel;
lblResult: TLabel;
sedFirst: TSpinEdit;
sedSecond: TSpinEdit;
sedResult: TSpinEdit;
procedure btnAddIntClick(Sender: TObject);
procedure btnDivideIntDivClick(Sender: TObject);
procedure btnDivideRealClick(Sender: TObject);
procedure btnSubtractRealClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.btnAddIntClick(Sender: TObject);
begin
sedResult.Value:=sedFirst.Value+sedSecond.Value;
btnAddInt.Enabled:=FALSE;
sedFirst.Enabled:=FALSE;
SedSecond.Enabled:=FALSE;
end;
procedure TForm1.btnDivideIntDivClick(Sender: TObject);
begin
sedResult.Value:=sedFirst.Value/sedSecond.Value;
end;
procedure TForm1.btnDivideRealClick(Sender: TObject);
var Answer: double;
begin
Answer:=StrToFloat(edtFirst.Text)/StrToFloat(edtSecond.Text);
edtResult.Text:=FloatTostrF(Answer, ffFIXED, 15, 2);
btnDivideReal.Enabled:=FALSE;
edtFirst.Enabled:=FALSE;
edtSecond.Enabled:=FALSE;
end;
procedure TForm1.btnSubtractRealClick(Sender: TObject);
begin
edtResult.Text:=FloatToStr(StrToFloat(edtFirst.Text)-StrToFloat(edtSecond.Text));
btnSubtractReal.Enabled:=FALSE;
edtFirst.Enabled:=FALSE;
edtSecond.Enabled:=FALSE;
end;
end.
|
{ Routines for opening and closing a use of the CAN library.
}
module can_open;
define can_init;
define can_open;
define can_close;
%include 'can2.ins.pas';
{
********************************************************************************
*
* Subroutine CAN_INIT (CL)
*
* Initialize the CAN library state CL. System resources will be allocated
* that will be released when the library use state is closed by calling
* CAN_CLOSE.
*
* After this call, the library use state is fully functional, but with no
* driver installed. This means that attempts to send CAN frames are silently
* ignored, and no CAN frames are ever received.
}
procedure can_init ( {init CAN library use state}
out cl: can_t); {library use state to initialize}
val_param;
var
ii: sys_int_machine_t;
stat: sys_err_t;
begin
cl.dev.name.max := size_char(cl.dev.name.str);
cl.dev.name.len := 0;
cl.dev.path.max := size_char(cl.dev.path.str);
cl.dev.path.len := 0;
cl.dev.nspec := 0;
for ii := 0 to can_spec_last_k do begin
cl.dev.spec[ii] := 0;
end;
cl.dev.devtype := can_dev_none_k;
sys_thread_lock_create (cl.lk_send, stat);
sys_error_abort (stat, '', '', nil, 0);
util_mem_context_get (util_top_mem_context, cl.mem_p); {create memory context}
can_queue_init (cl.inq, cl.mem_p^); {set up and init the input queue}
cl.dat_p := nil;
cl.send_p := nil;
cl.recv_p := nil;
cl.close_p := nil;
cl.quit := false;
end;
{
********************************************************************************
*
* Subroutine CAN_OPEN (CL, STAT)
*
* Open a use of the CAN library using CL as the library state. CL must have
* been previously initialized with CAN_INIT, with some modifications made
* afterwards. CL.DEV specifies the CAN device to use. If this does not
* specify a particular device, then the first compatible device that is found
* and not already in use is used.
}
procedure can_open ( {open new library use}
in out cl: can_t; {library use state}
out stat: sys_err_t); {completion status}
val_param;
var
scandev: boolean; {scan the device types until find a device}
label
try_dev;
begin
sys_error_none(stat); {init to no error encountered}
scandev := false; {init to try device type specified only}
if cl.dev.devtype = can_dev_none_k then begin {no device type specified ?}
scandev := true; {indicate scanning the device types}
cl.dev.devtype := succ(can_dev_custom_k); {init first device type to try}
end;
try_dev: {try opening the current device type}
case cl.dev.devtype of {which type of device to try to open ?}
can_dev_none_k: begin {not a real device type}
sys_stat_set (sys_subsys_k, sys_stat_failed_k, stat);
end;
can_dev_usbcan_k: begin {USBCAN device type}
can_open_usbcan (cl, stat);
end;
otherwise
sys_stat_set (can_subsys_k, can_stat_devtype_bad_k, stat);
sys_stat_parm_int (ord(cl.dev.devtype), stat);
return;
end;
if sys_error(stat) then begin {device not opened ?}
if scandev then begin {scanning device types ?}
if cl.dev.devtype = lastof(cl.dev.devtype) then begin {done scanning all device types ?}
cl.dev.devtype := can_dev_none_k;
sys_stat_set (can_subsys_k, can_stat_nodev_k, stat);
return; {hit end of devices list}
end;
cl.dev.devtype := succ(cl.dev.devtype); {advance to next device type}
goto try_dev; {back to try this new device type}
end;
return; {failed to open specific device}
end;
end;
{
********************************************************************************
*
* Subroutine CAN_CLOSE (CL, STAT)
*
* Close a use of the CAN library. CL is the library use state, which will be
* returned invalid.
}
procedure can_close ( {end a use of this library}
in out cl: can_t; {library use state, returned invalid}
out stat: sys_err_t); {completion status}
val_param;
var
stat2: sys_err_t; {to avoid corrupting STAT}
begin
cl.quit := true; {indicate trying to close this library use}
sys_error_none (stat); {init to no error}
if cl.close_p <> nil then begin {driver close routine exists ?}
cl.close_p^ (addr(cl), cl.dat_p, stat); {call driver close routine}
end;
can_queue_release (cl.inq); {release input queue resources}
util_mem_context_del (cl.mem_p); {delete all dynamic memory of this lib use}
sys_thread_lock_delete (cl.lk_send, stat2); {delete SEND_P mutex}
end;
|
namespace RemObjects.Elements.System;
interface
uses
Foundation;
type
TaskState = enum(Created, Queued, Started, Done) of Integer;
TaskBlock = public block();
TaskBlockGen<T> = public block(): T;
TaskCompletionSource<T> = public __ElementsTaskCompletionSource<T>;
Task = public __ElementsTask;
Task1<T> = public __ElementsTask1<T>;
__ElementsTask = public class
assembly
fState: TaskState;
fException: NSException;
fAsyncState: Object;
fDelegate: Object; // callable<T>; runnable
fDoneHandlers: Object; // nil, NSMutableArrayList or task
fLock: NSCondition := new NSCondition;
method DoRun; virtual;
method Done(ex: NSException);
method AddOrRunContinueWith(aTask: __ElementsTask);
constructor(aDelegate: Object; aState: Object);
public
constructor(aIn:TaskBlock; aState: Object := nil);
method ContinueWith(aAction: block(aTask: __ElementsTask); aState: Object := nil): __ElementsTask;
method ContinueWith<T>(aAction: block(aTask: __ElementsTask): T; aState: Object := nil): __ElementsTask1<T>;
class method Run(aIn: TaskBlock): __ElementsTask;
class method Run<T>(aIn: TaskBlockGen<T>): __ElementsTask1<T>;
property Exception: NSException read fException;
property AsyncState: Object read fAsyncState;
property IsFaulted: Boolean read fException <> nil;
property IsCompleted: Boolean read fState = TaskState.Done;
method &Await(aCompletion: __ElementsIAwaitCompletion): Boolean; // true = yield; false = long done
{$HIDE W38}
method Wait; reintroduce; virtual;
{$SHOW W38}
method Wait(aTimeoutMSec: Integer): Boolean; virtual;
method Start(aScheduler: dispatch_queue_t := nil); virtual;
class property CompletedTask: Task read new Task(fState := TaskState.Done); lazy;
class method FromResult<T>(x: T): Task1<T>;
begin
exit new Task1<T>(fState := TaskState.Done, fResult := x);
end;
class property ThreadSyncHelper: IThreadSyncHelper := new __ElementsDefaultThreadSyncHelper;
end;
__ElementsTask1<T> = public class(__ElementsTask)
assembly
fResult: T;
constructor(aDelegate: Object; aState: Object); empty;
method getResult: T;
method DoRun; override;
public
constructor(aIn: TaskBlockGen<T>; aState: Object := nil);
method ContinueWith(aAction: block(aTask: __ElementsTask1<T>); aState: Object := nil): __ElementsTask;
method ContinueWith<TR>(aAction: block(aTask: __ElementsTask1<T>): TR; aState: Object := nil): __ElementsTask1<TR>;
property &Result: T read getResult;
end;
__ElementsTaskCompletionSource<T> = public class
private
fTask: __ElementsTask1<T>;
public
constructor(aState: Object := nil);
method SetException(ex: NSException);
method SetResult(val: T);
property Task: __ElementsTask1<T> read fTask;
end;
TaskCompletionSourceTask<T> = class(__ElementsTask1<T>)
assembly
method DoRun; override; empty;
end;
__ElementsIAwaitCompletion = public interface
method moveNext(aState: Object);
end;
IThreadSyncHelper = public interface
method GetThreadContext: dispatch_queue_t;
method SyncBack(aContext: dispatch_queue_t; aAction: dispatch_block_t);
end;
__ElementsDefaultThreadSyncHelper = public class(IThreadSyncHelper)
public
method SyncBack(aContext: dispatch_queue_t; aAction: dispatch_block_t);
method GetThreadContext: dispatch_queue_t;
end;
implementation
{ __ElementsTask }
constructor __ElementsTask(aDelegate: Object; aState: Object);
begin
fDelegate := aDelegate;
fAsyncState := aState;
end;
constructor __ElementsTask(aIn: TaskBlock; aState: Object);
begin
if aIn = nil then raise new NSException withName(NSInvalidArgumentException) reason('aIn is nil') userInfo(nil);
constructor(Object(aIn), aState);
end;
method __ElementsTask.DoRun;
begin
fLock.lock;
try
fState := TaskState.Started;
finally
fLock.unlock;
end;
try
TaskBlock(fDelegate)();
Done(nil);
except
on ex: NSException do
Done(ex);
end;
end;
method __ElementsTask.Done(ex: NSException);
begin
fException := ex;
var lCW: Object;
fLock.lock;
try
fState := TaskState.Done;
lCW := fDoneHandlers;
fDoneHandlers := nil;
fLock.broadcast;
finally
fLock.unlock;
end;
if lCW <> nil then begin
var lTask := __ElementsTask(lCW);
if lTask <> nil then begin
lTask.DoRun;
end
else begin
var lList := NSMutableArray<__ElementsTask>(lCW);
for i: Integer := 0 to lList.count -1 do
lList[i].DoRun;
end;
end;
end;
method __ElementsTask.ContinueWith(aAction: block(aTask: __ElementsTask); aState: Object): __ElementsTask;
begin
result := new __ElementsTask(-> aAction(self), aState);
result.fState := TaskState.Queued;
AddOrRunContinueWith(result);
end;
method __ElementsTask.ContinueWith<T>(aAction:block(aTask: __ElementsTask): T; aState: Object): __ElementsTask1<T>;
begin
var r: TaskBlockGen<T> := -> aAction(self);
result := new __ElementsTask1(r, aState);
result.fState := TaskState.Queued;
AddOrRunContinueWith(result);
end;
method __ElementsTask.AddOrRunContinueWith(aTask: __ElementsTask);
begin
var lDone := false;
if fState = TaskState.Done then begin
lDone := true
end
else locking self do begin
if fState = TaskState.Done then begin
lDone := true
end
else if fDoneHandlers = nil then begin
fDoneHandlers := aTask
end
else begin
var lNew := new NSMutableArray<__ElementsTask>();
lNew.addObject(duck<__ElementsTask>(fDoneHandlers));
lNew.addObject(aTask);
fDoneHandlers := lNew;
end;
end;
if lDone then begin
aTask.DoRun;
end;
end;
method __ElementsTask.Wait;
begin
if fState = TaskState.Done then exit;
fLock.lock;
try
if fState = TaskState.Done then exit;
while fState <> TaskState.Done do begin
fLock.wait()
end;
finally
fLock.unlock;
end;
end;
method __ElementsTask.Wait(aTimeoutMSec: Integer): Boolean;
begin
if fState = TaskState.Done then
exit true;
fLock.lock;
try
if fState = TaskState.Done then
exit true;
var lTO := NSDate.date.dateByAddingTimeInterval(aTimeoutMSec * 0.001);
while fState <> TaskState.Done do begin
if not fLock.waitUntilDate(lTO) then
exit false;
end;
result := true;
finally
fLock.unlock;
end;
end;
method __ElementsTask.Start(aScheduler: dispatch_queue_t);
begin
fLock.lock;
try
if fState <> TaskState.Created then
raise new NSException withName(NSInvalidArgumentException) reason('Task already started/queued/done') userInfo(nil);
fState := TaskState.Queued;
finally
fLock.unlock;
end;
dispatch_async(coalesce(aScheduler, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)), -> DoRun());
end;
class method __ElementsTask.Run(aIn: TaskBlock): __ElementsTask;
begin
result := new __ElementsTask(aIn);
result.Start;
end;
class method __ElementsTask.Run<T>(aIn: TaskBlockGen<T>): __ElementsTask1<T>;
begin
result := new __ElementsTask1<T>(aIn);
result.Start;
end;
method __ElementsTask.Await(aCompletion: __ElementsIAwaitCompletion): Boolean;
begin
if IsCompleted then
exit false;
var q := __ElementsTask.ThreadSyncHelper.GetThreadContext;
if q <> nil then begin
ContinueWith(a -> begin
__ElementsTask.ThreadSyncHelper.SyncBack(q, -> begin
aCompletion.moveNext(a);
end);
end);
end else
ContinueWith(a -> begin
aCompletion.moveNext(a);
end, nil);
result := true;
end;
{ __ElementsTask1<T> }
method __ElementsTask1<T>.getResult: T;
begin
Wait();
if fException <> nil then
raise fException;
result := fResult;
end;
method __ElementsTask1<T>.DoRun;
begin
fLock.lock;
try
fState := TaskState.Started;
finally
fLock.unlock;
end;
try
fResult := TaskBlockGen<T>(fDelegate)();
Done(nil);
except
on ex: NSException do
Done(ex);
end;
end;
constructor __ElementsTask1<T>(aIn: TaskBlockGen<T>; aState: Object);
begin
if aIn = nil then raise new NSException withName(NSInvalidArgumentException) reason('aIn is nil') userInfo(nil);
inherited constructor(aIn, aState);
end;
method __ElementsTask1<T>.ContinueWith(aAction: block(aTask: __ElementsTask1<T>); aState: Object := nil): __ElementsTask;
begin
result := new __ElementsTask(-> aAction(self), aState);
result.fState := TaskState.Queued;
AddOrRunContinueWith(result);
end;
method __ElementsTask1<T>.ContinueWith<TR>(aAction: block(aTask: __ElementsTask1<T>): TR; aState: Object := nil): __ElementsTask1<TR>;
begin
var r: TaskBlockGen<TR> := -> aAction(self);
result := new __ElementsTask1(r, aState);
result.fState := TaskState.Queued;
AddOrRunContinueWith(result);
end;
{ __ElementsTaskCompletionSource<T> }
constructor __ElementsTaskCompletionSource<T>(aState: Object);
begin
fTask := new TaskCompletionSourceTask<T>(Object(nil), aState);
fTask.fState := TaskState.Started;
end;
method __ElementsTaskCompletionSource<T>.SetException(ex: NSException);
begin
fTask.fLock.lock;
try
if fTask.fState = TaskState.Done then raise new NSException withName(NSInvalidArgumentException) reason('Task already done') userInfo(nil);
fTask.fException := ex;
fTask.fState := TaskState.Done;
finally
fTask.fLock.unlock;
end;
fTask.Done(ex);
end;
method __ElementsTaskCompletionSource<T>.SetResult(val: T);
begin
fTask.fLock.lock;
try
if fTask.fState = TaskState.Done then raise new NSException withName(NSInvalidArgumentException) reason('Task already done') userInfo(nil);
fTask.fResult := val;
fTask.fState := TaskState.Done;
finally
fTask.fLock.unlock;
end;
fTask.Done(nil);
end;
{ __ElementsDefaultThreadSyncHelper }
method __ElementsDefaultThreadSyncHelper.GetThreadContext: dispatch_queue_t;
begin
if NSThread.isMainThread then
result := dispatch_get_main_queue;
end;
method __ElementsDefaultThreadSyncHelper.SyncBack(aContext: dispatch_queue_t; aAction: dispatch_block_t);
begin
dispatch_async(aContext, aAction);
end;
end. |
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
SysUtils, Dialogs, OpenGL;
type
TfrmGL = class(TForm)
Timer: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc : HGLRC;
Angle : GLfloat;
qObj : gluQuadricObj;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
implementation
uses DGLUT;
{$R *.DFM}
const
MaterialCyan : Array[0..3] of GLfloat = (0.0, 1.0, 1.0, 1.0);
MaterialYellow : Array[0..3] of GLfloat = (1.0, 1.0, 0.0, 0.0);
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
// очистка буфера цвета и буфера глубины
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
// трехмерность
glPushMatrix;
glRotatef(Angle, 0.0, 1.0, 0.0); // поворот на угол
glRotatef(Angle, 1.0, 0.0, 0.0); // поворот на угол
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @MaterialCyan);
glutSolidCube (2.0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @MaterialYellow);
glTranslatef (0.0, 0.0, -2.0);
gluCylinder (qObj, 0.2, 0.2, 4.0, 10, 10);
glRotatef (90, 1.0, 0.0, 0.0);
glTranslatef (0.0, 2.0, -2.0);
gluCylinder (qObj, 0.2, 0.2, 4.0, 10, 10);
glTranslatef (-2.0, 0.0, 2.0);
glRotatef (90, 0.0, 1.0, 0.0);
gluCylinder (qObj, 0.2, 0.2, 4.0, 10, 10);
glPopMatrix;
SwapBuffers(DC); // конец работы
EndPaint(Handle, ps);
end;
{=======================================================================
Обработка таймера}
procedure TfrmGL.TimerTimer(Sender: TObject);
begin
// Каждый "тик" изменяется значение угла
Angle := Angle + 1.0;
InvalidateRect(Handle, nil, False); // перерисовка региона
end;
{=======================================================================
Установка формата пикселей}
procedure TfrmGL.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 TfrmGL.FormCreate(Sender: TObject);
begin
Angle := 0;
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glEnable(GL_DEPTH_TEST); // разрешаем тест глубины
glEnable(GL_LIGHTING); // разрешаем работу с освещенностью
glEnable(GL_LIGHT0); // включаем источник света 0
// Определяем свойства материала - лицевые стороны - рассеянный
// цвет материала и диффузное отражение материала - значения из массива
qObj := gluNewQuadric;
Timer.Enabled := True;
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(40.0, ClientWidth / ClientHeight, 3.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -8.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
Timer.Enabled := False;
gluDeleteQuadric (qObj);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
end.
|
unit Chocolatey;
{$mode objfpc}{$H+}
interface
uses
Classes, Process, SysUtils;
type
{ TChocolatey }
TChocolatey = class
public
function Search(AString: String): String;
procedure DivideLines(AString: String; AList: TStringList);
function PackageInfo(AString: String): String;
end;
implementation
const
CHOCO = 'C:\ProgramData\chocolatey\bin\choco.exe';
{ TChocolatey }
function TChocolatey.Search(AString: String): String;
begin
RunCommand(CHOCO, ['list', AString], Result);
end;
procedure TChocolatey.DivideLines(AString: String; AList: TStringList);
var
CrPos: Integer;
StringBeforeCr: String;
begin
AList.Clear;
CrPos:= Pos(#13#10, AString);
while CrPos >= 1 do
begin
StringBeforeCr:= Copy(AString, 1, CrPos - 1);
AList.Add(StringBeforeCr);
AString:= Copy(AString, CrPos + 2, Length(AString));
CrPos:= Pos(#13#10, AString);
end
end;
function TChocolatey.PackageInfo(AString: String): String;
begin
RunCommand(CHOCO, ['info', AString], Result);
end;
end.
|
unit DX.Messages.Dialog.Listener.FMX;
interface
uses
System.Classes, System.SysUtils,
DX.Messages.Dialog.Listener, DX.Messages.Dialog;
type
TMessageDialogListener = class(TMessageDialogListenerBase)
strict protected
procedure ShowMessageDialog(const AMessageRequest: TMessageDialogRequest); override;
public
end;
implementation
uses
System.UITypes,
FMX.DialogService, DX.Messages.Dialog.Types, DX.Messages.Dialog.UITypesHelper;
procedure TMessageDialogListener.ShowMessageDialog(const AMessageRequest: TMessageDialogRequest);
begin
TDialogService.MessageDialog(AMessageRequest.Message, TMsgDlgType.mtConfirmation, TUITypesHelper.MessageButtonsFromDialogOptions(AMessageRequest.Options),
TUITypesHelper.MessageButtonFromDialogOption(AMessageRequest.Response), 0,
procedure(const AResult: TModalResult)
begin
AMessageRequest.Response := TUITypesHelper.DialogOptionFromModalResult(AResult);
end);
end;
end.
|
unit mergevertices;
//this function merges nearby vertices as a single vertex
// due to rouding errors, meshes can exhibit gaps and tears creating non-manifold meshes
// this code merges vertices that are within a given radius (the tolerance)
// if the tolerance is zero, only identical vertices are merged
// if the tolerance is 0.0001 than vertices within 0.001 are merged
{$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF}
interface
uses
Classes, sysutils, meshify_simplify_quadric;
//procedure UnifyVertices(var faces: TFaces; var vertices: TVertices; Radius: single);
procedure UnifyVertices(var faces: TFaces; var vertices: TVertices; Radius: single);
implementation
type
TSortType = single; //can be integer, single, double, etc
TSort = record
index: integer;
value: TSortType;
end;
TSortArray = array of TSort;
TInts = array of integer;
//http://stackoverflow.com/questions/24335585/quicksort-drama
procedure QuickSort(left, right: integer; var s: TSortArray);
// left: Index des 1. Elements, right: Index des letzten Elements
var
l, r, lswap: integer;
pivot: TSortType;
begin
if (right > left) then begin
l := left;
r := right;
pivot := s[s[(right + left) div 2].index].value;
while (l < r) do begin
while s[s[l].index].value < pivot do
l := l + 1;
while s[s[r].index].value > pivot do
r := r - 1;
if (l <= r) then begin
lswap := s[r].index;
s[r].index := s[l].index;
s[l].index := lswap;
l := l + 1;
r := r - 1;
end;
end;
if (left < r) then
QuickSort(left, r, s);
if (right > l) then
QuickSort(l, right, s);
end;
end;
procedure SortArrayIndices(var s: TSortArray); //sorts indices, not values!
var
i : integer;
begin
if length(s) < 1 then exit;
for i := 0 to (length(s)-1) do //set indices
s[i].index := i;
quicksort(low(s), high(s), s);
end;
procedure vectorAdd (var A: TPoint3f; B: TPoint3f); inline;
//sum two vectors
begin
A.X := A.X + B.X;
A.Y := A.Y + B.Y;
A.Z := A.Z + B.Z;
end; // vectorAdd()
function vectorScale(A: TPoint3f; Scale: single): TPoint3f;// overload;
begin
result.X := A.X * Scale;
result.Y := A.Y * Scale;
result.Z := A.Z * Scale;
end;
procedure ClusterVertex( var faces: TFaces; var vertices: TVertices; Radius: single);
var
s: TSortArray;
j,i, nv,nc,nvPost: integer;
z, dz, dx: TSortType;
pt,sum: TPoint3f;
face: TPoint3i;
newVert: TVertices;
oldFaces: TFaces;
radiusSqr: single;
cluster, remap: TInts;
begin
nv := length(vertices);
if (nv < 3) or (Radius < 0) then exit;
setlength(s,nv);
setlength(remap,nv);
setlength(cluster,nv);
for i := 0 to (nv -1) do begin
s[i].value := vertices[i].Z;
cluster[i] := i;
remap[i] := -1;
end;
SortArrayIndices(s);
nvPost := 0;
setLength(newVert, nv);
if Radius <= 0 then begin
for i := 0 to (nv - 1) do begin
if cluster[i] = i then begin //not part of previous cluster
pt := vertices[s[i].index];
j := i + 1;
while (j < nv) and (vertices[s[j].index].Z = pt.Z) do begin //i.Z==j.Z
if (vertices[s[j].index].X = pt.X) and (vertices[s[j].index].Y = pt.Y) then begin//i.X==j.X, i.Y==j.Y
cluster[j] := nvPost;
remap[s[j].index] := nvPost;
end;
j := j + 1;
end;
newVert[nvPost] := pt;
cluster[i] := nvPost;
remap[s[i].index] := nvPost;
nvPost := nvPost + 1; //no neighbors
end; //not yet clustered
end; //for each vertex
end else begin //Radius > 0
radiusSqr := sqr(Radius); //avoids calculating square-root for each comparison
for i := 0 to (nv - 1) do begin
if cluster[i] = i then begin //not part of previous cluster
z := s[s[i].index].value;
pt := vertices[s[i].index];
sum := pt;
dz := 0;
j := i + 1;
nc := 1;
while (dz <= Radius) and (j < nv) do begin
dz := abs(s[s[j].index].value - z);
//dx := vectorDistance(pt, vertices[s[j].index]);
dx := sqr(pt.X-vertices[s[j].index].X)+ sqr(pt.Y-vertices[s[j].index].Y) + sqr(pt.Z-vertices[s[j].index].Z);
if dx <= radiusSqr then begin
vectorAdd(sum, vertices[s[j].index]);
cluster[j] := nvPost;
remap[s[j].index] := nvPost;
nc := nc + 1;
end;
j := j + 1;
end;
newVert[nvPost] := vectorScale(sum, 1/nc);
cluster[i] := nvPost;
remap[s[i].index] := nvPost;
nvPost := nvPost + 1; //no neighbors
end; //not yet clustered
end; //for each vertex
end;
if nvPost = nv then exit; //no clusters - no change!
vertices := Copy(newVert, Low(newVert), nvPost);
//remap faces to new vertices
oldFaces := Copy(faces, Low(faces), Length(faces));
setlength(faces,0);
for i := 0 to (length(oldFaces) - 1) do begin
face.X := remap[oldFaces[i].X];
face.Y := remap[oldFaces[i].Y];
face.Z := remap[oldFaces[i].Z];
if (face.X <> face.Y) and (face.X <> face.Z) and (face.Y <> face.Z) then begin //exclude degenerate faces
setlength(Faces,length(Faces)+1);
Faces[High(Faces)].X := face.X;
Faces[High(Faces)].Y := face.Y;
Faces[High(Faces)].Z := face.Z;
end;
end;
end;
procedure UnifyVertices(var faces: TFaces; var vertices: TVertices; Radius: single);
//STL format saves raw vertices, this uses a lot of RAM and makes estimating vertex normals impossible...
// http://www.mathworks.com/matlabcentral/fileexchange/29986-patch-slim--patchslim-m-
var vStart, vEnd: integer;
begin
if (Radius < 0) then exit;
vStart := length(vertices);
ClusterVertex(faces, vertices, Radius);
vEnd := length(vertices);
if vStart = vEnd then exit;
if (Radius = 0) then
writeln(format(' removed identical vertices, reducing number from %d to %d', [vStart, vEnd ]))
else
writeln(format(' removed identical(ish) vertices, reducing number from %d to %d', [vStart, vEnd ]));
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
File types colors options page
Copyright (C) 2006-2016 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
}
unit fOptionsFileTypesColors;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, StdCtrls, ColorBox, Dialogs, Buttons,
fOptionsFrame;
type
{ TfrmOptionsFileTypesColors }
TfrmOptionsFileTypesColors = class(TOptionsEditor)
optColorDialog: TColorDialog;
btnAddCategory: TBitBtn;
btnApplyCategory: TBitBtn;
btnDeleteCategory: TBitBtn;
btnCategoryColor: TButton;
btnSearchTemplate: TBitBtn;
cbCategoryColor: TColorBox;
edtCategoryAttr: TEdit;
edtCategoryMask: TEdit;
edtCategoryName: TEdit;
gbFileTypesColors: TGroupBox;
lbCategories: TListBox;
lblCategoryAttr: TLabel;
lblCategoryColor: TLabel;
lblCategoryMask: TLabel;
lblCategoryName: TLabel;
procedure lbCategoriesClick(Sender: TObject);
procedure btnSearchTemplateClick(Sender: TObject);
procedure btnAddCategoryClick(Sender: TObject);
procedure btnApplyCategoryClick(Sender: TObject);
procedure btnDeleteCategoryClick(Sender: TObject);
procedure btnCategoryColorClick(Sender: TObject);
procedure lbCategoriesDragDrop(Sender, {%H-}Source: TObject; {%H-}X, Y: Integer);
procedure lbCategoriesDragOver(Sender, Source: TObject; {%H-}X, {%H-}Y: Integer;
{%H-}State: TDragState; var Accept: Boolean);
procedure lbCategoriesDrawItem(Control: TWinControl; Index: Integer;
ARect: TRect; {%H-}State: TOwnerDrawState);
procedure Clear;
protected
procedure Init; override;
procedure Load; override;
function Save: TOptionsEditorSaveFlags; override;
public
destructor Destroy; override;
class function GetIconIndex: Integer; override;
class function GetTitle: String; override;
function IsSignatureComputedFromAllWindowComponents: Boolean; override;
end;
implementation
{$R *.lfm}
uses
Graphics, uLng, uGlobs, uColorExt, fMaskInputDlg, uSearchTemplate, uDCUtils;
{ TfrmOptionsFileTypesColors }
procedure TfrmOptionsFileTypesColors.lbCategoriesClick(Sender: TObject);
var
MaskItem : TMaskItem;
bEnabled: Boolean;
begin
if (lbCategories.ItemIndex <> -1) then
begin
MaskItem := TMaskItem(lbCategories.Items.Objects[lbCategories.ItemIndex]);
edtCategoryName.Text := MaskItem.sName;
edtCategoryMask.Text := MaskItem.sExt;
SetColorInColorBox(cbCategoryColor, MaskItem.cColor);
bEnabled:= (MaskItem.sExt = '') or (MaskItem.sExt[1] <> '>');
edtCategoryMask.Enabled:= bEnabled;
edtCategoryAttr.Enabled:= bEnabled;
edtCategoryAttr.Text := MaskItem.sModeStr;
end
else
begin
edtCategoryName.Text := '';
edtCategoryMask.Text := '';
edtCategoryAttr.Text := '';
cbCategoryColor.ItemIndex := -1;
end;
end;
procedure TfrmOptionsFileTypesColors.btnSearchTemplateClick(Sender: TObject);
var
sMask: String;
bTemplate: Boolean;
begin
sMask:= edtCategoryMask.Text;
if ShowMaskInputDlg(rsMarkPlus, rsMaskInput, glsMaskHistory, sMask) then
begin
bTemplate:= IsMaskSearchTemplate(sMask);
edtCategoryMask.Text:= sMask;
if bTemplate then edtCategoryAttr.Text:= EmptyStr;
edtCategoryMask.Enabled:= not bTemplate;
edtCategoryAttr.Enabled:= not bTemplate;
end;
end;
procedure TfrmOptionsFileTypesColors.btnAddCategoryClick(Sender: TObject);
var
iIndex : Integer;
MaskItem: TMaskItem;
begin
if lbCategories.Count = 0 then
begin
edtCategoryName.Enabled := True;
edtCategoryMask.Enabled := True;
edtCategoryAttr.Enabled := True;
cbCategoryColor.Enabled := True;
btnCategoryColor.Enabled := True;
btnDeleteCategory.Enabled := True;
btnApplyCategory.Enabled := True;
end;
MaskItem := TMaskItem.Create;
try
edtCategoryName.Text := rsOptionsEditorFileNewFileTypes;
edtCategoryMask.Text := '*';
edtCategoryAttr.Text := '';
cbCategoryColor.ItemIndex := -1;
MaskItem.sName:= edtCategoryName.Text;
MaskItem.sExt:= edtCategoryMask.Text;
MaskItem.sModeStr:= edtCategoryAttr.Text;
MaskItem.cColor:= clBlack;
iIndex := lbCategories.Items.AddObject(MaskItem.sName, MaskItem);
except
FreeAndNil(MaskItem);
raise;
end;
lbCategories.ItemIndex:= iIndex;
edtCategoryName.SetFocus;
end;
procedure TfrmOptionsFileTypesColors.btnApplyCategoryClick(Sender: TObject);
var
MaskItem : TMaskItem;
begin
if (lbCategories.ItemIndex <> -1) then
begin
lbCategories.Items[lbCategories.ItemIndex] := edtCategoryName.Text;
if edtCategoryMask.Text = '' then
edtCategoryMask.Text := '*'; // because we load colors from ini by mask
MaskItem := TMaskItem(lbCategories.Items.Objects[lbCategories.ItemIndex]);
MaskItem.sName := edtCategoryName.Text;
MaskItem.cColor := cbCategoryColor.Selected;
MaskItem.sExt := edtCategoryMask.Text;
MaskItem.sModeStr := edtCategoryAttr.Text;
end;
end;
procedure TfrmOptionsFileTypesColors.btnDeleteCategoryClick(Sender: TObject);
begin
if (lbCategories.ItemIndex <> -1) then
begin
lbCategories.Items.Objects[lbCategories.ItemIndex].Free;
lbCategories.Items.Delete(lbCategories.ItemIndex);
if lbCategories.Count > 0 then
lbCategories.ItemIndex := 0;
lbCategoriesClick(lbCategories);
end;
end;
procedure TfrmOptionsFileTypesColors.btnCategoryColorClick(Sender: TObject);
begin
optColorDialog.Color:= cbCategoryColor.Selected;
if optColorDialog.Execute then
SetColorInColorBox(cbCategoryColor, optColorDialog.Color);
end;
procedure TfrmOptionsFileTypesColors.lbCategoriesDragDrop(Sender,
Source: TObject; X, Y: Integer);
var
SrcIndex, DestIndex: Integer;
begin
SrcIndex := lbCategories.ItemIndex;
if SrcIndex = -1 then
Exit;
DestIndex := lbCategories.GetIndexAtY(Y);
if (DestIndex < 0) or (DestIndex >= lbCategories.Count) then
DestIndex := lbCategories.Count - 1;
lbCategories.Items.Move(SrcIndex, DestIndex);
lbCategories.ItemIndex := DestIndex;
end;
procedure TfrmOptionsFileTypesColors.lbCategoriesDragOver(Sender,
Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
Accept := (Source = lbCategories) and (lbCategories.ItemIndex <> -1);
end;
procedure TfrmOptionsFileTypesColors.lbCategoriesDrawItem(Control: TWinControl;
Index: Integer; ARect: TRect; State: TOwnerDrawState);
begin
with (Control as TListBox) do
begin
if (not Selected[Index]) and Assigned(Items.Objects[Index]) then
begin
Canvas.Brush.Color:= gBackColor;
Canvas.Font.Color:= TMaskItem(Items.Objects[Index]).cColor;
end
else
begin
Canvas.Brush.Color:= gCursorColor;
Canvas.Font.Color:= gCursorText;
end;
Canvas.FillRect(ARect);
Canvas.TextOut(ARect.Left+2,ARect.Top,Items[Index]);
end;
end;
procedure TfrmOptionsFileTypesColors.Clear;
var
i: Integer;
begin
for i := lbCategories.Count - 1 downto 0 do
lbCategories.Items.Objects[i].Free;
lbCategories.Clear;
end;
procedure TfrmOptionsFileTypesColors.Init;
begin
lbCategories.Canvas.Font := lbCategories.Font;
lbCategories.ItemHeight := lbCategories.Canvas.TextHeight('Wg');
end;
class function TfrmOptionsFileTypesColors.GetIconIndex: Integer;
begin
Result := 21;
end;
class function TfrmOptionsFileTypesColors.GetTitle: String;
begin
Result := rsOptionsEditorFileTypes;
end;
function TfrmOptionsFileTypesColors.IsSignatureComputedFromAllWindowComponents: Boolean;
begin
Result := False;
end;
procedure TfrmOptionsFileTypesColors.Load;
var
I : Integer;
MaskItem: TMaskItem;
begin
Clear;
lbCategories.Color:= gBackColor;
{ File lbtypes category color }
for I := 0 to gColorExt.Count - 1 do
begin
MaskItem := TMaskItem.Create;
try
MaskItem.Assign(gColorExt[I]);
lbCategories.Items.AddObject(MaskItem.sName, MaskItem);
except
FreeAndNil(MaskItem);
raise;
end;
end; // for
if lbCategories.Count > 0 then
lbCategories.ItemIndex := 0
else
begin
edtCategoryName.Enabled := False;
edtCategoryMask.Enabled := False;
edtCategoryAttr.Enabled := False;
cbCategoryColor.Enabled := False;
btnCategoryColor.Enabled := False;
btnDeleteCategory.Enabled := False;
btnApplyCategory.Enabled := False;
end;
lbCategoriesClick(lbCategories);
end;
function TfrmOptionsFileTypesColors.Save: TOptionsEditorSaveFlags;
var
i: Integer;
MaskItem: TMaskItem;
begin
Result := [];
gColorExt.Clear;
for I := 0 to lbCategories.Count - 1 do //write new categories
if Assigned(lbCategories.Items.Objects[I]) then
begin
MaskItem := TMaskItem.Create;
try
MaskItem.Assign(TMaskItem(lbCategories.Items.Objects[I]));
gColorExt.Add(MaskItem);
except
FreeAndNil(MaskItem);
raise;
end;
end;
end;
destructor TfrmOptionsFileTypesColors.Destroy;
begin
Clear;
inherited;
end;
end.
|
unit MAIN;
interface
uses
Forms, ImgList, Controls, StdActns, Classes, ActnList, Dialogs, Menus,
ComCtrls, ToolWin, Utils;
// Windows, SysUtils, Graphics,
// StdCtrls, Buttons, Messages, ExtCtrls,
type
TMainForm = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
FileNewItem: TMenuItem;
FileOpenItem: TMenuItem;
FileCloseItem: TMenuItem;
Window1: TMenuItem;
Help1: TMenuItem;
N1: TMenuItem;
FileExitItem: TMenuItem;
WindowCascadeItem: TMenuItem;
WindowTileItem: TMenuItem;
WindowArrangeItem: TMenuItem;
HelpAboutItem: TMenuItem;
OpenDialog: TOpenDialog;
FileSaveItem: TMenuItem;
FileSaveAsItem: TMenuItem;
Edit1: TMenuItem;
CutItem: TMenuItem;
CopyItem: TMenuItem;
PasteItem: TMenuItem;
WindowMinimizeItem: TMenuItem;
StatusBar: TStatusBar;
ActionList1: TActionList;
EditCut1: TEditCut;
EditCopy1: TEditCopy;
EditPaste1: TEditPaste;
FileNew1: TAction;
FileSave1: TAction;
FileExit1: TAction;
FileOpen1: TAction;
FileSaveAs1: TAction;
WindowCascade1: TWindowCascade;
WindowTileHorizontal1: TWindowTileHorizontal;
WindowArrangeAll1: TWindowArrange;
WindowMinimizeAll1: TWindowMinimizeAll;
HelpAbout: TAction;
FileClose1: TWindowClose;
WindowTileVertical1: TWindowTileVertical;
WindowTileItem2: TMenuItem;
ToolBar2: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton9: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton10: TToolButton;
ToolButton11: TToolButton;
ImageList1: TImageList;
procedure FileNew1Execute(Sender: TObject);
procedure FileOpen1Execute(Sender: TObject);
procedure HelpAboutExecute(Sender: TObject);
procedure FileExit1Execute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure CreateMDIChild(const Name: string);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses ProProgramu;
{$R *.dfm}
//uses CHILDWIN, about;
procedure TMainForm.CreateMDIChild(const Name: string);
{
var
Child: TMDIChild;
}
begin
{
Child := TMDIChild.Create(Application);
Child.Caption := Name;
if FileExists(Name) then Child.Memo1.Lines.LoadFromFile(Name);
}
end;
procedure TMainForm.FileNew1Execute(Sender: TObject);
begin
{
CreateMDIChild('NONAME' + IntToStr(MDIChildCount + 1));
}
end;
procedure TMainForm.FileOpen1Execute(Sender: TObject);
begin
{
if OpenDialog.Execute then
CreateMDIChild(OpenDialog.FileName);
}
end;
procedure TMainForm.FormCreate(Sender: TObject);
{
var
ws: integer;
Path, srvname: string;
UserName, Password: string;
}
begin
{
ws:=0;
//Начальные параметры окна
try
Application.OnMessage:=frmMain.AppMessage;
Application.OnHint:=ShowHint;
frmMain.Caption:='Адміністративно-запобіжні заходи';
INIAZZ:=TIniFile.Create(ExtractFilePath(Application.ExeName)+'AZZ.INI');
frmMain.Width:=INIAZZ.ReadInteger('Main','Width',Width);
frmMain.Height:=INIAZZ.ReadInteger('Main','Height',Height);
frmMain.Left:=INIAZZ.ReadInteger('Main','Left',Left);
frmMain.Top:=INIAZZ.ReadInteger('Main','Top',Top);
ws:=INIAZZ.ReadInteger('Main','WindowState',ws);
case ws of
0: frmMain.WindowState:=wsNormal;
1: frmMain.WindowState:=wsNormal;
2: frmMain.WindowState:=wsMaximized;
end;
Path:=INIAZZ.ReadString('DataBase','AliasName',Path);
srvname:=INIAZZ.ReadString('DataBase','ServerName',srvname);
if frmMain.dbAzz.Connected then frmMain.dbAzz.Connected:=false;
if frmMain.trAzz.Active then frmMain.trAzz.Active:=false;
frmMain.dbAzz.DatabaseName:=srvname+':'+path;
trAzz.Params.Clear;
trAzz.Params.Add('read_committed');
trAzz.Params.Add('rec_version');
trAzz.Params.Add('nowait');
UserName:=INIAZZ.ReadString('DataBase','UserName',UserName);
Password:=INIAZZ.ReadString('DataBase','Password',Password);
dbAzz.Params.Clear;
dbAzz.Params.Add('user_name='+UserName);
dbAzz.Params.Add('password='+Password);
INIAZZ.Free;
finally
if not frmMain.IsFormOpen('frmLogOn') then frmLogOn:=TfrmLogOn.Create(Self);
frmLogOn.Show;
frmLogOn.FormStyle:=fsStayOnTop;
frmLogOn.BorderStyle:=bsDialog;
frmLogOn.Caption:='Пыдключення до БД';
frmLogOn.Position:=poMainFormCenter;
frmLogOn.edtServer.Text:=frmMain.dbAzz.DatabaseName;
frmLogOn.edtUser_Name.Text:='';
frmLogOn.edtPassword.Text:='';
frmMain.Enabled:=false;
frmLogOn.edtUser_Name.SetFocus;
end;
frmMain.cbMain.AutoSize:=true;
// ShowMessage('доделать проверку пользователя и пароля');
if frmMain.IsFormOpen('frmFinansoviSankcii') then
begin
with frmMain do
begin
N13.Visible:=true;
mnZahodiFinansovi_SankciiNeVrucheni.Visible:=true;
mnZahodiFinansovi_SankciiNeSplacheni.Visible:=true;
mnZahodiFinansovi_SankciiOskarzheni.Visible:=true;
mnZahodiFinansovi_SankciiObjekt.Visible:=true;
mnZahodiFinansovi_SankciiObjektNazvaObjektu.Visible:=true;
mnZahodiFinansovi_SankciiObjektAdresaObjektu.Visible:=true;
mnZahodiFinansovi_SankciiSES.Visible:=true;
mnZahodiFinansovi_SankciiSESPIBPredstavnika.Visible:=true;
mnZahodiFinansovi_SankciiSESPosadaPredstavnika.Visible:=true;
mnZahodiFinansovi_SankciiTipProdukcii.Visible:=true;
mnZahodiFinansovi_SankciiRozdilT23F18.Visible:=true;
end;
end
else
begin
with frmMain do
begin
N13.Visible:=true;
mnZahodiFinansovi_SankciiNeVrucheni.Visible:=false;
mnZahodiFinansovi_SankciiNeSplacheni.Visible:=false;
mnZahodiFinansovi_SankciiOskarzheni.Visible:=false;
mnZahodiFinansovi_SankciiObjekt.Visible:=false;
mnZahodiFinansovi_SankciiObjektNazvaObjektu.Visible:=false;
mnZahodiFinansovi_SankciiObjektAdresaObjektu.Visible:=false;
mnZahodiFinansovi_SankciiSES.Visible:=false;
mnZahodiFinansovi_SankciiSESPIBPredstavnika.Visible:=false;
mnZahodiFinansovi_SankciiSESPosadaPredstavnika.Visible:=false;
mnZahodiFinansovi_SankciiTipProdukcii.Visible:=false;
mnZahodiFinansovi_SankciiRozdilT23F18.Visible:=false;
end;
end;
if frmMain.IsFormOpen('frmViluchennyZRealizacii') then
begin
with frmMain do
begin
mnVibir_Viluchenny_Choices.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiNeVrucheni.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiOskarzheni.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiNazvaObjektu.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiAdresaObjektu.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiTipPostanovi.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiPIBOsobiSES.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiPosadaOsobiSES.Visible:=true;
mnZahodiViluchenny_Z_RealizaciiTipProdukcii.Visible:=true;
mnZahodiViluchenny_Z_RealizaciilRozdilT23F18.Visible:=true;
end;
end
else
begin
with frmMain do
begin
mnVibir_Viluchenny_Choices.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiNeVrucheni.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiOskarzheni.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiNazvaObjektu.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiAdresaObjektu.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiTipPostanovi.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiPIBOsobiSES.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiPosadaOsobiSES.Visible:=false;
mnZahodiViluchenny_Z_RealizaciiTipProdukcii.Visible:=false;
mnZahodiViluchenny_Z_RealizaciilRozdilT23F18.Visible:=false;
end;
end;
if frmMain.IsFormOpen('frmAdminZapobizhZahodi') then
begin
with frmMain do
begin
mnAdminChoices.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiNeVrucheni.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiNeZnytiZKontrolu.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiOskarzheni.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiNePovidomleni.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiPovidomleni.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiOpechatani.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiNeVidnovleni.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiObmezhennyAsortimentu.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiNazvaObjektu.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiAdresaObjektu.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiPIBPredstavnikaSES.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiTipPostanovi.Visible:=true;
mnZahodiAdmin_Zapobizh_ZahodiRozdilT23F18.Visible:=true;
end;
end
else
begin
with frmMain do
begin
mnAdminChoices.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiNeVrucheni.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiNeZnytiZKontrolu.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiOskarzheni.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiNePovidomleni.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiPovidomleni.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiOpechatani.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiNeVidnovleni.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiObmezhennyAsortimentu.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiNazvaObjektu.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiAdresaObjektu.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiPIBPredstavnikaSES.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiTipPostanovi.Visible:=false;
mnZahodiAdmin_Zapobizh_ZahodiRozdilT23F18.Visible:=false;
end;
end;
if frmMain.IsFormOpen('frmShtrafi') then
begin
with frmMain do
begin
mnShtrafiChoices.Visible:=true;
mnZahodiShtrafiNeSplacheni.Visible:=true;
mnZahodiShtrafiNeVrucheni.Visible:=true;
mnZahodiShtrafiPeredaniDoVDVS.Visible:=true;
mnZahodiShtrafiPeredaniDoVDVSPeredani.Visible:=true;
mnZahodiShtrafiPeredaniDoVDVSSplacheni.Visible:=true;
mnZahodiShtrafiNePeredaniDoVDVS.Visible:=true;
mnZahodiShtrafiPrimusovoStygneni.Visible:=true;
mnZahodiShtrafiSkasovani.Visible:=true;
mnZahodiShtrafiSpivrobitnik.Visible:=true;
mnZahodiShtrafiTipShtrafu.Visible:=true;
mnZahodiShtrafiObjekt.Visible:=true;
mnZahodiShtrafiObjektAdresa.Visible:=true;
mnZahodiShtrafiObjektNazva.Visible:=true;
mnZahodiShtrafiRozdilT23F18.Visible:=true;
end;
end
else
begin
with frmMain do
begin
mnShtrafiChoices.Visible:=false;
mnZahodiShtrafiNeSplacheni.Visible:=false;
mnZahodiShtrafiNeVrucheni.Visible:=false;
mnZahodiShtrafiPeredaniDoVDVS.Visible:=false;
mnZahodiShtrafiPeredaniDoVDVSPeredani.Visible:=false;
mnZahodiShtrafiPeredaniDoVDVSSplacheni.Visible:=false;
mnZahodiShtrafiNePeredaniDoVDVS.Visible:=false;
mnZahodiShtrafiPrimusovoStygneni.Visible:=false;
mnZahodiShtrafiSkasovani.Visible:=false;
mnZahodiShtrafiSpivrobitnik.Visible:=false;
mnZahodiShtrafiTipShtrafu.Visible:=false;
mnZahodiShtrafiObjekt.Visible:=false;
mnZahodiShtrafiObjektAdresa.Visible:=false;
mnZahodiShtrafiObjektNazva.Visible:=false;
mnZahodiShtrafiRozdilT23F18.Visible:=false;
end;
end;
}
end;
procedure TMainForm.HelpAboutExecute(Sender: TObject);
begin
try
if not IsFormOpen('frmProProgramu') then frmProProgramu:=TfrmProProgramu.Create(self);
try
frmProProgramu.Caption:='Про програму...';
frmProProgramu.Position:=poMainFormCenter;
frmProProgramu.BorderStyle:=bsDialog;
frmProProgramu.ShowModal;
finally
frmProProgramu.Free;
end;
except
Exit;
end;
{
if not IsFormOpen('frmProProgramu') then
begin
try
frmProProgramu:=TfrmProProgramu.Create(self);
except
exit;
end;
end
else
begin
frmProProgramu.Free;
frmProProgramu:=TfrmProProgramu.Create(self);
end;
frmMain.Enabled:=false;
frmProProgramu.Show;
}
{
AboutBox.ShowModal;
}
end;
procedure TMainForm.FileExit1Execute(Sender: TObject);
begin
{
Close;
}
end;
end.
|
unit Main.Controller;
interface
uses
AnnotatedImage, Annotation.Interfaces, SysUtils, Classes, Generics.Collections,
Vcl.Graphics, Controls, Vcl.StdActns, Vcl.ExtCtrls, StdCtrls, Settings;
type
TAnnotatedImageController = class(TObject)
private
FView: IImageAnnotationView;
FPresentMode: TPresentMode;
FAnnotatedImages: TObjectList<TAnnotatedImage>;
FCurrentIndex: integer;
FZoomFactor: Byte;
FApplicationSettings: ISettings;
procedure AddImage(const AFileName: TFileName);
function GetCurrentImage: TAnnotatedImage;
procedure SetCurrentImageIndex(const Value: integer);
procedure ShowCurrentImage;
procedure ShowImageAt(const Index: integer);
procedure SaveImageAnnotation(const AnnotatedImage: TAnnotatedImage);
procedure SetPresentMode(const Value: TPresentMode);
procedure CloseImageAt(const AIndex: integer);
procedure SetPresentationModeCombined(Sender: TObject);
procedure SetPresentationModeMask(Sender: TObject);
procedure SetPresentationModeOriginal(Sender: TObject);
procedure ViewImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ShowApplicationSettings(Sender: TObject);
public
constructor Create(const AView: IImageAnnotationView);
destructor Destroy; override;
// properties
property CurrentImage: TAnnotatedImage read GetCurrentImage;
property PresentMode: TPresentMode read FPresentMode write SetPresentMode;
property ZoomFactor: Byte read FZoomFactor;
// methods
procedure OpenImages(const AFiles: TStrings);
procedure PutMarkerAt(const X, Y, ViewportWidth, ViewportHeight: integer);
procedure SaveCurrentAnnotations(Sender: TObject = nil);
procedure NextImage(Sender: TObject = nil);
procedure PreviousImage(Sender: TObject = nil);
procedure SaveAllAnnotations(Sender: TObject = nil);
procedure ClearMarkersOnCurrentImage(Sender: TObject = nil);
function HasUnsavedChanges: boolean;
procedure SetAnnotationActionIndex(const AValue: integer); overload;
procedure SetAnnotationActionIndex(Sender: TObject); overload;
procedure CloseCurrentImage(Sender: TObject = nil);
procedure LoadAnnotationsToCurrentImage(const AFileName: TFileName); overload;
procedure LoadAnnotationsToCurrentImage(Sender: TObject); overload;
procedure ShowZoomPatch(const X, Y, Width, Height, ViewPortWidth, ViewPortHeight: integer; SourceBitmap: TBitmap);
procedure SetZoomFactor(const Value: Byte); overload;
procedure SetZoomFactor(Sender: TObject); overload;
procedure ViewCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure ViewImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer);
end;
implementation
uses
superobject, JPeg, math, IOUtils, Windows, Dialogs, System.UITypes,
SettingsView, SettingsController, Vcl.Forms;
{ TAnnotatedImageController }
procedure TAnnotatedImageController.AddImage(const AFileName: TFileName);
var
Picture: TPicture;
begin
Picture:= TPicture.Create;
try
Picture.LoadFromFile(AFileName);
FAnnotatedImages.Add(TAnnotatedImage.Create(Picture.Graphic, AFileName))
finally
Picture.Free;
end;
end;
procedure TAnnotatedImageController.ClearMarkersOnCurrentImage(Sender: TObject = nil);
begin
if not Assigned(CurrentImage) then
Exit;
CurrentImage.ClearAnnotationActions;
ShowCurrentImage;
end;
procedure TAnnotatedImageController.CloseCurrentImage(Sender: TObject = nil);
begin
if Assigned(CurrentImage) and (FCurrentIndex > -1) then
if CurrentImage.IsChanged then
begin
if MessageDlg('There are some unsaved changes. Do you really want to close this image?',
mtConfirmation, mbYesNo, 0) = mrYes then
CloseImageAt(FCurrentIndex);
end else
CloseImageAt(FCurrentIndex);
end;
procedure TAnnotatedImageController.CloseImageAt(const AIndex: integer);
begin
if (AIndex < 0) and (AIndex >= FAnnotatedImages.Count) then
Exit;
FAnnotatedImages.Delete(AIndex);
SetCurrentImageIndex(AIndex - 1);
end;
constructor TAnnotatedImageController.Create(const AView: IImageAnnotationView);
begin
FAnnotatedImages:= TObjectList<TAnnotatedImage>.Create(True);
FView:= AView;
FCurrentIndex:= -1;
FPresentMode:= prmdCombined;
FZoomFactor:= 2;
FView.SetActionSaveAllAnnotationsExecute(SaveAllAnnotations);
FView.SetActionClearMarkersExecute(ClearMarkersOnCurrentImage);
FView.SetActionCloseCurrentImageExecute(CloseCurrentImage);
FView.SetActionLoadAnnotationsAccept(LoadAnnotationsToCurrentImage);
FView.SetActionNextImageExecute(NextImage);
FView.SetActionPresentationModeCombinedExecute(SetPresentationModeCombined);
FView.SetActionPresentationModeMaskExecute(SetPresentationModeMask);
FView.SetActionPresentationModeOriginalExecute(SetPresentationModeOriginal);
FView.SetActionPreviousImageExecute(PreviousImage);
FView.SetActionSaveCurrentAnnotationExecute(SaveCurrentAnnotations);
FView.SetActionZoomFactorChangeExecute(SetZoomFactor);
FView.SetFormCloseQuery(ViewCloseQuery);
FView.SetImageContainerMouseMoveEvent(ViewImageMouseMove);
FView.SetImageCOntainerMouseDownEvent(ViewImageMouseDown);
FView.SetHistoryBoxOnclickEvent(SetAnnotationActionIndex);
FView.SetLoadImageMethod(OpenImages);
FView.SetShowSettingsExecute(ShowApplicationSettings);
FApplicationSettings:= TSettingsRegistry.Create('Software\ImageAnnotationTool\');
end;
destructor TAnnotatedImageController.Destroy;
begin
FApplicationSettings:= nil;
FAnnotatedImages.Free;
inherited;
end;
function TAnnotatedImageController.GetCurrentImage: TAnnotatedImage;
begin
Result:= nil;
if (FCurrentIndex > -1) and (FCurrentIndex < FAnnotatedImages.Count) then
Result:= FAnnotatedImages[FCurrentIndex];
end;
function TAnnotatedImageController.HasUnsavedChanges: boolean;
var
AnnotatedImage: TAnnotatedImage;
begin
Result:= false;
for AnnotatedImage in FAnnotatedImages do
if AnnotatedImage.IsChanged then
begin
Result:= True;
Exit;
end;
end;
procedure TAnnotatedImageController.LoadAnnotationsToCurrentImage(
Sender: TObject);
begin
LoadAnnotationsToCurrentImage((Sender as TFileOpen).Dialog.FileName);
end;
procedure TAnnotatedImageController.LoadAnnotationsToCurrentImage(
const AFileName: TFileName);
var
AnnotationsJSON: ISuperObject;
begin
if not Assigned(CurrentImage) then
exit;
AnnotationsJSON:= SO(TFile.ReadAllText(AFileName));
CurrentImage.LoadAnnotationsFromJSON(AnnotationsJSON.A['annotations']);
ShowCurrentImage;
end;
procedure TAnnotatedImageController.NextImage(Sender: TObject = nil);
begin
SetCurrentImageIndex(FCurrentIndex + 1);
end;
procedure TAnnotatedImageController.OpenImages(const AFiles: TStrings);
var
FileName: string;
begin
for FileName in AFiles do
AddImage(FileName);
FCurrentIndex:= 0;
ShowCurrentImage;
end;
procedure TAnnotatedImageController.PreviousImage(Sender: TObject = nil);
begin
SetCurrentImageIndex(FCurrentIndex - 1);
end;
procedure TAnnotatedImageController.PutMarkerAt(const X, Y, ViewportWidth, ViewportHeight: integer);
begin
if not Assigned(CurrentImage) then
Exit;
CurrentImage.PutDotMarkerAt(X, Y, ViewportWidth, ViewportHeight);
ShowCurrentImage;
end;
procedure TAnnotatedImageController.SaveAllAnnotations(Sender: TObject = nil);
var
AnnotatedImage: TAnnotatedImage;
begin
for AnnotatedImage in FAnnotatedImages do
SaveImageAnnotation(AnnotatedImage);
end;
procedure TAnnotatedImageController.SaveCurrentAnnotations(Sender: TObject = nil);
begin
SaveImageAnnotation(CurrentImage);
end;
procedure TAnnotatedImageController.SaveImageAnnotation(
const AnnotatedImage: TAnnotatedImage);
var
Mask: TJPEGImage;
MaskBitmap: Vcl.Graphics.TBitmap;
MaskJSON: ISuperObject;
FileName, BaseName: TFileName;
begin
if not Assigned(AnnotatedImage) then
Exit;
case FApplicationSettings.GetSavepathRelativeTo of
sprApplication: BaseName:= ExtractFilePath(Application.ExeName);
sprImage: BaseName:= ExtractFilePath(AnnotatedImage.Name);
else
BaseName:= ExtractFilePath(Application.ExeName);
end;
// save mask
Mask:= TJPEGImage.Create;
try
MaskBitmap:= AnnotatedImage.MaskBitmap;
Mask.Assign(MaskBitmap);
FileName:= BaseName +
IncludeTrailingPathDelimiter(FApplicationSettings.GetSavePathForMasks) +
ExtractFileName(ChangeFileExt(AnnotatedImage.Name, '')) + '_mask' +
'.jpg';
if ForceDirectories(ExtractFileDir(FileName)) then
Mask.SaveToFile(FileName);
finally
Mask.Free;
MaskBitmap.Free;
end;
// save JSON
MaskJSON:= AnnotatedImage.AnnotationActionsJSON;
MaskJSON.AsJSon(True);
FileName:= BaseName +
IncludeTrailingPathDelimiter(FApplicationSettings.GetSavePathForMarkers) +
ExtractFileName(ChangeFileExt(AnnotatedImage.Name, '')) + '_markers' +
'.txt';
if ForceDirectories(ExtractFileDir(FileName)) then
MaskJSON.SaveTo(FileName, true, true);
AnnotatedImage.OnSaved;
end;
procedure TAnnotatedImageController.SetAnnotationActionIndex(
const AValue: integer);
begin
CurrentImage.SetAnnotationActionIndex(AValue);
ShowCurrentImage;
end;
procedure TAnnotatedImageController.SetAnnotationActionIndex(Sender: TObject);
begin
SetAnnotationActionIndex(TListBox(Sender).ItemIndex);
end;
procedure TAnnotatedImageController.SetCurrentImageIndex(const Value: integer);
begin
if FAnnotatedImages.Count = 0 then
begin
FCurrentIndex:= -1;
FView.Clear;
Exit;
end;
if Value >= FAnnotatedImages.Count then
FCurrentIndex:= FAnnotatedImages.Count - 1
else if Value < 0 then
FCurrentIndex:= 0
else
FCurrentIndex:= Value;
ShowCurrentImage;
end;
procedure TAnnotatedImageController.SetPresentationModeCombined(
Sender: TObject);
begin
PresentMode:= prmdCombined;
end;
procedure TAnnotatedImageController.SetPresentationModeMask(Sender: TObject);
begin
PresentMode:= prmdMask;
end;
procedure TAnnotatedImageController.SetPresentationModeOriginal(
Sender: TObject);
begin
PresentMode:= prmdOriginal;
end;
procedure TAnnotatedImageController.SetPresentMode(const Value: TPresentMode);
begin
if Value <> FPresentMode then
begin
FPresentMode:= Value;
ShowCurrentImage;
end else
FPresentMode := Value;
end;
procedure TAnnotatedImageController.SetZoomFactor(Sender: TObject);
begin
SetZoomFactor(FView.GetZoomFactor);
end;
procedure TAnnotatedImageController.SetZoomFactor(const Value: Byte);
begin
if (Value >= 1) and (Value <= 10) then
FZoomFactor := Value;
end;
procedure TAnnotatedImageController.ShowApplicationSettings(Sender: TObject);
var
SettingsController: TSettingsController;
SettingsView: TFormSettings;
begin
SettingsView:= TFormSettings.Create(nil);
SettingsController:= TSettingsController.Create(FApplicationSettings, SettingsView);
try
SettingsController.ShowSettings;
finally
SettingsController.Free;
SettingsView.Free;
end;
ShowCurrentImage;
end;
procedure TAnnotatedImageController.ShowCurrentImage;
begin
ShowImageAt(FCurrentIndex);
end;
procedure TAnnotatedImageController.ShowImageAt(const Index: integer);
var
ImageInfo: TImageInfo;
BitmapToRender: Vcl.Graphics.TBitmap;
begin
if (Index >= FAnnotatedImages.Count) or (Index < 0) then
Exit;
case FPresentMode of
prmdOriginal: BitmapToRender:= FAnnotatedImages[Index].ImageBitmap;
prmdCombined: BitmapToRender:= FAnnotatedImages[Index].CombinedBitmap;
prmdMask: BitmapToRender:= FAnnotatedImages[Index].MaskBitmap;
end;
try
FView.RenderBitmap(BitmapToRender);
finally
BitmapToRender.Free;
end;
ImageInfo.FileName:= FAnnotatedImages[Index].Name;
ImageInfo.Width:= FAnnotatedImages[Index].Width;
ImageInfo.Height:= FAnnotatedImages[Index].Height;
FView.ShowImageInfo(ImageInfo);
FView.ShowHistory(CurrentImage.AnnotationActions, CurrentImage.CurrentAnnotationActionIndex);
FView.ShowImageCount(Index + 1, FAnnotatedImages.Count);
end;
procedure TAnnotatedImageController.ShowZoomPatch(const X, Y, Width,
Height, ViewPortWidth, ViewPortHeight: integer; SourceBitmap: Vcl.Graphics.TBitmap);
var
Bitmap: Vcl.Graphics.TBitmap;
begin
if Assigned(CurrentImage) then
begin
Bitmap:= TAnnotatedImage.GetPatch(X, Y, Width, Height,
ViewPortWidth, ViewPortHeight,
ZoomFactor,
SourceBitmap);
try
FView.RenderZoomBox(Bitmap);
finally
Bitmap.Free;
end;
end;
end;
procedure TAnnotatedImageController.ViewCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose:= True;
if HasUnsavedChanges then
if MessageDlg('There are some unsaved changes. Do you really want to close?',
mtConfirmation, mbYesNo, 0) = mrNo then
CanClose:= False;
end;
procedure TAnnotatedImageController.ViewImageMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
case Button of
TMouseButton.mbLeft: PutMarkerAt(X, Y, TImage(Sender).Width, TImage(Sender).Height);
TMouseButton.mbRight: FView.ToggleMagnifier;
TMouseButton.mbMiddle: Exit;
end;
end;
procedure TAnnotatedImageController.ViewImageMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: integer);
begin
FView.SetMagnifierTopLeft(Y + 5, X + 5);
ShowZoomPatch(X, Y, FView.GetZoomBoxWidth, FView.GetZoomBoxHeight,
TImage(Sender).Width, TImage(Sender).Height,
TImage(Sender).Picture.Bitmap);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ MTS Remote Data Module }
{*******************************************************}
unit Datasnap.Win.MtsRdm;
{$H+,X+}
interface
uses Winapi.Windows, System.Classes, Datasnap.DataBkr, Winapi.Mtx, Datasnap.Midas;
type
{ TMtsDataModule }
TMtsDataModule = class(TRemoteDataModule, IAppServer, IObjectControl)
private
FAutoComplete: Boolean;
FOnActivate: TNotifyEvent;
FOnDeActivate: TNotifyEvent;
FObjectContext: IObjectContext;
FCanBePooled: Boolean;
protected
{ IObjectControl }
procedure Activate; safecall;
procedure Deactivate; stdcall;
function CanBePooled: Bool; virtual; stdcall;
{ 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;
procedure CallComplete(Complete: Boolean); virtual;
property ObjectContext: IObjectContext read FObjectContext;
public
constructor Create(AOwner: TComponent); override;
procedure SetComplete;
procedure SetAbort;
procedure EnableCommit;
procedure DisableCommit;
function IsInTransaction: Boolean;
function IsSecurityEnabled: Boolean;
function IsCallerInRole(const Role: WideString): Boolean;
published
[Default(True)]
property AutoComplete: Boolean read FAutoComplete write FAutoComplete default True;
property OnActivate: TNotifyEvent read FOnActivate write FOnActivate;
property OnDeactivate: TNotifyEvent read FOnDeactivate write FOnDeactivate;
property Pooled: Boolean read FCanBePooled write FCanBePooled;
end;
implementation
constructor TMtsDataModule.Create(AOwner: TComponent);
begin
FAutoComplete := True;
inherited Create(AOwner);
end;
procedure TMtsDataModule.Activate;
begin
FObjectContext := GetObjectContext;
if Assigned(FOnActivate) then FOnActivate(Self);
end;
procedure TMtsDataModule.Deactivate;
begin
if Assigned(FOnDeactivate) then FOnDeactivate(Self);
FObjectContext := nil;
end;
function TMtsDataModule.CanBePooled: Bool;
begin
Result := FCanBePooled;
end;
procedure TMtsDataModule.SetComplete;
begin
if Assigned(FObjectContext) then FObjectContext.SetComplete;
end;
procedure TMtsDataModule.SetAbort;
begin
if Assigned(FObjectContext) then FObjectContext.SetAbort;
end;
procedure TMtsDataModule.EnableCommit;
begin
if Assigned(FObjectContext) then FObjectContext.EnableCommit;
end;
procedure TMtsDataModule.DisableCommit;
begin
if Assigned(FObjectContext) then FObjectContext.DisableCommit;
end;
function TMtsDataModule.IsInTransaction: Boolean;
begin
if Assigned(FObjectContext) then Result := FObjectContext.IsInTransaction
else Result := False;
end;
function TMtsDataModule.IsSecurityEnabled: Boolean;
begin
if Assigned(FObjectContext) then Result := FObjectContext.IsSecurityEnabled
else Result := False;
end;
function TMtsDataModule.IsCallerInRole(const Role: WideString): Boolean;
begin
if Assigned(FObjectContext) then Result := FObjectContext.IsCallerInRole(Role)
else Result := False;
end;
{ IAppServer support }
procedure TMtsDataModule.CallComplete(Complete: Boolean);
begin
if AutoComplete then
if Complete then
SetComplete else
SetAbort;
end;
function TMtsDataModule.AS_GetProviderNames: OleVariant;
begin
try
Result := inherited AS_GetProviderNames;
finally
CallComplete(True);
end;
end;
function TMtsDataModule.AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer;
var OwnerData: OleVariant): OleVariant;
begin
try
Result := inherited AS_ApplyUpdates(ProviderName, Delta, MaxErrors, ErrorCount, OwnerData);
if (ErrorCount <= MaxErrors) or (MaxErrors = -1) then
CallComplete(True)
else
CallComplete(False);
except
CallComplete(False);
raise;
end;
end;
function TMtsDataModule.AS_GetRecords(const ProviderName: WideString; Count: Integer;
out RecsOut: Integer; Options: Integer; const CommandText: WideString;
var Params, OwnerData: OleVariant): OleVariant;
begin
try
Result := inherited AS_GetRecords(ProviderName, Count, RecsOut, Options,
CommandText, Params, OwnerData);
finally
CallComplete(True);
end;
end;
function TMtsDataModule.AS_DataRequest(const ProviderName: WideString;
Data: OleVariant): OleVariant;
begin
{ No SetComplete call because I don't know what the developer is doing here.
Developer needs to call SetComplete in the OnDataRequest event. }
Result := inherited AS_DataRequest(ProviderName, Data);
end;
function TMtsDataModule.AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant;
begin
try
Result := inherited AS_GetParams(ProviderName, OwnerData);
finally
CallComplete(True);
end;
end;
function TMtsDataModule.AS_RowRequest(const ProviderName: WideString; Row: OleVariant;
RequestType: Integer; var OwnerData: OleVariant): OleVariant;
begin
try
Result := inherited AS_RowRequest(ProviderName, Row, RequestType, OwnerData);
finally
CallComplete(True);
end;
end;
procedure TMtsDataModule.AS_Execute(const ProviderName: WideString;
const CommandText: WideString; var Params, OwnerData: OleVariant);
begin
try
inherited AS_Execute(ProviderName, CommandText, Params, OwnerData);
finally
CallComplete(True);
end;
end;
end.
|
unit Teste.Build.Builder;
interface
uses
DUnitX.TestFramework, System.JSON, Vigilante.Compilacao.Model;
type
[TestFixture]
TBuildBuilderTest = class
private
FJson: TJsonObject;
FBuild: ICompilacaoModel;
procedure CarregarJSONDoArquivo;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure ImportaComSucesso;
end;
implementation
uses
System.Classes, System.IOUtils, System.SysUtils,
Vigilante.Infra.Compilacao.Builder, Vigilante.Infra.Compilacao.Builder.Impl;
procedure TBuildBuilderTest.Setup;
var
_compilacaoBuilder: ICompilacaoBuilder;
begin
CarregarJSONDoArquivo;
_compilacaoBuilder := TCompilacaoBuilder.Create(FJson);
FBuild := _compilacaoBuilder.PegarCompilacao;
end;
procedure TBuildBuilderTest.TearDown;
begin
FJson.Free;
end;
procedure TBuildBuilderTest.CarregarJSONDoArquivo;
var
_arquivoJson: TStringList;
begin
if not TFile.Exists('build.json') then
raise Exception.Create('O arquivo build.json não foi encontrado!');
_arquivoJson := TStringList.Create;
try
_arquivoJson.LoadFromFile('build.json');
FJson := TJsonObject.ParseJSONValue(_arquivoJson.Text) as TJsonObject;
finally
_arquivoJson.Free;
end;
end;
procedure TBuildBuilderTest.ImportaComSucesso;
begin
Assert.AreEqual('build-simulado #725', FBuild.Nome);
end;
initialization
TDUnitX.RegisterTestFixture(TBuildBuilderTest);
end.
|
{
@html(<b>)
Client Module for Remote Functions
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
This unit introduces @Link(TRtcClientModule), the client-side component for ENABLING remote functions.
By using @Link(TRtcClientModule), you can easily call remote server functions and get results
in form of objects, passed to the event handlers you define. Also, by assigning a
@Link(TRtcFunctionGroup) component to your @Link(TRtcClientModule) component,
server can (as a result of any remote function call from the client) return functions which
will be executed on the client side before the result object is passed to the local event handler.
Implementing a RTC Remote Function is as easy as writing a local function.
}
unit rtcCliModule;
{$INCLUDE rtcDefs.inc}
interface
uses
Classes,
Windows,
SysUtils,
rtcTimer,
rtcInfo,
rtcConn,
rtcCrypt,
rtcSyncObjs,
rtcDataCli,
rtcFunction,
{$IFDEF COMPRESS}
rtcZLib,
{$ENDIF}
rtcFastStrings,
memObjList;
type
// @exclude
EPostInteractive = class(EAbort);
// @exclude
TRtcInteractiveResult = class
public
FEvent:TRtcResult;
Data,Result:TRtcValue;
destructor Destroy; override;
end;
{ @abstract(Used to store all calls for a single Post from a ClientModule)
@exclude }
TRtcClientModuleCallsArray=class(TRtcArray)
private
FEvents:array of TRtcResult;
function GetEvent(index: integer): TRtcResult;
procedure SetEvent(index: integer; const _Value: TRtcResult);
public
constructor Create; override;
destructor Destroy; override;
property Event[index:integer]:TRtcResult read GetEvent write SetEvent;
end;
// @exclude
TRtcCryptClient=class(TRtcObject)
public
HaveHello,HaveStart:boolean;
ControlCounter:integer;
ClientHello,ServerHello,
ClientKey,ServerKey,
ControlKey:string;
Read,Write:TRtcCrypt;
destructor Destroy; override;
procedure Init;
procedure Kill; override;
end;
// @exclude
TRtcClientModuleData=class
public
FRequest:TRtcClientRequest;
FData:TRtcValue;
FPostLevel:integer;
FCalls:TRtcClientModuleCallsArray;
constructor Create; virtual;
destructor Destroy; override;
end;
{ @abstract(Use to call remote functions and receive their results)
ClientModule is used to prepare remote function calls, post them to
the server, accept server's response and call local event handlers with
the result received for each call. You can post a single call or multiple
function calls with one request, or even use a timer-based trigger to post
all the requests prepared until now. }
TRtcClientModule=class(TRtcAbsDataClientLink)
private
FMyData:TObjList;
FMainThrData:TRtcClientModuleData;
FIntCS:TRtcCritSec;
FCS:TRtcCritSec;
FIntTimer:TRtcTimer;
FIntRes:TList;
FFunctions:TRtcFunctionGroup;
FRelease:boolean;
FModuleFileName:string;
FModuleHost:string;
FAutoRepost:integer;
FAutoSessions: boolean;
FOnBeginRequest: TRtcNotifyEvent;
FOnResponseAbort: TRtcNotifyEvent;
FOnResponseDone: TRtcNotifyEvent;
FOnResponseReject: TRtcNotifyEvent;
FOnConnectLost: TRtcNotifyEvent;
FOnSessionExpired: TRtcNotifyEvent;
FOnRepostCheck: TRtcNotifyEvent;
FOnSessionOpen: TRtcNotifyEvent;
FOnSessionClose: TRtcNotifyEvent;
FAutoEncrypt: integer;
FForceEncrypt: boolean;
FOnResponseError: TRtcNotifyEvent;
FSecureKey: string;
{$IFDEF COMPRESS}
FCompress: TRtcCompressLevel;
{$ENDIF}
FOnNoEncryption: TRtcNotifyEvent;
FOnNeedEncryption: TRtcNotifyEvent;
FOnWrongEncryption: TRtcNotifyEvent;
FOnLoginResult: TRtcResultEvent;
FOnLoginAborted: TRtcResultEvent;
FHyperThreading: boolean;
FDataFormat: TRtcDataFormat;
FOnLogin: TRtcFunctionPrepareEvent;
FResetLogin,
FAutoLogin: boolean;
FLoginResult: TRtcResult;
function CheckMyData:TRtcClientModuleData;
function GetMyData:TRtcClientModuleData;
procedure ClearMyData;
function IsRemoteCallRequest(Sender:TRtcConnection):boolean;
procedure NotifyResultAborted(Sender:TRtcConnection);
procedure Response_Problem(Sender:TRtcConnection);
procedure Call_SessionExpired(Sender:TRtcConnection);
procedure Call_NoEncryption(Sender:TRtcConnection);
procedure Call_NeedEncryption(Sender:TRtcConnection);
procedure Call_WrongResponse(Sender:TRtcConnection);
procedure Call_WrongEncryption(Sender:TRtcConnection);
function GetCrypt(Session:TRtcSession):TRtcCryptClient;
procedure NewCrypt(Session:TRtcSession);
procedure DelCrypt(Session:TRtcSession);
function GetFunctionGroup: TRtcFunctionGroup;
procedure SetFunctionGroup(const Value: TRtcFunctionGroup);
function GetModuleFileName: string;
procedure SetModuleFileName(const Value: string);
function GetModuleHost: string;
procedure SetModuleHost(const Value: string);
procedure SetAutoEncrypt(const Value: integer);
procedure SetAutoSessions(const Value: boolean);
procedure SetForceEncrypt(const Value: boolean);
procedure PostInteractiveResult(Event:TRtcResult; Data,Result:TRtcValue);
procedure DoInteractiveResult;
function GetData: TRtcValue;
function GetPostLevel: integer;
function GetRequest: TRtcClientRequest;
{$IFDEF COMPRESS}
procedure SetCompress(const Value: TRtcCompressLevel);
procedure SetDataFormat(const Value: TRtcDataFormat);
{$ENDIF}
procedure SetAutoLogin(const Value: boolean);
procedure LoginCall(ResultHandler: TRtcResult; Sender:TRtcConnection; Insert:boolean=False); virtual;
procedure Call_LoginResult(Sender:TRtcConnection; Data:TRtcValue; Result:TRtcValue);
procedure Call_LoginAborted(Sender:TRtcConnection; Data:TRtcValue; Result:TRtcValue);
protected
// @exclude
procedure Call_BeginRequest(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseDone(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseData(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseAbort(Sender:TRtcConnection); override;
// @exclude
procedure Call_ResponseReject(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionOpen(Sender:TRtcConnection); override;
// @exclude
procedure Call_SessionClose(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataReceived(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataOut(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataIn(Sender:TRtcConnection); override;
// @exclude
procedure Call_DataSent(Sender:TRtcConnection); override;
// @exclude
procedure Call_ReadyToSend(Sender:TRtcConnection); override;
// @exclude
procedure Call_ConnectLost(Sender:TRtcConnection); override;
// @exclude
procedure Call_RepostCheck(Sender:TRtcConnection); override;
public
// @exclude
constructor Create(AOwner:TComponent); override;
// @exclude
destructor Destroy; override;
// You can call this method from Interactive result function to destroy the ClientModule object.
procedure Release;
{ Use this method when you want to force the next remote call to make a new login attempt,
even if the component thinks the user is already logged in. }
procedure ResetLogin;
{ If you want to post multiple calls in one request (and not each in its own request),
you can use the "StartCalls" methods to open a new "call transaction", which is closed
by a call to "Post". Each "StartCalls" has to be closed by a call to "Post". Using
StartCalls/Call/Call/Post, you can combine a number of remote calls in one request.
Another thing you don't have to worry about when using StartCalls/Post is clearing
of the Data object in case of an exception during Data preparation. }
procedure StartCalls; virtual;
{ After you have used the "Data" property to prepare the objects and functions
you want to send to the server, use the "Call" method to define the event handler
which has to receive the result after the data has been posted to the server.
If you are not interested in the result values of your request, but just
want to send this to the server as a "procedure call" and ignore the result,
you can use "Call(nil)" and any result received will be simply thrown away.
A result WILL be received in any case, which ensures that the function was executed.
But, even in case of an exception, result with be ignored. @html(<br><br>)
After "Call()", an object will be created to hold the prepared "Data" with a
pointer to the TRtcResult component, after which the Data property will be cleared,
so that you can prepare and Call new remote functions immediatelly. @html(<br><br>)
If you are calling a remote function from inside other remote functions event,
"FromInsideEvent" parameter has to be TRUE to avoid memory consumption and
you should pass the Sender:TRtcConnection parameter to the Call() method.
If you didn't start a separate call transaction using "StartCalls", your call will be
automaticaly posted to the server in a single request. To post multiple calls in
one request, simply call "StartCalls" before, prepare "Data" before each "Call" and
after the last call, use the "Post" method to send everything out. }
procedure Call(ResultHandler:TRtcResult; FromInsideEvent:boolean=False; Sender:TRtcConnection=nil); overload;
{ "Post" will decrease the call transaction level which was increased by a "StartCalls"
and if the last StartCalls was closed by calling this Post, an object will be created
to hold the prepared Request info and a list of remote calls will be sent to the server
if connection with server is established. @html(<br><br>)
When posting from inside a RTC event or a remote function,
"FromInsideEvent" parameter has to be TRUE to avoid memory consumption and
you should pass the Sender:TRtcConnection parameter to the Post() method.
Events assigned to this TRtcClientModule will not be removed nor cleared,
so you can define them at design-time and not worry about them at runtime. }
procedure Post(FromInsideEvent:boolean=False; Sender:TRtcConnection=nil); virtual;
{ ONLY use this Request property if you need to prepare a request BEFORE posting.
@html(<br>)
DO NOT directly use this property when processing function calls.
After a request has been posted, it is moved to the DataClient,
so you can access it (from events) using Sender's Request property. }
property Request:TRtcClientRequest read GetRequest;
{ To prepare a remote call, use this "Data" property to define and/or assign object(s)
you want to send to the server. After you have defined the "Data" property to hold
all information you want to send to the server, use the "Call" method to store that
data and define the event handler to be used when a result is received. @html(<br>)
ONLY use this Data property to prepare data for a remote call. @html(<br>)
DO NOT directly use this property when processing the received result. }
property Data:TRtcValue read GetData;
{ Using this property, you can check at which Calls level your ClientModule currently is.
CallsLevel will be 0 outside of StartCalls, increased by 1 after each StartCalls
and decreased by 1 after each Post. }
property CallsLevel:integer read GetPostLevel;
published
{$IFDEF COMPRESS}
{ Use this property to define what compression level you want to use when sending
data from Client to Server. Default Compression value is "cNone" (no compression).
You can use different compression levels between client and server (for example,
fast or no compression from client and max from server). If your client has to
work with servers which don't support compression, you have to use "cNone". }
property Compression:TRtcCompressLevel read FCompress write SetCompress default cNone;
{$ENDIF}
{ Use this property to define what data format you want to use when sending data from
Client to Server. If your client will only be talking to a Server written using RTC
components, it is recommended to use "fmt_RTC", which upports all RTC data types, automatic
compression, automatic encryption and automatic Sessions, as well as nested function calls
and sending multiple function calls in a single request. On the other hand, if your client
has to communicate with a Server which does NOT support the RTC format, you can use
the "fmt_XMLRPC" format, which will work with Servers implementing the XML-RPC format. @html(<br><br>)
NOTE: Since advanced functionality like automatic Compression, auto Encryption
and automatic Sessions are native to the RTC format and other Servers do not implement it,
those advanced properties will be ignored and assumed to be FALSE with all formats other
then the "fmt_RTC" format. If you need those advanced options, use the "fmt_RTC" format. }
property DataFormat:TRtcDataFormat read FDataFormat write SetDataFormat default fmt_RTC;
{ If you want to enable the possibility to use this Client Module to send remote function
calls from multiple threads AT THE SAME TIME, where this component will acs as if
it were X components, one for each thread, simply set HyperThreading to TRUE. @html(<br><br>)
This is useful if you need to send remote function calls to another Server from
within your Server running in multi-threaded mode and want to use only one set of
rtcHttpClient/rtcClientModule components for all clients connected to your Server.
Even in HyperThreading mode, only properties and methods needed to prepare and post remote
function calls (Data, Request, Call, StartCalls, PostLevel and Post) will use a separate
copy for each thread, while all other properties and methods exist only once for all threads,
so don't try to modify them while your application is actively using the component in
multi-threaded mode. @html(<br><br>)
Leave HyperThreading as FALSE to use this component "the stadard way" (for example,
when you're writing a client application where remote calls are done from the main thread
or if you are creating a separate component for every thread that needs it). }
property HyperThreading:boolean read FHyperThreading write FHyperThreading default False;
{ Set this property to a value other than 0 if you want to use automatic Encryption
with a random generated key of "EncryptKey" bytes. One byte stands for
encryption strength of 8 bits. For strong 256-bit encryption, use 32 bytes. @html(<br><br>)
The final encryption key is combined from a client-side key and a key
received from the server, where server decides about its encryption strength.
If server doesn't support Encryption, data will not be encrypted,
regardless of the value you use for AutoEncrypt. @html(<br><br>)
EncryptionKey uses sessions to keep the encryption keys. When you set EncryptionKey
to a value other than 0 (turn it ON), AutoSessions will be set to TRUE.
Also, setting AutoSessions to FALSE will set EncryptionKey to 0 (OFF). }
property EncryptionKey:integer read FAutoEncrypt write SetAutoEncrypt default 0;
{ If you need a 100% secure connection, define a Secure Key string
(combination of letters, numbers and special characters) for each
ServerModule/ClientModule pair, additionally to the EncryptionKey value.
ClientModule will be able to communicate with the ServerModule ONLY if
they both use the same SecureKey. Default value for the SecureKey is
an empty string (means: no secure key). @html(<br><br>)
SecureKey will be used in the encryption initialisation handshake,
to encrypt the first key combination sent by the ClientModule.
Since all other data packages are already sent using some kind of encryption,
by defining a SecureKey, you encrypt the only key part which would have
been sent out without special encryption. }
property SecureKey:string read FSecureKey write FSecureKey;
{ Setting this property to TRUE will tell the ClientModule to work with the
Server ONLY if Server supports encryption. If AutoEncryptKey is > 0 and
server doesn't support encryption, function calls will not be passed to
the server and any response coming from the server will be rejected, until
server enables encryption. }
property ForceEncryption:boolean read FForceEncrypt write SetForceEncrypt default False;
{ Set this property to TRUE if you want ClientModule to request a new session
automatically if the Session.ID is not set when posting a request.
Session handling is built into the ClientModule and uses Request.Params to
send the Session.ID to the server and Response.Cookie['ID'] to receive a
new session ID from the server and initialize the session object. @html(<br><br>)
Since session ID's are communicated automaticaly by the ClientModule and
ServerModule components, all TRtcFunction and TRtcResult components used by
this ClientModule will have direct access to the session object.
When AutoSessions is set to true, a new session will be requested if
no session exists or when a session expires. @html(<br><br>)
When AutoSessions is FALSE, you have to request a new session by calling
a remote server function to generate a new session and return the session ID. }
property AutoSessions:boolean read FAutoSessions write SetAutoSessions default false;
{ Set this property to a value other than 0 (zero) if you want the ClientModule to
auto-repost any request up to "AutoRepost" times, in case the connection gets lost
while sending data to server or receiving data from server.
If value is lower than zero, requests will be reposted unlimited number of times. }
property AutoRepost:integer read FAutoRepost write FAutoRepost default 0;
{ Set this property to TRUE if you want to enable the use of the
OnLogin, OnLoginResult and OnLoginAborted events to implement automatic login. }
property AutoLogin:boolean read FAutoLogin write SetAutoLogin default false;
{ "Request.Host" will be assigned this property before sending the request out. @html(<br>)
It is not necessary to set this property if your server's ServerModule component
left its ModuleHost property blank and there's no remote Functions used by that
ServerModule which would explicitly use the "Request.Host" header. On the other hand,
for servers which serve multiple hosts, mostly where ServerModule has assigned its
ModuleHost property, it is very important to set this ClientModule's ModuleHost
property to the appropriate host name. }
property ModuleHost:string read GetModuleHost write SetModuleHost;
{ To be able to call remote functions, this ClientModule's ModuleFileName
property has to be identical to the "ModuleFileName" property of the ServerModule
which you want to use. "Request.FileName" will be assigned this property before
sending any request out, so you won't be preparing the Request headers manualy. @html(<br>)
All data (parameters and function calls) will be passed to the server module through
request's Content body, so that ServerModule won't need to check the request headers
for anything else than it's FileName to know if the request is directed to it. }
property ModuleFileName:string read GetModuleFileName write SetModuleFileName;
{ Set this property to tell the RtcClientModule to use this TRtcFunctionGroup
component to execute all functions received as a response from server, for
any request sent from this TRtcClientModule component. }
property FunctionGroup:TRtcFunctionGroup read GetFunctionGroup write SetFunctionGroup;
{ This event will be called if your SecretKey does not match the SecretKey
specified by the ServerModule you're connecting to.
On this event, you can decide not to work with that server (Response.Reject or Disconnect),
or to update your SecretKey property to mirror the SercetKey of your ServerModule. }
property OnEncryptWrongKey:TRtcNotifyEvent read FOnWrongEncryption write FOnWrongEncryption;
{ This event will be called if your EncryptionKey>0 and ForceEncryption=TRUE,
but the Server says it does not support encryption for this ServerModule.
On this event, you can decide not to work with that server (Response.Reject or Disconnect),
or to set your ForceEncryption property to False and repost the request. }
property OnEncryptNotSupported:TRtcNotifyEvent read FOnNoEncryption write FOnNoEncryption;
{ This event will be called if your EncryptionKey=0,
but the Server wants to ForceEncryption for this ServerModule.
On this event, you can decide to not work with that server (Response.Reject or Disconnect),
or to activate encryption by setting the EncryptionKey. }
property OnEncryptRequired:TRtcNotifyEvent read FOnNeedEncryption write FOnNeedEncryption;
{ This event will be called if we receave invalid response from the Server,
which could mean that our Client or our Server are not up to date. }
property OnResponseError:TRtcNotifyEvent read FOnResponseError write FOnResponseError;
{ This event will be called if you have called a remote function with a Session ID that
has expired. You can choose to clear the local Session object and Repost the request
with an empty session ID to receive a new session ID, or reject the Request.
If you do not implement this event, Session ID will be cleared and the request
will be reposted, so your client will receive a new Session ID. }
property OnSessionExpired:TRtcNotifyEvent read FOnSessionExpired write FOnSessionExpired;
{ This event will be called after ClientModule component has prepared the request for sending,
but before the request has been sent out (no writing has been done yet).
You can use this event to check or update the request object before it is sent out. @html(<br>)
This event does not have to be defined for the ClientModule to work. }
property OnBeginRequest:TRtcNotifyEvent read FOnBeginRequest write FOnBeginRequest;
{ This event will be called after the last DataReceived event for this request,
read after the request has been sent out and a complete response was received (Response.Done). @html(<br>)
This event does not have to be defined for the ClientModule to work. }
property OnResponseDone:TRtcNotifyEvent read FOnResponseDone write FOnResponseDone;
{ This event will be called after the OnConnectLost, OnConnectFail and OnConnectError events,
if the request was NOT marked for reposting. }
property OnRepostCheck:TRtcNotifyEvent read FOnRepostCheck write FOnRepostCheck;
{ This event will be called after the OnRepostCheck event, if the request was not marked for reposting.
If this event gets triggered, it means that there is a major problem with the server and
user has to be notified about that problem and consulted about further actions. }
property OnResponseAbort:TRtcNotifyEvent read FOnResponseAbort write FOnResponseAbort;
{ This event will be called after the response has been rejected by calling "Response.Reject" }
property OnResponseReject:TRtcNotifyEvent read FOnResponseReject write FOnResponseReject;
{ This event will be called after a new Session has been opened. }
property OnSessionOpen:TRtcNotifyEvent read FOnSessionOpen write FOnSessionOpen;
{ This event will be called before an existing Session is going to be closed. }
property OnSessionClose:TRtcNotifyEvent read FOnSessionClose write FOnSessionClose;
{ This event will be mapped as @Link(TRtcClient.OnConnectLost) event
to the assigned DataClient component and called if your connection gets
closed while you are still processing your request. }
property OnConnectLost:TRtcNotifyEvent read FOnConnectLost write FOnConnectLost;
{ Use this event to implement automatic user login. Set AutoLogin to TRUE and
this event will be fired immediately after the initial connection handshake.
To prepare the remote function, use the "Data" object passed as a parameter.
After the function call has returned, the OnLoginResult event will be triggered.
If there was an error and the request was aborted, OnLoginAborted will be called. }
property OnLogin:TRtcFunctionPrepareEvent read FOnLogin write FOnLogin;
{ Use this event to implement automatic user login. See "OnLogin" for more info. }
property OnLoginResult:TRtcResultEvent read FOnLoginResult write FOnLoginResult;
{ Use this event to implement automatic user login. See "OnLogin" for more info. }
property OnLoginAborted:TRtcResultEvent read FOnLoginAborted write FOnLoginAborted;
end;
{ Call this procedure if user interaction is required anywhere inside your result event.
When this procedure is called, the event will be posted to the main thread outside of
the client connection's context, so that the connection can continue functioning
and receiving new data, without being blocked by a window waiting for user input.
Without using "PostInteractive" to post the event, the connection would be blocked until
the event returns. This could take several minutes if user doesn't notice your window,
which would most likely result in a session timeout on the server, so the user would
be automaticaly logged out after he responded to your questions. @html(<br><br>)
Even though events are posted outside of the connection context, a mechanism integrated
into TRtcClientModule will take care that all events posted interactively from the same
ClientModule's result event, do not overlap or get called in a different order. So,
if you need your result events to block any upcoming resuts, you can post all your
dependent events interactively to ensure they will get called AFTER the user responded,
while the connection continues receiving new data from the server and keeps the session alive. @html(<br><br>)
NOTE: This procedure works only when called from inside TRtcResult event
which was triggered by TRtcClientModule to return a result from a remote function call.
When a function is called asynchtonously outside of the connection context,
Sender parameter is NIL. This has two reasons: @html(<br>)
1. You can check "Sender" to know if your event would block a connection. @html(<br>)
2. You can not expect the connection to remain in the same state forever and you
can not use the connection directly from an interactive event. }
procedure PostInteractive;
implementation
procedure PostInteractive;
begin
raise EPostInteractive.Create('');
end;
{ TRtcClientModuleData }
constructor TRtcClientModuleData.Create;
begin
inherited;
FRequest:=nil;
FData:=nil;
FCalls:=nil;
FPostLevel:=0;
end;
destructor TRtcClientModuleData.Destroy;
begin
if assigned(FRequest) then
begin
FRequest.Free;
FRequest:=nil;
end;
if assigned(FData) then
begin
FData.Free;
FData:=nil;
end;
if assigned(FCalls) then
begin
FCalls.Free;
FCalls:=nil;
end;
inherited;
end;
{ TRtcClientModule }
constructor TRtcClientModule.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHyperThreading:=False;
FIntCS:=TRtcCritSec.Create;
FIntRes:=TList.Create;
FIntTimer:=nil;
FRelease:=False;
FFunctions:=nil;
FModuleFileName:='';
FModuleHost:='';
FAutoRepost:=0;
FCS:=TRtcCritSec.Create;
FMyData:=tObjList.Create(32);
FMainThrData:=TRtcClientModuleData.Create;
FLoginResult:=TRtcResult.Create(nil);
FLoginResult.OnReturn:=Call_LoginResult;
FLoginResult.RequestAborted:=Call_LoginAborted;
end;
destructor TRtcClientModule.Destroy;
begin
FFunctions:=nil;
FModuleFileName:='';
FModuleHost:='';
if assigned(FMainThrData) then
begin
FMainThrData.Free;
FMainThrData:=nil;
end;
if assigned(FMyData) then
begin
FMyData.Free;
FMyData:=nil;
end;
FLoginResult.Free;
FIntRes.Free;
FIntCS.Free;
FCS.Free;
inherited;
end;
function TRtcClientModule.GetCrypt(Session:TRtcSession): TRtcCryptClient;
begin
Result:=TRtcCryptClient(Session.Obj[ModuleHost+ModuleFileName+':$Crypt$']);
end;
procedure TRtcClientModule.NewCrypt(Session:TRtcSession);
begin
if TRtcCryptClient(Session.Obj[ModuleHost+ModuleFileName+':$Crypt$'])<>nil then
TRtcCryptClient(Session.Obj[ModuleHost+ModuleFileName+':$Crypt$']).Init
else
Session.Obj[ModuleHost+ModuleFileName+':$Crypt$']:=TRtcCryptClient.Create;
end;
procedure TRtcClientModule.DelCrypt(Session:TRtcSession);
begin
if TRtcCryptClient(Session.Obj[ModuleHost+ModuleFileName+':$Crypt$'])<>nil then
begin
TRtcCryptClient(Session.Obj[ModuleHost+ModuleFileName+':$Crypt$']).Free;
Session.Obj[ModuleHost+ModuleFileName+':$Crypt$']:=nil;
end;
end;
procedure TRtcClientModule.Call_ConnectLost(Sender: TRtcConnection);
begin
if assigned(FOnConnectLost) then
if AutoSyncEvents then
Sender.Sync(FOnConnectLost)
else
FOnConnectLost(Sender);
end;
function RandomKey(len:integer):string;
var
a:integer;
begin
SetLength(Result,len);
for a:=1 to len do
Result[a]:=Char(random(256));
end;
procedure CryptRead(Crypt:TRtcCryptClient; var Data:string);
begin
if assigned(Crypt) and assigned(Crypt.Read) then
Crypt.Read.DeCrypt(Data);
end;
procedure CryptWrite(Crypt:TRtcCryptClient; var Data:string);
begin
if assigned(Crypt) and assigned(Crypt.Write) then
Crypt.Write.Crypt(Data);
end;
function GenerateControlKey(var Counter:integer):string;
var
len,a,b,c:integer;
begin
Inc(Counter);
if Counter>99 then Counter:=1;
len:=5+random(5);
SetLength(Result,len+4);
b:=(10-len)*9+8;
for a:=5 to len+4 do
begin
c:=random(10); Inc(b,c);
Result[a]:=Char(c+Ord('0'));
end;
Result[1]:=Char(b div 10 + Ord('0'));
Result[2]:=Char(b mod 10 + Ord('0'));
Result[3]:=Char(Counter div 10 + Ord('0'));
Result[4]:=Char(Counter mod 10 + Ord('0'));
end;
procedure TRtcClientModule.Call_BeginRequest(Sender: TRtcConnection);
var
idx:integer;
MyCalls:TRtcClientModuleCallsArray;
compressed:boolean;
code,temp:string;
output:TRtcHugeString;
crypt:TRtcCryptClient;
DataReq:TRtcDataRequestInfo;
MyRequest:TRtcClientRequest;
obj:TRtcValueObject;
begin
if FResetLogin then
begin
FResetLogin:=False;
TRtcDataClient(Sender).Session.Close;
end;
if (FDataFormat=fmt_RTC) and (EncryptionKey>0) then
begin
with TRtcDataClient(Sender) do
begin
crypt:=GetCrypt(Session);
if (Request.Query['ACTION']='HELLO') then // Sending HELLO to the Server
begin
if Session.ID<>'' then
Request.Query['ID']:=Session.ID
else
Request.Query['ID']:='';
// Initialize encryption for this ClientModule
NewCrypt(Session);
crypt:=GetCrypt(Session);
// Generate Client-Hello
crypt.ClientHello:=RandomKey(EncryptionKey);
{ Generate randoml control number to add at the end of the request,
so we can check if the response is correctly encrypted. }
crypt.ControlKey := GenerateControlKey(crypt.ControlCounter);
code:=crypt.ClientHello+#13+crypt.ControlKey;
if SecureKey<>'' then
begin
with TRtcCrypt.Create do
begin
Key:=SecureKey;
Crypt(code);
Free;
end;
end;
// Send ClientHello + ControlKey
Write(code);
Exit;
end
else if {(Session.ID='') or} (crypt=nil) or not crypt.HaveHello then
begin
if ModuleFileName='' then
raise Exception.Create('Module FileName is undefined. Can not Post the request.');
if (Request.Reposted>1) and (Session.ID<>'') then
Session.Init;
MyRequest:=TRtcClientRequest.Create;
MyRequest.Method:='POST';
MyRequest.FileName:=ModuleFileName;
MyRequest.Query['ACTION']:='HELLO';
if ModuleHost<>'' then
MyRequest.Host:=ModuleHost;
DataReq:=TRtcDataRequestInfo.Create;
DataReq.Request:=MyRequest;
DataReq.Events:=Self;
try
InsertRequest(DataReq);
except
DataReq.Events:=nil;
DataReq.Free;
end;
Exit;
end
else if (Request.Query['ACTION']='START') then
begin
if Session.ID<>'' then
Request.Query['ID']:=Session.ID
else
Request.Query['ID']:='';
// Generate Client-Key
crypt.ClientKey:=RandomKey(EncryptionKey);
{ Generate a random control number to add at the end of the request,
so we can check if the response is correctly encrypted. }
crypt.ControlKey := GenerateControlKey(crypt.ControlCounter);
code:=crypt.ClientKey+#13+crypt.ControlKey;
CryptWrite(crypt, code);
// Send ClientKey + ControlKey
Write( code );
Exit;
end
else if not crypt.HaveStart then
begin
if ModuleFileName='' then
raise Exception.Create('Module FileName is undefined. Can not Post the request.');
MyRequest:=TRtcClientRequest.Create;
MyRequest.Method:='POST';
MyRequest.FileName:=ModuleFileName;
MyRequest.Query['ACTION']:='START';
if ModuleHost<>'' then MyRequest.Host:=ModuleHost;
DataReq:=TRtcDataRequestInfo.Create;
DataReq.Request:=MyRequest;
DataReq.Events:=Self;
try
InsertRequest(DataReq);
except
DataReq.Events:=nil;
DataReq.Free;
end;
Exit;
end;
end;
end;
with TRtcDataClient(Sender) do
if Session.ID<>'' then
Request.Query['ID']:=Session.ID
else if AutoSessions then
Request.Query['ID']:='NEW'
else
Request.Query['ID']:='';
if FAutoLogin then
if not assigned(FOnLogin) then
raise Exception.Create('OnLogin event missing for ClientModule "'+ModuleFileName+'", but AutoLogin is TRUE.')
else if not TRtcDataClient(Sender).Session.asBoolean['ClientModule.Login$'] and
not TRtcDataClient(Sender).Request.Info.asBoolean['ClientModule.Login$'] then
begin
LoginCall(FLoginResult,Sender,True);
Exit;
end;
if assigned(Link) then
Link.Call_BeginRequest(Sender)
else if assigned(Client) then
Client.CallBeginRequest;
if not TRtcDataClient(Sender).RequestInserted and
not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
begin
if assigned(FOnBeginRequest) then
if AutoSyncEvents then
Sender.Sync(FOnBeginRequest)
else
FOnBeginRequest(Sender);
if not TRtcDataClient(Sender).RequestInserted and
not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
begin
with TRtcDataClient(Sender) do
begin
MyCalls:=TRtcClientModuleCallsArray(Request.Info.Obj['ClientModule.Call$']);
if not assigned(MyCalls) then
raise Exception.Create('Internal error! ClientModule objects undefined!');
if FDataFormat=fmt_RTC then
crypt:=GetCrypt(Session)
else
crypt:=nil;
compressed:=False;
{$IFDEF COMPRESS}
if (FDataFormat=fmt_RTC) and (FCompress<>cNone) then
begin
if MyCalls.Count=1 then
code:=MyCalls.asCode[0]
else
begin
output:=TRtcHugeString.Create;
try
for idx:=0 to MyCalls.Count-1 do
output.Add(MyCalls.asCode[idx]);
code:= output.Get;
finally
output.Free;
end;
end;
if length(code)<RTC_MIN_COMPRESS_SIZE then
begin
CryptWrite(crypt, code);
Write(code);
end
else
begin
{ Using compression,
need to compress all data now. }
case FCompress of
cFast: temp:=ZCompress_Str(code,zcFastest);
cMax: temp:=ZCompress_Str(code,zcMax);
else temp:=ZCompress_Str(code,zcDefault);
end;
// use compressed version ONLY if smaller than uncompressed
if length(temp)<length(code)-1 then
begin
code:='';
CryptWrite(crypt, temp);
Write(temp);
temp:=#0;
CryptWrite(crypt, temp);
Write(temp);
temp:='';
compressed:=True;
end
else
begin
temp:='';
CryptWrite(crypt, code);
Write(code);
code:='';
end;
end;
end
else
{$ENDIF}
begin
if FDataFormat=fmt_RTC then
begin
if not assigned(crypt) then
begin
for idx:=0 to MyCalls.Count-1 do
begin
code:=MyCalls.asCode[idx];
Write(code);
end;
end
else
begin
for idx:=0 to MyCalls.Count-1 do
begin
code:=MyCalls.asCode[idx];
CryptWrite(crypt, code);
Write(code);
end;
end;
end
else
begin
for idx:=0 to MyCalls.Count-1 do
begin
obj:=MyCalls.asObject[idx];
if not assigned(obj) then
raise Exception.Create('XML-RPC Error! Can not make a "NIL" call!')
else
code:=obj.toXMLrpcRequest;
Write(code);
end;
end;
end;
if (FDataFormat=fmt_RTC) then
begin
if assigned(crypt) and assigned(crypt.Write) then
begin
{ Add random control number at the end of the request,
so we can check if the response is correctly encrypted. }
crypt.ControlKey := GenerateControlKey(crypt.ControlCounter);
if not compressed then
code:=#13+crypt.ControlKey
else // #0 was allready added
code:=crypt.ControlKey; // we just need to add the control number
CryptWrite(crypt, code);
Write(code);
end;
end;
code:='';
end;
end;
end;
end;
procedure TRtcClientModule.Call_DataReceived(Sender: TRtcConnection);
var
idx:integer;
code:string;
at:integer;
MyTemp:TRtcValue;
crypt:TRtcCryptClient;
c1,c2:string;
c3:integer;
MyData,MyResult:TRtcValueObject;
MyCalls:TRtcClientModuleCallsArray;
begin
with TRtcDataClient(Sender) do if Response.Done then
if AutoSyncEvents and not Sender.inMainThread then
{$IFDEF FPC}
Sender.Sync(@Call_DataReceived)
{$ELSE}
Sender.Sync(Call_DataReceived)
{$ENDIF}
else if Response.StatusCode=410 then // Status 410 = Gone: Session ID invalid, clear local Session info.
begin
Call_SessionExpired(Sender);
end
else if Response.StatusCode=412 then // Status 412 = Precondition Failed: Encryption required
begin
Call_NeedEncryption(Sender);
end
else if Response.StatusCode=409 then // Status 409 = Conflict: Wrong Encryption Key
begin
Call_WrongEncryption(Sender);
end
else if Response.StatusCode<>200 then // Accept only responses with status 200 OK.
begin
Call_WrongResponse(Sender);
end
else if (EncryptionKey>0) and
(Request.Query['ACTION']='HELLO') then
begin
// Prepare Session
if (Session.ID='') then
begin
if (Response.Cookie['ID']='') then
begin
if ForceEncryption then
begin
Call_WrongResponse(Sender);
Exit;
end
else
begin
NewCrypt(Session);
crypt:=GetCrypt(Session);
end;
end
else
begin
c1:=GetCrypt(Session).ClientHello;
c2:=GetCrypt(Session).ControlKey;
c3:=GetCrypt(Session).ControlCounter;
Session.Open(Response.Cookie['ID']); // Set new Session ID
NewCrypt(Session);
crypt:=GetCrypt(Session);
crypt.ClientHello:=c1;
crypt.ControlKey:=c2;
crypt.ControlCounter:=c3;
end;
end
else if (Response.Cookie['ID']<>'') and
(Session.ID<>Response.Cookie['ID']) then
begin
c1:=GetCrypt(Session).ClientHello;
c2:=GetCrypt(Session).ControlKey;
c3:=GetCrypt(Session).ControlCounter;
Session.Open(Response.Cookie['ID']); // Set new Session ID
NewCrypt(Session);
crypt:=GetCrypt(Session);
crypt.ClientHello:=c1;
crypt.ControlKey:=c2;
crypt.ControlCounter:=c3;
end
else
crypt:=GetCrypt(Session);
code:=Read;
crypt.HaveHello:=True;
if code='' then // Server does not support encryption
begin
if ForceEncryption then
begin
Call_NoEncryption(Sender);
Exit;
end
else
begin
crypt.Init;
crypt.HaveHello:=True;
crypt.HaveStart:=True;
end;
end
else if length(code)<=length(crypt.ControlKey) then // Wrong response from server
begin
Call_WrongEncryption(Sender);
Exit;
end
else
begin
// Prepare the Encryption object for Reading
if assigned(crypt.Read) then
crypt.Read.Free;
crypt.Read:=TRtcCrypt.Create;
crypt.Read.Key:=crypt.ClientHello;
// DeCrypt Server-Hello + Client-Hello
CryptRead(crypt, code);
// Check if response ends with sent control key
if Copy(code, length(code)-length(crypt.ControlKey)+1, length(crypt.ControlKey))<>
crypt.ControlKey then
begin
Call_WrongEncryption(Sender);
Exit;
end
else
Delete(code, length(code)-length(crypt.ControlKey)+1, length(crypt.ControlKey));
crypt.ServerHello:=code;
// Prepare the Encryption object for Writing
if assigned(crypt.Write) then crypt.Write.Free;
crypt.Write:=TRtcCrypt.Create;
crypt.Write.Key:=crypt.ServerHello;
end;
end
else if (EncryptionKey>0) and
(Request.Query['ACTION']='START') then
begin
crypt:=GetCrypt(Session);
code:=Read;
crypt.HaveStart:=True;
if code='' then // Server canceled encryption
begin
if ForceEncryption then
begin
Call_NoEncryption(Sender);
Exit;
end
else
begin
crypt.Init;
crypt.HaveHello:=True;
crypt.HaveStart:=True;
end;
end
else if length(code)<=length(crypt.ControlKey) then // Wrong response from server
begin
Call_WrongEncryption(Sender);
Exit;
end
else
begin
// Set new Reading Key
crypt.Read.Key:=crypt.ClientKey + crypt.ServerHello;
// DeCrypt response: Server-Key + Client-Key
CryptRead(crypt, code);
// Check if response ends with sent Control Key
if Copy(code, length(code)-length(crypt.ControlKey)+1, length(crypt.ControlKey))<>
crypt.ControlKey then
begin
Call_WrongEncryption(Sender);
Exit;
end
else
Delete(code, length(code)-length(crypt.ControlKey)+1, length(crypt.ControlKey));
crypt.ServerKey:=code;
// Set new Writing Key
crypt.Write.Key:=crypt.ServerKey + crypt.ClientHello;
end;
end
else
begin
if Request.Query['ID']='NEW' then // we have requested a new session ID
if Response.Cookie['ID']<>'' then
Session.Open(Response.Cookie['ID']);
MyCalls:=TRtcClientModuleCallsArray(Request.Info.Obj['ClientModule.Call$']);
if not assigned(MyCalls) then
raise Exception.Create('Internal error! ClientModule objects undefined!');
code := Read;
if FDataFormat=fmt_RTC then
begin
crypt:=GetCrypt(Session);
if assigned(crypt) and assigned(crypt.Read) then
begin
if code='' then
begin
Call_WrongEncryption(Sender);
Exit;
end
else if length(code)<=length(crypt.ControlKey) then // Wrong response from server
begin
Call_WrongEncryption(Sender);
Exit;
end
else
begin
// Response has to END with our ControlKey
CryptRead(crypt, code);
if Copy(code, length(code)-length(crypt.ControlKey)+1, length(crypt.ControlKey))<>
crypt.ControlKey then
begin
Call_WrongEncryption(Sender);
Exit;
end
else
begin
{$IFDEF COMPRESS}
// There is #0 before the Control Key, data is compressed
if Copy(code,length(code)-length(crypt.ControlKey),1)=#0 then
begin
try
code:=ZDecompress_Str(code, length(code)-length(crypt.ControlKey)-1);
except
on E:Exception do
begin
Call_WrongResponse(Sender);
Exit;
end;
end;
end
else
SetLength(code, length(code)-length(crypt.ControlKey));
{$ELSE}
// There is #0 before the Control Key, data is compressed
if Copy(code,length(code)-length(crypt.ControlKey),1)=#0 then
begin
Call_WrongResponse(Sender);
Exit;
end
else
SetLength(code, length(code)-length(crypt.ControlKey));
{$ENDIF}
end;
end;
end
else if ForceEncryption and (EncryptionKey>0) then
begin
Call_NoEncryption(Sender);
Exit;
end
else if Copy(code,length(code),1)=#0 then // compressed data
begin
{$IFDEF COMPRESS}
try
code:=ZDecompress_Str(code, length(code)-1);
except
on E:Exception do
begin
Call_WrongResponse(Sender);
Exit;
end;
end;
{$ELSE}
Call_WrongResponse(Sender);
Exit;
{$ENDIF}
end;
end;
idx:=0;
at:=0;
try
if Code='' then
raise Exception.Create('No data received.')
else while at<length(Code) do
begin
case FDataFormat of
fmt_XMLRPC: MyData:=TRtcValue.FromXMLrpc(code,at);
else MyData:=TRtcValue.FromCode(code,at);
end;
try
if not isSimpleValue(MyData) then
begin
if assigned(FFunctions) then
begin
MyResult:=FFunctions.ExecuteData(Sender, MyData);
if MyData<>MyResult then
begin
MyData.Free;
MyData:=MyResult;
end;
end;
end;
if MyData<>nil then
begin
if idx<MyCalls.Count then
begin
if assigned(MyCalls.Event[idx]) then
begin
if not (MyData is TRtcValue) then
begin
MyTemp:=TRtcValue.Create;
MyTemp.asObject:=MyData;
MyData:=MyTemp;
end;
try
MyCalls.Event[idx].
Call_Return(Sender,
TRtcValue(MyCalls.asObject[idx]),
TRtcValue(MyData));
except
on E:EPostInteractive do
begin
PostInteractiveResult(MyCalls.Event[idx],
TRtcValue(MyCalls.asObject[idx]),
TRtcValue(MyData));
MyCalls.asObject[idx]:=nil;
MyData:=nil;
end;
end;
end;
end
else
raise Exception.Create('More Results received than Calls sent.');
end
else
raise Exception.Create('Response missing a result.');
Inc(idx);
finally
if assigned(MyData) then
MyData.Free;
end;
end;
except
on E:Exception do
begin
Response.StatusCode:=0; // Internal exception
Response.StatusText:=E.Message;
Call_WrongResponse(Sender);
end;
end;
end;
end;
{$IFDEF COMPRESS}
procedure TRtcClientModule.SetCompress(const Value: TRtcCompressLevel);
begin
FCompress := Value;
end;
{$ENDIF}
procedure TRtcClientModule.Call_DataOut(Sender: TRtcConnection);
begin
// empty
end;
procedure TRtcClientModule.Call_DataIn(Sender: TRtcConnection);
begin
// empty
end;
procedure TRtcClientModule.Call_DataSent(Sender: TRtcConnection);
begin
// empty
end;
procedure TRtcClientModule.Call_ReadyToSend(Sender: TRtcConnection);
begin
// empty
end;
procedure TRtcClientModule.Call_ResponseData(Sender: TRtcConnection);
begin
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(Link) then
Link.Call_ResponseData(Sender)
else if assigned(Client) then
Client.CallResponseData;
end;
procedure TRtcClientModule.Call_ResponseDone(Sender: TRtcConnection);
begin
if assigned(FOnResponseDone) then
if AutoSyncEvents then
Sender.Sync(FOnResponseDone)
else
FOnResponseDone(Sender);
if not TRtcDataClient(Sender).Request.Skipped and
not TRtcDataClient(Sender).Response.Rejected then
if assigned(Link) then
Link.Call_ResponseDone(Sender)
else if assigned(Client) then
Client.CallResponseDone;
end;
procedure TRtcClientModule.Call_RepostCheck(Sender: TRtcConnection);
begin
if ((AutoRepost<0) or (TRtcDataClient(Sender).Request.Reposted<AutoRepost)) then
TRtcDataClient(Sender).Request.Repost;
if not TRtcDataClient(Sender).Request.Reposting then
begin
if assigned(FOnRepostCheck) then
FOnRepostCheck(Sender);
if not TRtcDataClient(Sender).Request.Reposting then
begin
if assigned(Link) then
Link.Call_RepostCheck(Sender)
else if assigned(Client) then
Client.CallRepostCheck;
end;
end;
end;
procedure TRtcClientModule.Call_ResponseAbort(Sender: TRtcConnection);
begin
if IsRemoteCallRequest(Sender) then
begin
if assigned(FOnResponseAbort) then
if AutoSyncEvents then
Sender.Sync(FOnResponseAbort)
else
FOnResponseAbort(Sender);
if not TRtcDataClient(Sender).Request.Reposting then
begin
if assigned(Link) then
Link.Call_ResponseAbort(Sender)
else if assigned(Client) then
Client.CallResponseAbort;
if not TRtcDataClient(Sender).Request.Reposting then
if AutoSyncEvents then
Sender.Sync(NotifyResultAborted)
else
NotifyResultAborted(Sender);
end;
end
else
begin
if assigned(Link) then
Link.Call_ResponseAbort(Sender)
else if assigned(Client) then
Client.CallResponseAbort;
end;
end;
procedure TRtcClientModule.Call_ResponseReject(Sender: TRtcConnection);
begin
if assigned(FOnResponseReject) then
if AutoSyncEvents then
Sender.Sync(FOnResponseReject)
else
FOnResponseReject(Sender);
if assigned(Link) then
Link.Call_ResponseReject(Sender)
else if assigned(Client) then
Client.CallResponseReject;
end;
procedure TRtcClientModule.Call_SessionClose(Sender: TRtcConnection);
begin
if assigned(FOnSessionClose) then
if AutoSyncEvents then
Sender.Sync(FOnSessionClose)
else
FOnSessionClose(Sender);
if assigned(Link) then
Link.Call_SessionClose(Sender)
else if assigned(Client) then
Client.CallSessionClose;
end;
procedure TRtcClientModule.Call_SessionOpen(Sender: TRtcConnection);
begin
if assigned(FOnSessionOpen) then
if AutoSyncEvents then
Sender.Sync(FOnSessionOpen)
else
FOnSessionOpen(Sender);
if assigned(Link) then
Link.Call_SessionOpen(Sender)
else if assigned(Client) then
Client.CallSessionOpen;
end;
procedure TRtcClientModule.Call(ResultHandler: TRtcResult; FromInsideEvent:boolean=False; Sender:TRtcConnection=nil);
var
idx:integer;
myData:TRtcClientModuleData;
begin
myData:=CheckMyData;
if myData=nil then
raise Exception.Create('No data defined. Use the Data property before "Call".');
if myData.FData=nil then
raise Exception.Create('No data defined. Use the Data property before "Call".');
if myData.FData.isNull then
raise Exception.Create('No data defined. Use the Data property before "Call".');
{if not assigned(ResultHandler) then
raise Exception.Create('Can not use "Call" with NIL as parameter.');
if not assigned(ResultHandler.OnReturn) then
raise Exception.Create('OnReturn event undefined for given TRtcResult component.'); }
with myData do
begin
if not assigned(FCalls) then
FCalls:=TRtcClientModuleCallsArray.Create;
// Add Data and ResultHandler to our list of calls
idx:=FCalls.Count;
FCalls.asObject[idx]:=FData;
FCalls.Event[idx]:=ResultHandler;
// set to NIL
FData:=nil;
if FPostLevel=0 then
begin
Inc(FPostLevel);
Post(FromInsideEvent, Sender);
end;
end;
end;
procedure TRtcClientModule.LoginCall(ResultHandler: TRtcResult; Sender:TRtcConnection; Insert:boolean=False);
var
DataReq:TRtcDataRequestInfo;
FCalls:TRtcClientModuleCallsArray;
FRequest:TRtcClientRequest;
CallData:TRtcValue;
begin
CallData:=TRtcValue.Create;
try
if AutoSyncEvents then
Sender.Sync(FOnLogin, CallData)
else
FOnLogin(Sender, CallData);
except
CallData.Free;
raise;
end;
// Create the "Calls" object with our remote function call
FCalls:=TRtcClientModuleCallsArray.Create;
FCalls.asObject[0]:=CallData;
FCalls.Event[0]:=ResultHandler;
// Create a new "Request" object
FRequest:=TRtcClientRequest.Create;
if ModuleFileName<>'' then
FRequest.FileName:=ModuleFileName;
if ModuleHost<>'' then
FRequest.Host:=ModuleHost;
FRequest.Method:='POST';
if FDataFormat=fmt_XMLRPC then // need to send more info in header
begin
if FRequest.Host='' then
FRequest.Host:=Sender.ServerAddr;
if FRequest.Agent='' then
FRequest.Agent:='RTC Client';
FRequest.ContentType:='text/xml';
end;
// Assign our "Calls" object to the Request object, so we can access it after we post it.
FRequest.Info.Obj['ClientModule.Call$']:=FCalls;
FRequest.Info.asBoolean['ClientModule.Login$']:=True;
// Create a "DataRequest" object and store the "Request" object into it
DataReq:=TRtcDataRequestInfo.Create;
DataReq.Request:=FRequest;
DataReq.Events:=Self;
// Insert the Request
try
if Insert then
TRtcDataClient(Sender).InsertRequest(DataReq)
else
TRtcDataClient(Sender).PostRequest(DataReq,True);
except
DataReq.Free;
raise;
end;
end;
procedure TRtcClientModule.StartCalls;
begin
with GetMyData do
begin
Inc(FPostLevel);
if assigned(FData) then FData.Clear;
end;
end;
procedure TRtcClientModule.ClearMyData;
var
id:longword;
obj:TObject;
cli:TRtcClientModuleData;
begin
if FHyperThreading then
begin
id:=GetCurrentThreadId;
if id<>MainThreadID then
begin
FCS.Enter;
try
obj:=FMyData.search(id);
if obj<>nil then
begin
cli:=TRtcClientModuleData(obj);
cli.Free;
FMyData.remove(id);
end;
finally
FCS.Leave;
end;
end;
end;
end;
function TRtcClientModule.CheckMyData: TRtcClientModuleData;
var
id:longword;
obj:TObject;
begin
if not FHyperThreading then
Result:=FMainThrData
else
begin
id:=GetCurrentThreadId;
if id=MainThreadID then
Result:=FMainThrData
else
begin
FCS.Enter;
try
obj:=FMyData.search(id);
if obj<>nil then
Result:=TRtcClientModuleData(obj)
else
Result:=nil;
finally
FCS.Leave;
end;
end;
end;
end;
function TRtcClientModule.GetMyData: TRtcClientModuleData;
var
id:longword;
obj:TObject;
begin
if not FHyperThreading then
Result:=FMainThrData
else
begin
id:=GetCurrentThreadId;
if id=MainThreadID then
Result:=FMainThrData
else
begin
FCS.Enter;
try
obj:=FMyData.search(id);
if obj=nil then
begin
obj:=TRtcClientModuleData.Create;
FMyData.insert(id, obj);
end;
Result:=TRtcClientModuleData(obj);
finally
FCS.Leave;
end;
end;
end;
end;
function TRtcClientModule.GetData: TRtcValue;
var
myData:TRtcClientModuleData;
begin
myData:=GetMyData;
if not assigned(myData.FData) then
myData.FData:=TRtcValue.Create;
Result:=myData.FData;
end;
function TRtcClientModule.GetPostLevel: integer;
var
myData:TRtcClientModuleData;
begin
myData:=GetMyData;
Result:=myData.FPostLevel;
end;
function TRtcClientModule.GetRequest: TRtcClientRequest;
var
myData:TRtcClientModuleData;
begin
myData:=GetMyData;
if not assigned(myData.FRequest) then
myData.FRequest:=TRtcClientRequest.Create;
Result:=myData.FRequest;
end;
procedure TRtcClientModule.Post(FromInsideEvent:boolean=False; Sender:TRtcConnection=nil);
var
DataReq:TRtcDataRequestInfo;
myData:TRtcClientModuleData;
begin
myData:=CheckMyData;
if myData=nil then
raise Exception.Create('Have to use "StartCalls" before "Post",'#13#10+
'to post multiple calls in one request.');
if myData.FPostLevel<=0 then
raise Exception.Create('Have to use "StartCalls" before "Post",'#13#10+
'to post multiple calls in one request.');
with myData do
begin
Dec(FPostLevel);
if FPostLevel>0 then Exit;
if assigned(FCalls) then
begin
if not assigned(FRequest) then
FRequest:=TRtcClientRequest.Create;
if ModuleFileName<>'' then
FRequest.FileName:=ModuleFileName;
if FRequest.FileName='' then
raise Exception.Create('Module FileName is undefined. Can not Post the request.');
if ModuleHost<>'' then
FRequest.Host:=ModuleHost;
FRequest.Method:='POST';
if FDataFormat=fmt_XMLRPC then // need to send more info in header
begin
if (FRequest.Host='') and assigned(Sender) then
FRequest.Host:=Sender.ServerAddr;
if FRequest.Agent='' then
FRequest.Agent:='RTC Client';
FRequest.ContentType:='text/xml';
end;
// Assign our Calls to the Request object, so we can access it after we post it.
FRequest.Info.Obj['ClientModule.Call$']:=FCalls;
FCalls:=nil;
DataReq:=TRtcDataRequestInfo.Create;
DataReq.Request:=FRequest;
DataReq.Events:=Self;
FRequest:=nil;
try
if assigned(Sender) and (Sender is TRtcDataClient) then
TRtcDataClient(Sender).PostRequest(DataReq,FromInsideEvent)
else
PostRequest(DataReq,FromInsideEvent);
except
DataReq.Free;
raise;
end;
end;
end;
// Free ClientModuleData and remove it from the list
ClearMyData;
end;
function TRtcClientModule.GetFunctionGroup: TRtcFunctionGroup;
begin
try
Result:=FFunctions;
if not (Result is TRtcFunctionGroup) then
Result:=nil;
except
Result:=nil;
end;
end;
procedure TRtcClientModule.SetFunctionGroup(const Value: TRtcFunctionGroup);
begin
FFunctions:=Value;
end;
function TRtcClientModule.GetModuleFileName: string;
begin
Result:=FModuleFileName;
end;
procedure TRtcClientModule.SetModuleFileName(const Value: string);
begin
if FModuleFileName<>Value then
begin
FModuleFileName:=Value;
if FModuleFileName<>'' then
begin
// FileName has to start with '/'
if Copy(FModuleFileName,1,1)<>'/' then
FModuleFileName:='/'+FModuleFileName;
end;
end;
end;
function TRtcClientModule.GetModuleHost: string;
begin
Result:=FModuleHost;
end;
procedure TRtcClientModule.SetModuleHost(const Value: string);
begin
if FModuleHost<>Value then
// Convert to uppercase now, so we don't have to do it on every request.
FModuleHost:=UpperCase(Value);
end;
procedure TRtcClientModule.Response_Problem(Sender: TRtcConnection);
begin
with TRtcDataClient(Sender) do
begin
if not Request.Reposting and not Response.Rejected then
begin
Call_RepostCheck(Sender);
if not Request.Reposting and not Response.Rejected then
Call_ResponseAbort(Sender);
end;
end;
end;
procedure TRtcClientModule.Call_SessionExpired(Sender: TRtcConnection);
begin
DelCrypt(TRtcDataClient(Sender).Session);
if assigned(FOnSessionExpired) then
FOnSessionExpired(Sender);
with TRtcDataClient(Sender) do
begin
Session.Init;
Request.Query['ID']:='';
if not Request.Reposting and not Response.Rejected then
if Request.Reposted<1 then // if Session expires, we will try to repost 1 time ...
Request.Repost
else // ... and leave all other decisions to the user
Response_Problem(Sender);
end;
end;
procedure TRtcClientModule.Call_WrongResponse(Sender: TRtcConnection);
begin
DelCrypt(TRtcDataClient(Sender).Session);
if assigned(FOnResponseError) then
FOnResponseError(Sender);
Response_Problem(Sender);
end;
procedure TRtcClientModule.Call_WrongEncryption(Sender: TRtcConnection);
begin
DelCrypt(TRtcDataClient(Sender).Session);
if assigned(FOnWrongEncryption) then
FOnWrongEncryption(Sender);
Response_Problem(Sender);
end;
procedure TRtcClientModule.Call_NoEncryption(Sender: TRtcConnection);
begin
DelCrypt(TRtcDataClient(Sender).Session);
if assigned(FOnNoEncryption) then
FOnNoEncryption(Sender);
Response_Problem(Sender);
end;
procedure TRtcClientModule.Call_NeedEncryption(Sender: TRtcConnection);
begin
DelCrypt(TRtcDataClient(Sender).Session);
if assigned(FOnNeedEncryption) then
FOnNeedEncryption(Sender);
Response_Problem(Sender);
end;
procedure TRtcClientModule.SetAutoEncrypt(const Value: integer);
begin
if Value<0 then
raise Exception.Create('Negative values not allowed for EncryptionKey.');
FAutoEncrypt := Value;
if FAutoEncrypt > 0 then
FAutoSessions:=True
else
FForceEncrypt:=False;
end;
procedure TRtcClientModule.SetAutoSessions(const Value: boolean);
begin
FAutoSessions := Value;
if not FAutoSessions then
begin
FAutoEncrypt:=0;
FAutoLogin:=False;
FForceEncrypt:=False;
end;
end;
procedure TRtcClientModule.SetForceEncrypt(const Value: boolean);
begin
FForceEncrypt := Value;
if FForceEncrypt then
begin
FAutoSessions:=True;
if FAutoEncrypt=0 then
FAutoEncrypt:=16;
end;
end;
procedure TRtcClientModule.PostInteractiveResult(Event: TRtcResult; Data, Result: TRtcValue);
var
res:TRtcInteractiveResult;
begin
FIntCS.Enter;
try
res:=TRtcInteractiveResult.Create;
res.FEvent:=Event;
res.Data:=Data;
res.Result:=Result;
FIntRes.Add(res);
if not assigned(FIntTimer) then
begin
FIntTimer:=TRtcTimer.Create(False);
{$IFDEF FPC}
TRtcTimer.Enable(FIntTimer,1,@DoInteractiveResult,True);
{$ELSE}
TRtcTimer.Enable(FIntTimer,1,DoInteractiveResult,True);
{$ENDIF}
end;
finally
FIntCS.Leave;
end;
end;
procedure TRtcClientModule.DoInteractiveResult;
var
res:TRtcInteractiveResult;
begin
FIntCS.Enter;
try
res:=TRtcInteractiveResult(FIntRes.Items[0]);
FIntRes.Delete(0);
finally
FIntCS.Leave;
end;
try
res.FEvent.Call_Return(nil, res.Data, res.Result);
finally
res.Free;
FIntCS.Enter;
try
if FIntRes.Count>0 then
{$IFDEF FPC}
TRtcTimer.Enable(FIntTimer,1,@DoInteractiveResult,True)
{$ELSE}
TRtcTimer.Enable(FIntTimer,1,DoInteractiveResult,True)
{$ENDIF}
else
begin
TRtcTimer.Stop(FIntTimer);
FIntTimer:=nil;
end;
finally
FIntCS.Leave;
end;
end;
if FRelease then
Free;
end;
procedure TRtcClientModule.Release;
begin
FRelease:=True;
end;
procedure TRtcClientModule.NotifyResultAborted(Sender: TRtcConnection);
var
MyCalls:TRtcClientModuleCallsArray;
event:TRtcResult;
data:TRtcValue;
a:integer;
begin
MyCalls:=TRtcClientModuleCallsArray(TRtcDataClient(Sender).Request.Info.Obj['ClientModule.Call$']);
if assigned(MyCalls) then
begin
for a:=0 to MyCalls.Count-1 do
begin
event:=MyCalls.Event[a];
if assigned(event) then
begin
data:=TRtcValue(MyCalls.AsObject[a]);
event.Call_Aborted(Sender,data,nil);
end;
end;
end;
end;
function TRtcClientModule.IsRemoteCallRequest(Sender:TRtcConnection): boolean;
begin
Result:= assigned(TRtcClientModuleCallsArray(TRtcDataClient(Sender).Request.Info.Obj['ClientModule.Call$']));
end;
procedure TRtcClientModule.SetDataFormat(const Value: TRtcDataFormat);
begin
FDataFormat := Value;
end;
procedure TRtcClientModule.SetAutoLogin(const Value: boolean);
begin
FAutoLogin := Value;
if FAutoLogin then
FAutoSessions:=True;
end;
procedure TRtcClientModule.Call_LoginAborted(Sender: TRtcConnection; Data, Result: TRtcValue);
begin
if assigned(FOnLoginAborted) then
FOnLoginAborted(Sender,Data,Result);
end;
procedure TRtcClientModule.Call_LoginResult(Sender: TRtcConnection; Data, Result: TRtcValue);
begin
if assigned(FOnLoginResult) then
FOnLoginResult(Sender,Data,Result);
if Result.isType<>rtc_Exception then
TRtcDataClient(Sender).Session.asBoolean['ClientModule.Login$']:=True;
end;
procedure TRtcClientModule.ResetLogin;
begin
FResetLogin:=True;
end;
{ TRtcInteractiveResult }
destructor TRtcInteractiveResult.Destroy;
begin
Data.Free;
Result.Free;
inherited;
end;
{ TRtcClientModuleCallsArray }
constructor TRtcClientModuleCallsArray.Create;
begin
inherited;
SetLength(FEvents,0);
end;
destructor TRtcClientModuleCallsArray.Destroy;
begin
SetLength(FEvents,0);
inherited;
end;
function TRtcClientModuleCallsArray.GetEvent(index: integer): TRtcResult;
begin
if (index>=0) and (index<=length(FEvents)) then
Result:=FEvents[index]
else
Result:=nil;
end;
procedure TRtcClientModuleCallsArray.SetEvent(index: integer; const _Value: TRtcResult);
begin
if length(FEvents)<index+1 then
SetLength(FEvents, index+1);
FEvents[index]:=_Value;
end;
{ TRtcCryptClient }
destructor TRtcCryptClient.Destroy;
begin
Init;
inherited;
end;
procedure TRtcCryptClient.Kill;
begin
Free;
end;
procedure TRtcCryptClient.Init;
begin
HaveHello:=False;
HaveStart:=False;
ControlCounter:=0;
ClientHello:='';
ServerHello:='';
ClientKey:='';
ServerKey:='';
if assigned(Read) then
begin
Read.Free;
Read:=nil;
end;
if assigned(Write) then
begin
Write.Free;
Write:=nil;
end;
end;
initialization
randomize;
end.
|
{**********************************************************}
{ }
{ TinyDB Database Engine }
{ Version 2.94 }
{ }
{ Author: DayDream Software }
{ Email: haoxg@21cn.com }
{ URL: http://www.tinydb.com }
{ Last Modified Date: 2005-10-31 }
{ }
{**********************************************************}
unit TinyDB;
{$I TinyDB.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms,
Dialogs, Db, {DbTables,} StdCtrls, ExtCtrls, Graphics, Math,
{$IFDEF COMPILER_6_UP}{ QConsts,} Variants, RTLConsts, {$ENDIF}
DbConsts, Consts, BdeConst;
const
tdbWebsite = 'http://www.tinydb.com'; // TinyDB网站
tdbSupportEmail = 'haoxg@21cn.com'; // TinyDB的Support Email
tdbSoftName = 'TinyDB';
tdbSoftVer = '2.94'; // 数据库引擎版本号
tdbFileFmtVer = '2.0'; // 数据库文件格式版本号
tdbDBFileExt = '.tdb'; // 默认扩展名
tdbMaxTable = 256; // 最大表数
tdbMaxField = 96; // 最大字段数
tdbMaxIndex = 8; // 一个表中允许定义的最多索引数
tdbMaxFieldNameChar = 32; // 字段名最大字符数
tdbMaxTableNameChar = 32; // 表名最大字符数
tdbMaxIndexNameChar = 32; // 索引名最大字符数
tdbMaxAlgoNameChar = 32; // 算法名称最大字符数
tdbMaxCommentsChar = 256; // 数据库注释最大字节数
tdbMaxExtDataSize = 1024*2; // 附加数据块的字节数
tdbMaxHashPwdSize = 128; // Hash后数据库密码最长字节数
tdbRndBufferSize = 256; // 随机填充区大小
tdbRecTabUnitNum = 1024; // 记录表块元素个数为多少的整数倍
tdbIdxTabUnitNum = 1024; // 索引表块元素个数为多少的整数倍
tdbMaxTextFieldSize = 8192; // Text字段的最大长度
tdbBlobSizeUnitNum = 64; // 不定长度(Blob)型字段存储长度为多少的整数倍
tdbMaxMultiIndexFields = 8; // 复合索引的最多字段数
tdbDefaultLockRetryCount = 20; // 等待锁定资源的重试次数缺省值
tdbDefaultLockWaitTime = 100; // 两次重试之间的时间间隔缺省值(毫秒)
tdbDefAutoFlushInterval = 60*1000; // 自动Flush的时间间隔缺省值(毫秒)
SGeneralError = 'General error';
SAccessDenied = 'Access denied';
STableNotFound = 'Table ''%s'' not found';
SBookmarkNotFound = 'Bookmark not found';
SFieldCountMismatch = 'Field count mismatch';
STooManyTables = 'Too many tables';
STooManyFields = 'Too many fields';
STooManyIndexes = 'Too many indexes';
SDuplicateTableName = 'Duplicate table name ''%s''';
SDuplicateIndexName = 'Duplicate index name ''%s''';
SDuplicatePrimaryIndex = 'Duplicate primary index';
SDuplicateAutoIncField = 'Duplicate AutoInc field';
SInvalidDatabaseName = 'Invalid database name ''%s''';
SInvalidTableName = 'Invalid table name ''%s''';
SInvalidFieldName = 'Invalid field name ''%s''';
SInvalidIndexName = 'Invalid index name ''%s''';
SInvalidDatabase = 'Database file ''%s'' is a invalid TinyDB';
SInvalidVersion100 = 'Version 1.00 is not compatible';
SInvalidVersionTooHigh = 'Version of database file is too High';
SFieldNameExpected = 'Field name expected';
SFailToCreateIndex = 'Fail to create index';
SInvalidUniqueFieldValue = 'Invalid unique field value ''%s''';
SInvalidMultiIndex = 'Invalid complex index';
SSQLInvalid = 'Invalid SQL statement: ''%s''';
SSQLInvalidChar = 'Invalid SQL character: ''%s''';
SCompressAlgNotFound = 'Compression algorithm module ''%s'' not found';
SEncryptAlgNotFound = 'Encryption algorithm module ''%s'' not found';
SDatabaseReadOnly = 'Cannot modify a read-only database';
SNoRecords = 'No records';
SWaitForUnlockTimeOut = 'Wait for unlock time out';
type
PMemoryStream = ^TMemoryStream;
PBoolean = ^Boolean;
PWordBool = ^WordBool;
PLargeInt = ^LargeInt;
TIntegerAry = array of Integer;
TTinyDBMediumType = (mtDisk, mtMemory);
TTDIndexOption = (tiPrimary, tiUnique, tiDescending, tiCaseInsensitive);
TTDIndexOptions = set of TTDIndexOption;
TTDKeyIndex = (tkLookup, tkRangeStart, tkRangeEnd, tkSave);
TCompressLevel = (clMaximum, clNormal, clFast, clSuperFast);
TEncryptMode = (emCTS, emCBC, emCFB, emOFB, emECB);
TFieldDataProcessMode = (fdDefault, fdOriginal);
TFieldDPModeAry = array of TFieldDataProcessMode;
TOnProgressEvent = procedure (Sender: TObject; Percent: Integer) of object;
//---用于定义数据库文件格式的记录类型------------------------
// 数据库文件头
TFileHeader = packed record
SoftName: array[0..6] of Char;
FileFmtVer: array[0..4] of Char;
end;
// 附加数据块
TExtData = array[0..tdbMaxExtDataSize-1] of Byte;
TExtDataBlock = packed record
Comments: array[0..tdbMaxCommentsChar] of Char; // 数据库注释
Data: TExtData; // 存放用户自定义数据
end;
TAlgoNameString = array[0..tdbMaxAlgoNameChar] of Char;
// 数据库选项设置
TDBOptions = packed record
CompressBlob: Boolean; // 是否压缩Blob字段(只对以后的数据库操作产生作用)
CompressLevel: TCompressLevel; // 压缩级别
CompressAlgoName: TAlgoNameString; // 压缩算法名称
Encrypt: Boolean; // 数据库是否加密(决定整个数据库是否加密)
EncryptMode: TEncryptMode; // 加密模式
EncryptAlgoName: TAlgoNameString; // 加密算法名称
CRC32: Boolean; // 写BLOB字段时是否进行CRC32校检
RandomBuffer: array[0..tdbRndBufferSize-1] of Char; // 随机填充
HashPassword: array[0..tdbMaxHashPwdSize] of Char; // 经过Hash算法后的数据库访问口令
Reserved: array[0..15] of Byte;
end;
// 数据库中所有表
TTableTab = packed record
TableCount: Integer; // 表数目
Reserved: Integer;
TableHeaderOffset: array[0..tdbMaxTable-1] of Integer; // 表头偏移
end;
// 字段项目
TFieldTabItem = packed record
FieldName: array[0..tdbMaxFieldNameChar] of Char; // 字段名
FieldType: TFieldType; // 字段类型
FieldSize: Integer; // 字段大小
DPMode: TFieldDataProcessMode; // 该字段的数据处理方式
Reserved: Integer;
end;
// 索引头
TIndexHeader = packed record
IndexName: array[0..tdbMaxIndexNameChar] of Char; // 索引名
IndexOptions: TTDIndexOptions; // 索引类型
FieldIdx: array[0..tdbMaxMultiIndexFields-1] of Integer; // 索引字段
IndexOffset: Integer; // 索引项目表偏移
StartIndex: Integer; // 第一个索引项目的下标
Reserved: Integer;
end;
TTableNameString = array[0..tdbMaxTableNameChar] of Char;
// 表头
TTableHeader = packed record
// 下面四个成员不能乱动
TableName: TTableNameString; // 表名
RecTabOffset: Integer; // 记录项目表的偏移
RecordTotal: Integer; // 记录总数,包括有删除标记的记录
AutoIncCounter: Integer; // 自动增长计数器
FieldCount: Integer; // 字段总数
FieldTab: array[0..tdbMaxField-1] of TFieldTabItem; // 字段表
IndexCount: Integer; // 索引总数
IndexHeader: array[0..tdbMaxIndex-1] of TIndexHeader; // 索引头部信息
Reserved: array[0..15] of Byte;
end;
// 记录项目
TRecordTabItem = packed record
DataOffset: Integer; // 记录数据偏移
DeleteFlag: Boolean; // 删除标记,为True时表示删除
end;
TRecordTabItems = array of TRecordTabItem;
PRecordTabItems = ^TRecordTabItems;
// 索引项目
TIndexTabItem = packed record
RecIndex: Integer; // 指向文件中RecordTable的某个元素(0-based)
Next: Integer; // 下一个索引项目的Index (0-based)
end;
TIndexTabItems = array of TIndexTabItem;
// 不定长度字段头
TBlobFieldHeader = packed record
DataOffset: Integer; // 实际数据的偏移
DataSize: Integer; // 实际数据的有效长度
AreaSize: Integer; // 为Blob预留的总长度
Reserved1: Integer;
Reserved2: Integer;
end;
PBlobFieldHeader = ^TBlobFieldHeader;
//---用于在内存中管理数据库的记录类型------------------------
TMemRecTabItem = record
DataOffset: Integer; // 指向记录数据在文件中的偏移位置
RecIndex: Integer; // 这条记录在文件中RecordTab中的下标号(0-based)
end;
PMemRecTabItem = ^TMemRecTabItem;
TMemQryRecItem = record
DataOffsets: array of Integer;
end;
// TDataSet中要用到的类型
PRecInfo = ^TRecInfo;
TRecInfo = packed record
Bookmark: Integer;
BookmarkFlag: TBookmarkFlag;
end;
// 字段项目,CreateTable中的参数类型
TFieldItem = record
FieldName: string[tdbMaxFieldNameChar+1]; // 字段名
FieldType: TFieldType; // 字段类型
DataSize: Integer; // 字段大小
DPMode: TFieldDataProcessMode; // 字段数据处理方式
end;
//-------------------------------------------------------------------
{ classes }
TTinyAboutBox = class;
TTinyIndexDef = class;
TTinyIndexDefs = class;
TTinyTableDef = class;
TTinyTableDefs = class;
TTinyDBFileIO = class;
TTinyTableIO = class;
TTDEDataSet = class;
TTinyTable = class;
TTinyQuery = class;
TTinyDatabase = class;
TTinySession = class;
TTinySessionList = class;
TTinyBlobStream = class;
TExprNodes = class;
TExprParserBase = class;
//-------------------------------------------------------------------
{ TTinyDefCollection }
TTinyDefCollection = class(TOwnedCollection)
private
protected
procedure SetItemName(AItem: TCollectionItem); override;
public
constructor Create(AOwner: TPersistent; AClass: TCollectionItemClass);
function Find(const AName: string): TNamedItem;
procedure GetItemNames(List: TStrings);
function IndexOf(const AName: string): Integer;
end;
{ TTinyTableDef }
TTinyTableDef = class(TNamedItem)
private
FTableIdx: Integer;
protected
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
property TableIdx: Integer read FTableIdx write FTableIdx;
published
end;
{ TTinyTableDefs }
TTinyTableDefs = class(TOwnedCollection)
private
function GetItem(Index: Integer): TTinyTableDef;
protected
public
constructor Create(AOwner: TPersistent);
function IndexOf(const Name: string): Integer;
function Find(const Name: string): TTinyTableDef;
property Items[Index: Integer]: TTinyTableDef read GetItem; default;
end;
{ TTinyFieldDef }
TTinyFieldDef = class(TNamedItem)
private
FFieldType: TFieldType;
FFieldSize: Integer;
FDPMode: TFieldDataProcessMode;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property FieldType: TFieldType read FFieldType write FFieldType;
property FieldSize: Integer read FFieldSize write FFieldSize;
property DPMode: TFieldDataProcessMode read FDPMode write FDPMode;
end;
{ TTinyFieldDefs }
TTinyFieldDefs = class(TTinyDefCollection)
private
function GetFieldDef(Index: Integer): TTinyFieldDef;
procedure SetFieldDef(Index: Integer; Value: TTinyFieldDef);
protected
procedure SetItemName(AItem: TCollectionItem); override;
public
constructor Create(AOwner: TPersistent);
function AddIndexDef: TTinyFieldDef;
function Find(const Name: string): TTinyFieldDef;
property Items[Index: Integer]: TTinyFieldDef read GetFieldDef write SetFieldDef; default;
end;
{ TTinyIndexDef }
TTinyIndexDef = class(TNamedItem)
private
FOptions: TTDIndexOptions;
FFieldIdxes: TIntegerAry; // 物理字段号
procedure SetOptions(Value: TTDIndexOptions);
protected
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property FieldIdxes: TIntegerAry read FFieldIdxes write FFieldIdxes;
published
property Options: TTDIndexOptions read FOptions write SetOptions default [];
end;
{ TTinyIndexDefs }
TTinyIndexDefs = class(TTinyDefCollection)
private
function GetIndexDef(Index: Integer): TTinyIndexDef;
procedure SetIndexDef(Index: Integer; Value: TTinyIndexDef);
protected
procedure SetItemName(AItem: TCollectionItem); override;
public
constructor Create(AOwner: TPersistent);
function AddIndexDef: TTinyIndexDef;
function Find(const Name: string): TTinyIndexDef;
property Items[Index: Integer]: TTinyIndexDef read GetIndexDef write SetIndexDef; default;
end;
{ TTinyBlobStream }
TTinyBlobStream = class(TMemoryStream)
private
FField: TBlobField;
FDataSet: TTinyTable;
FMode: TBlobStreamMode;
FFieldNo: Integer;
FOpened: Boolean;
FModified: Boolean;
procedure LoadBlobData;
procedure SaveBlobData;
public
constructor Create(Field: TBlobField; Mode: TBlobStreamMode);
destructor Destroy; override;
function Write(const Buffer; Count: Longint): Longint; override;
procedure Truncate;
end;
{ TOptimBlobStream }
TOptimBlobStream = class(TMemoryStream)
private
FDataSet: TTDEDataSet;
FFldDataOffset: Integer;
FShouldEncrypt: Boolean;
FShouldCompress: Boolean;
FDataLoaded: Boolean;
procedure LoadBlobData;
protected
function Realloc(var NewCapacity: Longint): Pointer; override;
public
constructor Create(ADataSet: TTDEDataSet);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
procedure SetSize(NewSize: Longint); override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure Init(FldDataOffset: Integer; ShouldEncrypt, ShouldCompress: Boolean);
property DataLoaded: Boolean read FDataLoaded;
end;
{ TCachedFileStream }
TCachedFileStream = class(TStream)
private
FCacheStream: TMemoryStream;
public
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
constructor Create(const FileName: string; Mode: Word);
destructor Destroy; override;
end;
{ TExprNode }
TTinyOperator = (
toNOTDEFINED, toISBLANK, toNOTBLANK,
toEQ, toNE, toGT, toLT, toGE, toLE,
toNOT, toAND, toOR,
toADD, toSUB, toMUL, toDIV, toMOD,
toLIKE, toIN, toASSIGN
);
TTinyFunction = (
tfUnknown, tfUpper, tfLower, tfSubString, tfTrim, tfTrimLeft, tfTrimRight,
tfYear, tfMonth, tfDay, tfHour, tfMinute, tfSecond, tfGetDate
);
TStrCompOption = (scCaseInsensitive, scNoPartialCompare);
TStrCompOptions = set of TStrCompOption;
TExprNodeKind = (enField, enConst, enFunc, enOperator);
TExprToken = (
etEnd, etSymbol, etName, etNumLiteral, etCharLiteral, etLParen, etRParen,
etEQ, etNE, etGE, etLE, etGT, etLT, etADD, etSUB, etMUL, etDIV,
etComma, etAsterisk, etLIKE, etISNULL, etISNOTNULL, etIN );
TChrSet = set of Char;
TExprNode = class(TObject)
public
FExprNodes: TExprNodes;
FNext: TExprNode;
FKind: TExprNodeKind;
FOperator: TTinyOperator;
FFunction: TTinyFunction;
FSymbol: string;
FData: PChar;
FDataSize: Integer;
FLeft: TExprNode;
FRight: TExprNode;
FDataType: TFieldType;
FArgs: TList;
FIsBlobField: Boolean;
FFieldIdx: Integer;
FBlobData: string;
FPartialLength: Integer;
constructor Create(ExprNodes: TExprNodes);
destructor Destroy; override;
procedure Calculate(Options: TStrCompOptions);
procedure EvaluateOperator(ResultNode: TExprNode; Operator: TTinyOperator;
LeftNode, RightNode: TExprNode; Args: TList; Options: TStrCompOptions);
procedure EvaluateFunction(ResultNode: TExprNode; AFunction: TTinyFunction; Args: TList);
function IsIntegerType: Boolean;
function IsLargeIntType: Boolean;
function IsFloatType: Boolean;
function IsTemporalType: Boolean;
function IsStringType: Boolean;
function IsBooleanType: Boolean;
function IsNumericType: Boolean;
function IsTemporalStringType: Boolean;
procedure SetDataSize(Size: Integer);
function GetDataSet: TTDEDataSet;
function AsBoolean: Boolean;
procedure ConvertStringToDateTime;
class function FuncNameToEnum(const FuncName: string): TTinyFunction;
property DataSize: Integer read FDataSize write SetDataSize;
end;
{ TExprNodes }
TExprNodes = class(TObject)
private
FExprParser: TExprParserBase;
FNodes: TExprNode;
FRoot: TExprNode;
public
constructor Create(AExprParser: TExprParserBase);
destructor Destroy; override;
procedure Clear;
function NewNode(NodeKind: TExprNodeKind;
DataType: TFieldType;
ADataSize: Integer;
Operator: TTinyOperator;
Left, Right: TExprNode): TExprNode;
function NewFuncNode(const FuncName: string): TExprNode;
function NewFieldNode(const FieldName: string): TExprNode;
property Root: TExprNode read FRoot write FRoot;
end;
{ TSyntaxParserBase }
TSyntaxParserBase = class(TObject)
protected
FText: string;
FTokenString: string;
FToken: TExprToken;
FPrevToken: TExprToken;
FSourcePtr: PChar;
FTokenPtr: PChar;
procedure SetText(const Value: string);
function IsKatakana(const Chr: Byte): Boolean;
procedure Skip(var P: PChar; TheSet: TChrSet);
function TokenName: string;
function TokenSymbolIs(const S: string): Boolean;
procedure Rewind;
procedure GetNextToken;
function SkipBeforeGetToken(Pos: PChar): PChar; virtual;
function InternalGetNextToken(Pos: PChar): PChar; virtual; abstract;
public
constructor Create;
destructor Destroy; override;
property Text: string read FText write SetText;
property TokenString: string read FTokenString;
property Token: TExprToken read FToken;
end;
{ TExprParserBase }
TExprParserBase = class(TSyntaxParserBase)
protected
FExprNodes: TExprNodes;
FStrCompOpts: TStrCompOptions;
function ParseExpr: TExprNode; virtual; abstract;
function GetFieldDataType(const Name: string): TFieldType; virtual; abstract;
function GetFieldValue(const Name: string): Variant; virtual; abstract;
function GetFuncDataType(const Name: string): TFieldType; virtual; abstract;
function TokenSymbolIsFunc(const S: string) : Boolean; virtual;
procedure ParseFinished; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Parse(const AText: string); virtual;
function Calculate(Options: TStrCompOptions = []): Variant; virtual;
end;
{ TFilterParser }
TFilterParser = class(TExprParserBase)
protected
FDataSet: TTDEDataSet;
function NextTokenIsLParen: Boolean;
procedure TypeCheckArithOp(Node: TExprNode);
procedure TypeCheckLogicOp(Node: TExprNode);
procedure TypeCheckInOp(Node: TExprNode);
procedure TypeCheckRelationOp(Node: TExprNode);
procedure TypeCheckLikeOp(Node: TExprNode);
procedure TypeCheckFunction(Node: TExprNode);
function ParseExpr2: TExprNode;
function ParseExpr3: TExprNode;
function ParseExpr4: TExprNode;
function ParseExpr5: TExprNode;
function ParseExpr6: TExprNode;
function ParseExpr7: TExprNode;
function InternalGetNextToken(Pos: PChar): PChar; override;
function ParseExpr: TExprNode; override;
function GetFieldDataType(const Name: string): TFieldType; override;
function GetFieldValue(const Name: string): Variant; override;
function GetFuncDataType(const Name: string): TFieldType; override;
function TokenSymbolIsFunc(const S: string): Boolean; override;
public
constructor Create(ADataSet: TTDEDataSet);
end;
{ TSQLWhereExprParser }
TSQLWhereExprParser = class(TFilterParser)
protected
function GetFieldValue(const Name: string): Variant; override;
public
constructor Create(ADataSet: TTDEDataSet);
end;
{ TSQLParserBase }
TSQLParserBase = class(TSyntaxParserBase)
protected
FQuery: TTinyQuery;
FRowsAffected: Integer;
function SkipBeforeGetToken(Pos: PChar): PChar; override;
function InternalGetNextToken(Pos: PChar): PChar; override;
public
constructor Create(AQuery: TTinyQuery);
destructor Destroy; override;
procedure Parse(const ASQL: string); virtual;
procedure Execute; virtual; abstract;
property RowsAffected: Integer read FRowsAffected;
end;
{ TSQLSelectParser }
TNameItem = record
RealName: string;
AliasName: string;
end;
TTableNameItem = TNameItem;
TSelectFieldItem = record
TableName: string;
RealFldName: string;
AliasFldName: string;
Index: Integer;
end;
TOrderByType = (obAsc, obDesc);
TOrderByFieldItem = record
FldName: string;
Index: Integer;
OrderByType: TOrderByType;
end;
TSQLSelectParser = class(TSQLParserBase)
private
FTopNum: Integer;
FFromItems: array of TTableNameItem;
FSelectItems: array of TSelectFieldItem;
FWhereExprParser: TSQLWhereExprParser;
FOrderByItems: array of TOrderByFieldItem;
// FTableTab: TTableTab; // 数据库中所有表
// FTableHeaders: array of TTableHeader; // 表头信息
function ParseFrom: PChar;
function ParseSelect: PChar;
// function ParseWhere(Pos: PChar): PChar;
// function ParseOrderBy(Pos: PChar): PChar;
public
constructor Create(AQuery: TTinyQuery);
destructor Destroy; override;
procedure Parse(const ASQL: string); override;
procedure Execute; override;
end;
{ TSQLParser }
TSQLType = (stNONE, stSELECT, stINSERT, stDELETE, stUPDATE);
TSQLParser = class(TSQLParserBase)
private
FSQLType: TSQLType;
public
constructor Create(AQuery: TTinyQuery);
destructor Destroy; override;
procedure Parse(const ASQL: string); override;
procedure Execute; override;
end;
{ TRecordsMap }
TRecordsMap = class(TObject)
private
FList: TList;
FByIndexIdx: Integer;
function GetCount: Integer;
function GetItem(Index: Integer): Integer;
procedure SetItem(Index, Value: Integer);
public
constructor Create;
destructor Destroy; override;
procedure Add(Value: Integer);
procedure Delete(Index: Integer);
procedure Clear;
procedure DoAnd(Right, Result: TRecordsMap);
procedure DoOr(Right, Result: TRecordsMap);
procedure DoNot(Right, Result: TRecordsMap);
property ByIndexIdx: Integer read FByIndexIdx write FByIndexIdx;
property Count: Integer read GetCount;
property Items[Index: Integer]: Integer read GetItem write SetItem;
end;
{ TDataProcessAlgo }
TDataProcessAlgoClass = class of TDataProcessAlgo;
TDataProcessAlgo = class(TObject)
private
FOwner: TObject;
FOnEncodeProgress: TOnProgressEvent;
FOnDecodeProgress: TOnProgressEvent;
protected
procedure DoEncodeProgress(Percent: Integer);
procedure DoDecodeProgress(Percent: Integer);
public
constructor Create(AOwner: TObject); virtual;
destructor Destroy; override;
procedure EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); virtual; abstract;
procedure DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); virtual; abstract;
property OnEncodeProgress: TOnProgressEvent read FOnEncodeProgress write FOnEncodeProgress;
property OnDecodeProgress: TOnProgressEvent read FOnDecodeProgress write FOnDecodeProgress;
end;
{ TCompressAlgo }
TCompressAlgoClass = class of TCompressAlgo;
TCompressAlgo = class(TDataProcessAlgo)
protected
procedure SetLevel(Value: TCompressLevel); virtual;
function GetLevel: TCompressLevel; virtual;
public
property Level: TCompressLevel read GetLevel write SetLevel;
end;
{ TEncryptAlgo }
TEncryptAlgoClass = class of TEncryptAlgo;
TEncryptAlgo = class(TDataProcessAlgo)
protected
procedure DoProgress(Current, Maximal: Integer; Encode: Boolean);
procedure InternalCodeStream(Source, Dest: TMemoryStream; DataSize: Integer; Encode: Boolean);
procedure SetMode(Value: TEncryptMode); virtual;
function GetMode: TEncryptMode; virtual;
public
procedure InitKey(const Key: string); virtual; abstract;
procedure Done; virtual;
procedure EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override;
procedure DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override;
procedure EncodeBuffer(const Source; var Dest; DataSize: Integer); virtual; abstract;
procedure DecodeBuffer(const Source; var Dest; DataSize: Integer); virtual; abstract;
property Mode: TEncryptMode read GetMode write SetMode;
end;
{ TDataProcessMgr }
TDataProcessMgr = class(TObject)
protected
FTinyDBFile: TTinyDBFileIO;
FDPObject: TDataProcessAlgo;
public
constructor Create(AOwner: TTinyDBFileIO);
destructor Destroy; override;
class function CheckAlgoRegistered(const AlgoName: string): Integer; virtual;
procedure SetAlgoName(const Value: string); virtual; abstract;
procedure EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); virtual;
procedure DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); virtual;
end;
{ TCompressMgr }
TCompressMgr = class(TDataProcessMgr)
private
function GetLevel: TCompressLevel;
procedure SetLevel(const Value: TCompressLevel);
public
class function CheckAlgoRegistered(const AlgoName: string): Integer; override;
procedure SetAlgoName(const Value: string); override;
property Level: TCompressLevel read GetLevel write SetLevel;
end;
{ TEncryptMgr }
TEncryptMgr = class(TDataProcessMgr)
protected
function GetMode: TEncryptMode;
procedure SetMode(const Value: TEncryptMode);
public
procedure InitKey(const Key: string);
procedure Done;
class function CheckAlgoRegistered(const AlgoName: string): Integer; override;
procedure SetAlgoName(const Value: string); override;
procedure EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override;
procedure DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer); override;
procedure EncodeBuffer(const Source; var Dest; DataSize: Integer); virtual;
procedure DecodeBuffer(const Source; var Dest; DataSize: Integer); virtual;
property Mode: TEncryptMode read GetMode write SetMode;
end;
{ TFieldBufferItem }
TFieldBufferItem = class(TObject)
private
FBuffer: Pointer; // 字段数据
FFieldType: TFieldType; // 字段类型
FFieldSize: Integer; // 字段数据大小(类型为字符串时:大小为Field.DataSize; 类型为BLOB时:大小为Stream.Size)
FMemAlloc: Boolean; // 是否分配内存
FActive: Boolean; // 这个字段是否有效
function GetAsString: string;
function GetDataBuf: Pointer;
public
constructor Create;
destructor Destroy; override;
procedure AllocBuffer;
procedure FreeBuffer;
function IsBlob: Boolean;
property FieldType: TFieldType read FFieldType write FFieldType;
property FieldSize: Integer read FFieldSize write FFieldSize;
property Buffer: Pointer read FBuffer;
property DataBuf: Pointer read GetDataBuf;
property Active: Boolean read FActive write FActive;
property AsString: string read GetAsString;
end;
{ TFieldBuffers }
TFieldBuffers = class(TObject)
private
FItems: TList;
function GetCount: Integer;
function GetItem(Index: Integer): TFieldBufferItem;
public
constructor Create;
destructor Destroy; override;
procedure Add(FieldType: TFieldType; FieldSize: Integer); overload;
procedure Add(Buffer: Pointer; FieldType: TFieldType; FieldSize: Integer); overload;
procedure Delete(Index: Integer);
procedure Clear;
property Count: Integer read GetCount;
property Items[Index: Integer]: TFieldBufferItem read GetItem;
end;
{ TTinyDBFileStream }
TTinyDBFileStream = class(TFileStream)
private
FFlushed: Boolean; // 文件缓冲区内容是否写入到介质中
public
constructor Create(const FileName: string; Mode: Word); overload;
{$IFDEF COMPILER_6_UP}
constructor Create(const FileName: string; Mode: Word; Rights: Cardinal); overload;
{$ENDIF}
function Write(const Buffer; Count: Longint): Longint; override;
procedure Flush;
property Flushed: Boolean read FFlushed write FFlushed;
end;
{ TTinyDBFileIO }
TTinyDBFileIO = class(TObject)
private
FDatabase: TTinyDatabase;
FDatabaseName: string; // 文件名或内存地址名
FMediumType: TTinyDBMediumType;
FExclusive: Boolean;
FDBStream: TStream;
FFileIsReadOnly: Boolean; // 数据库文件是否为只读
FCompressMgr: TCompressMgr; // 压缩对象
FEncryptMgr: TEncryptMgr; // 加密对象
FDBOptions: TDBOptions; // 数据库选项
FTableTab: TTableTab; // 数据库中所有表
FDPCSect: TRTLCriticalSection; // 数据处理(加密压缩)临界区变量
function GetIsOpen: Boolean;
function GetFlushed: Boolean;
procedure InitDBOptions;
procedure InitTableTab;
procedure DoOperationProgressEvent(ADatabase: TTinyDatabase; Pos, Max: Integer);
protected
procedure DecodeMemoryStream(SrcStream, DstStream: TMemoryStream; Encrypt, Compress: Boolean);
procedure DecodeMemoryBuffer(SrcBuffer, DstBuffer: PChar; DataSize: Integer; Encrypt: Boolean);
procedure EncodeMemoryStream(SrcStream, DstStream: TMemoryStream; Encrypt, Compress: Boolean);
procedure EncodeMemoryBuffer(SrcBuffer, DstBuffer: PChar; DataSize: Integer; Encrypt: Boolean);
procedure OnCompressProgressEvent(Sender: TObject; Percent: Integer);
procedure OnUncompressProgressEvent(Sender: TObject; Percent: Integer);
procedure OnEncryptProgressEvent(Sender: TObject; Percent: Integer);
procedure OnDecryptProgressEvent(Sender: TObject; Percent: Integer);
function CheckDupTableName(const TableName: string): Boolean;
function CheckDupIndexName(var TableHeader: TTableHeader; const IndexName: string): Boolean;
function CheckDupPrimaryIndex(var TableHeader: TTableHeader; IndexOptions: TTDIndexOptions): Boolean;
procedure CheckValidFields(Fields: array of TFieldItem);
procedure CheckValidIndexFields(FieldNames: array of string; IndexOptions: TTDIndexOptions; var TableHeader: TTableHeader);
function GetFieldIdxByName(const TableHeader: TTableHeader; const FieldName: string): Integer;
function GetIndexIdxByName(const TableHeader: TTableHeader; const IndexName: string): Integer;
function GetTableIdxByName(const TableName: string): Integer;
function GetTempFileName: string;
function ReCreate(NewCompressBlob: Boolean; NewCompressLevel: TCompressLevel; const NewCompressAlgoName: string;
NewEncrypt: Boolean; const NewEncAlgoName, OldPassword, NewPassword: string; NewCRC32: Boolean): Boolean;
public
constructor Create(AOwner: TTinyDatabase);
destructor Destroy; override;
procedure Open(const ADatabaseName: string; AMediumType: TTinyDBMediumType; AExclusive: Boolean);
procedure Close;
procedure Flush;
function SetPassword(const Value: string): Boolean;
procedure Lock;
procedure Unlock;
procedure ReadBuffer(var Buffer; Position, Count: Longint);
procedure ReadDBVersion(var Dest: string);
procedure ReadExtDataBlock(var Dest: TExtDataBlock);
procedure WriteExtDataBlock(var Dest: TExtDataBlock);
procedure ReadDBOptions(var Dest: TDBOptions);
procedure WriteDBOptions(var Dest: TDBOptions);
procedure ReadTableTab(var Dest: TTableTab);
procedure WriteTableTab(var Dest: TTableTab);
procedure ReadTableHeader(TableIdx: Integer; var Dest: TTableHeader);
procedure WriteTableHeader(TableIdx: Integer; var Dest: TTableHeader);
class function CheckValidTinyDB(ADBStream: TStream): Boolean; overload;
class function CheckValidTinyDB(const FileName: string): Boolean; overload;
class function CheckTinyDBVersion(ADBStream: TStream): Boolean; overload;
class function CheckTinyDBVersion(const FileName: string): Boolean; overload;
procedure GetTableNames(List: TStrings);
procedure GetFieldNames(const TableName: string; List: TStrings);
procedure GetIndexNames(const TableName: string; List: TStrings);
procedure ReadFieldData(DstStream: TMemoryStream; RecTabItemOffset, DiskFieldOffset, FieldSize: Integer;
IsBlob: Boolean; ShouldEncrypt, ShouldCompress: Boolean); overload;
procedure ReadFieldData(DstStream: TMemoryStream; FieldDataOffset, FieldSize: Integer;
IsBlob: Boolean; ShouldEncrypt, ShouldCompress: Boolean); overload;
procedure ReadAllRecordTabItems(const TableHeader: TTableHeader;
var Items: TRecordTabItems; var BlockOffsets: TIntegerAry);
procedure ReadAllIndexTabItems(const TableHeader: TTableHeader; IndexIdx: Integer;
var Items: TIndexTabItems; var BlockOffsets: TIntegerAry);
procedure WriteDeleteFlag(RecTabItemOffset: Integer);
function CreateDatabase(const DBFileName: string;
CompressBlob: Boolean; CompressLevel: TCompressLevel; const CompressAlgoName: string;
Encrypt: Boolean; const EncryptAlgoName, Password: string; CRC32: Boolean = False): Boolean; overload;
function CreateTable(const TableName: string; Fields: array of TFieldItem): Boolean;
function DeleteTable(const TableName: string): Boolean;
function CreateIndex(const TableName, IndexName: string; IndexOptions: TTDIndexOptions; FieldNames: array of string): Boolean;
function DeleteIndex(const TableName, IndexName: string): Boolean;
function RenameTable(const OldTableName, NewTableName: string): Boolean;
function RenameField(const TableName, OldFieldName, NewFieldName: string): Boolean;
function RenameIndex(const TableName, OldIndexName, NewIndexName: string): Boolean;
function Compact(const Password: string): Boolean;
function Repair(const Password: string): Boolean;
function ChangePassword(const OldPassword, NewPassword: string; Check: Boolean = True): Boolean;
function ChangeEncrypt(NewEncrypt: Boolean; const NewEncAlgo, OldPassword, NewPassword: string): Boolean;
function SetComments(const Value: string; const Password: string): Boolean;
function GetComments(var Value: string; const Password: string): Boolean;
function SetExtData(Buffer: PChar; Size: Integer): Boolean;
function GetExtData(Buffer: PChar): Boolean;
property DBStream: TStream read FDBStream;
property DBOptions: TDBOptions read FDBOptions;
property TableTab: TTableTab read FTableTab;
property IsOpen: Boolean read GetIsOpen;
property FileIsReadOnly: Boolean read FFileIsReadOnly;
property Flushed: Boolean read GetFlushed;
end;
{ TTinyTableIO }
TOnAdjustIndexForAppendEvent = procedure(IndexIdx, InsertPos: Integer; MemRecTabItem: TMemRecTabItem) of object;
TOnAdjustIndexForModifyEvent = procedure(IndexIdx, FromRecIdx, ToRecIdx: Integer) of object;
TTinyTableIO = class(TObject)
private
FDatabase: TTinyDatabase;
FRefCount: Integer; // 引用计数,初始为0
FTableName: string; // 此表的表名
FTableIdx: Integer; // 此表的表号 (0-based)
FFieldDefs: TTinyFieldDefs; // 字段定义(内部使用,不允许用户修改)
FIndexDefs: TTinyIndexDefs; // 索引定义(内部使用,不允许用户修改)
FDiskRecSize: Integer; // 数据库中记录数据的长度
FDiskFieldOffsets: TIntegerAry; // 数据库中各字段在数据行中的偏移
FAutoIncFieldIdx: Integer; // 自动增长字段的物理字段号(0-based),无则为-1
FTableHeader: TTableHeader; // 表头信息
FInitRecordTab: TRecordTabItems; // 初始化时要用到的RecordTab
FRecTabBlockOffsets: TIntegerAry; // 每个记录表块的偏移
FIdxTabBlockOffsets: array of TIntegerAry; // 所有索引表块的偏移
FRecTabLists: array of TList; // 所有记录集(FRecTabLists[0]为物理顺序记录集,[1]为第0个索引的记录集... )
procedure SetActive(Value: Boolean);
procedure SetTableName(const Value: string);
function GetActive: Boolean;
function GetRecTabList(Index: Integer): TList;
function GetTableIdxByName(const TableName: string): Integer;
procedure InitFieldDefs;
procedure InitIndexDefs;
procedure InitRecTabList(ListIdx: Integer; ReadRecTabItems: Boolean = True);
procedure InitAllRecTabLists;
procedure InitDiskRecInfo;
procedure InitAutoInc;
procedure ClearMemRecTab(AList: TList);
procedure AddMemRecTabItem(AList: TList; Value: TMemRecTabItem);
procedure InsertMemRecTabItem(AList: TList; Index: Integer; Value: TMemRecTabItem);
procedure DeleteMemRecTabItem(AList: TList; Index: Integer);
function GetMemRecTabItem(AList: TList; Index: Integer): TMemRecTabItem;
function ShouldEncrypt(FieldIdx: Integer): Boolean;
function ShouldCompress(FieldIdx: Integer): Boolean;
function GetRecTabItemOffset(ItemIdx: Integer): Integer;
function GetIdxTabItemOffset(IndexIdx: Integer; ItemIdx: Integer): Integer;
procedure AdjustIndexesForAppend(FieldBuffers: TFieldBuffers; RecDataOffset, RecTotal: Integer; OnAdjustIndex: TOnAdjustIndexForAppendEvent);
procedure AdjustIndexesForModify(FieldBuffers: TFieldBuffers; EditPhyRecordIdx: Integer; OnAdjustIndex: TOnAdjustIndexForModifyEvent);
procedure AdjustIndexesForDelete(DeletePhyRecordIdx: Integer);
procedure WriteDeleteFlag(PhyRecordIdx: Integer);
procedure AdjustStrFldInBuffer(FieldBuffers: TFieldBuffers);
procedure ClearAllRecTabLists;
protected
procedure Initialize;
procedure Finalize;
public
constructor Create(AOwner: TTinyDatabase);
destructor Destroy; override;
procedure Open;
procedure Close;
procedure Refresh;
procedure AppendRecordData(FieldBuffers: TFieldBuffers; Flush: Boolean;
OnAdjustIndex: TOnAdjustIndexForAppendEvent);
procedure ModifyRecordData(FieldBuffers: TFieldBuffers;
PhyRecordIdx: Integer; Flush: Boolean;
OnAdjustIndex: TOnAdjustIndexForModifyEvent);
procedure DeleteRecordData(PhyRecordIdx: Integer; Flush: Boolean);
procedure DeleteAllRecords;
procedure ReadFieldData(DstStream: TMemoryStream; DiskRecIndex, FieldIdx: Integer);
procedure ReadRecordData(FieldBuffers: TFieldBuffers; RecTabList: TList; RecordIdx: Integer);
function CompFieldData(FieldBuffer1, FieldBuffer2: Pointer; FieldType: TFieldType;
CaseInsensitive, PartialCompare: Boolean): Integer;
function SearchIndexedField(FieldBuffers: TFieldBuffers; RecTabList: TList; IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0; PartialCompare: Boolean = False): Integer;
function SearchIndexedFieldBound(FieldBuffers: TFieldBuffers; RecTabList: TList; IndexIdx: Integer; LowBound: Boolean; var ResultState: Integer; EffFieldCount: Integer = 0; PartialCompare: Boolean = False): Integer;
function SearchRangeStart(FieldBuffers: TFieldBuffers; RecTabList: TList; IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0): Integer;
function SearchRangeEnd(FieldBuffers: TFieldBuffers; RecTabList: TList; IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0): Integer;
function SearchInsertPos(FieldBuffers: TFieldBuffers; IndexIdx: Integer; var ResultState: Integer): Integer;
function CheckPrimaryFieldExists: Integer;
function CheckUniqueFieldForAppend(FieldBuffers: TFieldBuffers): Boolean;
function CheckUniqueFieldForModify(FieldBuffers: TFieldBuffers; PhyRecordIdx: Integer): Boolean;
procedure ConvertRecordIdx(SrcIndexIdx, SrcRecordIdx, DstIndexIdx: Integer; var DstRecordIdx: Integer); overload;
procedure ConvertRecordIdx(SrcRecTabList: TList; SrcRecordIdx: Integer; DstRecTabList: TList; var DstRecordIdx: Integer); overload;
procedure ConvertRecIdxForPhy(SrcIndexIdx, SrcRecordIdx: Integer; var DstRecordIdx: Integer); overload;
procedure ConvertRecIdxForPhy(SrcRecTabList: TList; SrcRecordIdx: Integer; var DstRecordIdx: Integer); overload;
procedure ConvertRecIdxForCur(SrcIndexIdx, SrcRecordIdx: Integer; RecTabList: TList; var DstRecordIdx: Integer);
property Active: Boolean read GetActive write SetActive;
property TableName: string read FTableName write SetTableName;
property TableIdx: Integer read FTableIdx;
property FieldDefs: TTinyFieldDefs read FFieldDefs;
property IndexDefs: TTinyIndexDefs read FIndexDefs;
property RecTabLists[Index: Integer]: TList read GetRecTabList;
end;
{ TTDBDataSet }
TTDBDataSet = class(TDataSet)
private
FDatabaseName: string;
FDatabase: TTinyDatabase;
FSessionName: string;
procedure CheckDBSessionName;
function GetDBSession: TTinySession;
procedure SetSessionName(const Value: string);
protected
procedure SetDatabaseName(const Value: string); virtual;
procedure Disconnect; virtual;
procedure OpenCursor(InfoQuery: Boolean); override;
procedure CloseCursor; override;
public
constructor Create(AOwner: TComponent); override;
procedure CloseDatabase(Database: TTinyDatabase);
function OpenDatabase(IncRef: Boolean): TTinyDatabase;
property Database: TTinyDatabase read FDatabase;
property DBSession: TTinySession read GetDBSession;
published
property DatabaseName: string read FDatabaseName write SetDatabaseName;
property SessionName: string read FSessionName write SetSessionName;
end;
{ TTDEDataSet }
TTDEDataSet = class(TTDBDataSet)
private
FAboutBox: TTinyAboutBox;
FMediumType: TTinyDBMediumType; // 数据库存储介质类型
FFilterParser: TExprParserBase; // Filter句法分析器
FCurRec: Integer; // 当前记录号 (0-based)
FRecordSize: Integer; // 内存中记录数据的长度
FRecBufSize: Integer; // FRecordSize + SizeOf(TRecInfo);
FFieldOffsets: TIntegerAry; // 每个字段数据在ActiveBuffer中的偏移,不包括计算字段和查找字段。数组下标意义为FieldNo-1.
FKeyBuffers: array[TTDKeyIndex] of PChar; // 存放Key数据,比如SetKey或SetRangeStart后
FKeyBuffer: PChar; // 指向FKeyBuffers中的某个元素
FFilterBuffer: PChar; // Filter用的Record Buffer
FFilterMapsToIndex: Boolean; // Filter是否可以根据Index优化
FCanModify: Boolean; // 是否允许修改数据库
procedure SetMediumType(Value: TTinyDBMediumType);
procedure SetPassword(const Value: string);
procedure SetCRC32(Value: Boolean);
function GetCRC32: Boolean;
function GetCanAccess: Boolean;
procedure InitRecordSize;
procedure InitFieldOffsets;
function FiltersAccept: Boolean;
procedure SetFilterData(const Text: string; Options: TFilterOptions);
procedure AllocKeyBuffers;
procedure FreeKeyBuffers;
procedure InitKeyBuffer(KeyIndex: TTDKeyIndex);
protected
{ Overriden abstract methods (required) }
function AllocRecordBuffer: PChar; override;
procedure FreeRecordBuffer(var Buffer: PChar); override;
procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override;
function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override;
function GetRecordSize: Word; override;
procedure InternalInitRecord(Buffer: PChar); override;
procedure InternalFirst; override;
procedure InternalLast; override;
procedure InternalHandleException; override;
procedure InternalSetToRecord(Buffer: PChar); override;
procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override;
procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override;
procedure SetFieldData(Field: TField; Buffer: Pointer); override;
function IsCursorOpen: Boolean; override;
procedure DataConvert(Field: TField; Source, Dest: Pointer; ToNative: Boolean); override;
{ Additional overrides (optional) }
function GetRecordCount: Integer; override;
function GetRecNo: Integer; override;
procedure SetRecNo(Value: Integer); override;
function GetCanModify: Boolean; override;
procedure SetFiltered(Value: Boolean); override;
procedure SetFilterOptions(Value: TFilterOptions); override;
procedure SetFilterText(const Value: string); override;
procedure DoAfterOpen; override;
function FindRecord(Restart, GoForward: Boolean): Boolean; override;
{ Virtual functions }
function GetActiveRecBuf(var RecBuf: PChar): Boolean; virtual;
procedure ActivateFilters; virtual;
procedure DeactivateFilters; virtual;
procedure ReadRecordData(Buffer: PChar; RecordIdx: Integer); virtual;
protected
function GetFieldOffsetByFieldNo(FieldNo: Integer): Integer;
procedure ReadFieldData(DstStream: TMemoryStream; FieldDataOffset, FieldSize: Integer;
IsBlob: Boolean; ShouldEncrypt, ShouldCompress: Boolean);
public
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Password: string write SetPassword;
property CanAccess: Boolean read GetCanAccess;
property CRC32: Boolean read GetCRC32 write SetCRC32;
published
property About: TTinyAboutBox read FAboutBox write FAboutBox;
property MediumType: TTinyDBMediumType read FMediumType write SetMediumType default mtDisk;
property Active;
property AutoCalcFields;
property Filter;
property Filtered;
property FilterOptions;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property OnFilterRecord;
end;
{ TTinyTable }
TTinyTable = class(TTDEDataSet)
private
FTableName: string; // 此表的表名
FIndexDefs: TIndexDefs; // 可让用户修改的IndexDefs
FIndexName: string; // 当前激活的索引的名称
FIndexIdx: Integer; // 当前激活的索引号,即在FIndexDefs中的下标
FRecTabList: TList; // 当前正使用的记录集 (TMemRecTabItem)
FUpdateCount: Integer; // BeginUpdate调用计数
FSetRanged: Boolean; // 是否SetRange
FEffFieldCount: Integer; // 对复合索引进行查找等操作时,指定有效字段的个数,缺省为0时表示按复合索引实际字段数计
FReadOnly: Boolean; // 此表是否ReadOnly
FMasterLink: TMasterDataLink; // 处理Master-detail
FTableIO: TTinyTableIO; // 指向TinyDatabase中的某个TableIO
FOnFilterProgress: TOnProgressEvent;
procedure SetTableName(const Value: string);
procedure SetIndexName(const Value: string);
procedure SetReadOnly(Value: Boolean);
procedure SetMasterFields(const Value: string);
procedure SetDataSource(Value: TDataSource);
function GetTableIdx: Integer;
function GetMasterFields: string;
procedure InitIndexDefs;
procedure InitCurRecordTab;
procedure ClearMemRecTab(AList: TList);
procedure AddMemRecTabItem(AList: TList; Value: TMemRecTabItem);
procedure InsertMemRecTabItem(AList: TList; Index: Integer; Value: TMemRecTabItem);
procedure DeleteMemRecTabItem(AList: TList; Index: Integer);
function GetMemRecTabItem(AList: TList; Index: Integer): TMemRecTabItem;
procedure SwitchToIndex(IndexIdx: Integer);
procedure AppendRecordData(Buffer: PChar);
procedure ModifyRecordData(Buffer: PChar; RecordIdx: Integer);
procedure DeleteRecordData(RecordIdx: Integer);
procedure DeleteAllRecords;
procedure OnAdjustIndexForAppend(IndexIdx, InsertPos: Integer; MemRecTabItem: TMemRecTabItem);
procedure OnAdjustIndexForModify(IndexIdx, FromRecIdx, ToRecIdx: Integer);
function SearchIndexedField(RecTabList: TList; IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0; PartialCompare: Boolean = False): Integer;
function SearchIndexedFieldBound(RecTabList: TList; IndexIdx: Integer; LowBound: Boolean; var ResultState: Integer; EffFieldCount: Integer = 0; PartialCompare: Boolean = False): Integer;
function SearchRangeStart(RecTabList: TList; IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0): Integer;
function SearchRangeEnd(RecTabList: TList; IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0): Integer;
function SearchKey(RecTabList: TList; IndexIdx: Integer; EffFieldCount: Integer = 0; Nearest: Boolean = False): Boolean;
function SearchInsertPos(IndexIdx: Integer; var ResultState: Integer): Integer;
procedure SetKeyFields(KeyIndex: TTDKeyIndex; const Values: array of const); overload;
procedure SetKeyFields(IndexIdx: Integer; KeyIndex: TTDKeyIndex; const Values: array of const); overload;
procedure SetKeyBuffer(KeyIndex: TTDKeyIndex; Clear: Boolean);
function LocateRecord(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions; SyncCursor: Boolean): Boolean;
function MapsToIndexForSearch(Fields: TList; CaseInsensitive: Boolean): Integer;
function CheckFilterMapsToIndex: Boolean;
procedure MasterChanged(Sender: TObject);
procedure MasterDisabled(Sender: TObject);
procedure SetLinkRange(MasterFields: TList);
procedure CheckMasterRange;
procedure RecordBufferToFieldBuffers(RecordBuffer: PChar; FieldBuffers: TFieldBuffers);
function FieldDefsStored: Boolean;
function IndexDefsStored: Boolean;
protected
{ Overriden abstract methods (required) }
function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override;
procedure InternalOpen; override;
procedure InternalClose; override;
procedure InternalInitFieldDefs; override;
procedure InternalDelete; override;
procedure InternalPost; override;
procedure InternalRefresh; override;
procedure InternalGotoBookmark(Bookmark: Pointer); override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override;
function IsCursorOpen: Boolean; override;
{ Other overrides }
function GetRecordCount: Integer; override;
function GetCanModify: Boolean; override;
function GetDataSource: TDataSource; override;
procedure SetDatabaseName(const Value: string); override;
procedure DoAfterOpen; override;
procedure ActivateFilters; override;
procedure DeactivateFilters; override;
procedure ReadRecordData(Buffer: PChar; RecordIdx: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
procedure Post; override;
function BookmarkValid(Bookmark: TBookmark): Boolean; override;
procedure SetKey;
procedure EditKey;
function GotoKey: Boolean; overload;
function GotoKey(const IndexName: string): Boolean; overload;
procedure GotoNearest; overload;
procedure GotoNearest(const IndexName: string); overload;
function FindKey(const KeyValues: array of const): Boolean; overload;
function FindKey(const IndexName: string; const KeyValues: array of const): Boolean; overload;
procedure FindNearest(const KeyValues: array of const); overload;
procedure FindNearest(const IndexName: string; const KeyValues: array of const); overload;
procedure SetRangeStart;
procedure SetRangeEnd;
procedure EditRangeStart;
procedure EditRangeEnd;
procedure ApplyRange; overload;
procedure ApplyRange(const IndexName: string); overload;
procedure SetRange(const StartValues, EndValues: array of const); overload;
procedure SetRange(const IndexName: string; const StartValues, EndValues: array of const); overload;
procedure CancelRange;
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean; override;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant; override;
procedure EmptyTable;
procedure CreateTable;
property TableIO: TTinyTableIO read FTableIO;
property TableIdx: Integer read GetTableIdx;
property IndexIdx: Integer read FIndexIdx;
published
property TableName: string read FTableName write SetTableName;
property IndexName: string read FIndexName write SetIndexName;
property ReadOnly: Boolean read FReadOnly write SetReadOnly default False;
property MasterFields: string read GetMasterFields write SetMasterFields;
property MasterSource: TDataSource read GetDataSource write SetDataSource;
property IndexDefs: TIndexDefs read FIndexDefs write FIndexDefs stored IndexDefsStored;
property FieldDefs stored FieldDefsStored;
property OnFilterProgress: TOnProgressEvent read FOnFilterProgress write FOnFilterProgress;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
end;
{ TTinyQuery }
TTinyQuery = class(TTDEDataSet)
private
FSQL: TStrings;
FSQLParser: TSQLParser;
procedure SetQuery(Value: TStrings);
function GetRowsAffected: Integer;
protected
procedure InternalOpen; override;
procedure InternalClose; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ExecSQL;
property RowsAffected: Integer read GetRowsAffected;
published
property SQL: TStrings read FSQL write SetQuery;
end;
{ TTinyDatabase }
TTinyDatabase = class(TComponent)
private
FAboutBox: TTinyAboutBox;
FDBFileIO: TTinyDBFileIO;
FDataSets: TList;
FKeepConnection: Boolean;
FTemporary: Boolean;
FHandleShared: Boolean;
FExclusive: Boolean;
FRefCount: Integer;
FStreamedConnected: Boolean;
FSession: TTinySession;
FSessionName: string;
FDatabaseName: string;
FFileName: string;
FMediumType: TTinyDBMediumType; // 数据库存储介质类型
FCanAccess: Boolean; // 是否允许访问数据库
FPassword: string; // 数据库密码(原文)
FPasswordModified: Boolean; // 密码是否被用户修改
FTableDefs: TTinyTableDefs; // 表定义(内部不使用)
FTableIOs: TList;
FFlushCacheAlways: Boolean;
FAutoFlush: Boolean;
FAutoFlushInterval: Integer;
FAutoFlushTimer: TTimer;
FBeforeConnect: TNotifyEvent;
FBeforeDisconnect: TNotifyEvent;
FAfterConnect: TNotifyEvent;
FAfterDisconnect: TNotifyEvent;
FOnCompressProgress: TOnProgressEvent;
FOnUncompressProgress: TOnProgressEvent;
FOnEncryptProgress: TOnProgressEvent;
FOnDecryptProgress: TOnProgressEvent;
FOnOperationProgress: TOnProgressEvent;
function GetConnected: Boolean;
function GetEncrypted: Boolean;
function GetEncryptAlgoName: string;
function GetCompressed: Boolean;
function GetCompressLevel: TCompressLevel;
function GetCompressAlgoName: string;
function GetCRC32: Boolean;
function GetTableIOs(Index: Integer): TTinyTableIO;
function GetFileSize: Integer;
function GetFileDate: TDateTime;
function GetFileIsReadOnly: Boolean;
procedure SetDatabaseName(const Value: string);
procedure SetFileName(const Value: string);
procedure SetMediumType(const Value: TTinyDBMediumType);
procedure SetExclusive(const Value: Boolean);
procedure SetKeepConnection(const Value: Boolean);
procedure SetSessionName(const Value: string);
procedure SetConnected(const Value: Boolean);
procedure SetPassword(Value: string);
procedure SetCRC32(Value: Boolean);
procedure SetAutoFlush(Value: Boolean);
procedure SetAutoFlushInterval(Value: Integer);
function CreateLoginDialog(const ADatabaseName: string): TForm;
function ShowLoginDialog(const ADatabaseName: string; var APassword: string): Boolean;
function TableIOByName(const Name: string): TTinyTableIO;
function GetDBFileName: string;
procedure CheckSessionName(Required: Boolean);
procedure CheckInactive;
procedure CheckDatabaseName;
procedure InitTableIOs;
procedure FreeTableIOs;
procedure AddTableIO(const TableName: string);
procedure DeleteTableIO(const TableName: string);
procedure RenameTableIO(const OldTableName, NewTableName: string);
procedure RefreshAllTableIOs;
procedure RefreshAllDataSets;
procedure InitTableDefs;
procedure AutoFlushTimer(Sender: TObject);
protected
procedure DoConnect; virtual;
procedure DoDisconnect; virtual;
procedure CheckCanAccess; virtual;
function GetDataSet(Index: Integer): TTDEDataSet; virtual;
function GetDataSetCount: Integer; virtual;
procedure RegisterClient(Client: TObject; Event: TConnectChangeEvent = nil); virtual;
procedure UnRegisterClient(Client: TObject); virtual;
procedure SendConnectEvent(Connecting: Boolean);
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property StreamedConnected: Boolean read FStreamedConnected write FStreamedConnected;
property HandleShared: Boolean read FHandleShared;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Open;
procedure Close;
procedure CloseDataSets;
procedure FlushCache;
//procedure ApplyUpdates(const DataSets: array of TDBDataSet);
//procedure StartTransaction;
//procedure Commit;
//procedure Rollback;
procedure ValidateName(const Name: string);
procedure GetTableNames(List: TStrings);
procedure GetFieldNames(const TableName: string; List: TStrings);
procedure GetIndexNames(const TableName: string; List: TStrings);
function TableExists(const TableName: string): Boolean;
class function GetCompressAlgoNames(List: TStrings): Integer;
class function GetEncryptAlgoNames(List: TStrings): Integer;
class function IsTinyDBFile(const FileName: string): Boolean;
function CreateDatabase(const DBFileName: string): Boolean; overload;
function CreateDatabase(const DBFileName: string;
CompressBlob: Boolean; CompressLevel: TCompressLevel; const CompressAlgoName: string;
Encrypt: Boolean; const EncryptAlgoName, Password: string; CRC32: Boolean = False): Boolean; overload;
function CreateTable(const TableName: string; Fields: array of TFieldItem): Boolean;
function DeleteTable(const TableName: string): Boolean;
function CreateIndex(const TableName, IndexName: string; IndexOptions: TTDIndexOptions; FieldNames: array of string): Boolean;
function DeleteIndex(const TableName, IndexName: string): Boolean;
function RenameTable(const OldTableName, NewTableName: string): Boolean;
function RenameField(const TableName, OldFieldName, NewFieldName: string): Boolean;
function RenameIndex(const TableName, OldIndexName, NewIndexName: string): Boolean;
function Compact: Boolean;
function Repair: Boolean;
function ChangePassword(const NewPassword: string; Check: Boolean = True): Boolean;
function ChangeEncrypt(NewEncrypt: Boolean; const NewEncAlgo, NewPassword: string): Boolean;
function SetComments(const Value: string): Boolean;
function GetComments(var Value: string): Boolean;
function SetExtData(Buffer: PChar; Size: Integer): Boolean;
function GetExtData(Buffer: PChar): Boolean;
property DBFileIO: TTinyDBFileIO read FDBFileIO;
property TableIOs[Index: Integer]: TTinyTableIO read GetTableIOs;
property DataSets[Index: Integer]: TTDEDataSet read GetDataSet;
property DataSetCount: Integer read GetDataSetCount;
property Session: TTinySession read FSession;
property TableDefs: TTinyTableDefs read FTableDefs;
property Temporary: Boolean read FTemporary write FTemporary;
property Password: string read FPassword write SetPassword;
property CanAccess: Boolean read FCanAccess;
property Encrypted: Boolean read GetEncrypted;
property EncryptAlgoName: string read GetEncryptAlgoName;
property Compressed: Boolean read GetCompressed;
property CompressLevel: TCompressLevel read GetCompressLevel;
property CompressAlgoName: string read GetCompressAlgoName;
property CRC32: Boolean read GetCRC32 write SetCRC32;
property FlushCacheAlways: Boolean read FFlushCacheAlways write FFlushCacheAlways;
property FileSize: Integer read GetFileSize;
property FileDate: TDateTime read GetFileDate;
property FileIsReadOnly: Boolean read GetFileIsReadOnly;
published
property About: TTinyAboutBox read FAboutBox write FAboutBox;
property FileName: string read FFileName write SetFileName;
property DatabaseName: string read FDatabaseName write SetDatabaseName;
property MediumType: TTinyDBMediumType read FMediumType write SetMediumType default mtDisk;
property Connected: Boolean read GetConnected write SetConnected default False;
property Exclusive: Boolean read FExclusive write SetExclusive default False;
property KeepConnection: Boolean read FKeepConnection write SetKeepConnection default False;
property SessionName: string read FSessionName write SetSessionName;
property AutoFlush: Boolean read FAutoFlush write SetAutoFlush default False;
property AutoFlushInterval: Integer read FAutoFlushInterval write SetAutoFlushInterval default tdbDefAutoFlushInterval;
property BeforeConnect: TNotifyEvent read FBeforeConnect write FBeforeConnect;
property BeforeDisconnect: TNotifyEvent read FBeforeDisconnect write FBeforeDisconnect;
property AfterConnect: TNotifyEvent read FAfterConnect write FAfterConnect;
property AfterDisconnect: TNotifyEvent read FAfterDisconnect write FAfterDisconnect;
property OnCompressProgress: TOnProgressEvent read FOnCompressProgress write FOnCompressProgress;
property OnUncompressProgress: TOnProgressEvent read FOnUncompressProgress write FOnUnCompressProgress;
property OnEncryptProgress: TOnProgressEvent read FOnEncryptProgress write FOnEncryptProgress;
property OnDecryptProgress: TOnProgressEvent read FOnDecryptProgress write FOnDecryptProgress;
property OnOperationProgress: TOnProgressEvent read FOnOperationProgress write FOnOperationProgress;
end;
{ TTinySession }
TTinyDatabaseEvent = (dbOpen, dbClose, dbAdd, dbRemove, dbAddAlias, dbDeleteAlias,
dbAddDriver, dbDeleteDriver);
TTinyDatabaseNotifyEvent = procedure(DBEvent: TTinyDatabaseEvent; const Param) of object;
TTinySession = class(TComponent)
private
FAboutBox: TTinyAboutBox;
FActive: Boolean;
FDatabases: TList;
FKeepConnections: Boolean;
FDefault: Boolean;
FSessionName: string;
FSessionNumber: Integer;
FAutoSessionName: Boolean;
FSQLHourGlass: Boolean;
FLockCount: Integer;
FStreamedActive: Boolean;
FUpdatingAutoSessionName: Boolean;
FLockRetryCount: Integer; // 等待锁定资源的重试次数
FLockWaitTime: Integer; // 两次重试之间的时间间隔(毫秒)
FPasswords: TStrings;
FOnStartup: TNotifyEvent;
FOnDBNotify: TTinyDatabaseNotifyEvent;
procedure CheckInactive;
function GetActive: Boolean;
function GetDatabase(Index: Integer): TTinyDatabase;
function GetDatabaseCount: Integer;
procedure SetActive(Value: Boolean);
procedure SetAutoSessionName(Value: Boolean);
procedure SetSessionName(const Value: string);
procedure SetSessionNames;
procedure SetLockRetryCount(Value: Integer);
procedure SetLockWaitTime(Value: Integer);
function SessionNameStored: Boolean;
procedure ValidateAutoSession(AOwner: TComponent; AllSessions: Boolean);
function DoFindDatabase(const DatabaseName: string; AOwner: TComponent): TTinyDatabase;
function DoOpenDatabase(const DatabaseName: string; AOwner: TComponent;
ADataSet: TTDBDataSet; IncRef: Boolean): TTinyDatabase;
procedure AddDatabase(Value: TTinyDatabase);
procedure RemoveDatabase(Value: TTinyDatabase);
procedure DBNotification(DBEvent: TTinyDatabaseEvent; const Param);
procedure LockSession;
procedure UnlockSession;
procedure StartSession(Value: Boolean);
procedure UpdateAutoSessionName;
function GetPasswordIndex(const Password: string): Integer;
protected
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetName(const NewName: TComponentName); override;
property OnDBNotify: TTinyDatabaseNotifyEvent read FOnDBNotify write FOnDBNotify;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Open;
procedure Close;
function OpenDatabase(const DatabaseName: string): TTinyDatabase;
procedure CloseDatabase(Database: TTinyDatabase);
function FindDatabase(const DatabaseName: string): TTinyDatabase;
procedure DropConnections;
procedure GetDatabaseNames(List: TStrings);
procedure GetTableNames(const DatabaseName: string; List: TStrings);
procedure GetFieldNames(const DatabaseName, TableName: string; List: TStrings);
procedure GetIndexNames(const DatabaseName, TableName: string; List: TStrings);
procedure AddPassword(const Password: string);
procedure RemovePassword(const Password: string);
procedure RemoveAllPasswords;
property DatabaseCount: Integer read GetDatabaseCount;
property Databases[Index: Integer]: TTinyDatabase read GetDatabase;
published
property About: TTinyAboutBox read FAboutBox write FAboutBox;
property Active: Boolean read GetActive write SetActive default False;
property AutoSessionName: Boolean read FAutoSessionName write SetAutoSessionName default False;
property KeepConnections: Boolean read FKeepConnections write FKeepConnections default False;
property SessionName: string read FSessionName write SetSessionName stored SessionNameStored;
property SQLHourGlass: Boolean read FSQLHourGlass write FSQLHourGlass default True;
property LockRetryCount: Integer read FLockRetryCount write SetLockRetryCount default tdbDefaultLockRetryCount;
property LockWaitTime: Integer read FLockWaitTime write SetLockWaitTime default tdbDefaultLockWaitTime;
property OnStartup: TNotifyEvent read FOnStartup write FOnStartup;
end;
{ TTinySessionList }
TTinySessionList = class(TObject)
FSessions: TThreadList;
FSessionNumbers: TBits;
procedure AddSession(ASession: TTinySession);
procedure CloseAll;
function GetCount: Integer;
function GetSession(Index: Integer): TTinySession;
function GetSessionByName(const SessionName: string): TTinySession;
public
constructor Create;
destructor Destroy; override;
function FindSession(const SessionName: string): TTinySession;
procedure GetSessionNames(List: TStrings);
function OpenSession(const SessionName: string): TTinySession;
property Count: Integer read GetCount;
property Sessions[Index: Integer]: TTinySession read GetSession; default;
property List[const SessionName: string]: TTinySession read GetSessionByName;
end;
{ TTinyAboutBox }
TTinyAboutBox = class(TObject)
end;
// Register Algorithm Routines
procedure RegisterCompressClass(AClass: TCompressAlgoClass; AlgoName: string);
procedure RegisterEncryptClass(AClass: TEncryptAlgoClass; AlgoName: string);
// Hashing & Encryption Routines
function HashMD5(const Source: string; Digest: Pointer = nil): string;
function HashSHA(const Source: string; Digest: Pointer = nil): string;
function HashSHA1(const Source: string; Digest: Pointer = nil): string;
function CheckSumCRC32(const Data; DataSize: Integer): Longword;
procedure EncryptBuffer(Buffer: PChar; DataSize: Integer;
EncAlgo: string; EncMode: TEncryptMode; Password: string);
procedure DecryptBuffer(Buffer: PChar; DataSize: Integer;
EncAlgo: string; EncMode: TEncryptMode; Password: string);
procedure EncryptBufferBlowfish(Buffer: PChar; DataSize: Integer; Password: string);
procedure DecryptBufferBlowfish(Buffer: PChar; DataSize: Integer; Password: string);
// Misc Routines
function FieldItem(FieldName: string; FieldType: TFieldType; DataSize: Integer = 0; DPMode: TFieldDataProcessMode = fdDefault): TFieldItem;
function PointerToStr(P: Pointer): string;
var
Session: TTinySession;
Sessions: TTinySessionList;
implementation
{$WRITEABLECONST ON}
uses
Compress_Zlib,
EncryptBase, Enc_Blowfish, Enc_Twofish, Enc_Gost,
HashBase, Hash_MD, Hash_SHA, Hash_CheckSum;
const
TinyDBFieldTypes = [ftAutoInc, ftString, ftFixedChar,
ftSmallint, ftInteger, ftWord, ftLargeint, ftBoolean, ftFloat, ftCurrency,
ftDate, ftTime, ftDateTime, ftBlob, ftMemo, ftFmtMemo, ftGraphic];
StringFieldTypes = [ftString, ftFixedChar, ftWideString, ftGuid];
BlobFieldTypes = [ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle,
ftTypedBinary, ftOraBlob, ftOraClob];
const
// 保存已注册的压缩类
FCompressClassList: TStringList = nil;
// 保存已注册的加密类
FEncryptClassList: TStringList = nil;
// TinyDB的缺省Hash算法类
FTinyDBDefaultHashClass: THashClass = THash_SHA;
// Hash之后保存在数据库中的用来做密码验证的Hash算法类
FTinyDBCheckPwdHashClass: THashClass = THash_SHA;
// TinyDB的缺省加密算法
FTinyDBDefaultEncAlgo = 'Blowfish';
// TinyDB的缺省加密模式
FTinyDBDefaultEncMode = emCTS;
var
FSessionCSect: TRTLCriticalSection;
type
{ TTinyDBLoginForm }
TTinyDBLoginForm = class(TForm)
public
constructor CreateNew(AOwner: TComponent); reintroduce;
end;
{ Misc proc }
{$WRITEABLECONST ON}
procedure ShowNagScreen(AComponent: TComponent);
const
FirstShow: Boolean = True;
begin
{$IFDEF TDB_SHOW_NAGSCREEN}
if not (csDesigning in AComponent.ComponentState) then
begin
if FirstShow then
begin
MessageBox(0, PChar(
'You use UNREGISTERED version of TinyDB.' + #13 +
'Please register at ' + tdbWebsite + #13 +
'(Registered users will get full source code of TinyDB!)' + #13 +
#13 +
'Thanks!'),
'TinyDB Engine',
MB_OK + MB_ICONINFORMATION);
FirstShow := False;
end;
end;
{$ENDIF}
end;
{$WRITEABLECONST OFF}
procedure RegisterCompressClass(AClass: TCompressAlgoClass; AlgoName: string);
var
I: Integer;
begin
if FCompressClassList = nil then
FCompressClassList := TStringList.Create;
I := FCompressClassList.IndexOfObject(Pointer(AClass));
if I < 0 then FCompressClassList.AddObject(AlgoName, Pointer(AClass))
else FCompressClassList[I] := AlgoName;
end;
procedure RegisterEncryptClass(AClass: TEncryptAlgoClass; AlgoName: string);
var
I: Integer;
begin
if FEncryptClassList = nil then
FEncryptClassList := TStringList.Create;
I := FEncryptClassList.IndexOfObject(Pointer(AClass));
if I < 0 then FEncryptClassList.AddObject(AlgoName, Pointer(AClass))
else FEncryptClassList[I] := AlgoName;
end;
function DefaultSession: TTinySession;
begin
Result := TinyDB.Session;
end;
function FieldItem(FieldName: string; FieldType: TFieldType; DataSize: Integer = 0; DPMode: TFieldDataProcessMode = fdDefault): TFieldItem;
begin
Result.FieldName := FieldName;
Result.FieldType := FieldType;
Result.DataSize := DataSize;
Result.DPMode := DPMode;
end;
function GetFieldSize(FieldType: TFieldType; StringLength: Integer = 0): Integer;
begin
if not (FieldType in TinyDBFieldTypes) then
DatabaseError(SGeneralError);
Result := 0;
if FieldType in StringFieldTypes then
Result := StringLength + 1
else if FieldType in BlobFieldTypes then
Result := 0
else
begin
case FieldType of
ftBoolean: Result := SizeOf(WordBool);
ftDateTime,
ftCurrency,
ftFloat: Result := SizeOf(Double);
ftTime,
ftDate,
ftAutoInc,
ftInteger: Result := SizeOf(Integer);
ftSmallint: Result := SizeOf(SmallInt);
ftWord: Result := SizeOf(Word);
ftLargeint: Result := SizeOf(Largeint);
else
DatabaseError(SGeneralError);
end;
end;
end;
function PointerToStr(P: Pointer): string;
var
V: Longword;
begin
V := Longword(P);
Result := ':' + IntToHex(V, 8);
end;
function StrToPointer(S: string): Pointer;
var
P: Longword;
I, J: Integer;
C: Char;
begin
Result := nil;
if S[1] <> ':' then Exit;
Delete(S, 1, 1);
S := UpperCase(S);
P := 0;
for I := 1 to Length(S) do
begin
C := S[I];
if (C >= '0') and (C <= '9') then J := Ord(C) - Ord('0')
else J := Ord(C) - Ord('A') + 10;
P := (P shl 4) + Longword(J);
end;
Result := Pointer(P);
end;
function IsPointerStr(S: string): Boolean;
function IsHexChar(C: Char): Boolean;
begin
Result := (C >= '0') and (C <= '9') or
(C >= 'A') and (C <= 'F') or
(C >= 'a') and (C <= 'f');
end;
function IsHexStr(S: string): Boolean;
var
I: Integer;
begin
for I := 1 to Length(S) do
begin
if not IsHexChar(S[I]) then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
begin
Result := False;
if S[1] <> ':' then Exit;
Delete(S, 1, 1);
if not IsHexStr(S) then Exit;
Result := True;
end;
//-----------------------------------------------------------------------------
// 计算LIKE表达式,支持通配符'%' 和 '_'
// Value: 母串
// Pattern: 子串
// CaseSensitive: 区分大小写
// 例: LikeString('abcdefg', 'abc%', True);
//-----------------------------------------------------------------------------
{
function LikeString(Value, Pattern: WideString; CaseSensitive: Boolean): Boolean;
const
MultiWildChar = '%';
SingleWildChar = '_';
function MatchPattern(ValueStart, PatternStart: Integer): Boolean;
begin
if (Pattern[PatternStart] = MultiWildChar) and (Pattern[PatternStart + 1] = #0) then
Result := True
else if (Value[ValueStart] = #0) and (Pattern[PatternStart] <> #0) then
Result := False
else if (Value[ValueStart] = #0) then
Result := True
else
begin
case Pattern[PatternStart] of
MultiWildChar:
begin
if MatchPattern(ValueStart, PatternStart + 1) then
Result := True
else
Result := MatchPattern(ValueStart + 1, PatternStart);
end;
SingleWildChar:
Result := MatchPattern(ValueStart + 1, PatternStart + 1);
else
begin
if CaseSensitive and (Value[ValueStart] = Pattern[PatternStart]) or
not CaseSensitive and (UpperCase(Value[ValueStart]) = UpperCase(Pattern[PatternStart])) then
Result := MatchPattern(ValueStart + 1, PatternStart + 1)
else
Result := False;
end;
end;
end;
end;
begin
if Value = '' then Value := #0;
if Pattern = '' then Pattern := #0;
Result := MatchPattern(1, 1);
end;
}
function LikeString(Value, Pattern: WideString; CaseSensitive: Boolean): Boolean;
const
MultiWildChar = '%';
SingleWildChar = '_';
var
ValuePtr, PatternPtr: PWideChar;
I: Integer;
B: Boolean;
begin
ValuePtr := PWideChar(Value);
PatternPtr := PWideChar(Pattern);
while True do
begin
if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE + SORT_STRINGSORT,
PatternPtr, Length(PatternPtr), WideChar(MultiWildChar), 1) - 2 = 0) then
begin
Result := True;
Exit;
end
else if (ValuePtr^ = #0) and (PatternPtr^ <> #0) then
begin
Result := False;
Exit;
end
else if (ValuePtr^ = #0) then
begin
Result := True;
Exit;
end else
begin
case PatternPtr^ of
MultiWildChar:
begin
for I := 0 to Length(ValuePtr) - 1 do
begin
if LikeString(ValuePtr + I, PatternPtr + 1, CaseSensitive) then
begin
Result := True;
Exit;
end;
end;
Result := False;
Exit;
end;
SingleWildChar:
begin
Inc(ValuePtr);
Inc(PatternPtr);
end;
else
begin
B := False;
if CaseSensitive then
begin
if (CompareStringW(LOCALE_USER_DEFAULT, SORT_STRINGSORT,
PatternPtr, 1, ValuePtr, 1) - 2 = 0) then
B := True;
end else
begin
if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE + SORT_STRINGSORT,
PatternPtr, 1, ValuePtr, 1) - 2 = 0) then
B := True;
end;
if B then
begin
Inc(ValuePtr);
Inc(PatternPtr);
end else
begin
Result := False;
Exit;
end;
end;
end; // case
end;
end;
end;
function TinyDBCompareString(const S1, S2: string; PartialCompare: Boolean;
PartialLength: Integer; CaseInsensitive: Boolean): Integer;
begin
if not PartialCompare then
PartialLength := -1;
if CaseInsensitive then
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PChar(S1),
PartialLength, PChar(S2), PartialLength) - 2;
end else
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0, PChar(S1),
PartialLength, PChar(S2), PartialLength) - 2;
end;
end;
function IsValidDBName(S: string): Boolean;
var
I: Integer;
begin
Result := False;
if S = '' then Exit;
for I := 1 to Length(S) do
if S[I] < ' ' then Exit;
Result := True;
end;
function IsInt(const S: string): Boolean;
var
E, R: Integer;
begin
Val(S, R, E);
Result := E = 0;
E := R; // avoid hints
end;
procedure RandomFillBuffer(Buffer: PChar; Size: Integer; FromVal, ToVal: Integer);
var
I: Integer;
begin
Randomize;
for I := 0 to Size - 1 do
begin
Buffer^ := Chr(Random(ToVal-FromVal+1)+FromVal);
Inc(Buffer);
end;
end;
procedure ScanBlanks(const S: string; var Pos: Integer);
var
I: Integer;
begin
I := Pos;
while (I <= Length(S)) and (S[I] = ' ') do Inc(I);
Pos := I;
end;
function ScanNumber(const S: string; var Pos: Integer;
var Number: Word; var CharCount: Byte): Boolean;
var
I: Integer;
N: Word;
begin
Result := False;
CharCount := 0;
ScanBlanks(S, Pos);
I := Pos;
N := 0;
while (I <= Length(S)) and (S[I] in ['0'..'9']) and (N < 1000) do
begin
N := N * 10 + (Ord(S[I]) - Ord('0'));
Inc(I);
end;
if I > Pos then
begin
CharCount := I - Pos;
Pos := I;
Number := N;
Result := True;
end;
end;
function ScanString(const S: string; var Pos: Integer;
const Symbol: string): Boolean;
begin
Result := False;
if Symbol <> '' then
begin
ScanBlanks(S, Pos);
if AnsiCompareText(Symbol, Copy(S, Pos, Length(Symbol))) = 0 then
begin
Inc(Pos, Length(Symbol));
Result := True;
end;
end;
end;
function ScanChar(const S: string; var Pos: Integer; Ch: Char): Boolean;
begin
Result := False;
ScanBlanks(S, Pos);
if (Pos <= Length(S)) and (S[Pos] = Ch) then
begin
Inc(Pos);
Result := True;
end;
end;
function ScanDate(const S: string; var Pos: Integer; var Date: TDateTime): Boolean;
function CurrentYear: Word;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
Result := SystemTime.wYear;
end;
const
SDateSeparator = '/';
var
N1, N2, N3, Y, M, D: Word;
L1, L2, L3, YearLen: Byte;
CenturyBase: Integer;
begin
Result := False;
if not (ScanNumber(S, Pos, N1, L1) and ScanChar(S, Pos, SDateSeparator) and
ScanNumber(S, Pos, N2, L2) and ScanChar(S, Pos, SDateSeparator) and
ScanNumber(S, Pos, N3, L3)) then Exit;
M := N1;
D := N2;
Y := N3;
YearLen := L3;
if YearLen <= 2 then
begin
CenturyBase := CurrentYear - TwoDigitYearCenturyWindow;
Inc(Y, CenturyBase div 100 * 100);
if (TwoDigitYearCenturyWindow > 0) and (Y < CenturyBase) then
Inc(Y, 100);
end;
Result := True;
try
Date := EncodeDate(Y, M, D);
except
Result := False;
end;
end;
function ScanTime(const S: string; var Pos: Integer; var Time: TDateTime): Boolean;
const
STimeSeparator = ':';
var
BaseHour: Integer;
Hour, Min, Sec, MSec: Word;
Junk: Byte;
begin
Result := False;
BaseHour := -1;
if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then
BaseHour := 0
else if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then
BaseHour := 12;
if BaseHour >= 0 then ScanBlanks(S, Pos);
if not ScanNumber(S, Pos, Hour, Junk) then Exit;
Min := 0;
if ScanChar(S, Pos, STimeSeparator) then
if not ScanNumber(S, Pos, Min, Junk) then Exit;
Sec := 0;
if ScanChar(S, Pos, STimeSeparator) then
if not ScanNumber(S, Pos, Sec, Junk) then Exit;
MSec := 0;
if ScanChar(S, Pos, DecimalSeparator) then
if not ScanNumber(S, Pos, MSec, Junk) then Exit;
if BaseHour < 0 then
if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then
BaseHour := 0
else
if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then
BaseHour := 12;
if BaseHour >= 0 then
begin
if (Hour = 0) or (Hour > 12) then Exit;
if Hour = 12 then Hour := 0;
Inc(Hour, BaseHour);
end;
ScanBlanks(S, Pos);
Result := True;
try
Time := EncodeTime(Hour, Min, Sec, MSec);
except
Result := False;
end;
end;
function DbStrToDate(const S: string; var Date: TDateTime): Boolean;
var
Pos: Integer;
begin
Result := True;
Pos := 1;
if not ScanDate(S, Pos, Date) or (Pos <= Length(S)) then
Result := False;
end;
function DbStrToTime(const S: string; var Date: TDateTime): Boolean;
var
Pos: Integer;
begin
Result := True;
Pos := 1;
if not ScanTime(S, Pos, Date) or (Pos <= Length(S)) then
Result := False;
end;
function DbStrToDateTime(const S: string; var DateTime: TDateTime): Boolean;
var
Pos: Integer;
Date, Time: TDateTime;
begin
Result := True;
Pos := 1;
Time := 0;
if not ScanDate(S, Pos, Date) or not ((Pos > Length(S)) or
ScanTime(S, Pos, Time)) then
begin // Try time only
Pos := 1;
if not ScanTime(S, Pos, DateTime) or (Pos <= Length(S)) then
Result := False;
end else
if Date >= 0 then
DateTime := Date + Time else
DateTime := Date - Time;
end;
function CompareDbDateTime(const MSecsA, MSecsB: Double): Integer;
begin
if Abs(MSecsA - MSecsB) < 1000 then
Result := 0
else if MSecsA < MSecsB then
Result := -1
else
Result := 1;
end;
function Hash(HashClass: THashClass; const Source: string; Digest: Pointer = nil): string;
begin
Result := HashClass.CalcString(Digest, Source);
end;
function HashMD5(const Source: string; Digest: Pointer = nil): string;
begin
Result := Hash(THash_MD5, Source, Digest);
end;
function HashSHA(const Source: string; Digest: Pointer = nil): string;
begin
Result := Hash(THash_SHA, Source, Digest);
end;
function HashSHA1(const Source: string; Digest: Pointer = nil): string;
begin
Result := Hash(THash_SHA1, Source, Digest);
end;
function CheckSumCRC32(const Data; DataSize: Integer): Longword;
begin
THash_CRC32.CalcBuffer(@Result, Data, DataSize);
end;
procedure EncryptBuffer(Buffer: PChar; DataSize: Integer;
EncAlgo: string; EncMode: TEncryptMode; Password: string);
var
EncObj: TEncryptMgr;
begin
EncObj := TEncryptMgr.Create(nil);
try
EncObj.SetAlgoName(EncAlgo);
EncObj.Mode := EncMode;
EncObj.InitKey(Password);
EncObj.EncodeBuffer(Buffer^, Buffer^, DataSize);
finally
EncObj.Free;
end;
end;
procedure DecryptBuffer(Buffer: PChar; DataSize: Integer;
EncAlgo: string; EncMode: TEncryptMode; Password: string);
var
EncObj: TEncryptMgr;
begin
EncObj := TEncryptMgr.Create(nil);
try
EncObj.SetAlgoName(EncAlgo);
EncObj.Mode := EncMode;
EncObj.InitKey(Password);
EncObj.DecodeBuffer(Buffer^, Buffer^, DataSize);
finally
EncObj.Free;
end;
end;
procedure EncryptBufferBlowfish(Buffer: PChar; DataSize: Integer; Password: string);
begin
EncryptBuffer(Buffer, DataSize, 'Blowfish', FTinyDBDefaultEncMode, Password);
end;
procedure DecryptBufferBlowfish(Buffer: PChar; DataSize: Integer; Password: string);
begin
DecryptBuffer(Buffer, DataSize, 'Blowfish', FTinyDBDefaultEncMode, Password);
end;
{ TTinyDefCollection }
constructor TTinyDefCollection.Create(AOwner: TPersistent; AClass: TCollectionItemClass);
begin
inherited Create(AOwner, AClass);
end;
procedure TTinyDefCollection.SetItemName(AItem: TCollectionItem);
begin
with TNamedItem(AItem) do
if (Name = '') then
Name := Copy(ClassName, 2, 5) + IntToStr(ID+1);
end;
function TTinyDefCollection.IndexOf(const AName: string): Integer;
begin
for Result := 0 to Count - 1 do
if AnsiCompareText(TNamedItem(Items[Result]).Name, AName) = 0 then Exit;
Result := -1;
end;
function TTinyDefCollection.Find(const AName: string): TNamedItem;
var
I: Integer;
begin
I := IndexOf(AName);
if I < 0 then Result := nil else Result := TNamedItem(Items[I]);
end;
procedure TTinyDefCollection.GetItemNames(List: TStrings);
var
I: Integer;
begin
List.BeginUpdate;
try
List.Clear;
for I := 0 to Count - 1 do
with TNamedItem(Items[I]) do
if Name <> '' then List.Add(Name);
finally
List.EndUpdate;
end;
end;
{ TTinyTableDef }
constructor TTinyTableDef.Create(Collection: TCollection);
begin
inherited Create(Collection);
end;
destructor TTinyTableDef.Destroy;
begin
inherited Destroy;
end;
{ TTinyTableDefs }
constructor TTinyTableDefs.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TTinyTableDef);
end;
function TTinyTableDefs.GetItem(Index: Integer): TTinyTableDef;
begin
Result := TTinyTableDef(inherited Items[Index]);
end;
function TTinyTableDefs.IndexOf(const Name: string): Integer;
var
Item: TTinyTableDef;
I: Integer;
begin
for I := 0 to Count - 1 do
begin
Item := GetItem(I);
if AnsiCompareText(Item.Name, Name) = 0 then
begin
Result := I;
Exit;
end;
end;
Result := -1;
end;
function TTinyTableDefs.Find(const Name: string): TTinyTableDef;
var
I: Integer;
begin
I := IndexOf(Name);
if I = -1 then
DatabaseErrorFmt(STableNotFound, [Name]);
Result := Items[I];
end;
{ TTinyFieldDef }
constructor TTinyFieldDef.Create(Collection: TCollection);
begin
inherited Create(Collection);
FFieldType := ftUnknown;
FFieldSize := 0;
FDPMode := fdDefault;
end;
destructor TTinyFieldDef.Destroy;
begin
inherited;
end;
procedure TTinyFieldDef.Assign(Source: TPersistent);
var
S: TTinyFieldDef;
begin
if Source is TTinyFieldDef then
begin
if Collection <> nil then Collection.BeginUpdate;
try
S := TTinyFieldDef(Source);
Name := S.Name;
FFieldType := S.FFieldType;
FFieldSize := S.FFieldSize;
FDPMode := S.FDPMode;
finally
if Collection <> nil then Collection.EndUpdate;
end;
end else
inherited;
end;
{ TTinyFieldDefs }
constructor TTinyFieldDefs.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TTinyFieldDef);
end;
function TTinyFieldDefs.AddIndexDef: TTinyFieldDef;
begin
Result := TTinyFieldDef(inherited Add);
end;
function TTinyFieldDefs.Find(const Name: string): TTinyFieldDef;
begin
Result := TTinyFieldDef(inherited Find(Name));
if Result = nil then DatabaseErrorFmt(SFieldNotFound, [Name]);
end;
function TTinyFieldDefs.GetFieldDef(Index: Integer): TTinyFieldDef;
begin
Result := TTinyFieldDef(inherited Items[Index]);
end;
procedure TTinyFieldDefs.SetFieldDef(Index: Integer; Value: TTinyFieldDef);
begin
inherited Items[Index] := Value;
end;
procedure TTinyFieldDefs.SetItemName(AItem: TCollectionItem);
begin
with TNamedItem(AItem) do
if Name = '' then
Name := Copy(ClassName, 2, 5) + IntToStr(ID+1);
end;
{ TTinyIndexDef }
constructor TTinyIndexDef.Create(Collection: TCollection);
begin
inherited Create(Collection);
FOptions := [];
end;
destructor TTinyIndexDef.Destroy;
begin
inherited Destroy;
end;
procedure TTinyIndexDef.Assign(Source: TPersistent);
var
S: TTinyIndexDef;
begin
if Source is TTinyIndexDef then
begin
if Collection <> nil then Collection.BeginUpdate;
try
S := TTinyIndexDef(Source);
Name := S.Name;
Options := S.Options;
FieldIdxes := S.FieldIdxes;
finally
if Collection <> nil then Collection.EndUpdate;
end;
end else
inherited;
end;
procedure TTinyIndexDef.SetOptions(Value: TTDIndexOptions);
begin
FOptions := Value;
end;
{ TTinyIndexDefs }
function TTinyIndexDefs.GetIndexDef(Index: Integer): TTinyIndexDef;
begin
Result := TTinyIndexDef(inherited Items[Index]);
end;
procedure TTinyIndexDefs.SetIndexDef(Index: Integer; Value: TTinyIndexDef);
begin
inherited Items[Index] := Value;
end;
procedure TTinyIndexDefs.SetItemName(AItem: TCollectionItem);
begin
with TNamedItem(AItem) do
if Name = '' then
Name := Copy(ClassName, 2, 5) + IntToStr(ID+1);
end;
constructor TTinyIndexDefs.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TTinyIndexDef);
end;
function TTinyIndexDefs.AddIndexDef: TTinyIndexDef;
begin
Result := TTinyIndexDef(inherited Add);
end;
function TTinyIndexDefs.Find(const Name: string): TTinyIndexDef;
begin
Result := TTinyIndexDef(inherited Find(Name));
if Result = nil then DatabaseErrorFmt(SIndexNotFound, [Name]);
end;
{ TTinyBlobStream }
constructor TTinyBlobStream.Create(Field: TBlobField; Mode: TBlobStreamMode);
begin
FMode := Mode;
FField := Field;
FDataSet := FField.DataSet as TTinyTable;
FFieldNo := FField.FieldNo;
if Mode in [bmRead, bmReadWrite] then
begin
LoadBlobData;
end;
FOpened := True;
if Mode = bmWrite then Truncate;
end;
destructor TTinyBlobStream.Destroy;
begin
inherited Destroy;
end;
function TTinyBlobStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := inherited Write(Buffer, Count);
if FMode in [bmWrite, bmReadWrite] then
begin
FModified := True;
SaveBlobData;
FField.Modified := True;
FDataSet.DataEvent(deFieldChange, Longint(FField));
end;
end;
procedure TTinyBlobStream.LoadBlobData;
var
RecBuf: PChar;
BlobStream: TMemoryStream;
begin
if FDataSet.GetActiveRecBuf(RecBuf) then
begin
Inc(RecBuf, FDataSet.GetFieldOffsetByFieldNo(FFieldNo));
BlobStream := PMemoryStream(RecBuf)^;
if Assigned(BlobStream) then
begin
Clear;
CopyFrom(BlobStream, 0);
Position := 0;
end;
end;
end;
procedure TTinyBlobStream.SaveBlobData;
var
RecBuf: PChar;
BlobStream: TMemoryStream;
SavePos: Integer;
begin
if FDataSet.GetActiveRecBuf(RecBuf) then
begin
SavePos := Position;
try
Inc(RecBuf, FDataSet.GetFieldOffsetByFieldNo(FFieldNo));
BlobStream := PMemoryStream(RecBuf)^;
if Assigned(BlobStream) then
begin
BlobStream.Clear;
BlobStream.CopyFrom(Self, 0);
end;
finally
Position := SavePos;
end;
end;
end;
procedure TTinyBlobStream.Truncate;
begin
if FOpened then
begin
Clear;
SaveBlobData;
FField.Modified := True;
FModified := True;
end;
end;
{ TOptimBlobStream }
constructor TOptimBlobStream.Create(ADataSet: TTDEDataSet);
begin
FDataSet := ADataSet;
FFldDataOffset := 0;
FDataLoaded := False;
end;
destructor TOptimBlobStream.Destroy;
begin
inherited;
end;
procedure TOptimBlobStream.Init(FldDataOffset: Integer; ShouldEncrypt, ShouldCompress: Boolean);
begin
FFldDataOffset := FldDataOffset;
FShouldEncrypt := ShouldEncrypt;
FShouldCompress := ShouldCompress;
FDataLoaded := False;
end;
procedure TOptimBlobStream.LoadBlobData;
begin
if FFldDataOffset = 0 then Exit;
if FDataLoaded then Exit;
FDataLoaded := True;
// 从数据库读入BLOB数据到内存中
FDataSet.ReadFieldData(Self, FFldDataOffset, SizeOf(TBlobFieldHeader),
True, FShouldEncrypt, FShouldCompress);
end;
function TOptimBlobStream.Realloc(var NewCapacity: Integer): Pointer;
begin
FDataLoaded := True;
Result := inherited Realloc(NewCapacity);
end;
function TOptimBlobStream.Read(var Buffer; Count: Integer): Longint;
begin
LoadBlobData;
Result := inherited Read(Buffer, Count);
end;
function TOptimBlobStream.Seek(Offset: Integer; Origin: Word): Longint;
begin
LoadBlobData;
Result := inherited Seek(Offset, Origin);
end;
procedure TOptimBlobStream.SetSize(NewSize: Integer);
begin
FDataLoaded := True;
inherited;
end;
function TOptimBlobStream.Write(const Buffer; Count: Integer): Longint;
begin
FDataLoaded := True;
Result := inherited Write(Buffer, Count);
end;
{ TCachedFileStream }
constructor TCachedFileStream.Create(const FileName: string; Mode: Word);
begin
// inherited;
FCacheStream := TMemoryStream.Create;
FCacheStream.LoadFromFile(FileName);
end;
destructor TCachedFileStream.Destroy;
begin
FCacheStream.Free;
// inherited;
end;
function TCachedFileStream.Read(var Buffer; Count: Integer): Longint;
begin
Result := FCacheStream.Read(Buffer, Count);
end;
function TCachedFileStream.Write(const Buffer; Count: Integer): Longint;
begin
Result := FCacheStream.Write(Buffer, Count);
end;
function TCachedFileStream.Seek(Offset: Integer; Origin: Word): Longint;
begin
Result := FCacheStream.Seek(Offset, Origin);
end;
{ TExprNode }
constructor TExprNode.Create(ExprNodes: TExprNodes);
begin
FExprNodes := ExprNodes;
FArgs := nil;
FPartialLength := -1;
end;
destructor TExprNode.Destroy;
begin
if FArgs <> nil then FArgs.Free;
SetDataSize(0);
inherited;
end;
procedure TExprNode.Calculate(Options: TStrCompOptions);
var
I: Integer;
RecBuf: PChar;
begin
case FKind of
enField:
begin
if FIsBlobField then
begin
with GetDataSet do
begin
FBlobData := Fields[FFieldIdx].AsString;
FData := @FBlobData[1];
end;
end else
begin
if FData = nil then
with GetDataSet do
begin
GetActiveRecBuf(RecBuf);
FData := RecBuf + GetFieldOffsetByFieldNo(Fields[FFieldIdx].FieldNo);
end;
end;
end;
enFunc:
begin
for I := 0 to FArgs.Count - 1 do
TExprNode(FArgs[I]).Calculate(Options);
EvaluateFunction(Self, FFunction, FArgs);
end;
enOperator:
begin
case FOperator of
toOR:
begin
FLeft.Calculate(Options);
if not PBoolean(FLeft.FData)^ then FRight.Calculate(Options);
EvaluateOperator(Self, FOperator, FLeft, FRight, nil, Options);
end;
toAND:
begin
FLeft.Calculate(Options);
if PBoolean(FLeft.FData)^ then FRight.Calculate(Options);
EvaluateOperator(Self, FOperator, FLeft, FRight, nil, Options);
end;
toNOT:
begin
FLeft.Calculate(Options);
EvaluateOperator(Self, FOperator, FLeft, FRight, nil, Options);
end;
toEQ, toNE, toGT, toLT, toGE, toLE,
toADD, toSUB, toMUL, toDIV,
toLIKE:
begin
FLeft.Calculate(Options);
FRight.Calculate(Options);
EvaluateOperator(Self, FOperator, FLeft, FRight, nil, Options);
end;
toIN:
begin
FLeft.Calculate(Options);
for I := 0 to FArgs.Count - 1 do
TExprNode(FArgs[I]).Calculate(Options);
EvaluateOperator(Self, FOperator, FLeft, nil, FArgs, Options);
end;
end;
end;
end;
end;
procedure TExprNode.EvaluateOperator(ResultNode: TExprNode; Operator: TTinyOperator;
LeftNode, RightNode: TExprNode; Args: TList; Options: TStrCompOptions);
var
TempTimeStamp: TTimeStamp;
W1, W2: WideString;
I: Integer;
begin
case Operator of
toOR:
begin
if PBoolean(LeftNode.FData)^ then
PBoolean(ResultNode.FData)^ := True
else
PBoolean(ResultNode.FData)^ := PBoolean(RightNode.FData)^;
end;
toAND:
begin
if PBoolean(LeftNode.FData)^ then
PBoolean(ResultNode.FData)^ := PBoolean(RightNode.FData)^
else
PBoolean(ResultNode.FData)^ := False;
end;
toNOT:
begin
PBoolean(ResultNode.FData)^ := not PBoolean(LeftNode.FData)^;
end;
toEQ: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftBoolean:
PBoolean(ResultNode.FData)^ := PBoolean(LeftNode.FData)^ = PBoolean(RightNode.FData)^;
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ = PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ = PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) = Integer(PWord(RightNode.FData)^);
ftLargeInt:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ = PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ = PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ = PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ = PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ = PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ = PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ = PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) = Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ = PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ = PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ = PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ = PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ = PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ = PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ = PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ = PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ = PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ = PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ = PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ = PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ = PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ = PDouble(RightNode.FData)^;
end;
ftDate:
case RightNode.FDataType of
ftDate:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ = PInteger(RightNode.FData)^;
ftDateTime:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(RightNode.FData)^);
PBoolean(ResultNode.FData)^ := TempTimeStamp.Date = PInteger(LeftNode.FData)^;
end;
end;
ftTime:
case RightNode.FDataType of
ftTime:
PBoolean(ResultNode.FData)^ := CompareDbDateTime(PInteger(LeftNode.FData)^, PInteger(RightNode.FData)^) = 0;
end;
ftDateTime:
case RightNode.FDataType of
ftDate:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
PBoolean(ResultNode.FData)^ := TempTimeStamp.Date = PInteger(RightNode.FData)^;
end;
ftDateTime:
PBoolean(ResultNode.FData)^ := CompareDbDateTime(PDouble(LeftNode.FData)^, PDouble(RightNode.FData)^) = 0;
end;
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
case RightNode.FDataType of
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
PBoolean(ResultNode.FData)^ := TinyDBCompareString(LeftNode.FData, RightNode.FData,
not (scNoPartialCompare in Options), RightNode.FPartialLength, scCaseInsensitive in Options) = 0;
end;
end;
end;
toNE: //-----------------------------------------------------------------
begin
EvaluateOperator(ResultNode, toEQ, LeftNode, RightNode, nil, Options);
PBoolean(ResultNode.FData)^ := not PBoolean(ResultNode.FData)^;
end;
toGT: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftBoolean:
PBoolean(ResultNode.FData)^ := PBoolean(LeftNode.FData)^ > PBoolean(RightNode.FData)^;
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ > PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ > PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) > Integer(PWord(RightNode.FData)^);
ftLargeInt:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ > PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ > PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) > Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ > PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ > PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ > PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ > PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ > PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ > PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ > PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ > PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ > PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ > PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ > PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ > PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ > PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ > PDouble(RightNode.FData)^;
end;
ftDate:
case RightNode.FDataType of
ftDate:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > PInteger(RightNode.FData)^;
ftDateTime:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(RightNode.FData)^);
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ > TempTimeStamp.Date;
end;
end;
ftTime:
case RightNode.FDataType of
ftTime:
PBoolean(ResultNode.FData)^ := CompareDbDateTime(PInteger(LeftNode.FData)^, PInteger(RightNode.FData)^) > 0;
end;
ftDateTime:
case RightNode.FDataType of
ftDate:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
PBoolean(ResultNode.FData)^ := TempTimeStamp.Date > PInteger(RightNode.FData)^;
end;
ftDateTime:
PBoolean(ResultNode.FData)^ := CompareDbDateTime(PDouble(LeftNode.FData)^, PDouble(RightNode.FData)^) > 0;
end;
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
case RightNode.FDataType of
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
PBoolean(ResultNode.FData)^ := TinyDBCompareString(LeftNode.FData, RightNode.FData,
not (scNoPartialCompare in Options), RightNode.FPartialLength, scCaseInsensitive in Options) > 0;
end;
end;
end;
toLT: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftBoolean:
PBoolean(ResultNode.FData)^ := PBoolean(LeftNode.FData)^ < PBoolean(RightNode.FData)^;
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ < PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ < PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) < Integer(PWord(RightNode.FData)^);
ftLargeInt:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ < PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ < PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) < Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ < PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ < PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ < PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PWord(LeftNode.FData)^ < PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ < PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ < PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ < PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ < PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ < PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ < PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ < PInteger(RightNode.FData)^;
ftWord:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ < PWord(RightNode.FData)^;
ftLargeInt:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ < PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PBoolean(ResultNode.FData)^ := PDouble(LeftNode.FData)^ < PDouble(RightNode.FData)^;
end;
ftDate:
case RightNode.FDataType of
ftDate:
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < PInteger(RightNode.FData)^;
ftDateTime:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(RightNode.FData)^);
PBoolean(ResultNode.FData)^ := PInteger(LeftNode.FData)^ < TempTimeStamp.Date;
end;
end;
ftTime:
case RightNode.FDataType of
ftTime:
PBoolean(ResultNode.FData)^ := CompareDbDateTime(PInteger(LeftNode.FData)^, PInteger(RightNode.FData)^) < 0;
end;
ftDateTime:
case RightNode.FDataType of
ftDate:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
PBoolean(ResultNode.FData)^ := TempTimeStamp.Date < PInteger(RightNode.FData)^;
end;
ftDateTime:
PBoolean(ResultNode.FData)^ := CompareDbDateTime(PDouble(LeftNode.FData)^, PDouble(RightNode.FData)^) < 0;
end;
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
case RightNode.FDataType of
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
PBoolean(ResultNode.FData)^ := TinyDBCompareString(LeftNode.FData, RightNode.FData,
not (scNoPartialCompare in Options), RightNode.FPartialLength, scCaseInsensitive in Options) < 0;
end;
end;
end;
toGE: //-----------------------------------------------------------------
begin
EvaluateOperator(ResultNode, toLT, LeftNode, RightNode, nil, Options);
PBoolean(ResultNode.FData)^ := not PBoolean(ResultNode.FData)^;
end;
toLE: //-----------------------------------------------------------------
begin
EvaluateOperator(ResultNode, toGT, LeftNode, RightNode, nil, Options);
PBoolean(ResultNode.FData)^ := not PBoolean(ResultNode.FData)^;
end;
toADD: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ + PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) + Integer(PWord(RightNode.FData)^);
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) + Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PWord(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PWord(LeftNode.FData)^ + PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PWord(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ + PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ + PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ + PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ + PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftDate:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftTime:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ + PDouble(RightNode.FData)^;
end;
ftDateTime:
case RightNode.FDataType of
ftSmallInt:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Inc(TempTimeStamp.Date, PSmallInt(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftInteger, ftAutoInc:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Inc(TempTimeStamp.Date, PInteger(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftWord:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Inc(TempTimeStamp.Date, PWord(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftLargeInt:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Inc(TempTimeStamp.Date, PLargeInt(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftFloat, ftCurrency:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Inc(TempTimeStamp.Date, Trunc(PDouble(RightNode.FData)^));
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
end;
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
case RightNode.FDataType of
ftString, ftFixedChar, ftBlob, ftMemo, ftFmtMemo, ftGraphic:
begin
ResultNode.DataSize := StrLen(LeftNode.FData) + StrLen(RightNode.FData) + 1;
StrCopy(ResultNode.FData, LeftNode.FData);
StrCat(ResultNode.FData, RightNode.FData);
end;
end;
end;
end;
toSUB: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ - PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) - Integer(PWord(RightNode.FData)^);
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ - PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) - Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PWord(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PWord(LeftNode.FData)^ - PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PWord(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ - PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ - PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ - PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ - PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ - PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ - PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ - PDouble(RightNode.FData)^;
end;
ftDate:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc, ftDate:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PWord(RightNode.FData)^;
ftLargeInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - Trunc(PDouble(RightNode.FData)^);
end;
ftTime:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc, ftTime:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PWord(RightNode.FData)^;
ftLargeInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ - Trunc(PDouble(RightNode.FData)^);
end;
ftDateTime:
case RightNode.FDataType of
ftSmallInt:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Dec(TempTimeStamp.Date, PSmallInt(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftInteger, ftAutoInc:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Dec(TempTimeStamp.Date, PInteger(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftWord:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Dec(TempTimeStamp.Date, PWord(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftLargeInt:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Dec(TempTimeStamp.Date, PLargeInt(RightNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftFloat, ftCurrency:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
Dec(TempTimeStamp.Date, Trunc(PDouble(RightNode.FData)^));
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp);
end;
ftDate, ftTime:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(LeftNode.FData)^);
PDouble(ResultNode.FData)^ := TimeStampToMSecs(TempTimeStamp) - PInteger(RightNode.FData)^;
end;
ftDateTime:
begin
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ - PDouble(RightNode.FData)^;
end;
end;
end;
end;
toMUL: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ * PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ * PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) * Integer(PWord(RightNode.FData)^);
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ * PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ * PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ * PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ * PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PInteger(LeftNode.FData)^ * PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PInteger(LeftNode.FData)^ * PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ * PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PInteger(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) * Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PInteger(ResultNode.FData)^ := PWord(LeftNode.FData)^ * PInteger(RightNode.FData)^;
ftWord:
PInteger(ResultNode.FData)^ := PWord(LeftNode.FData)^ * PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PWord(LeftNode.FData)^ * PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ * PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ * PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ * PInteger(RightNode.FData)^;
ftWord:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ * PWord(RightNode.FData)^;
ftLargeInt:
PLargeInt(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ * PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ * PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ * PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ * PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ * PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ * PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ * PDouble(RightNode.FData)^;
end;
end;
end;
toDIV: //-----------------------------------------------------------------
begin
case LeftNode.FDataType of
ftSmallInt:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ / PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ / PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := Integer(PSmallInt(LeftNode.FData)^) / Integer(PWord(RightNode.FData)^);
ftLargeInt:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ / PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PSmallInt(LeftNode.FData)^ / PDouble(RightNode.FData)^;
end;
ftInteger, ftAutoInc:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ / PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ / PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ / PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ / PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PInteger(LeftNode.FData)^ / PDouble(RightNode.FData)^;
end;
ftWord:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := Integer(PWord(LeftNode.FData)^) / Integer(PSmallInt(RightNode.FData)^);
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ / PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ / PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ / PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PWord(LeftNode.FData)^ / PDouble(RightNode.FData)^;
end;
ftLargeInt:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ / PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ / PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ / PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ / PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PLargeInt(LeftNode.FData)^ / PDouble(RightNode.FData)^;
end;
ftFloat, ftCurrency:
case RightNode.FDataType of
ftSmallInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ / PSmallInt(RightNode.FData)^;
ftInteger, ftAutoInc:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ / PInteger(RightNode.FData)^;
ftWord:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ / PWord(RightNode.FData)^;
ftLargeInt:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ / PLargeInt(RightNode.FData)^;
ftFloat, ftCurrency:
PDouble(ResultNode.FData)^ := PDouble(LeftNode.FData)^ / PDouble(RightNode.FData)^;
end;
end;
end;
toLIKE: //-----------------------------------------------------------------
begin
W1 := LeftNode.FData;
W2 := RightNode.FData;
PBoolean(ResultNode.FData)^ := LikeString(W1, W2, not (scCaseInsensitive in Options));
end;
toIN: //-----------------------------------------------------------------
begin
for I := 0 to Args.Count - 1 do
begin
EvaluateOperator(ResultNode, toEQ, LeftNode, TExprNode(Args[I]), nil, Options);
if PBoolean(ResultNode.FData)^ then Break;
end;
end;
end;
end;
procedure TExprNode.EvaluateFunction(ResultNode: TExprNode; AFunction: TTinyFunction; Args: TList);
var
TempNode: TExprNode;
TempTimeStamp: TTimeStamp;
Year, Month, Day, Hour, Minute, Second, MSec: Word;
begin
case AFunction of
tfUpper:
begin
TempNode := TExprNode(Args[0]);
ResultNode.DataSize := StrLen(TempNode.FData) + 1;
StrCopy(ResultNode.FData, StrUpper(TempNode.FData));
end;
tfLower:
begin
TempNode := TExprNode(Args[0]);
ResultNode.DataSize := StrLen(TempNode.FData) + 1;
StrCopy(ResultNode.FData, StrLower(TempNode.FData));
end;
tfSubString:
begin
ResultNode.DataSize := PInteger(TExprNode(Args[2]).FData)^ + 1; //Sub Length
StrLCopy(ResultNode.FData,
TExprNode(Args[0]).FData + PInteger(TExprNode(Args[1]).FData)^ - 1,
PInteger(TExprNode(Args[2]).FData)^);
end;
tfTrim:
begin
TempNode := TExprNode(Args[0]);
ResultNode.DataSize := StrLen(TempNode.FData) + 1;
StrCopy(ResultNode.FData, PChar(Trim(string(TempNode.FData))));
end;
tfTrimLeft:
begin
TempNode := TExprNode(Args[0]);
ResultNode.DataSize := StrLen(TempNode.FData) + 1;
StrCopy(ResultNode.FData, PChar(TrimLeft(string(TempNode.FData))));
end;
tfTrimRight:
begin
TempNode := TExprNode(Args[0]);
ResultNode.DataSize := StrLen(TempNode.FData) + 1;
StrCopy(ResultNode.FData, PChar(TrimRight(string(TempNode.FData))));
end;
tfYear, tfMonth, tfDay:
begin
TempNode := TExprNode(Args[0]);
case TempNode.FDataType of
ftDate:
begin
TempTimeStamp.Date := PInteger(TempNode.FData)^;
TempTimeStamp.Time := 0;
DecodeDate(TimeStampToDateTime(TempTimeStamp), Year, Month, Day);
end;
ftDateTime:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(TempNode.FData)^);
DecodeDate(TimeStampToDateTime(TempTimeStamp), Year, Month, Day);
end;
end;
case AFunction of
tfYear: PInteger(ResultNode.FData)^ := Year;
tfMonth: PInteger(ResultNode.FData)^ := Month;
tfDay: PInteger(ResultNode.FData)^ := Day;
end;
end;
tfHour, tfMinute, tfSecond:
begin
TempNode := TExprNode(Args[0]);
case TempNode.FDataType of
ftTime:
begin
TempTimeStamp.Date := Trunc(Date);
TempTimeStamp.Time := PInteger(TempNode.FData)^;
DecodeTime(TimeStampToDateTime(TempTimeStamp), Hour, Minute, Second, MSec);
end;
ftDateTime:
begin
TempTimeStamp := MSecsToTimeStamp(PDouble(TempNode.FData)^);
DecodeTime(TimeStampToDateTime(TempTimeStamp), Hour, Minute, Second, MSec);
end;
end;
case AFunction of
tfHour: PInteger(ResultNode.FData)^ := Hour;
tfMinute: PInteger(ResultNode.FData)^ := Minute;
tfSecond: PInteger(ResultNode.FData)^ := Second;
end;
end;
end;
end;
function TExprNode.IsIntegerType: Boolean;
begin
Result := FDataType in [ftSmallint, ftInteger, ftWord, ftAutoInc];
end;
function TExprNode.IsLargeIntType: Boolean;
begin
Result := FDataType in [ftLargeInt];
end;
function TExprNode.IsFloatType: Boolean;
begin
Result := FDataType in [ftFloat, ftCurrency];
end;
function TExprNode.IsTemporalType: Boolean;
begin
Result := FDataType in [ftDate, ftTime, ftDateTime];
end;
function TExprNode.IsStringType: Boolean;
begin
Result := (FDataType in StringFieldTypes) or (FDataType in BlobFieldTypes);
end;
function TExprNode.IsBooleanType: Boolean;
begin
Result := (FDataType = ftBoolean);
end;
function TExprNode.IsNumericType: Boolean;
begin
Result := IsIntegerType or IsLargeIntType or IsFloatType;
end;
function TExprNode.IsTemporalStringType: Boolean;
var
TempStr: string;
TempDateTime: TDateTime;
begin
TempStr := FData;
Result := IsStringType and (FKind = enConst);
if Result then
begin
Result := DbStrToDateTime(TempStr, TempDateTime);
if not Result then
begin
Result := True;
try
StrToDateTime(TempStr);
except
Result := False;
end;
end;
end;
end;
procedure TExprNode.SetDataSize(Size: Integer);
begin
if FDataSize <> Size then
begin
if Size > 0 then
begin
if FDataSize = 0 then
FData := AllocMem(Size)
else
ReallocMem(FData, Size);
end else
begin
FreeMem(FData);
end;
FDataSize := Size;
end;
end;
function TExprNode.GetDataSet: TTDEDataSet;
begin
Result := (FExprNodes.FExprParser as TFilterParser).FDataSet;
end;
function TExprNode.AsBoolean: Boolean;
begin
Result := PBoolean(FData)^;
end;
procedure TExprNode.ConvertStringToDateTime;
var
DateTimeString: string;
DateTime: TDateTime;
DstType: TFieldType;
begin
DateTimeString := Trim(FData);
if Pos(#32, DateTimeString) > 0 then
DstType := ftDateTime
else if Pos(':', DateTimeString) > 0 then
DstType := ftTime
else
DstType := ftDate;
case DstType of
ftDate:
begin
if not DbStrToDate(DateTimeString, DateTime) then
DateTime := StrToDate(DateTimeString);
DataSize := SizeOf(Integer);
FDataType := ftDate;
PInteger(FData)^ := DateTimeToTimeStamp(DateTime).Date;
end;
ftTime:
begin
if not DbStrToTime(DateTimeString, DateTime) then
DateTime := StrToTime(DateTimeString);
DataSize := SizeOf(Integer);
FDataType := ftTime;
PInteger(FData)^ := DateTimeToTimeStamp(DateTime).Time;
end;
ftDateTime:
begin
if not DbStrToDateTime(DateTimeString, DateTime) then
DateTime := StrToDateTime(DateTimeString);
DataSize := SizeOf(Double);
FDataType := ftDateTime;
PDouble(FData)^ := TimeStampToMSecs(DateTimeToTimeStamp(DateTime));
end;
end;
end;
class function TExprNode.FuncNameToEnum(const FuncName: string): TTinyFunction;
var
FuncNames: array[TTinyFunction] of string;
I: TTinyFunction;
begin
FuncNames[tfUpper] := 'UPPER';
FuncNames[tfLower] := 'LOWER';
FuncNames[tfSubString] := 'SUBSTRING';
FuncNames[tfTrim] := 'TRIM';
FuncNames[tfTrimLeft] := 'TRIMLEFT';
FuncNames[tfTrimRight] := 'TRIMRIGHT';
FuncNames[tfYear] := 'YEAR';
FuncNames[tfMonth] := 'MONTH';
FuncNames[tfDay] := 'DAY';
FuncNames[tfHour] := 'HOUR';
FuncNames[tfMinute] := 'MINUTE';
FuncNames[tfSecond] := 'SECOND';
FuncNames[tfGetDate] := 'GETDATE';
for I := Low(FuncNames) to High(FuncNames) do
begin
if CompareText(FuncName, FuncNames[I]) = 0 then
begin
Result := I;
Exit;
end;
end;
Result := tfUnknown;
end;
{ TExprNodes }
constructor TExprNodes.Create(AExprParser: TExprParserBase);
begin
FExprParser := AExprParser;
FNodes := nil;
FRoot := nil;
end;
destructor TExprNodes.Destroy;
begin
Clear;
inherited;
end;
procedure TExprNodes.Clear;
var
Node: TExprNode;
begin
while FNodes <> nil do
begin
Node := FNodes;
FNodes := Node.FNext;
Node.Free;
end;
FNodes := nil;
end;
function TExprNodes.NewNode(NodeKind: TExprNodeKind; DataType: TFieldType;
ADataSize: Integer; Operator: TTinyOperator; Left, Right: TExprNode): TExprNode;
begin
Result := TExprNode.Create(Self);
with Result do
begin
FNext := FNodes;
FKind := NodeKind;
FDataType := DataType;
DataSize := ADataSize;
FOperator := Operator;
FLeft := Left;
FRight := Right;
end;
FNodes := Result;
end;
function TExprNodes.NewFuncNode(const FuncName: string): TExprNode;
begin
Result := TExprNode.Create(Self);
with Result do
begin
FNext := FNodes;
FKind := enFunc;
FDataType := FExprParser.GetFuncDataType(FuncName);
DataSize := 0;
FSymbol := FuncName;
FOperator := toNOTDEFINED;
FFunction := FuncNameToEnum(FuncName);
FLeft := nil;
FRight := nil;
end;
FNodes := Result;
end;
function TExprNodes.NewFieldNode(const FieldName: string): TExprNode;
begin
Result := TExprNode.Create(Self);
with Result do
begin
FNext := FNodes;
FKind := enField;
FDataType := FExprParser.GetFieldDataType(FieldName);
DataSize := 0;
FData := nil;
FSymbol := FieldName;
FOperator := toNOTDEFINED;
FLeft := nil;
FRight := nil;
FIsBlobField := GetDataSet.FieldByName(FieldName).IsBlob;
FFieldIdx := GetDataSet.FieldByName(FieldName).Index;
end;
FNodes := Result;
end;
{ TSyntaxParserBase }
constructor TSyntaxParserBase.Create;
begin
end;
destructor TSyntaxParserBase.Destroy;
begin
inherited;
end;
procedure TSyntaxParserBase.SetText(const Value: string);
begin
FText := Value;
FSourcePtr := PChar(FText);
end;
function TSyntaxParserBase.IsKatakana(const Chr: Byte): Boolean;
begin
Result := (SysLocale.PriLangID = LANG_JAPANESE) and (Chr in [$A1..$DF]);
end;
procedure TSyntaxParserBase.Skip(var P: PChar; TheSet: TChrSet);
begin
while True do
begin
if P^ in LeadBytes then
Inc(P, 2)
else if (P^ in TheSet) or IsKatakana(Byte(P^)) then
Inc(P)
else
Exit;
end;
end;
function TSyntaxParserBase.TokenName: string;
begin
if FSourcePtr = FTokenPtr then Result := SExprNothing else
begin
SetString(Result, FTokenPtr, FSourcePtr - FTokenPtr);
Result := '''' + Result + '''';
end;
end;
function TSyntaxParserBase.TokenSymbolIs(const S: string): Boolean;
begin
Result := (FToken = etSymbol) and (CompareText(FTokenString, S) = 0);
end;
procedure TSyntaxParserBase.Rewind;
begin
FSourcePtr := PChar(FText);
FTokenPtr := FSourcePtr;
FTokenString := '';
end;
function TSyntaxParserBase.SkipBeforeGetToken(Pos: PChar): PChar;
var
P: PChar;
begin
P := Pos;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
// 处理通用注释标志“/**/”
if (P^ <> #0) and (P^ = '/') and (P[1] <> #0) and (P[1] = '*')then
begin
P := P + 2;
while (P^ <> #0) and (P^ <> '*') do Inc(P);
if (P^ = '*') and (P[1] <> #0) and (P[1] = '/') then
P := P + 2
else
DatabaseErrorFmt(SExprInvalidChar, [P^]);
end;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
Result := P;
end;
procedure TSyntaxParserBase.GetNextToken;
begin
FPrevToken := FToken;
FTokenString := '';
FTokenPtr := SkipBeforeGetToken(FSourcePtr);
FSourcePtr := InternalGetNextToken(FTokenPtr);
end;
{ TExprParserBase }
constructor TExprParserBase.Create;
begin
FExprNodes := TExprNodes.Create(Self);
end;
destructor TExprParserBase.Destroy;
begin
FExprNodes.Free;
inherited;
end;
procedure TExprParserBase.Parse(const AText: string);
begin
FExprNodes.Clear;
Text := AText;
GetNextToken;
FExprNodes.Root := ParseExpr;
ParseFinished;
end;
procedure TExprParserBase.ParseFinished;
begin
if FToken <> etEnd then DatabaseError(SExprTermination);
end;
function TExprParserBase.Calculate(Options: TStrCompOptions = []): Variant;
begin
FStrCompOpts := Options;
FExprNodes.Root.Calculate(Options);
Result := FExprNodes.Root.AsBoolean;
end;
function TExprParserBase.TokenSymbolIsFunc(const S: string) : Boolean;
begin
Result := False;
end;
{ TFilterParser }
constructor TFilterParser.Create(ADataSet: TTDEDataSet);
begin
inherited Create;
FDataSet := ADataSet;
end;
function TFilterParser.GetFieldDataType(const Name: string): TFieldType;
begin
Result := FDataSet.FieldByName(Name).DataType;
end;
function TFilterParser.GetFieldValue(const Name: string): Variant;
begin
Result := FDataSet.FieldByName(Name).Value;
end;
function TFilterParser.GetFuncDataType(const Name: string): TFieldType;
begin
Result := ftUnknown;
if (CompareText(Name, 'YEAR') = 0) or
(CompareText(Name, 'MONTH') = 0) or
(CompareText(Name, 'DAY') = 0) or
(CompareText(Name, 'HOUR') = 0) or
(CompareText(Name, 'MINUTE') = 0) or
(CompareText(Name, 'SECOND') = 0 ) then
begin
Result := ftInteger;
end else
if CompareText(Name, 'GETDATE') = 0 then
begin
Result := ftDateTime;
end;
end;
function TFilterParser.TokenSymbolIsFunc(const S: string): Boolean;
begin
Result := TExprNode.FuncNameToEnum(S) <> tfUnknown;
end;
function TFilterParser.InternalGetNextToken(Pos: PChar): PChar;
var
P, TokenStart: PChar;
L: Integer;
StrBuf: array[0..255] of Char;
begin
P := Pos;
case P^ of
'A'..'Z', 'a'..'z', '_', #$81..#$fe:
begin
TokenStart := P;
if not SysLocale.FarEast then
begin
Inc(P);
while P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '[', ']'] do Inc(P);
end
else
Skip(P, ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '[', ']']);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etSymbol;
if CompareText(FTokenString, 'LIKE') = 0 then
FToken := etLIKE
else if CompareText(FTokenString, 'IN') = 0 then
FToken := etIN
{
else if CompareText(FTokenString, 'IS') = 0 then
begin
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
TokenStart := P;
Skip(P, ['A'..'Z', 'a'..'z']);
SetString(FTokenString, TokenStart, P - TokenStart);
if CompareText(FTokenString, 'NOT')= 0 then
begin
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
TokenStart := P;
Skip(P, ['A'..'Z', 'a'..'z']);
SetString(FTokenString, TokenStart, P - TokenStart);
if CompareText(FTokenString, 'NULL') = 0 then
FToken := etISNOTNULL
else
DatabaseError(SInvalidKeywordUse);
end
else if CompareText (FTokenString, 'NULL') = 0 then
begin
FToken := etISNULL;
end
else
DatabaseError(SInvalidKeywordUse);
end;
}
end;
'[':
begin
Inc(P);
TokenStart := P;
P := AnsiStrScan(P, ']');
if P = nil then DatabaseError(SExprNameError);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etName;
Inc(P);
end;
'''':
begin
Inc(P);
L := 0;
while True do
begin
if P^ = #0 then DatabaseError(SExprStringError);
if P^ = '''' then
begin
Inc(P);
if P^ <> '''' then Break;
end;
if L < SizeOf(StrBuf) then
begin
StrBuf[L] := P^;
Inc(L);
end;
Inc(P);
end;
SetString(FTokenString, StrBuf, L);
FToken := etCharLiteral;
end;
'-', '0'..'9':
begin
if (P^ = '-') and
((FPrevToken = etCharLiteral) or (FPrevToken = etNumLiteral) or (FPrevToken = etName) or
(FPrevToken = etSymbol) or (FPrevToken = etRParen)) then
begin
FToken := etSUB;
Inc(P);
end else
begin
TokenStart := P;
Inc(P);
while (P^ in ['0'..'9', DecimalSeparator, 'e', 'E', '+', '-']) do
begin
if (P^ in ['+', '-']) and not ((P-1)^ in ['e', 'E']) and (P <> TokenStart) then Break;
Inc(P);
end;
if ((P-1)^ = ',') and (DecimalSeparator = ',') and (P^ = ' ') then Dec(P);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etNumLiteral;
end;
end;
'(':
begin
Inc(P);
FToken := etLParen;
end;
')':
begin
Inc(P);
FToken := etRParen;
end;
'<':
begin
Inc(P);
case P^ of
'=':
begin
Inc(P);
FToken := etLE;
end;
'>':
begin
Inc(P);
FToken := etNE;
end;
else
FToken := etLT;
end;
end;
'=':
begin
Inc(P);
FToken := etEQ;
end;
'>':
begin
Inc(P);
if P^ = '=' then
begin
Inc(P);
FToken := etGE;
end else
FToken := etGT;
end;
'+':
begin
Inc(P);
FToken := etADD;
end;
'*':
begin
Inc(P);
FToken := etMUL;
end;
'/':
begin
Inc(P);
FToken := etDIV;
end;
',':
begin
Inc(P);
FToken := etComma;
end;
#0:
FToken := etEnd;
else
DatabaseErrorFmt(SExprInvalidChar, [P^]);
end;
Result := P;
end;
function TFilterParser.NextTokenIsLParen: Boolean;
var
P : PChar;
begin
P := FSourcePtr;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
Result := P^ = '(';
end;
function TFilterParser.ParseExpr: TExprNode;
begin
Result := ParseExpr2;
while TokenSymbolIs('OR') do
begin
GetNextToken;
Result := FExprNodes.NewNode(enOperator, ftBoolean, SizeOf(Boolean), toOR, Result, ParseExpr2);
TypeCheckLogicOp(Result);
end;
end;
function TFilterParser.ParseExpr2: TExprNode;
begin
Result := ParseExpr3;
while TokenSymbolIs('AND') do
begin
GetNextToken;
Result := FExprNodes.NewNode(enOperator, ftBoolean, SizeOf(Boolean), toAND, Result, ParseExpr3);
TypeCheckLogicOp(Result);
end;
end;
function TFilterParser.ParseExpr3: TExprNode;
begin
if TokenSymbolIs('NOT') then
begin
GetNextToken;
Result := FExprNodes.NewNode(enOperator, ftBoolean, SizeOf(Boolean), toNOT, ParseExpr4, nil);
TypeCheckLogicOp(Result);
end else
Result := ParseExpr4;
end;
function TFilterParser.ParseExpr4: TExprNode;
const
Operators: array[etEQ..etLT] of TTinyOperator = (
toEQ, toNE, toGE, toLE, toGT, toLT);
var
Operator: TTinyOperator;
Left, Right: TExprNode;
begin
Result := ParseExpr5;
if (FToken in [etEQ..etLT]) or (FToken = etLIKE) or (FToken = etIN) then
begin
case FToken of
etEQ..etLT:
Operator := Operators[FToken];
etLIKE:
Operator := toLIKE;
etIN:
Operator := toIN;
else
Operator := toNOTDEFINED;
end;
GetNextToken;
Left := Result;
if Operator = toIN then
begin
if FToken <> etLParen then
DatabaseErrorFmt(SExprNoLParen, [TokenName]);
GetNextToken;
Result := FExprNodes.NewNode(enOperator, ftBoolean, SizeOf(Boolean), toIN, Left, nil);
if FToken <> etRParen then
begin
Result.FArgs := TList.Create;
repeat
Right := ParseExpr;
Result.FArgs.Add(Right);
if (FToken <> etComma) and (FToken <> etRParen) then
DatabaseErrorFmt(SExprNoRParenOrComma, [TokenName]);
if FToken = etComma then GetNextToken;
until (FToken = etRParen) or (FToken = etEnd);
if FToken <> etRParen then
DatabaseErrorFmt(SExprNoRParen, [TokenName]);
TypeCheckInOp(Result);
GetNextToken;
end else
DatabaseError(SExprEmptyInList);
end else
begin
Right := ParseExpr5;
Result := FExprNodes.NewNode(enOperator, ftBoolean, SizeOf(Boolean), Operator, Left, Right);
case Operator of
toEQ, toNE, toGE, toLE, toGT, toLT:
TypeCheckRelationOp(Result);
toLIKE:
TypeCheckLikeOp(Result);
end;
end;
end;
end;
function TFilterParser.ParseExpr5: TExprNode;
const
Operators: array[etADD..etDIV] of TTinyOperator = (
toADD, toSUB, toMUL, toDIV);
var
Operator: TTinyOperator;
Left, Right: TExprNode;
begin
Result := ParseExpr6;
while FToken in [etADD, etSUB] do
begin
Operator := Operators[FToken];
Left := Result;
GetNextToken;
Right := ParseExpr6;
Result := FExprNodes.NewNode(enOperator, ftUnknown, 0, Operator, Left, Right);
TypeCheckArithOp(Result);
end;
end;
function TFilterParser.ParseExpr6: TExprNode;
const
Operators: array[etADD..etDIV] of TTinyOperator = (
toADD, toSUB, toMUL, toDIV);
var
Operator: TTinyOperator;
Left, Right: TExprNode;
begin
Result := ParseExpr7;
while FToken in [etMUL, etDIV] do
begin
Operator := Operators[FToken];
Left := Result;
GetNextToken;
Right := ParseExpr7;
Result := FExprNodes.NewNode(enOperator, ftUnknown, 0, Operator, Left, Right);
TypeCheckArithOp(Result);
end;
end;
function TFilterParser.ParseExpr7: TExprNode;
var
FuncName: string;
begin
case FToken of
etSymbol:
if NextTokenIsLParen and TokenSymbolIsFunc(FTokenString) then
begin
FuncName := FTokenString;
GetNextToken;
if FToken <> etLParen then
DatabaseErrorFmt(SExprNoLParen, [TokenName]);
GetNextToken;
if (CompareText(FuncName,'COUNT') = 0) and (FToken = etMUL) then
begin
FuncName := 'COUNT(*)';
GetNextToken;
end;
Result := FExprNodes.NewFuncNode(FuncName);
if FToken <> etRParen then
begin
Result.FArgs := TList.Create;
repeat
Result.FArgs.Add(ParseExpr);
if (FToken <> etComma) and (FToken <> etRParen) then
DatabaseErrorFmt(SExprNoRParenOrComma, [TokenName]);
if FToken = etComma then GetNextToken;
until (FToken = etRParen) or (FToken = etEnd);
end else
Result.FArgs := nil;
TypeCheckFunction(Result);
end
else if TokenSymbolIs(STextTrue) then
begin
Result := FExprNodes.NewNode(enConst, ftBoolean, SizeOf(Boolean), toNOTDEFINED, nil, nil);
PBoolean(Result.FData)^ := True;
end
else if TokenSymbolIs(STextFalse) then
begin
Result := FExprNodes.NewNode(enConst, ftBoolean, SizeOf(Boolean), toNOTDEFINED, nil, nil);
PBoolean(Result.FData)^ := False;
end
else
begin
Result := FExprNodes.NewFieldNode(FTokenString);
end;
etName:
begin
Result := FExprNodes.NewFieldNode(FTokenString);
end;
etNumLiteral:
begin
if IsInt(FTokenString) then
begin
Result := FExprNodes.NewNode(enConst, ftInteger, SizeOf(Integer), toNOTDEFINED, nil, nil);
PInteger(Result.FData)^ := StrToInt(FTokenString);
end else
begin
Result := FExprNodes.NewNode(enConst, ftFloat, SizeOf(Double), toNOTDEFINED, nil, nil);
PDouble(Result.FData)^ := StrToFloat(FTokenString);
end;
end;
etCharLiteral:
begin
Result := FExprNodes.NewNode(enConst, ftString, Length(FTokenString) + 1, toNOTDEFINED, nil, nil);
StrPCopy(Result.FData, FTokenString);
Result.FPartialLength := Pos('*', Result.FData) - 1;
end;
etLParen:
begin
GetNextToken;
Result := ParseExpr;
if FToken <> etRParen then DatabaseErrorFmt(SExprNoRParen, [TokenName]);
end;
else
DatabaseErrorFmt(SExprExpected, [TokenName]);
Result := nil;
end;
GetNextToken;
end;
procedure TFilterParser.TypeCheckArithOp(Node: TExprNode);
function CompareNumTypePRI(DataType1, DataType2: TFieldType): Integer;
var
Value: array[TFieldType] of Integer;
begin
Value[ftSmallInt] := 1;
Value[ftWord] := 2;
Value[ftInteger] := 3;
Value[ftAutoInc] := 3;
Value[ftLargeInt] := 4;
Value[ftFloat] := 5;
Value[ftCurrency] := 6;
if Value[DataType1] > Value[DataType2] then
Result := 1
else if Value[DataType1] < Value[DataType2] then
Result := -1
else
Result := 0;
end;
var
Match: Boolean;
CompResult: Integer;
begin
Match := True;
with Node do
begin
if FLeft.IsNumericType then
begin
if FRight.IsNumericType then
begin
CompResult := CompareNumTypePRI(FLeft.FDataType, FRight.FDataType);
if CompResult >= 0 then
begin
FDataType := FLeft.FDataType;
DataSize := GetFieldSize(FLeft.FDataType);
end else
begin
FDataType := FRight.FDataType;
DataSize := GetFieldSize(FRight.FDataType);
end;
if FDataType in [ftSmallInt, ftWord] then
begin
FDataType := ftInteger;
DataSize := SizeOf(Integer);
end;
if FOperator = toDIV then
begin
FDataType := ftFloat;
DataSize := SizeOf(Double);
end;
end else
Match := False;
end
else if FLeft.IsTemporalType then
begin
if FOperator = toSUB then
begin
if FRight.IsTemporalStringType then
FRight.ConvertStringToDateTime;
if (FLeft.FDataType = ftDate) and
((FRight.FDataType = ftDate) or FRight.IsNumericType) then
begin
FDataType := ftInteger;
DataSize := SizeOf(Integer);
end
else if (FLeft.FDataType = ftTime) and
((FRight.FDataType = ftTime) or FRight.IsNumericType) then
begin
FDataType := ftInteger;
DataSize := SizeOf(Integer);
end
else if FRight.IsTemporalType or FRight.IsNumericType then
begin
FDataType := ftFloat;
DataSize := SizeOf(Double);
end else
Match := False;
end
else if FRight.IsNumericType and (FOperator = toADD) then
begin
FDataType := FLeft.FDataType;
DataSize := GetFieldSize(FLeft.FDataType);
end
else
Match := False;
end
else if FLeft.IsStringType then
begin
if FRight.IsStringType and (FOperator = toADD) then
FDataType := ftString
else if FLeft.IsTemporalStringType and FRight.IsTemporalType and (FOperator = toSUB) then
begin
FLeft.ConvertStringToDateTime;
FDataType := ftFloat;
DataSize := SizeOf(Double);
end else
Match := False;
end
else
Match := False;
end;
if not Match then
DatabaseError(SExprTypeMis);
end;
procedure TFilterParser.TypeCheckLogicOp(Node: TExprNode);
begin
with Node do
begin
if FLeft <> nil then
if not FLeft.IsBooleanType then
DatabaseError(SExprTypeMis);
if FRight <> nil then
if not FRight.IsBooleanType then
DatabaseError(SExprTypeMis);
end;
end;
procedure TFilterParser.TypeCheckInOp(Node: TExprNode);
var
I: Integer;
TempNode: TExprNode;
Match: Boolean;
begin
Match := True;
with Node do
begin
for I := 0 to FArgs.Count - 1 do
begin
TempNode := TExprNode(FArgs[I]);
if FLeft.IsNumericType then
begin
if not TempNode.IsNumericType then
Match := False;
end
else if FLeft.IsStringType then
begin
if not TempNode.IsStringType then
Match := False;
end
else if FLeft.IsTemporalType then
begin
if TempNode.IsTemporalStringType then
TempNode.ConvertStringToDateTime
else
if not TempNode.IsTemporalType then
Match := False;
end
else if FLeft.IsBooleanType then
begin
if not TempNode.IsBooleanType then
Match := False;
end;
if not Match then Break;
end;
end;
if not Match then
DatabaseError(SExprTypeMis);
end;
procedure TFilterParser.TypeCheckRelationOp(Node: TExprNode);
var
Match: Boolean;
begin
Match := True;
with Node do
begin
if FLeft.IsNumericType then
begin
if not FRight.IsNumericType then
Match := False;
end
else if FLeft.IsTemporalType then
begin
if FRight.IsTemporalStringType then
FRight.ConvertStringToDateTime
else
if not FRight.IsTemporalType then
Match := False;
end
else if FLeft.IsStringType then
begin
if FRight.IsTemporalType and FLeft.IsTemporalStringType then
FLeft.ConvertStringToDateTime
else
if not FRight.IsStringType then
Match := False;
end
else if FLeft.IsBooleanType then
begin
if not FRight.IsBooleanType then
Match := False;
if (FOperator <> toEQ) or (FOperator <> toNE) then
Match := False;
end
else
Match := False;
end;
if not Match then
DatabaseError(SExprTypeMis);
end;
procedure TFilterParser.TypeCheckLikeOp(Node: TExprNode);
begin
with Node do
begin
if not FLeft.IsStringType or not FRight.IsStringType then
DatabaseError(SExprTypeMis);
end;
end;
procedure TFilterParser.TypeCheckFunction(Node: TExprNode);
begin
with Node do
begin
case FFunction of
tfUpper, tfLower,
tfTrim, tfTrimLeft, tfTrimRight:
begin
if (FArgs = nil) or (FArgs.Count <> 1) then
DatabaseError(SExprTypeMis);
if not TExprNode(FArgs[0]).IsStringType then
DatabaseError(SExprTypeMis);
FDataType := ftString;
end;
tfSubString:
begin
if (FArgs = nil) or (FArgs.Count <> 3) then
DatabaseError(SExprTypeMis);
if not (TExprNode(FArgs[0]).IsStringType and
TExprNode(FArgs[1]).IsIntegerType and
(TExprNode(FArgs[1]).FKind = enConst) and
TExprNode(FArgs[2]).IsIntegerType and
(TExprNode(FArgs[2]).FKind = enConst) ) then
DatabaseError(SExprTypeMis);
FDataType := ftString;
end;
tfYear, tfMonth, tfDay:
begin
if (FArgs = nil) or (FArgs.Count <> 1) then
DatabaseError(SExprTypeMis);
if not ((TExprNode(FArgs[0]).FDataType = ftDate) or
(TExprNode(FArgs[0]).FDataType = ftDateTime)) then
DatabaseError(SExprTypeMis);
FDataType := ftInteger;
DataSize := SizeOf(Integer);
end;
tfHour, tfMinute, tfSecond:
begin
if (FArgs = nil) or (FArgs.Count <> 1) then
DatabaseError(SExprTypeMis);
if not ((TExprNode(FArgs[0]).FDataType = ftTime) or
(TExprNode(FArgs[0]).FDataType = ftDateTime)) then
DatabaseError(SExprTypeMis);
FDataType := ftInteger;
DataSize := SizeOf(Integer);
end;
tfGetDate:
begin
if (FArgs <> nil) and (FArgs.Count <> 0) then
DatabaseError(SExprTypeMis);
FDataType := ftDateTime;
DataSize := SizeOf(Double);
FKind := enConst;
PDouble(FData)^ := TimeStampToMSecs(DateTimeToTimeStamp(Now));
end;
end;
end;
end;
{ TSQLWhereExprParser }
constructor TSQLWhereExprParser.Create(ADataSet: TTDEDataSet);
begin
inherited;
end;
function TSQLWhereExprParser.GetFieldValue(const Name: string): Variant;
begin
end;
{ TSQLParserBase }
constructor TSQLParserBase.Create(AQuery: TTinyQuery);
begin
inherited Create;
FQuery := AQuery;
FRowsAffected := 0;
end;
destructor TSQLParserBase.Destroy;
begin
inherited;
end;
function TSQLParserBase.SkipBeforeGetToken(Pos: PChar): PChar;
var
P: PChar;
begin
P := inherited SkipBeforeGetToken(Pos);
// 处理SQL注释标志“--”
if (P^ <> #0) and (P^ = '-') and (P[1] <> #0) and (P[1] = '-')then
begin
P := P + 2;
while (P^ <> #0) and (P^ <> #13) and (P^ <> #10) do Inc(P);
end;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
Result := P;
end;
function TSQLParserBase.InternalGetNextToken(Pos: PChar): PChar;
var
P, TokenStart: PChar;
L: Integer;
StrBuf: array[0..255] of Char;
begin
P := Pos;
case P^ of
'A'..'Z', 'a'..'z', '_', #$81..#$fe:
begin
TokenStart := P;
if not SysLocale.FarEast then
begin
Inc(P);
while P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '[', ']'] do Inc(P);
end
else
Skip(P, ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '[', ']']);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etSymbol;
end;
'[':
begin
Inc(P);
TokenStart := P;
P := AnsiStrScan(P, ']');
if P = nil then DatabaseError(SExprNameError);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etName;
Inc(P);
end;
'''':
begin
Inc(P);
L := 0;
while True do
begin
if P^ = #0 then DatabaseError(SExprStringError);
if P^ = '''' then
begin
Inc(P);
if P^ <> '''' then Break;
end;
if L < SizeOf(StrBuf) then
begin
StrBuf[L] := P^;
Inc(L);
end;
Inc(P);
end;
SetString(FTokenString, StrBuf, L);
FToken := etCharLiteral;
end;
'-', '0'..'9':
begin
if (P^ = '-') and
((FPrevToken = etCharLiteral) or (FPrevToken = etNumLiteral) or (FPrevToken = etName) or
(FPrevToken = etSymbol) or (FPrevToken = etRParen)) then
begin
FToken := etSUB;
Inc(P);
end else
begin
TokenStart := P;
Inc(P);
while (P^ in ['0'..'9', DecimalSeparator, 'e', 'E', '+', '-']) do
begin
if (P^ in ['+', '-']) and not ((P-1)^ in ['e', 'E']) and (P <> TokenStart) then Break;
Inc(P);
end;
if ((P-1)^ = ',') and (DecimalSeparator = ',') and (P^ = ' ') then Dec(P);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etNumLiteral;
end;
end;
'(':
begin
Inc(P);
FToken := etLParen;
end;
')':
begin
Inc(P);
FToken := etRParen;
end;
'*':
begin
Inc(P);
FToken := etAsterisk;
end;
',':
begin
Inc(P);
FToken := etComma;
end;
#0:
FToken := etEnd;
else
DatabaseErrorFmt(SSQLInvalidChar, [P^]);
end;
Result := P;
end;
procedure TSQLParserBase.Parse(const ASQL: string);
begin
Text := ASQL;
end;
{ TSQLSelectParser }
constructor TSQLSelectParser.Create(AQuery: TTinyQuery);
begin
inherited;
FWhereExprParser := TSQLWhereExprParser.Create(AQuery);
end;
destructor TSQLSelectParser.Destroy;
begin
FWhereExprParser.Free;
inherited;
end;
function TSQLSelectParser.ParseFrom: PChar;
function CheckOutOfSection: Boolean;
begin
Result := TokenSymbolIs('WHERE') or TokenSymbolIs('ORDER') or (FToken = etEnd);
end;
var
TableName, AliasTableName: string;
begin
Rewind;
while not TokenSymbolIs('FROM') and (FToken <> etEnd) do GetNextToken;
if TokenSymbolIs('FROM') then
begin
GetNextToken;
while True do
begin
TableName := '';
AliasTableName := '';
if CheckOutOfSection then
begin
if Length(FFromItems) = 0 then
DatabaseErrorFmt(SSQLInvalid, [Text]);
Break;
end;
if (FToken = etSymbol) or (FToken = etName) then
TableName := FTokenString
else
DatabaseErrorFmt(SSQLInvalid, [Text]);
GetNextToken;
if not CheckOutOfSection then
begin
if TokenSymbolIs('AS') then
begin
GetNextToken;
if CheckOutOfSection then
DatabaseErrorFmt(SSQLInvalid, [Text]);
if (FToken = etSymbol) or (FToken = etName) then
begin
AliasTableName := FTokenString;
GetNextToken;
end else
DatabaseErrorFmt(SSQLInvalid, [Text]);
end
else if (FToken = etSymbol) or (FToken = etName) then
begin
AliasTableName := FTokenString;
GetNextToken;
end;
end;
if FToken = etComma then
begin
GetNextToken;
if CheckOutOfSection then
DatabaseErrorFmt(SSQLInvalid, [Text]);
end else
begin
if not CheckOutOfSection then
DatabaseErrorFmt(SSQLInvalid, [Text]);
end;
if AliasTableName = '' then AliasTableName := TableName;
SetLength(FFromItems, Length(FFromItems) + 1);
with FFromItems[High(FFromItems)] do
begin
RealName := TableName;
AliasName := AliasTableName;
end;
end;
//for I := 0 to High(FFromItems) do
// Showmessage(FFromItems[i].Realname + ',' + FFromItems[i].Aliasname);
end else
begin
DatabaseErrorFmt(SSQLInvalid, [Text]);
end;
Result := FSourcePtr;
end;
function TSQLSelectParser.ParseSelect: PChar;
begin
Rewind;
GetNextToken; // 'SELECT'
GetNextToken;
// 含"TOP"子句
if TokenSymbolIs('TOP') then
begin
GetNextToken;
if FToken = etNumLiteral then
begin
FTopNum := StrToInt(FTokenString);
if FTopNum <= 0 then
DatabaseErrorFmt(SSQLInvalid, [Text]);
end else
DatabaseErrorFmt(SSQLInvalid, [Text]);
GetNextToken;
end;
{ TODO : 未完成 }
Result := FSourcePtr;
end;
procedure TSQLSelectParser.Parse(const ASQL: string);
begin
inherited;
SetLength(FSelectItems, 0);
SetLength(FFromItems, 0);
SetLength(FOrderByItems, 0);
FTopNum := -1;
GetNextToken;
ParseFrom;
ParseSelect;
end;
procedure TSQLSelectParser.Execute;
begin
// showmessage('test');
end;
{ TSQLParser }
constructor TSQLParser.Create(AQuery: TTinyQuery);
begin
inherited;
FSQLType := stNONE;
end;
destructor TSQLParser.Destroy;
begin
inherited;
end;
procedure TSQLParser.Parse(const ASQL: string);
begin
inherited;
GetNextToken;
if TokenSymbolIs('SELECT') then
FSQLType := stSELECT
else if TokenSymbolIs('INSERT') then
FSQLType := stINSERT
else if TokenSymbolIs('DELETE') then
FSQLType := stDELETE
else if TokenSymbolIs('UPDATE') then
FSQLType := stUPDATE
else begin
FSQLType := stNONE;
DatabaseErrorFmt(SSQLInvalid, [ASQL]);
end;
end;
procedure TSQLParser.Execute;
var
SQLParser: TSQLParserBase;
begin
case FSQLType of
stSELECT: SQLParser := TSQLSelectParser.Create(FQuery);
//stINSERT: SQLParser := TSQLInsertParser.Create(FQuery);
//stDELETE: SQLParser := TSQLDeleteParser.Create(FQuery);
//stUPDATE: SQLParser := TSQLUpdateParser.Create(FQuery);
else SQLParser := nil;
end;
try
if SQLParser <> nil then
begin
SQLParser.Parse(Text);
SQLParser.Execute;
FRowsAffected := SQLParser.RowsAffected;
end;
finally
SQLParser.Free;
end;
end;
{ TRecordsMap }
constructor TRecordsMap.Create;
begin
FList := TList.Create;
FByIndexIdx := -1;
end;
destructor TRecordsMap.Destroy;
begin
FList.Free;
inherited;
end;
procedure TRecordsMap.Add(Value: Integer);
begin
FList.Add(Pointer(Value));
end;
procedure TRecordsMap.Delete(Index: Integer);
begin
FList.Delete(Index);
end;
procedure TRecordsMap.Clear;
begin
FList.Clear;
end;
procedure TRecordsMap.DoAnd(Right, Result: TRecordsMap);
begin
end;
procedure TRecordsMap.DoOr(Right, Result: TRecordsMap);
begin
end;
procedure TRecordsMap.DoNot(Right, Result: TRecordsMap);
begin
end;
function TRecordsMap.GetCount: Integer;
begin
Result := FList.Count;
end;
function TRecordsMap.GetItem(Index: Integer): Integer;
begin
Result := Integer(FList.Items[Index]);
end;
procedure TRecordsMap.SetItem(Index, Value: Integer);
begin
FList.Items[Index] := Pointer(Value);
end;
{ TDataProcessAlgo }
constructor TDataProcessAlgo.Create(AOwner: TObject);
begin
FOwner := AOwner;
end;
destructor TDataProcessAlgo.Destroy;
begin
inherited;
end;
procedure TDataProcessAlgo.DoEncodeProgress(Percent: Integer);
begin
if Assigned(FOnEncodeProgress) then
FOnEncodeProgress(FOwner, Percent);
end;
procedure TDataProcessAlgo.DoDecodeProgress(Percent: Integer);
begin
if Assigned(FOnDecodeProgress) then
FOnDecodeProgress(FOwner, Percent);
end;
{ TCompressAlgo }
procedure TCompressAlgo.SetLevel(Value: TCompressLevel);
begin
end;
function TCompressAlgo.GetLevel: TCompressLevel;
begin
Result := clNormal;
end;
{ TEncryptAlgo }
procedure TEncryptAlgo.DoProgress(Current, Maximal: Integer; Encode: Boolean);
begin
if Encode then
begin
if Maximal = 0 then
DoEncodeProgress(0)
else
DoEncodeProgress(Round(Current / Maximal * 100));
end else
begin
if Maximal = 0 then
DoDecodeProgress(0)
else
DoDecodeProgress(Round(Current / Maximal * 100));
end;
end;
procedure TEncryptAlgo.InternalCodeStream(Source, Dest: TMemoryStream;
DataSize: Integer; Encode: Boolean);
const
EncMaxBufSize = 1024 * 4;
type
TCodeProc = procedure(const Source; var Dest; DataSize: Integer) of object;
var
Buf: PChar;
SPos: Integer;
DPos: Integer;
Len: Integer;
Proc: TCodeProc;
Size: Integer;
begin
if Source = nil then Exit;
if Encode then Proc := EncodeBuffer else Proc := DecodeBuffer;
if Dest = nil then Dest := Source;
if DataSize < 0 then
begin
DataSize := Source.Size;
Source.Position := 0;
end;
Buf := nil;
Size := DataSize;
DoProgress(0, Size, Encode);
try
Buf := AllocMem(EncMaxBufSize);
DPos := Dest.Position;
SPos := Source.Position;
while DataSize > 0 do
begin
Source.Position := SPos;
Len := DataSize;
if Len > EncMaxBufSize then Len := EncMaxBufSize;
Len := Source.Read(Buf^, Len);
SPos := Source.Position;
if Len <= 0 then Break;
Proc(Buf^, Buf^, Len);
Dest.Position := DPos;
Dest.Write(Buf^, Len);
DPos := Dest.Position;
Dec(DataSize, Len);
DoProgress(Size - DataSize, Size, Encode);
end;
finally
DoProgress(0, 0, Encode);
ReallocMem(Buf, 0);
end;
end;
procedure TEncryptAlgo.SetMode(Value: TEncryptMode);
begin
end;
function TEncryptAlgo.GetMode: TEncryptMode;
begin
Result := FTinyDBDefaultEncMode;
end;
procedure TEncryptAlgo.Done;
begin
end;
procedure TEncryptAlgo.EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer);
begin
InternalCodeStream(Source, Dest, DataSize, True);
end;
procedure TEncryptAlgo.DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer);
begin
InternalCodeStream(Source, Dest, DataSize, False);
end;
{ TDataProcessMgr }
constructor TDataProcessMgr.Create(AOwner: TTinyDBFileIO);
begin
FTinyDBFile := AOwner;
end;
destructor TDataProcessMgr.Destroy;
begin
FDPObject.Free;
inherited;
end;
class function TDataProcessMgr.CheckAlgoRegistered(const AlgoName: string): Integer;
begin
Result := -1;
end;
procedure TDataProcessMgr.EncodeStream(Source, Dest: TMemoryStream; DataSize: Integer);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
FDPObject.EncodeStream(Source, Dest, DataSize);
end;
procedure TDataProcessMgr.DecodeStream(Source, Dest: TMemoryStream; DataSize: Integer);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
FDPObject.DecodeStream(Source, Dest, DataSize);
end;
{ TCompressMgr }
function TCompressMgr.GetLevel: TCompressLevel;
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
Result := (FDPObject as TCompressAlgo).GetLevel;
end;
procedure TCompressMgr.SetLevel(const Value: TCompressLevel);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
(FDPObject as TCompressAlgo).SetLevel(Value);
end;
class function TCompressMgr.CheckAlgoRegistered(const AlgoName: string): Integer;
begin
Result := FCompressClassList.IndexOf(AlgoName);
if Result = -1 then
DatabaseErrorFmt(SCompressAlgNotFound, [AlgoName]);
end;
procedure TCompressMgr.SetAlgoName(const Value: string);
var
I: Integer;
CmpClass: TCompressAlgoClass;
NewObj: Boolean;
begin
I := CheckAlgoRegistered(Value);
if I >= 0 then
begin
CmpClass := Pointer(FCompressClassList.Objects[I]);
if FDPObject = nil then NewObj := True
else if FDPObject.ClassType <> CmpClass then NewObj := True
else NewObj := False;
if NewObj then
begin
FDPObject.Free;
FDPObject := CmpClass.Create(FTinyDBFile);
if FTinyDBFile <> nil then
begin
FDPObject.OnEncodeProgress := FTinyDBFile.OnCompressProgressEvent;
FDPObject.OnDecodeProgress := FTinyDBFile.OnUncompressProgressEvent;
end;
end;
end;
end;
{ TEncryptMgr }
function TEncryptMgr.GetMode: TEncryptMode;
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
Result := (FDPObject as TEncryptAlgo).GetMode;
end;
procedure TEncryptMgr.SetMode(const Value: TEncryptMode);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
(FDPObject as TEncryptAlgo).SetMode(Value);
end;
procedure TEncryptMgr.InitKey(const Key: string);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
(FDPObject as TEncryptAlgo).InitKey(Key);
end;
procedure TEncryptMgr.Done;
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
(FDPObject as TEncryptAlgo).Done;
end;
class function TEncryptMgr.CheckAlgoRegistered(const AlgoName: string): Integer;
begin
Result := FEncryptClassList.IndexOf(AlgoName);
if Result = -1 then
DatabaseErrorFmt(SEncryptAlgNotFound, [AlgoName]);
end;
procedure TEncryptMgr.SetAlgoName(const Value: string);
var
I: Integer;
EncClass: TEncryptAlgoClass;
NewObj: Boolean;
begin
I := CheckAlgoRegistered(Value);
if I >= 0 then
begin
EncClass := Pointer(FEncryptClassList.Objects[I]);
if FDPObject = nil then NewObj := True
else if FDPObject.ClassType <> EncClass then NewObj := True
else NewObj := False;
if NewObj then
begin
FDPObject.Free;
FDPObject := EncClass.Create(FTinyDBFile);
if FTinyDBFile <> nil then
begin
FDPObject.OnEncodeProgress := FTinyDBFile.OnEncryptProgressEvent;
FDPObject.OnDecodeProgress := FTinyDBFile.OnDecryptProgressEvent;
end;
end;
end;
end;
procedure TEncryptMgr.DecodeStream(Source, Dest: TMemoryStream;
DataSize: Integer);
begin
inherited;
Done;
end;
procedure TEncryptMgr.EncodeStream(Source, Dest: TMemoryStream;
DataSize: Integer);
begin
inherited;
Done;
end;
procedure TEncryptMgr.EncodeBuffer(const Source; var Dest;
DataSize: Integer);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
(FDPObject as TEncryptAlgo).EncodeBuffer(Source, Dest, DataSize);
Done;
end;
procedure TEncryptMgr.DecodeBuffer(const Source; var Dest;
DataSize: Integer);
begin
if not Assigned(FDPObject) then DatabaseError(SGeneralError);
(FDPObject as TEncryptAlgo).DecodeBuffer(Source, Dest, DataSize);
Done;
end;
{ TFieldBufferItem }
constructor TFieldBufferItem.Create;
begin
inherited;
FActive := True;
end;
destructor TFieldBufferItem.Destroy;
begin
FreeBuffer;
inherited;
end;
function TFieldBufferItem.GetAsString: string;
var
TempTimeStamp: TTimeStamp;
begin
try
if FFieldType in StringFieldTypes then
Result := PChar(FBuffer)
else if FFieldType in BlobFieldTypes then
Result := PChar(TMemoryStream(FBuffer).Memory)
else if FFieldType in [ftInteger, ftAutoInc] then
Result := IntToStr(PInteger(FBuffer)^)
else if FFieldType in [ftWord] then
Result := IntToStr(PWord(FBuffer)^)
else if FFieldType in [ftLargeint] then
Result := IntToStr(PLargeInt(FBuffer)^)
else if FFieldType in [ftSmallint] then
Result := IntToStr(PSmallInt(FBuffer)^)
else if FFieldType in [ftFloat, ftCurrency] then
Result := FloatToStr(PDouble(FBuffer)^)
else if FFieldType in [ftBoolean] then
if PWordBool(FBuffer)^ then Result := STextTrue
else Result := STextFalse
else if FFieldType in [ftDateTime] then
Result := DateTimeToStr(TimeStampToDateTime(MSecsToTimeStamp(PDouble(FBuffer)^)))
else if FFieldType in [ftDate] then
begin
TempTimeStamp.Date := PInteger(FBuffer)^;
TempTimeStamp.Time := 0;
Result := DateToStr(TimeStampToDateTime(TempTimeStamp));
end
else if FFieldType in [ftTime] then
begin
TempTimeStamp.Date := Trunc(Date);
TempTimeStamp.Time := PInteger(FBuffer)^;
Result := TimeToStr(TimeStampToDateTime(TempTimeStamp));
end
else
Result := '';
except
Result := '';
end;
end;
function TFieldBufferItem.GetDataBuf: Pointer;
begin
if FFieldType in BlobFieldTypes then
Result := TMemoryStream(FBuffer).Memory
else
Result := FBuffer;
end;
procedure TFieldBufferItem.AllocBuffer;
begin
FreeBuffer;
if FFieldType in BlobFieldTypes then
FBuffer := TMemoryStream.Create
else
FBuffer := AllocMem(FFieldSize);
FMemAlloc := True;
end;
procedure TFieldBufferItem.FreeBuffer;
begin
if FMemAlloc then
begin
if FFieldType in BlobFieldTypes then
TMemoryStream(FBuffer).Free
else
FreeMem(FBuffer);
FMemAlloc := False;
end;
end;
function TFieldBufferItem.IsBlob: Boolean;
begin
Result := FFieldType in BlobFieldTypes;
end;
{ TFieldBuffers }
constructor TFieldBuffers.Create;
begin
FItems := TList.Create;
end;
destructor TFieldBuffers.Destroy;
begin
Clear;
FItems.Free;
inherited;
end;
function TFieldBuffers.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TFieldBuffers.GetItem(Index: Integer): TFieldBufferItem;
begin
Result := TFieldBufferItem(FItems[Index]);
end;
procedure TFieldBuffers.Add(FieldType: TFieldType; FieldSize: Integer);
var
FieldBufferItem: TFieldBufferItem;
begin
FieldBufferItem := TFieldBufferItem.Create;
FieldBufferItem.FieldType := FieldType;
FieldBufferItem.FieldSize := FieldSize;
FieldBufferItem.AllocBuffer;
FItems.Add(FieldBufferItem);
end;
procedure TFieldBuffers.Add(Buffer: Pointer; FieldType: TFieldType; FieldSize: Integer);
var
FieldBufferItem: TFieldBufferItem;
begin
FieldBufferItem := TFieldBufferItem.Create;
if FieldType in BlobFieldTypes then
FieldBufferItem.FBuffer := PMemoryStream(Buffer)^
else
FieldBufferItem.FBuffer := Buffer;
FieldBufferItem.FieldType := FieldType;
FieldBufferItem.FieldSize := FieldSize;
FItems.Add(FieldBufferItem);
end;
procedure TFieldBuffers.Delete(Index: Integer);
begin
TFieldBufferItem(FItems[Index]).Free;
FItems.Delete(Index);
end;
procedure TFieldBuffers.Clear;
var
I: Integer;
begin
for I := 0 to FItems.Count - 1 do
TFieldBufferItem(FItems[I]).Free;
FItems.Clear;
end;
{ TTinyDBFileStream }
constructor TTinyDBFileStream.Create(const FileName: string; Mode: Word);
begin
inherited;
FFlushed := True;
end;
{$IFDEF COMPILER_6_UP}
constructor TTinyDBFileStream.Create(const FileName: string; Mode: Word; Rights: Cardinal);
begin
inherited;
FFlushed := True;
end;
{$ENDIF}
function TTinyDBFileStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := inherited Write(Buffer, Count);
FFlushed := False;
end;
procedure TTinyDBFileStream.Flush;
begin
FlushFileBuffers(Handle);
FFlushed := True;
end;
{ TTinyDBFileIO }
constructor TTinyDBFileIO.Create(AOwner: TTinyDatabase);
begin
FDatabase := AOwner;
if FDatabase <> nil then
begin
FMediumType := FDatabase.MediumType;
FExclusive := FDatabase.Exclusive;
end;
FCompressMgr := TCompressMgr.Create(Self);
FEncryptMgr := TEncryptMgr.Create(Self);
InitializeCriticalSection(FDPCSect);
end;
destructor TTinyDBFileIO.Destroy;
begin
Close;
FCompressMgr.Free;
FEncryptMgr.Free;
DeleteCriticalSection(FDPCSect);
inherited;
end;
function TTinyDBFileIO.GetIsOpen: Boolean;
begin
Result := FDBStream <> nil;
end;
function TTinyDBFileIO.GetFlushed: Boolean;
begin
if FDBStream is TTinyDBFileStream then
Result := (FDBStream as TTinyDBFileStream).Flushed
else
Result := True;
end;
//-----------------------------------------------------------------------------
// 对Stream中的数据进行解码(解密和解压)
// Encrypt: 是否解密
// Compress: 是否解压
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.DecodeMemoryStream(SrcStream, DstStream: TMemoryStream; Encrypt, Compress: Boolean);
var
TempStream: TMemoryStream;
begin
EnterCriticalSection(FDPCSect);
try
SrcStream.Position := 0;
if SrcStream <> DstStream then DstStream.Clear;
// 如果不用任何处理
if not Encrypt and not Compress then
begin
if SrcStream <> DstStream then DstStream.CopyFrom(SrcStream, 0);
end;
// 解密
if Encrypt then
begin
FEncryptMgr.DecodeStream(SrcStream, DstStream, SrcStream.Size);
end;
// 解压
if Compress then
begin
if Encrypt then
begin
TempStream := TMemoryStream.Create;
TempStream.LoadFromStream(DstStream);
DstStream.Clear;
end else
TempStream := SrcStream;
TempStream.Position := 0;
try
FCompressMgr.DecodeStream(TempStream, DstStream, TempStream.Size);
finally
if TempStream <> SrcStream then
TempStream.Free;
end;
end;
finally
LeaveCriticalSection(FDPCSect);
end;
end;
//-----------------------------------------------------------------------------
// 对Buffer中的数据进行解码(解密)
// Encrypt: 是否解密
// 注: SrcBuffer,DstBuffer中不存在格式,只是普通的内存块
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.DecodeMemoryBuffer(SrcBuffer, DstBuffer: PChar; DataSize: Integer; Encrypt: Boolean);
begin
EnterCriticalSection(FDPCSect);
try
if Encrypt then
begin
FEncryptMgr.DecodeBuffer(SrcBuffer^, DstBuffer^, DataSize);
end else
begin
Move(SrcBuffer^, DstBuffer^, DataSize);
end;
finally
LeaveCriticalSection(FDPCSect);
end;
end;
//-----------------------------------------------------------------------------
// 对Stream中的数据进行编码(压缩和加密)
// Encrypt: 是否加密
// Compress: 是否压缩
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.EncodeMemoryStream(SrcStream, DstStream: TMemoryStream; Encrypt, Compress: Boolean);
var
TempStream: TMemoryStream;
begin
EnterCriticalSection(FDPCSect);
try
SrcStream.Position := 0;
if SrcStream <> DstStream then DstStream.Clear;
// 如果不用任何处理
if not Encrypt and not Compress then
begin
if SrcStream <> DstStream then DstStream.CopyFrom(SrcStream, 0);
end;
// 压缩
if Compress then
begin
FCompressMgr.EncodeStream(SrcStream, DstStream, SrcStream.Size)
end;
// 加密
if Encrypt then
begin
if Compress then
begin
TempStream := TMemoryStream.Create;
TempStream.LoadFromStream(DstStream);
DstStream.Clear;
end else
TempStream := SrcStream;
TempStream.Position := 0;
try
FEncryptMgr.EncodeStream(TempStream, DstStream, TempStream.Size);
finally
if TempStream <> SrcStream then
TempStream.Free;
end;
end;
finally
LeaveCriticalSection(FDPCSect);
end;
end;
//-----------------------------------------------------------------------------
// 对Buffer中的数据进行编码(加密)
// Encrypt: 是否加密
// 注: SrcBuffer,DstBuffer中不存在格式,只是普通的内存块
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.EncodeMemoryBuffer(SrcBuffer, DstBuffer: PChar; DataSize: Integer; Encrypt: Boolean);
begin
EnterCriticalSection(FDPCSect);
try
if Encrypt then
begin
FEncryptMgr.EncodeBuffer(SrcBuffer^, DstBuffer^, DataSize);
end else
begin
Move(SrcBuffer^, DstBuffer^, DataSize);
end;
finally
LeaveCriticalSection(FDPCSect);
end;
end;
procedure TTinyDBFileIO.OnCompressProgressEvent(Sender: TObject; Percent: Integer);
begin
if Assigned(FDatabase.FOnCompressProgress) then
FDatabase.FOnCompressProgress(FDatabase, Percent);
end;
procedure TTinyDBFileIO.OnUncompressProgressEvent(Sender: TObject; Percent: Integer);
begin
if Assigned(FDatabase.FOnUncompressProgress) then
FDatabase.FOnUncompressProgress(FDatabase, Percent);
end;
procedure TTinyDBFileIO.OnEncryptProgressEvent(Sender: TObject; Percent: Integer);
begin
if Assigned(FDatabase.FOnEncryptProgress) then
FDatabase.FOnEncryptProgress(FDatabase, Percent);
end;
procedure TTinyDBFileIO.OnDecryptProgressEvent(Sender: TObject; Percent: Integer);
begin
if Assigned(FDatabase.FOnDecryptProgress) then
FDatabase.FOnDecryptProgress(FDatabase, Percent);
end;
function TTinyDBFileIO.CheckDupTableName(const TableName: string): Boolean;
var
TableTab: TTableTab;
TableHeader: TTableHeader;
I: Integer;
begin
Result := False;
ReadTableTab(TableTab);
for I := 0 to TableTab.TableCount - 1 do
begin
ReadTableHeader(I, TableHeader);
if StrIComp(TableHeader.TableName, PChar(TableName)) = 0 then
begin
Result := True;
Break;
end;
end;
end;
function TTinyDBFileIO.CheckDupIndexName(var TableHeader: TTableHeader; const IndexName: string): Boolean;
var
I: Integer;
begin
for I := 0 to TableHeader.IndexCount - 1 do
begin
if StrIComp(TableHeader.IndexHeader[I].IndexName, PChar(IndexName)) = 0 then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
//-----------------------------------------------------------------------------
// 检查是否有多个Primary索引
// 返回值:有多个则返回True
//-----------------------------------------------------------------------------
function TTinyDBFileIO.CheckDupPrimaryIndex(var TableHeader: TTableHeader; IndexOptions: TTDIndexOptions): Boolean;
var
I: Integer;
PriExists: Boolean;
begin
Result := False;
if (tiPrimary in IndexOptions) then
begin
PriExists := False;
for I := 0 to TableHeader.IndexCount - 1 do
begin
if tiPrimary in TableHeader.IndexHeader[I].IndexOptions then
begin
PriExists := True;
Break;
end;
end;
if PriExists then Result := True;
end;
end;
procedure TTinyDBFileIO.CheckValidFields(Fields: array of TFieldItem);
var
I, J: Integer;
AutoIncFieldCount: Integer;
begin
if Length(Fields) >= tdbMaxField then
DatabaseError(STooManyFields);
if Length(Fields) = 0 then
DatabaseError(SFieldNameExpected);
for I := 0 to High(Fields) do
begin
if not (Fields[I].FieldType in TinyDBFieldTypes) then
DatabaseErrorFmt(SBadFieldType, [Fields[I].FieldName]);
if not IsValidDBName(Fields[I].FieldName) then
DatabaseErrorFmt(SInvalidFieldName, [Fields[I].FieldName]);
if (Fields[I].FieldType in BlobFieldTypes) then
begin
if Fields[I].DataSize <> 0 then DatabaseError(SInvalidFieldSize);
end else if (Fields[I].FieldType in StringFieldTypes) then
begin
if (Fields[I].DataSize <= 0) or (Fields[I].DataSize > tdbMaxTextFieldSize) then
DatabaseError(SInvalidFieldSize);
end;
end;
for I := 0 to High(Fields)-1 do
for J := I+1 to High(Fields) do
begin
if CompareText(Fields[I].FieldName, Fields[J].FieldName) = 0 then
DatabaseErrorFmt(SDuplicateFieldName, [Fields[I].FieldName]);
end;
// 检查是否含有多个AutoInc字段
AutoIncFieldCount := 0;
for I := 0 to High(Fields)-1 do
if Fields[I].FieldType = ftAutoInc then Inc(AutoIncFieldCount);
if AutoIncFieldCount > 1 then
DatabaseError(SDuplicateAutoIncField);
end;
procedure TTinyDBFileIO.CheckValidIndexFields(FieldNames: array of string; IndexOptions: TTDIndexOptions; var TableHeader: TTableHeader);
var
I, J: Integer;
begin
if Length(FieldNames) = 0 then
DatabaseError(SFieldNameExpected);
for I := 0 to High(FieldNames)-1 do
for J := I+1 to High(FieldNames) do
begin
if StrIComp(PChar(FieldNames[I]), PChar(FieldNames[J])) = 0 then
DatabaseErrorFmt(SDuplicateFieldName, [FieldNames[I]]);
end;
for I := 0 to High(FieldNames) do
begin
if GetFieldIdxByName(TableHeader, FieldNames[I]) = -1 then
DatabaseErrorFmt(SFieldNotFound, [FieldNames[I]]);
end;
end;
function TTinyDBFileIO.GetFieldIdxByName(const TableHeader: TTableHeader; const FieldName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to TableHeader.FieldCount - 1 do
begin
if StrIComp(TableHeader.FieldTab[I].FieldName, PChar(FieldName)) = 0 then
begin
Result := I;
Break;
end;
end;
end;
function TTinyDBFileIO.GetIndexIdxByName(const TableHeader: TTableHeader; const IndexName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to TableHeader.IndexCount - 1 do
begin
if StrIComp(TableHeader.IndexHeader[I].IndexName, PChar(IndexName)) = 0 then
begin
Result := I;
Break;
end;
end;
end;
function TTinyDBFileIO.GetTableIdxByName(const TableName: string): Integer;
var
TableHeader: TTableHeader;
I: Integer;
begin
Result := -1;
for I := 0 to FTableTab.TableCount - 1 do
begin
ReadTableHeader(I, TableHeader);
if StrIComp(TableHeader.TableName, PChar(TableName)) = 0 then
begin
Result := I;
Break;
end;
end;
end;
function TTinyDBFileIO.GetTempFileName: string;
var
Buf: array[0..MAX_PATH] of Char;
begin
GetTempPath(MAX_PATH, Buf);
Windows.GetTempFileName(Buf, 'TDB', 0, Buf);
Result := Buf;
end;
function TTinyDBFileIO.ReCreate(NewCompressBlob: Boolean; NewCompressLevel: TCompressLevel; const NewCompressAlgoName: string;
NewEncrypt: Boolean; const NewEncAlgoName, OldPassword, NewPassword: string; NewCRC32: Boolean): Boolean;
var
DstTinyDatabase: TTinyDataBase;
SrcTinyTable, DstTinyTable: TTinyTable;
DstFileName: string;
RealNewEncAlgoName: string;
Comments: string;
ExtData: TExtData;
TableHeader: TTableHeader;
TableIdx, FieldIdx, IndexIdx, RecIdx: Integer;
I: Integer;
FieldNames: array of string;
FieldItems: array of TFieldItem;
SaveKeepConn: Boolean;
begin
SaveKeepConn := FDatabase.KeepConnection;
FDatabase.KeepConnection := True;
try
DstTinyDatabase := TTinyDatabase.Create(nil);
SrcTinyTable := TTinyTable.Create(nil);
DstTinyTable := TTinyTable.Create(nil);
try
DstFileName := GetTempFileName;
// 调整加密算法
RealNewEncAlgoName := NewEncAlgoName;
if NewEncrypt then
if FEncryptClassList.IndexOf(NewEncAlgoName) = -1 then
RealNewEncAlgoName := FTinyDBDefaultEncAlgo;
// 建数据库
DstTinyDatabase.CreateDatabase(DstFileName, NewCompressBlob, NewCompressLevel, NewCompressAlgoName,
NewEncrypt, RealNewEncAlgoName, NewPassword, NewCRC32);
DstTinyDatabase.DatabaseName := DstFileName;
DstTinyDatabase.Password := NewPassword;
DstTinyDatabase.Open;
GetComments(Comments, OldPassword);
GetExtData(@ExtData);
DstTinyDatabase.SetComments(Comments);
DstTinyDatabase.SetExtData(@ExtData, SizeOf(ExtData));
SrcTinyTable.DatabaseName := FDatabase.DatabaseName;
for TableIdx := 0 to FTableTab.TableCount - 1 do
begin
ReadTableHeader(TableIdx, TableHeader);
SrcTinyTable.TableName := TableHeader.TableName;
SrcTinyTable.Password := OldPassword;
SrcTinyTable.Open;
// 建表
SetLength(FieldItems, SrcTinyTable.FieldDefs.Count);
for I := 0 to SrcTinyTable.FieldDefs.Count - 1 do
begin
FieldItems[I].FieldName := SrcTinyTable.FieldDefs[I].Name;
FieldItems[I].FieldType := SrcTinyTable.FieldDefs[I].DataType;
FieldItems[I].DataSize := SrcTinyTable.FieldDefs[I].Size;
end;
DstTinyDatabase.CreateTable(SrcTinyTable.TableName, FieldItems);
// 建立索引
for IndexIdx := 0 to SrcTinyTable.FTableIO.IndexDefs.Count - 1 do
begin
if SrcTinyTable.FieldDefs[SrcTinyTable.FTableIO.IndexDefs[IndexIdx].FieldIdxes[0]].DataType = ftAutoInc then Continue;
SetLength(FieldNames, Length(SrcTinyTable.FTableIO.IndexDefs[IndexIdx].FieldIdxes));
for FieldIdx := 0 to High(SrcTinyTable.FTableIO.IndexDefs[IndexIdx].FieldIdxes) do
begin
I := SrcTinyTable.FTableIO.IndexDefs[IndexIdx].FieldIdxes[FieldIdx];
FieldNames[FieldIdx] := SrcTinyTable.FieldDefs[I].Name;
end;
DstTinyDatabase.CreateIndex(SrcTinyTable.TableName, SrcTinyTable.FTableIO.IndexDefs[IndexIdx].Name,
SrcTinyTable.FTableIO.IndexDefs[IndexIdx].Options, FieldNames);
end;
SrcTinyTable.Close;
end;
// 拷贝记录
DstTinyTable.DatabaseName := DstFileName;
for TableIdx := 0 to FTableTab.TableCount - 1 do
begin
ReadTableHeader(TableIdx, TableHeader);
SrcTinyTable.TableName := TableHeader.TableName;
SrcTinyTable.Password := OldPassword;
SrcTinyTable.Open;
DstTinyTable.TableName := TableHeader.TableName;
DstTinyTable.Password := NewPassword;
DstTinyTable.Open;
DstTinyTable.BeginUpdate;
for RecIdx := 0 to SrcTinyTable.RecordCount - 1 do
begin
DoOperationProgressEvent(FDatabase, RecIdx + 1, SrcTinyTable.RecordCount);
DstTinyTable.Append;
for I := 0 to SrcTinyTable.Fields.Count - 1 do
DstTinyTable.Fields[I].Value := SrcTinyTable.Fields[I].Value;
DstTinyTable.Post;
SrcTinyTable.Next;
end;
SrcTinyTable.Close;
DstTinyTable.EndUpdate;
DstTinyTable.Close;
end;
finally
DstTinyTable.Free;
SrcTinyTable.Free;
DstTinyDatabase.Free;
end;
Lock;
try
Close;
try
Result := CopyFile(PChar(DstFileName), PChar(FDatabaseName), False);
DeleteFile(DstFileName);
finally
Open(FDatabaseName, FMediumType, FExclusive);
end;
finally
Unlock;
end;
finally
FDatabase.KeepConnection := SaveKeepConn;
end;
end;
procedure TTinyDBFileIO.Open(const ADatabaseName: string; AMediumType: TTinyDBMediumType; AExclusive: Boolean);
var
DBStream: TStream;
OpenMode: Word;
begin
if FDBStream = nil then
begin
FMediumType := AMediumType;
FExclusive := AExclusive;
case AMediumType of
mtDisk:
begin
if not FileExists(ADatabaseName) then
DatabaseErrorFmt(SFOpenError, [ADatabaseName]);
if not CheckValidTinyDB(ADatabaseName) then
DatabaseErrorFmt(SInvalidDatabase, [ADatabaseName]);
CheckTinyDBVersion(ADatabaseName);
FFileIsReadOnly := GetFileAttributes(PChar(ADatabaseName)) and FILE_ATTRIBUTE_READONLY > 0;
if FFileIsReadOnly then OpenMode := fmOpenRead
else OpenMode := fmOpenReadWrite;
if AExclusive then OpenMode := OpenMode or fmShareExclusive
else OpenMode := OpenMode or fmShareDenyNone;
FDBStream := TTinyDBFileStream.Create(ADatabaseName, OpenMode);
end;
mtMemory:
begin
if not IsPointerStr(ADatabaseName) then
DatabaseErrorFmt(SInvalidDatabaseName, [ADatabaseName]);
DBStream := StrToPointer(ADatabaseName);
if not CheckValidTinyDB(DBStream) then
DatabaseErrorFmt(SInvalidDatabase, [ADatabaseName]);
CheckTinyDBVersion(DBStream);
FDBStream := DBStream;
end;
end;
FDatabaseName := ADatabaseName;
InitDBOptions;
InitTableTab;
end;
end;
procedure TTinyDBFileIO.Close;
begin
if FMediumType = mtDisk then
FDBStream.Free;
FDBStream := nil;
// FDatabaseName := '';
end;
procedure TTinyDBFileIO.Flush;
begin
if FDBStream is TTinyDBFileStream then
(FDBStream as TTinyDBFileStream).Flush;
end;
procedure TTinyDBFileIO.InitDBOptions;
begin
ReadDBOptions(FDBOptions);
if FDBOptions.CompressBlob then
FCompressMgr.SetAlgoName(FDBOptions.CompressAlgoName);
if FDBOptions.Encrypt then
begin
FEncryptMgr.SetAlgoName(FDBOptions.EncryptAlgoName);
FEncryptMgr.Mode := FDBOptions.EncryptMode;
end;
end;
procedure TTinyDBFileIO.InitTableTab;
begin
ReadTableTab(FTableTab);
end;
procedure TTinyDBFileIO.DoOperationProgressEvent(ADatabase: TTinyDatabase; Pos, Max: Integer);
begin
if Assigned(ADatabase.FOnOperationProgress) then
begin
if Max = 0 then
ADatabase.FOnOperationProgress(ADatabase, 0)
else
ADatabase.FOnOperationProgress(ADatabase, Round(Pos / Max * 100));
end;
end;
function TTinyDBFileIO.SetPassword(const Value: string): Boolean;
begin
Result := False;
if not IsOpen then Exit;
if FDBOptions.Encrypt then
begin
if Hash(FTinyDBCheckPwdHashClass, Value) =
AnsiString(FDBOptions.HashPassword) then
begin
FEncryptMgr.InitKey(Value);
Result := True;
end else
begin
Result := False;
end;
end else
Result := True;
end;
procedure TTinyDBFileIO.Lock;
var
LockWaitTime, LockRetryCount: Integer;
RetryCount: Integer;
begin
if not IsOpen then Exit;
LockRetryCount := FDatabase.Session.LockRetryCount;
LockWaitTime := FDatabase.Session.LockWaitTime;
case FMediumType of
mtMemory:
begin
end;
mtDisk:
begin
RetryCount := 0;
while not LockFile((FDBStream as TFileStream).Handle, 1, 0, 1, 0) do
begin
Inc(RetryCount);
if (LockRetryCount <> 0) and (RetryCount > LockRetryCount) then
begin
DatabaseError(SWaitForUnlockTimeOut);
end;
Sleep(LockWaitTime);
end;
end;
end;
end;
procedure TTinyDBFileIO.Unlock;
begin
if not IsOpen then Exit;
case FMediumType of
mtMemory:
begin
end;
mtDisk:
begin
UnlockFile((FDBStream as TFileStream).Handle, 1, 0, 1, 0);
end;
end;
end;
procedure TTinyDBFileIO.ReadBuffer(var Buffer; Position, Count: Longint);
begin
FDBStream.Position := Position;
FDBStream.Read(Buffer, Count);
end;
procedure TTinyDBFileIO.ReadDBVersion(var Dest: string);
var
FileHeader: TFileHeader;
begin
FDBStream.Position := 0;
FDBStream.Read(FileHeader, SizeOf(FileHeader));
Dest := FileHeader.FileFmtVer;
end;
procedure TTinyDBFileIO.ReadExtDataBlock(var Dest: TExtDataBlock);
begin
FDBStream.Position := SizeOf(TFileHeader);
FDBStream.Read(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.WriteExtDataBlock(var Dest: TExtDataBlock);
begin
FDBStream.Position := SizeOf(TFileHeader);
FDBStream.Write(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.ReadDBOptions(var Dest: TDBOptions);
begin
FDBStream.Position := SizeOf(TFileHeader) + SizeOf(TExtDataBlock);
FDBStream.Read(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.WriteDBOptions(var Dest: TDBOptions);
begin
FDBStream.Position := SizeOf(TFileHeader) + SizeOf(TExtDataBlock);
FDBStream.Write(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.ReadTableTab(var Dest: TTableTab);
begin
FDBStream.Position := SizeOf(TFileHeader) + SizeOf(TExtDataBlock) + SizeOf(TDBOptions);
FDBStream.Read(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.WriteTableTab(var Dest: TTableTab);
begin
FDBStream.Position := SizeOf(TFileHeader) + SizeOf(TExtDataBlock) + SizeOf(TDBOptions);
FDBStream.Write(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.ReadTableHeader(TableIdx: Integer; var Dest: TTableHeader);
begin
FDBStream.Position := FTableTab.TableHeaderOffset[TableIdx];
FDBStream.Read(Dest, SizeOf(Dest));
end;
procedure TTinyDBFileIO.WriteTableHeader(TableIdx: Integer; var Dest: TTableHeader);
begin
FDBStream.Position := FTableTab.TableHeaderOffset[TableIdx];
FDBStream.Write(Dest, SizeOf(Dest));
end;
class function TTinyDBFileIO.CheckValidTinyDB(ADBStream: TStream): Boolean;
var
FileHeader: TFileHeader;
begin
ADBStream.Position := 0;
ADBStream.Read(FileHeader, SizeOf(FileHeader));
if FileHeader.SoftName = tdbSoftName then Result := True
else Result := False;
end;
class function TTinyDBFileIO.CheckValidTinyDB(const FileName: string): Boolean;
var
DBStream: TStream;
begin
DBStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
Result := CheckValidTinyDB(DBStream);
finally
DBStream.Free;
end;
end;
class function TTinyDBFileIO.CheckTinyDBVersion(ADBStream: TStream): Boolean;
const
tdbFileFmtVer100 = '1.00';
var
FileHeader: TFileHeader;
begin
ADBStream.Position := 0;
ADBStream.Read(FileHeader, SizeOf(FileHeader));
if FileHeader.FileFmtVer = tdbFileFmtVer100 then
DatabaseError(SInvalidVersion100);
if FileHeader.FileFmtVer > tdbFileFmtVer then
DatabaseError(SInvalidVersionTooHigh);
Result := True;
end;
class function TTinyDBFileIO.CheckTinyDBVersion(const FileName: string): Boolean;
var
DBStream: TStream;
begin
DBStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
Result := CheckTinyDBVersion(DBStream);
finally
DBStream.Free;
end;
end;
procedure TTinyDBFileIO.GetTableNames(List: TStrings);
var
I: Integer;
TableHeader: TTableHeader;
begin
List.BeginUpdate;
List.Clear;
for I := 0 to FTableTab.TableCount - 1 do
begin
ReadTableHeader(I, TableHeader);
List.Add(TableHeader.TableName);
end;
List.EndUpdate;
end;
procedure TTinyDBFileIO.GetFieldNames(const TableName: string; List: TStrings);
var
I, J: Integer;
TableHeader: TTableHeader;
begin
List.BeginUpdate;
List.Clear;
for I := 0 to FTableTab.TableCount - 1 do
begin
ReadTableHeader(I, TableHeader);
if CompareText(TableName, TableHeader.TableName) = 0 then
begin
for J := 0 to TableHeader.FieldCount - 1 do
List.Add(TableHeader.FieldTab[J].FieldName);
end;
end;
List.EndUpdate;
end;
procedure TTinyDBFileIO.GetIndexNames(const TableName: string; List: TStrings);
var
I, J: Integer;
TableHeader: TTableHeader;
begin
List.BeginUpdate;
List.Clear;
for I := 0 to FTableTab.TableCount - 1 do
begin
ReadTableHeader(I, TableHeader);
if CompareText(TableName, TableHeader.TableName) = 0 then
begin
for J := 0 to TableHeader.IndexCount - 1 do
List.Add(TableHeader.IndexHeader[J].IndexName);
end;
end;
List.EndUpdate;
end;
procedure TTinyDBFileIO.ReadFieldData(DstStream: TMemoryStream; RecTabItemOffset, DiskFieldOffset, FieldSize: Integer;
IsBlob: Boolean; ShouldEncrypt, ShouldCompress: Boolean);
var
RecTabItem: TRecordTabItem;
FieldDataOffset: Integer;
begin
FDBStream.Position := RecTabItemOffset;
FDBStream.Read(RecTabItem, SizeOf(RecTabItem));
FieldDataOffset := RecTabItem.DataOffset + DiskFieldOffset;
ReadFieldData(DstStream, FieldDataOffset, FieldSize, IsBlob, ShouldEncrypt, ShouldCompress);
end;
procedure TTinyDBFileIO.ReadFieldData(DstStream: TMemoryStream; FieldDataOffset, FieldSize: Integer;
IsBlob: Boolean; ShouldEncrypt, ShouldCompress: Boolean);
var
RecBuf: array of Char;
BlobOffset, BlobSize: Integer;
TmpStream: TMemoryStream;
begin
TmpStream := TMemoryStream.Create;
try
// 读取字段数据
FDBStream.Position := FieldDataOffset;
// 如果是BLOB字段
if IsBlob then
begin
SetLength(RecBuf, FieldSize);
FDBStream.Read(RecBuf[0], FieldSize);
BlobOffset := PBlobFieldHeader(@RecBuf[0])^.DataOffset;
BlobSize := PBlobFieldHeader(@RecBuf[0])^.DataSize;
FDBStream.Position := BlobOffset;
TmpStream.SetSize(BlobSize);
FDBStream.Read(TmpStream.Memory^, BlobSize);
SetLength(RecBuf, 0);
end else
// 如果不是BLOB字段
begin
TmpStream.SetSize(FieldSize);
FDBStream.Read(TmpStream.Memory^, FieldSize);
end;
// 解码
DecodeMemoryStream(TmpStream, DstStream, ShouldEncrypt, ShouldCompress);
finally
TmpStream.Free;
end;
end;
//-----------------------------------------------------------------------------
// 读入所有的RecTab到Items中,并把每块的偏移存入BlockOffsets中
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.ReadAllRecordTabItems(const TableHeader: TTableHeader;
var Items: TRecordTabItems; var BlockOffsets: TIntegerAry);
var
ReadCount, Count: Integer;
NextOffset: Integer;
BlockCount, BlockIdx: Integer;
begin
FDBStream.Position := TableHeader.RecTabOffset;
BlockCount := TableHeader.RecordTotal div tdbRecTabUnitNum;
if TableHeader.RecordTotal mod tdbRecTabUnitNum > 0 then Inc(BlockCount);
SetLength(BlockOffsets, BlockCount);
SetLength(Items, TableHeader.RecordTotal);
ReadCount := 0;
BlockIdx := 0;
while ReadCount < TableHeader.RecordTotal do
begin
BlockOffsets[BlockIdx] := FDBStream.Position;
Inc(BlockIdx);
Count := TableHeader.RecordTotal - ReadCount;
if Count > tdbRecTabUnitNum then Count := tdbRecTabUnitNum;
FDBStream.Read(NextOffset, SizeOf(Integer));
FDBStream.Read(Items[ReadCount], SizeOf(TRecordTabItem)*Count);
FDBStream.Position := NextOffset;
Inc(ReadCount, Count);
end;
end;
//-----------------------------------------------------------------------------
// 读入索引号为IndexIdx的索引的所有IndexTab到Items中,并把每块的偏移存入BlockOffsets中
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.ReadAllIndexTabItems(const TableHeader: TTableHeader; IndexIdx: Integer;
var Items: TIndexTabItems; var BlockOffsets: TIntegerAry);
var
ReadCount, Count: Integer;
NextOffset: Integer;
BlockCount, BlockIdx: Integer;
begin
FDBStream.Position := TableHeader.IndexHeader[IndexIdx].IndexOffset;
BlockCount := TableHeader.RecordTotal div tdbIdxTabUnitNum;
if TableHeader.RecordTotal mod tdbIdxTabUnitNum > 0 then Inc(BlockCount);
SetLength(BlockOffsets, BlockCount);
SetLength(Items, TableHeader.RecordTotal);
ReadCount := 0;
BlockIdx := 0;
while ReadCount < TableHeader.RecordTotal do
begin
BlockOffsets[BlockIdx] := FDBStream.Position;
Inc(BlockIdx);
Count := TableHeader.RecordTotal - ReadCount;
if Count > tdbIdxTabUnitNum then Count := tdbIdxTabUnitNum;
FDBStream.Read(NextOffset, SizeOf(Integer));
FDBStream.Read(Items[ReadCount], SizeOf(TIndexTabItem)*Count);
FDBStream.Position := NextOffset;
Inc(ReadCount, Count);
end;
end;
//-----------------------------------------------------------------------------
// 在数据库中做删除标记
// RecordIdx: 记录号 0-based
//-----------------------------------------------------------------------------
procedure TTinyDBFileIO.WriteDeleteFlag(RecTabItemOffset: Integer);
var
RecTabItem: TRecordTabItem;
BakFilePos: Integer;
begin
// 移至要做标记的位置
FDBStream.Position := RecTabItemOffset;
BakFilePos := FDBStream.Position;
FDBStream.Read(RecTabItem, SizeOf(RecTabItem));
RecTabItem.DeleteFlag := True;
FDBStream.Position := BakFilePos;
FDBStream.Write(RecTabItem, SizeOf(RecTabItem));
end;
function TTinyDBFileIO.CreateDatabase(const DBFileName: string;
CompressBlob: Boolean; CompressLevel: TCompressLevel; const CompressAlgoName: string;
Encrypt: Boolean; const EncryptAlgoName, Password: string; CRC32: Boolean = False): Boolean;
var
DBStream: TStream;
FileHeader: TFileHeader;
ExtDataBlock: TExtDataBlock;
DBOptions: TDBOptions;
TableTab: TTableTab;
begin
Result := True;
FillChar(FileHeader, SizeOf(FileHeader), 0);
StrCopy(PChar(@FileHeader.SoftName), tdbSoftName);
StrCopy(PChar(@FileHeader.FileFmtVer), tdbFileFmtVer);
FillChar(ExtDataBlock, SizeOf(ExtDataBlock), 0);
if Encrypt then
EncryptBuffer(ExtDataBlock.Comments, SizeOf(ExtDataBlock.Comments), EncryptAlgoName, FTinyDBDefaultEncMode, Password);
FillChar(DBOptions, SizeOf(DBOptions), 0);
RandomFillBuffer(DBOptions.RandomBuffer, SizeOf(DBOptions.RandomBuffer), 20, 122);
DBOptions.CompressBlob := CompressBlob;
DBOptions.CompressLevel := CompressLevel;
StrLCopy(DBOptions.CompressAlgoName, PChar(CompressAlgoName), tdbMaxAlgoNameChar);
DBOptions.Encrypt := Encrypt;
StrLCopy(DBOptions.EncryptAlgoName, PChar(EncryptAlgoName), tdbMaxAlgoNameChar);
DBOptions.EncryptMode := FTinyDBDefaultEncMode;
StrLCopy(DBOptions.HashPassword, PChar(Hash(FTinyDBCheckPwdHashClass, Password)), tdbMaxHashPwdSize);
DBOptions.CRC32 := CRC32;
FillChar(TableTab, SizeOf(TableTab), 0);
TableTab.TableCount := 0;
try
case FMediumType of
mtDisk:
DBStream := TFileStream.Create(DBFileName, fmCreate or fmShareDenyNone);
mtMemory:
DBStream := StrToPointer(DBFileName);
else
DBStream := nil;
end;
try
DBStream.Write(FileHeader, SizeOf(FileHeader));
DBStream.Write(ExtDataBlock, SizeOf(ExtDataBlock));
DBStream.Write(DBOptions, SizeOf(DBOptions));
DBStream.Write(TableTab, SizeOf(TableTab));
finally
if FMediumType = mtDisk then
DBStream.Free;
end;
except
Result := False;
end;
end;
function TTinyDBFileIO.CreateTable(const TableName: string; Fields: array of TFieldItem): Boolean;
var
TableHeader: TTableHeader;
I, AutoIncFieldIdx: Integer;
AutoIncFieldName: string;
begin
if not IsValidDBName(TableName) then
DatabaseErrorFmt(SInvalidTableName, [TableName]);
Lock;
try
CheckValidFields(Fields);
AutoIncFieldIdx := -1;
ReadTableTab(FTableTab);
if FTableTab.TableCount >= tdbMaxTable then
DatabaseError(STooManyTables);
if CheckDupTableName(TableName) then
DatabaseErrorFmt(SDuplicateTableName, [TableName]);
Inc(FTableTab.TableCount);
FTableTab.TableHeaderOffset[FTableTab.TableCount-1] := FDBStream.Size;
WriteTableTab(FTableTab);
FillChar(TableHeader, SizeOf(TableHeader), 0);
StrLCopy(TableHeader.TableName, PChar(TableName), tdbMaxTableNameChar);
TableHeader.RecTabOffset := 0;
TableHeader.RecordTotal := 0;
TableHeader.AutoIncCounter := 0;
TableHeader.FieldCount := Length(Fields);
for I := 0 to High(Fields) do
begin
if Fields[I].FieldType = ftAutoInc then AutoIncFieldIdx := I;
StrLCopy(TableHeader.FieldTab[I].FieldName, PChar(string(Fields[I].FieldName)), tdbMaxFieldNameChar);
TableHeader.FieldTab[I].FieldType := Fields[I].FieldType;
if Fields[I].FieldType in StringFieldTypes then
TableHeader.FieldTab[I].FieldSize := Fields[I].DataSize
else
TableHeader.FieldTab[I].FieldSize := 0;
TableHeader.FieldTab[I].DPMode := Fields[I].DPMode;
end;
TableHeader.IndexCount := 0;
FDBStream.Seek(0, soFromEnd);
FDBStream.Write(TableHeader, SizeOf(TableHeader));
Result := True;
finally
Unlock;
end;
if AutoIncFieldIdx <> -1 then
begin
AutoIncFieldName := Fields[AutoIncFieldIdx].FieldName;
Result := CreateIndex(TableName, AutoIncFieldName, [tiPrimary], [AutoIncFieldName]);
if not Result then DeleteTable(TableName);
end;
end;
function TTinyDBFileIO.DeleteTable(const TableName: string): Boolean;
var
TableHeader: TTableHeader;
I, TableIdx: Integer;
begin
if not IsValidDBName(TableName) then
DatabaseErrorFmt(SInvalidTableName, [TableName]);
Lock;
try
ReadTableTab(FTableTab);
// 查找要删除的表号
TableIdx := GetTableIdxByName(TableName);
if TableIdx <> -1 then
ReadTableHeader(TableIdx, TableHeader);
if TableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [TableName]);
// 删除表偏移信息
for I := TableIdx to FTableTab.TableCount - 2 do
FTableTab.TableHeaderOffset[I] := FTableTab.TableHeaderOffset[I + 1];
// 表总数减一
Dec(FTableTab.TableCount);
// 写回数据库
WriteTableTab(FTableTab);
Result := True;
finally
Unlock;
end;
end;
function TTinyDBFileIO.CreateIndex(const TableName, IndexName: string; IndexOptions: TTDIndexOptions; FieldNames: array of string): Boolean;
var
TableHeader: TTableHeader;
I: Integer;
TableIdx, IndexIdx, FieldIdx: Integer;
begin
if not IsValidDBName(TableName) then
DatabaseErrorFmt(SInvalidTableName, [TableName]);
if not IsValidDBName(IndexName) then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
Lock;
try
ReadTableTab(FTableTab);
// 取得TableName对应的TableIdx
TableIdx := GetTableIdxByName(TableName);
if TableIdx <> -1 then
ReadTableHeader(TableIdx, TableHeader);
// 合法检查
if TableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [TableName]);
if TableHeader.IndexCount >= tdbMaxIndex then
DatabaseError(STooManyIndexes);
if CheckDupIndexName(TableHeader, IndexName) then
DatabaseErrorFmt(SDuplicateIndexName, [IndexName]);
if CheckDupPrimaryIndex(TableHeader, IndexOptions) then
DatabaseError(SDuplicatePrimaryIndex);
if TableHeader.RecordTotal > 0 then
DatabaseError(SFailToCreateIndex);
CheckValidIndexFields(FieldNames, IndexOptions, TableHeader);
// 修改TableHeader
IndexIdx := TableHeader.IndexCount;
Inc(TableHeader.IndexCount);
StrLCopy(TableHeader.IndexHeader[IndexIdx].IndexName, PChar(IndexName), tdbMaxIndexNameChar);
TableHeader.IndexHeader[IndexIdx].IndexOptions := IndexOptions;
for I := 0 to tdbMaxMultiIndexFields - 1 do
begin
if I <= High(FieldNames) then
FieldIdx := GetFieldIdxByName(TableHeader, FieldNames[I])
else
FieldIdx := -1;
TableHeader.IndexHeader[IndexIdx].FieldIdx[I] := FieldIdx;
end;
TableHeader.IndexHeader[IndexIdx].IndexOffset := DBStream.Size;
TableHeader.IndexHeader[IndexIdx].StartIndex := 0;
// 回写TableHeader
WriteTableHeader(TableIdx, TableHeader);
Result := True;
finally
Unlock;
end;
end;
function TTinyDBFileIO.DeleteIndex(const TableName, IndexName: string): Boolean;
var
TableHeader: TTableHeader;
I: Integer;
TableIdx, IndexIdx: Integer;
begin
if not IsValidDBName(TableName) then
DatabaseErrorFmt(SInvalidTableName, [TableName]);
if not IsValidDBName(IndexName) then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
Lock;
try
ReadTableTab(FTableTab);
// 取得TableName对应的TableIdx
TableIdx := GetTableIdxByName(TableName);
if TableIdx <> -1 then
ReadTableHeader(TableIdx, TableHeader);
// 合法检查
if TableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [TableName]);
// 取得IndexName对应的IndexIdx
IndexIdx := GetIndexIdxByName(TableHeader, IndexName);
// 合法检查
if IndexIdx = -1 then
DatabaseErrorFmt(SIndexNotFound, [IndexName]);
// 删除索引信息
for I := IndexIdx to TableHeader.IndexCount - 2 do
TableHeader.IndexHeader[I] := TableHeader.IndexHeader[I + 1];
// 索引数目减一
Dec(TableHeader.IndexCount);
// 回写TableHeader
WriteTableHeader(TableIdx, TableHeader);
Result := True;
finally
Unlock;
end;
end;
function TTinyDBFileIO.RenameTable(const OldTableName, NewTableName: string): Boolean;
var
TableHeader: TTableHeader;
I, TableIdx: Integer;
begin
if not IsValidDBName(NewTableName) then
DatabaseErrorFmt(SInvalidTableName, [NewTableName]);
Lock;
try
ReadTableTab(FTableTab);
// 查找要改名的表号
TableIdx := GetTableIdxByName(OldTableName);
if TableIdx <> -1 then
ReadTableHeader(TableIdx, TableHeader);
if TableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [OldTableName]);
I := GetTableIdxByName(NewTableName);
if (I <> -1) and (I <> TableIdx) then
DatabaseErrorFmt(SDuplicateTableName, [NewTableName]);
// 写回数据库
StrLCopy(TableHeader.TableName, PChar(NewTableName), tdbMaxTableNameChar);
WriteTableHeader(TableIdx, TableHeader);
Result := True;
finally
Unlock;
end;
end;
function TTinyDBFileIO.RenameField(const TableName, OldFieldName, NewFieldName: string): Boolean;
var
TableHeader: TTableHeader;
I, TableIdx, FieldIdx: Integer;
begin
if not IsValidDBName(NewFieldName) then
DatabaseErrorFmt(SInvalidFieldName, [NewFieldName]);
Lock;
try
ReadTableTab(FTableTab);
// 查找要改字段名的表号
TableIdx := GetTableIdxByName(TableName);
if TableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [TableName]);
ReadTableHeader(TableIdx, TableHeader);
// 取得要修改的字段号
FieldIdx := GetFieldIdxByName(TableHeader, OldFieldName);
if FieldIdx = -1 then
DatabaseErrorFmt(SFieldNotFound, [OldFieldName]);
I := GetFieldIdxByName(TableHeader, NewFieldName);
if (I <> -1) and (I <> FieldIdx) then
DatabaseErrorFmt(SDuplicateFieldName, [NewFieldName]);
// 写回数据库
StrLCopy(TableHeader.FieldTab[FieldIdx].FieldName, PChar(NewFieldName), tdbMaxFieldNameChar);
WriteTableHeader(TableIdx, TableHeader);
Result := True;
finally
Unlock;
end;
end;
function TTinyDBFileIO.RenameIndex(const TableName, OldIndexName, NewIndexName: string): Boolean;
var
TableHeader: TTableHeader;
I, TableIdx, IndexIdx: Integer;
begin
if not IsValidDBName(NewIndexName) then
DatabaseErrorFmt(SInvalidIndexName, [NewIndexName]);
Lock;
try
ReadTableTab(FTableTab);
// 查找要改索引名的表号
TableIdx := GetTableIdxByName(TableName);
if TableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [TableName]);
ReadTableHeader(TableIdx, TableHeader);
// 取得要修改的索引号
IndexIdx := GetIndexIdxByName(TableHeader, OldIndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SIndexNotFound, [OldIndexName]);
I := GetIndexIdxByName(TableHeader, NewIndexName);
if (I <> -1) and (I <> IndexIdx) then
DatabaseErrorFmt(SDuplicateIndexName, [NewIndexName]);
// 写回数据库
StrLCopy(TableHeader.IndexHeader[IndexIdx].IndexName, PChar(NewIndexName), tdbMaxIndexNameChar);
WriteTableHeader(TableIdx, TableHeader);
Result := True;
finally
Unlock;
end;
end;
function TTinyDBFileIO.Compact(const Password: string): Boolean;
begin
Result := ReCreate(FDBOptions.CompressBlob, FDBOptions.CompressLevel, FDBOptions.CompressAlgoName,
FDBOptions.Encrypt, FDBOptions.EncryptAlgoName, Password, Password, FDBOptions.CRC32);
end;
function TTinyDBFileIO.Repair(const Password: string): Boolean;
begin
Result := ReCreate(FDBOptions.CompressBlob, FDBOptions.CompressLevel, FDBOptions.CompressAlgoName,
FDBOptions.Encrypt, FDBOptions.EncryptAlgoName, Password, Password, FDBOptions.CRC32);
end;
function TTinyDBFileIO.ChangePassword(const OldPassword, NewPassword: string; Check: Boolean = True): Boolean;
begin
Result := ReCreate(FDBOptions.CompressBlob, FDBOptions.CompressLevel, FDBOptions.CompressAlgoName,
Check, FDBOptions.EncryptAlgoName, OldPassword, NewPassword, FDBOptions.CRC32);
end;
function TTinyDBFileIO.ChangeEncrypt(NewEncrypt: Boolean; const NewEncAlgo, OldPassword, NewPassword: string): Boolean;
begin
Result := ReCreate(FDBOptions.CompressBlob, FDBOptions.CompressLevel, FDBOptions.CompressAlgoName,
NewEncrypt, NewEncAlgo, OldPassword, NewPassword, FDBOptions.CRC32);
end;
function TTinyDBFileIO.SetComments(const Value: string; const Password: string): Boolean;
var
ExtDataBlock: TExtDataBlock;
begin
Lock;
try
Result := True;
try
ReadExtDataBlock(ExtDataBlock);
if FDBOptions.Encrypt then
DecryptBuffer(ExtDataBlock.Comments, SizeOf(ExtDataBlock.Comments), FDBOptions.EncryptAlgoName, FTinyDBDefaultEncMode, Password);
StrLCopy(ExtDataBlock.Comments, PChar(Value), tdbMaxCommentsChar);
if FDBOptions.Encrypt then
EncryptBuffer(ExtDataBlock.Comments, SizeOf(ExtDataBlock.Comments), FDBOptions.EncryptAlgoName, FTinyDBDefaultEncMode, Password);
WriteExtDataBlock(ExtDataBlock);
except
Result := False;
end;
finally
Unlock;
end;
end;
function TTinyDBFileIO.GetComments(var Value: string; const Password: string): Boolean;
var
ExtDataBlock: TExtDataBlock;
begin
Lock;
try
Result := True;
try
ReadExtDataBlock(ExtDataBlock);
if FDBOptions.Encrypt then
DecryptBuffer(ExtDataBlock.Comments, SizeOf(ExtDataBlock.Comments), FDBOptions.EncryptAlgoName, FTinyDBDefaultEncMode, Password);
Value := AnsiString(ExtDataBlock.Comments);
except
Result := False;
end;
finally
Unlock;
end;
end;
function TTinyDBFileIO.SetExtData(Buffer: PChar; Size: Integer): Boolean;
var
ExtDataBlock: TExtDataBlock;
begin
Lock;
try
Result := True;
try
ReadExtDataBlock(ExtDataBlock);
FillChar(ExtDataBlock.Data[0], SizeOf(ExtDataBlock.Data), 0);
if Size > SizeOf(ExtDataBlock.Data) then
Size := SizeOf(ExtDataBlock.Data);
Move(Buffer^, ExtDataBlock.Data[0], Size);
WriteExtDataBlock(ExtDataBlock);
except
Result := False;
end;
finally
Unlock;
end;
end;
function TTinyDBFileIO.GetExtData(Buffer: PChar): Boolean;
var
ExtDataBlock: TExtDataBlock;
begin
Lock;
try
Result := True;
try
ReadExtDataBlock(ExtDataBlock);
Move(ExtDataBlock.Data[0], Buffer^, SizeOf(ExtDataBlock.Data));
except
Result := False;
end;
finally
Unlock;
end;
end;
{ TTinyTableIO }
constructor TTinyTableIO.Create(AOwner: TTinyDatabase);
begin
FDatabase := AOwner;
FTableIdx := -1;
FIndexDefs := TTinyIndexDefs.Create(AOwner);
FFieldDefs := TTinyFieldDefs.Create(AOwner);
end;
destructor TTinyTableIO.Destroy;
begin
Finalize;
FIndexDefs.Free;
FFieldDefs.Free;
inherited;
end;
procedure TTinyTableIO.SetActive(Value: Boolean);
begin
if Value <> Active then
begin
if Value then Open
else Close;
end;
end;
procedure TTinyTableIO.SetTableName(const Value: string);
begin
FTableName := Value;
end;
function TTinyTableIO.GetActive: Boolean;
begin
Result := FRefCount > 0;
end;
function TTinyTableIO.GetRecTabList(Index: Integer): TList;
begin
Result := FRecTabLists[Index];
end;
function TTinyTableIO.GetTableIdxByName(const TableName: string): Integer;
var
List: TStrings;
begin
List := TStringList.Create;
try
FDatabase.GetTableNames(List);
Result := List.IndexOf(TableName);
finally
List.Free;
end;
end;
procedure TTinyTableIO.InitFieldDefs;
var
I: Integer;
FieldDefItem: TTinyFieldDef;
begin
FFieldDefs.Clear;
for I := 0 to FTableHeader.FieldCount - 1 do
begin
FieldDefItem := TTinyFieldDef(FFieldDefs.Add);
FieldDefItem.Name := FTableHeader.FieldTab[I].FieldName;
FieldDefItem.FFieldType := FTableHeader.FieldTab[I].FieldType;
FieldDefItem.FFieldSize := FTableHeader.FieldTab[I].FieldSize;
FieldDefItem.FDPMode := FTableHeader.FieldTab[I].DPMode;
end;
end;
procedure TTinyTableIO.InitIndexDefs;
var
I, K: Integer;
IdxFieldCount: Integer;
IndexDefItem: TTinyIndexDef;
begin
FIndexDefs.Clear;
for I := 0 to FTableHeader.IndexCount - 1 do
begin
IndexDefItem := TTinyIndexDef(FIndexDefs.Add);
IndexDefItem.Name := FTableHeader.IndexHeader[I].IndexName;
IndexDefItem.Options := FTableHeader.IndexHeader[I].IndexOptions;
IdxFieldCount := 0;
for K := 0 to tdbMaxMultiIndexFields - 1 do
begin
if FTableHeader.IndexHeader[I].FieldIdx[K] = -1 then Break;
Inc(IdxFieldCount);
end;
SetLength(IndexDefItem.FFieldIdxes, IdxFieldCount);
for K := 0 to tdbMaxMultiIndexFields - 1 do
begin
if FTableHeader.IndexHeader[I].FieldIdx[K] = -1 then Break;
IndexDefItem.FFieldIdxes[K] := FTableHeader.IndexHeader[I].FieldIdx[K];
end;
end;
end;
procedure TTinyTableIO.InitRecTabList(ListIdx: Integer; ReadRecTabItems: Boolean);
var
IndexTab: TIndexTabItems;
MemRecTabItem: TMemRecTabItem;
IndexOffset, RecordTotal: Integer;
IndexIdx, Count, I: Integer;
begin
if FRecTabLists[ListIdx] <> nil then Exit;
if ReadRecTabItems then
FDatabase.DBFileIO.ReadAllRecordTabItems(FTableHeader, FInitRecordTab, FRecTabBlockOffsets);
RecordTotal := FTableHeader.RecordTotal;
FRecTabLists[ListIdx] := TList.Create;
IndexIdx := ListIdx - 1;
// 初始化物理顺序的记录集指针
if IndexIdx = -1 then
begin
for I := 0 to High(FInitRecordTab) do
begin
if not FInitRecordTab[I].DeleteFlag then
begin
MemRecTabItem.DataOffset := FInitRecordTab[I].DataOffset;
MemRecTabItem.RecIndex := I;
AddMemRecTabItem(FRecTabLists[ListIdx], MemRecTabItem);
end;
end;
end else
// 初始化索引
begin
IndexOffset := FTableHeader.IndexHeader[IndexIdx].IndexOffset;
if IndexOffset <> 0 then
begin
// 将索引数据读入
FDatabase.DBFileIO.ReadAllIndexTabItems(FTableHeader, IndexIdx, IndexTab, FIdxTabBlockOffsets[IndexIdx]);
// 按链表顺序依此整理到FRecTabLists[ListIdx]中
Count := 0;
I := FTableHeader.IndexHeader[IndexIdx].StartIndex;
while (I <> -1) and (Count < RecordTotal) do
begin
// 标有删除标记的记录不读进FIdxTabLists
if not FInitRecordTab[I].DeleteFlag then
begin
MemRecTabItem.DataOffset := FInitRecordTab[I].DataOffset;
MemRecTabItem.RecIndex := I;
AddMemRecTabItem(FRecTabLists[ListIdx], MemRecTabItem);
end;
Inc(Count);
I := IndexTab[I].Next;
end;
end;
end;
end;
procedure TTinyTableIO.InitAllRecTabLists;
var
ListIdx, IndexCount: Integer;
begin
FDatabase.DBFileIO.ReadAllRecordTabItems(FTableHeader, FInitRecordTab, FRecTabBlockOffsets);
IndexCount := FTableHeader.IndexCount;
SetLength(FRecTabLists, IndexCount + 1);
for ListIdx := 0 to High(FRecTabLists) do
begin
InitRecTabList(ListIdx, False);
end;
end;
procedure TTinyTableIO.InitDiskRecInfo;
var
I: Integer;
FieldType: TFieldType;
begin
// 初始化FDiskRecSize
FDiskRecSize := 0;
SetLength(FDiskFieldOffsets, FTableHeader.FieldCount);
for I := 0 to FTableHeader.FieldCount - 1 do
begin
FDiskFieldOffsets[I] := FDiskRecSize;
FieldType := FTableHeader.FieldTab[I].FieldType;
if FieldType in BlobFieldTypes then
Inc(FDiskRecSize, SizeOf(TBlobFieldHeader))
else
Inc(FDiskRecSize, GetFieldSize(FieldType, FTableHeader.FieldTab[I].FieldSize));
end;
end;
procedure TTinyTableIO.InitAutoInc;
var
I: Integer;
FieldType: TFieldType;
begin
FAutoIncFieldIdx := -1;
for I := 0 to FTableHeader.FieldCount - 1 do
begin
FieldType := FTableHeader.FieldTab[I].FieldType;
if FieldType = ftAutoInc then
begin
FAutoIncFieldIdx := I;
Break;
end;
end;
end;
procedure TTinyTableIO.ClearMemRecTab(AList: TList);
var
I: Integer;
begin
if not Assigned(AList) then Exit;
for I := 0 to AList.Count - 1 do
Dispose(PMemRecTabItem(AList.Items[I]));
AList.Clear;
end;
procedure TTinyTableIO.AddMemRecTabItem(AList: TList; Value: TMemRecTabItem);
var
MemRecTabItemPtr: PMemRecTabItem;
begin
New(MemRecTabItemPtr);
MemRecTabItemPtr^ := Value;
AList.Add(MemRecTabItemPtr);
end;
procedure TTinyTableIO.InsertMemRecTabItem(AList: TList; Index: Integer; Value: TMemRecTabItem);
var
MemRecTabItemPtr: PMemRecTabItem;
begin
New(MemRecTabItemPtr);
MemRecTabItemPtr^ := Value;
AList.Insert(Index, MemRecTabItemPtr);
end;
procedure TTinyTableIO.DeleteMemRecTabItem(AList: TList; Index: Integer);
var
F: PMemRecTabItem;
begin
F := AList.Items[Index];
Dispose(F);
AList.Delete(Index);
end;
function TTinyTableIO.GetMemRecTabItem(AList: TList; Index: Integer): TMemRecTabItem;
begin
Result := PMemRecTabItem(AList.Items[Index])^;
end;
function TTinyTableIO.ShouldEncrypt(FieldIdx: Integer): Boolean;
begin
Result := FDatabase.Encrypted and (FFieldDefs[FieldIdx].DPMode = fdDefault);
end;
function TTinyTableIO.ShouldCompress(FieldIdx: Integer): Boolean;
begin
Result := FDatabase.Compressed and
(FTableHeader.FieldTab[FieldIdx].FieldType in BlobFieldTypes) and
(FFieldDefs[FieldIdx].DPMode = fdDefault);
end;
//-----------------------------------------------------------------------------
// 取得第ItemIdx个记录表项目的偏移
//-----------------------------------------------------------------------------
function TTinyTableIO.GetRecTabItemOffset(ItemIdx: Integer): Integer;
var
BlockIdx: Integer;
begin
BlockIdx := ItemIdx div tdbRecTabUnitNum;
Result := FRecTabBlockOffsets[BlockIdx] + SizeOf(Integer) +
SizeOf(TRecordTabItem)*(ItemIdx mod tdbRecTabUnitNum);
end;
//-----------------------------------------------------------------------------
// 取得索引号为IndexIdx的索引的所有IndexTab中第ItemIdx个项目的偏移
//-----------------------------------------------------------------------------
function TTinyTableIO.GetIdxTabItemOffset(IndexIdx: Integer; ItemIdx: Integer): Integer;
var
BlockIdx: Integer;
begin
BlockIdx := ItemIdx div tdbIdxTabUnitNum;
Result := FIdxTabBlockOffsets[IndexIdx][BlockIdx] + SizeOf(Integer) +
SizeOf(TIndexTabItem)*(ItemIdx mod tdbIdxTabUnitNum);
end;
//-----------------------------------------------------------------------------
// 比较两个字段数据的大小
// 字段一的数据放在FieldBuffer1中,字段二的数据放在FieldBuffer2中
// FieldType: 字段类型
// CaseInsensitive: 不区分大小写
// PartialCompare: 是否只比较部分字符串
// 返回值:
// 若 Field1 等于或匹配 Field2 则返回值 = 0
// 若 Field1 > Field2 则返回值 > 0
// 若 Field1 < Field2 则返回值 < 0
//-----------------------------------------------------------------------------
function TTinyTableIO.CompFieldData(FieldBuffer1, FieldBuffer2: Pointer; FieldType: TFieldType;
CaseInsensitive, PartialCompare: Boolean): Integer;
var
ExprNodes: TExprNodes;
LeftNode, RightNode, ResultNode: TExprNode;
Options: TStrCompOptions;
begin
ExprNodes := TExprNodes.Create(nil);
try
LeftNode := ExprNodes.NewNode(enConst, FieldType, 0, toNOTDEFINED, nil, nil);
LeftNode.FData := FieldBuffer1;
if PartialCompare and (FieldType in StringFieldTypes) then
LeftNode.FPartialLength := Length(LeftNode.FData); // Pos('*', LeftNode.FData); //modified 2003.3.22
RightNode := ExprNodes.NewNode(enConst, FieldType, 0, toNOTDEFINED, nil, nil);
RightNode.FData := FieldBuffer2;
if PartialCompare and (FieldType in StringFieldTypes) then
RightNode.FPartialLength := LeftNode.FPartialLength; //Pos('*', RightNode.FData);
ResultNode := ExprNodes.NewNode(enOperator, ftBoolean, SizeOf(Boolean), toLT, LeftNode, RightNode);
Options := [];
if not PartialCompare then Include(Options, scNoPartialCompare);
if CaseInsensitive then Include(Options, scCaseInsensitive);
// 如果Field1 = Field2
ResultNode.FOperator := toEQ;
ResultNode.Calculate(Options);
if ResultNode.AsBoolean then
begin
Result := 0;
Exit;
end;
// 如果Field1 < Field2
ResultNode.FOperator := toLT;
ResultNode.Calculate(Options);
if ResultNode.AsBoolean then
begin
Result := -1;
Exit;
end;
// 否则Field1 > Field2
Result := 1;
finally
ExprNodes.Free;
end;
end;
//-----------------------------------------------------------------------------
// 根据索引查找离指定数据最近的位置(二分法)
// FieldBuffers: 待查找数据应事先存放于FieldBuffers中
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// ResultState: 存放搜索结果状态
// 0: 待查找的值 = 查找结果位置的值
// 1: 待查找的值 > 查找结果位置的值
// -1: 待查找的值 < 查找结果位置的值
// -2: 无记录
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// PartialCompare: 字符串的部分匹配
// 返回值:在RecTabList中的记录号(0-based),如果无记录则返回-1
//-----------------------------------------------------------------------------
function TTinyTableIO.SearchIndexedField(FieldBuffers: TFieldBuffers;
RecTabList: TList; IndexIdx: Integer; var ResultState: Integer;
EffFieldCount: Integer = 0; PartialCompare: Boolean = False): Integer;
var
I, Hi, Lo, Mid, Pos: Integer;
FieldIdx, CompRes: Integer;
IndexOptions: TTDIndexOptions;
MemRecTabItem: TMemRecTabItem;
DataStream: TMemoryStream;
begin
DataStream := TMemoryStream.Create;
IndexOptions := FIndexDefs[IndexIdx].Options;
Lo := 0;
Hi := RecTabList.Count - 1;
Pos := -1;
ResultState := -2;
while Lo <= Hi do
begin
Mid := (Lo + Hi) div 2;
MemRecTabItem := GetMemRecTabItem(RecTabList, Mid);
CompRes := 0;
for I := 0 to High(FIndexDefs[IndexIdx].FieldIdxes) do
begin
if (EffFieldCount <> 0) and (I >= EffFieldCount) then Break;
FieldIdx := FIndexDefs[IndexIdx].FieldIdxes[I]; // 物理字段号
ReadFieldData(DataStream, MemRecTabItem.RecIndex, FieldIdx);
CompRes := CompFieldData(FieldBuffers.Items[FieldIdx].DataBuf, DataStream.Memory,
FieldBuffers.Items[FieldIdx].FieldType, tiCaseInsensitive in IndexOptions, PartialCompare);
if CompRes <> 0 then Break;
end;
if tiDescending in IndexOptions then CompRes := - CompRes;
Pos := Mid;
if CompRes > 0 then
begin
Lo := Mid + 1;
ResultState := 1;
end else if CompRes < 0 then
begin
Hi := Mid - 1;
ResultState := -1;
end else
begin
ResultState := 0;
Break;
end;
end;
DataStream.Free;
Result := Pos;
end;
//-----------------------------------------------------------------------------
// 根据索引查找离指定数据的边界位置(二分法)
// FieldBuffers: 待查找数据应事先存放于FieldBuffers中
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// LowBound: 为True时查找低边界,为False时查找高边界
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// PartialCompare: 字符串的部分匹配
// 返回值:在RecTabList中的记录号(0-based),如果无记录则返回-1
//-----------------------------------------------------------------------------
function TTinyTableIO.SearchIndexedFieldBound(FieldBuffers: TFieldBuffers;
RecTabList: TList; IndexIdx: Integer; LowBound: Boolean; var ResultState: Integer;
EffFieldCount: Integer = 0; PartialCompare: Boolean = False): Integer;
var
I, Hi, Lo, Mid, Pos: Integer;
MemRecTabItem: TMemRecTabItem;
FieldIdx, CompRes: Integer;
IndexOptions: TTDIndexOptions;
DataStream: TMemoryStream;
begin
DataStream := TMemoryStream.Create;
IndexOptions := FIndexDefs[IndexIdx].Options;
Lo := 0;
Hi := RecTabList.Count - 1;
Pos := -1;
ResultState := -2;
while Lo <= Hi do
begin
Mid := (Lo + Hi) div 2;
MemRecTabItem := GetMemRecTabItem(RecTabList, Mid);
CompRes := 0;
for I := 0 to High(FIndexDefs[IndexIdx].FieldIdxes) do
begin
if (EffFieldCount <> 0) and (I >= EffFieldCount) then Break;
FieldIdx := FIndexDefs[IndexIdx].FieldIdxes[I];
ReadFieldData(DataStream, MemRecTabItem.RecIndex, FieldIdx);
CompRes := CompFieldData(FieldBuffers.Items[FieldIdx].DataBuf, DataStream.Memory,
FieldBuffers.Items[FieldIdx].FieldType, tiCaseInsensitive in IndexOptions, PartialCompare);
if CompRes <> 0 then Break;
end;
if tiDescending in IndexOptions then CompRes := - CompRes;
if ResultState <> 0 then Pos := Mid;
if CompRes > 0 then
begin
Lo := Mid + 1;
if ResultState <> 0 then ResultState := 1;
end else if CompRes < 0 then
begin
Hi := Mid - 1;
if ResultState <> 0 then ResultState := -1;
end else
begin
if LowBound then Hi := Mid - 1
else Lo := Mid + 1;
Pos := Mid;
ResultState := 0;
end;
end;
DataStream.Free;
Result := Pos;
end;
//-----------------------------------------------------------------------------
// 根据索引求取SubRangeStart的位置
// FieldBuffers: 待查找数据应事先存放于FieldBuffers中
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// EffFieldCount: FieldBuffers中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// 返回值:求得结果,在RecTabList中的记录号(0-based)
//-----------------------------------------------------------------------------
function TTinyTableIO.SearchRangeStart(FieldBuffers: TFieldBuffers; RecTabList: TList;
IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0): Integer;
begin
Result := SearchIndexedFieldBound(FieldBuffers, RecTabList, IndexIdx, True, ResultState, EffFieldCount);
if ResultState = 1 then Inc(Result);
end;
//-----------------------------------------------------------------------------
// 根据索引求取SubRangeEnd的位置
// FieldBuffers: 待查找数据应事先存放于FieldBuffers中
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// EffFieldCount: FieldBuffers中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// 返回值:求得结果,在RecTabList中的记录号(0-based)
//-----------------------------------------------------------------------------
function TTinyTableIO.SearchRangeEnd(FieldBuffers: TFieldBuffers; RecTabList: TList;
IndexIdx: Integer; var ResultState: Integer; EffFieldCount: Integer = 0): Integer;
begin
Result := SearchIndexedFieldBound(FieldBuffers, RecTabList, IndexIdx, False, ResultState, EffFieldCount);
if ResultState = -1 then Dec(Result);
end;
//-----------------------------------------------------------------------------
// 根据索引求取插入点
// FieldBuffers: 待查找数据应事先存放于FieldBuffers中
// IndexIdx: 索引号 0-based
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// 返回值:插入点的位置(0-based)
//-----------------------------------------------------------------------------
function TTinyTableIO.SearchInsertPos(FieldBuffers: TFieldBuffers; IndexIdx: Integer; var ResultState: Integer): Integer;
begin
Result := SearchIndexedField(FieldBuffers, FRecTabLists[IndexIdx+1], IndexIdx, ResultState);
if ResultState in [0, 1] then Inc(Result)
else if ResultState = -2 then Result := 0;
end;
//-----------------------------------------------------------------------------
// 检查是否含有Primary索引
// 返回值:
// 没有则返回 -1
// 有则返回索引号
//-----------------------------------------------------------------------------
function TTinyTableIO.CheckPrimaryFieldExists: Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to FIndexDefs.Count - 1 do
begin
if tiPrimary in FIndexDefs[I].Options then
begin
Result := I;
Break;
end;
end;
end;
//-----------------------------------------------------------------------------
// 新增记录时检查Primary,Unique字段的唯一性
// FieldBuffers: 待检查字段值应事先存放在其中
// 返回值: 合法(符合唯一性)则返回 True
//-----------------------------------------------------------------------------
function TTinyTableIO.CheckUniqueFieldForAppend(FieldBuffers: TFieldBuffers): Boolean;
var
I, Idx, ResultState: Integer;
S: string;
IndexOptions: TTDIndexOptions;
begin
Result := True;
for Idx := 0 to FIndexDefs.Count - 1 do
begin
IndexOptions := FIndexDefs[Idx].Options;
if (tiPrimary in IndexOptions) or (tiUnique in IndexOptions) then
begin
SearchIndexedField(FieldBuffers, FRecTabLists[Idx+1], Idx, ResultState);
if ResultState = 0 then
begin
Result := False;
S := '';
for I := 0 to Length(FIndexDefs[Idx].FieldIdxes) - 1 do
begin
if I > 0 then S := S + ',';
S := S + FieldBuffers.Items[FIndexDefs[Idx].FieldIdxes[I]].AsString;
end;
DatabaseErrorFmt(SInvalidUniqueFieldValue, [S]);
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// 修改记录时检查Primary,Unique字段的唯一性
// FieldBuffers: 待检查字段值应事先存放在其中
// PhyRecordIdx: 正在修改的记录的物理记录号
// 返回值: 合法(符合唯一性)则返回 True
//-----------------------------------------------------------------------------
function TTinyTableIO.CheckUniqueFieldForModify(FieldBuffers: TFieldBuffers; PhyRecordIdx: Integer): Boolean;
var
I, Idx, RecIdx, ResultState: Integer;
S: string;
IndexOptions: TTDIndexOptions;
begin
Result := True;
for Idx := 0 to FIndexDefs.Count - 1 do
begin
IndexOptions := FIndexDefs[Idx].Options;
if (tiPrimary in IndexOptions) or (tiUnique in IndexOptions) then
begin
RecIdx := SearchIndexedField(FieldBuffers, FRecTabLists[Idx+1], Idx, ResultState);
if ResultState = 0 then
begin
ConvertRecordIdx(Idx, RecIdx, -1, RecIdx);
if PhyRecordIdx <> RecIdx then
begin
Result := False;
S := '';
for I := 0 to Length(FIndexDefs[Idx].FieldIdxes) - 1 do
begin
if I > 0 then S := S + ',';
S := S + FieldBuffers.Items[FIndexDefs[Idx].FieldIdxes[I]].AsString;
end;
DatabaseErrorFmt(SInvalidUniqueFieldValue, [S]);
end;
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// 将索引号为SrcIndexIdx的索引中的记录号SrcRecordIdx转换成
// 索引号为DstIndexIdx的索引中的记录号,结果存放于DstRecordIdx中
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ConvertRecordIdx(SrcIndexIdx, SrcRecordIdx, DstIndexIdx: Integer; var DstRecordIdx: Integer);
var
I, RecIdx: Integer;
MemRecTabItem: TMemRecTabItem;
begin
if (SrcRecordIdx < 0) or (SrcRecordIdx >= FRecTabLists[SrcIndexIdx+1].Count) then
begin
DstRecordIdx := -1;
Exit;
end;
if SrcIndexIdx = DstIndexIdx then
begin
DstRecordIdx := SrcRecordIdx;
Exit;
end;
MemRecTabItem := GetMemRecTabItem(FRecTabLists[SrcIndexIdx+1], SrcRecordIdx);
RecIdx := MemRecTabItem.RecIndex;
if DstIndexIdx = -1 then
begin
ConvertRecIdxForPhy(SrcIndexIdx, SrcRecordIdx, DstRecordIdx);
Exit;
end else
begin
for I := 0 to FRecTabLists[DstIndexIdx+1].Count - 1 do
begin
MemRecTabItem := GetMemRecTabItem(FRecTabLists[DstIndexIdx+1], I);
if MemRecTabItem.RecIndex = RecIdx then
begin
DstRecordIdx := I;
Exit;
end;
end;
end;
DstRecordIdx := -1;
end;
//-----------------------------------------------------------------------------
// 将SrcRecTabList中的记录号SrcRecordIdx转换成
// DstRecTabList中的记录号,结果存放于DstRecordIdx中
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ConvertRecordIdx(SrcRecTabList: TList; SrcRecordIdx: Integer;
DstRecTabList: TList; var DstRecordIdx: Integer);
var
I, RecIdx: Integer;
MemRecTabItem: TMemRecTabItem;
begin
if (SrcRecordIdx < 0) or (SrcRecordIdx >= SrcRecTabList.Count) then
begin
DstRecordIdx := -1;
Exit;
end;
if SrcRecTabList = DstRecTabList then
begin
DstRecordIdx := SrcRecordIdx;
Exit;
end;
MemRecTabItem := GetMemRecTabItem(SrcRecTabList, SrcRecordIdx);
RecIdx := MemRecTabItem.RecIndex;
for I := 0 to DstRecTabList.Count - 1 do
begin
MemRecTabItem := GetMemRecTabItem(DstRecTabList, I);
if MemRecTabItem.RecIndex = RecIdx then
begin
DstRecordIdx := I;
Exit;
end;
end;
DstRecordIdx := -1;
end;
//-----------------------------------------------------------------------------
// 将索引号为SrcIndexIdx的索引中的记录号SrcRecordIdx转换成
// FRecTabLists[0]中对应的记录号,结果存放于DstRecordIdx中
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ConvertRecIdxForPhy(SrcIndexIdx, SrcRecordIdx: Integer; var DstRecordIdx: Integer);
var
Lo, Hi, Mid, Pos, RecIdx: Integer;
MemRecTabItem: TMemRecTabItem;
begin
if (SrcRecordIdx < 0) or (SrcRecordIdx >= FRecTabLists[SrcIndexIdx+1].Count) then
begin
DstRecordIdx := -1;
Exit;
end;
MemRecTabItem := GetMemRecTabItem(FRecTabLists[SrcIndexIdx+1], SrcRecordIdx);
RecIdx := MemRecTabItem.RecIndex;
// FRecTabLists[0] 中的RecIndex是有序的,所以可以用二分法
Lo := 0;
Hi := FRecTabLists[0].Count - 1;
Pos := -1;
while Lo <= Hi do
begin
Mid := (Lo + Hi) div 2;
MemRecTabItem := GetMemRecTabItem(FRecTabLists[0], Mid);
if RecIdx > MemRecTabItem.RecIndex then
begin
Lo := Mid + 1;
end else if RecIdx < MemRecTabItem.RecIndex then
begin
Hi := Mid - 1;
end else
begin
Pos := Mid;
Break;
end;
end;
DstRecordIdx := Pos;
end;
//-----------------------------------------------------------------------------
// 将记录集SrcRecTabList中的记录号SrcRecordIdx转换成
// FRecTabLists[0]中对应的记录号,结果存放于DstRecordIdx中
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ConvertRecIdxForPhy(SrcRecTabList: TList; SrcRecordIdx: Integer; var DstRecordIdx: Integer);
var
Lo, Hi, Mid, Pos, RecIdx: Integer;
MemRecTabItem: TMemRecTabItem;
begin
if (SrcRecordIdx < 0) or (SrcRecordIdx >= SrcRecTabList.Count) then
begin
DstRecordIdx := -1;
Exit;
end;
MemRecTabItem := GetMemRecTabItem(SrcRecTabList, SrcRecordIdx);
RecIdx := MemRecTabItem.RecIndex;
// FRecTabLists[0] 中的RecIndex是有序的,所以可以用二分法
Lo := 0;
Hi := FRecTabLists[0].Count - 1;
Pos := -1;
while Lo <= Hi do
begin
Mid := (Lo + Hi) div 2;
MemRecTabItem := GetMemRecTabItem(FRecTabLists[0], Mid);
if RecIdx > MemRecTabItem.RecIndex then
begin
Lo := Mid + 1;
end else if RecIdx < MemRecTabItem.RecIndex then
begin
Hi := Mid - 1;
end else
begin
Pos := Mid;
Break;
end;
end;
DstRecordIdx := Pos;
end;
//-----------------------------------------------------------------------------
// 将索引号为SrcIndexIdx的索引中的记录号SrcRecordIdx转换成
// RecTabList中对应的记录号,结果存放于DstRecordIdx中
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ConvertRecIdxForCur(SrcIndexIdx, SrcRecordIdx: Integer;
RecTabList: TList; var DstRecordIdx: Integer);
var
I, RecIdx: Integer;
MemRecTabItem: TMemRecTabItem;
begin
if (SrcRecordIdx < 0) or (SrcRecordIdx >= FRecTabLists[SrcIndexIdx+1].Count) then
begin
DstRecordIdx := -1;
Exit;
end;
if RecTabList = FRecTabLists[SrcIndexIdx + 1] then
begin
DstRecordIdx := SrcRecordIdx;
Exit;
end;
MemRecTabItem := GetMemRecTabItem(FRecTabLists[SrcIndexIdx+1], SrcRecordIdx);
RecIdx := MemRecTabItem.RecIndex;
for I := 0 to RecTabList.Count - 1 do
begin
MemRecTabItem := GetMemRecTabItem(RecTabList, I);
if MemRecTabItem.RecIndex = RecIdx then
begin
DstRecordIdx := I;
Exit;
end;
end;
DstRecordIdx := -1;
end;
//-----------------------------------------------------------------------------
// 新增记录时调整数据库索引
// RecDataOffset: 新增记录的数据区偏移
// RecTotal: 新增前的记录总数,包括有删除标记的记录
//-----------------------------------------------------------------------------
procedure TTinyTableIO.AdjustIndexesForAppend(FieldBuffers: TFieldBuffers;
RecDataOffset, RecTotal: Integer; OnAdjustIndex: TOnAdjustIndexForAppendEvent);
var
Idx, Pos, ResultState: Integer;
IdxTabOffset, StartIndex: Integer;
BakFilePos: Integer;
IdxTabItem, IdxTabItemA: TIndexTabItem;
MemRecTabItem: TMemRecTabItem;
IndexTabAry: array of TIndexTabItem;
NextBlockOffset: Integer;
DBStream: TStream;
begin
DBStream := FDatabase.DBFileIO.DBStream;
MemRecTabItem.DataOffset := RecDataOffset;
MemRecTabItem.RecIndex := RecTotal;
OnAdjustIndex(-1, -1, MemRecTabItem);
for Idx := 0 to High(FRecTabLists) - 1 do
begin
// 求取插入点
Pos := SearchInsertPos(FieldBuffers, Idx, ResultState);
if Assigned(OnAdjustIndex) then
begin
MemRecTabItem.DataOffset := RecDataOffset;
MemRecTabItem.RecIndex := RecTotal;
OnAdjustIndex(Idx, Pos, MemRecTabItem);
end;
// 调整FRecTabLists
MemRecTabItem.DataOffset := RecDataOffset;
MemRecTabItem.RecIndex := RecTotal;
InsertMemRecTabItem(FRecTabLists[Idx+1], Pos, MemRecTabItem);
// 将索引写入磁盘数据库文件中 ----------------------------
IdxTabOffset := FTableHeader.IndexHeader[Idx].IndexOffset;
// 如果已有记录数已经是调整步长的整数倍,则..
if RecTotal mod tdbIdxTabUnitNum = 0 then
begin
// 构造一个新的索引表块
SetLength(IndexTabAry, tdbIdxTabUnitNum);
FillChar(IndexTabAry[0], SizeOf(TIndexTabItem)*Length(IndexTabAry), 0);
// 调整上一索引表块首的Next指针
NextBlockOffset := DBStream.Size;
if Length(FIdxTabBlockOffsets[Idx]) > 0 then
begin
DBStream.Position := FIdxTabBlockOffsets[Idx][High(FIdxTabBlockOffsets[Idx])];
DBStream.Write(NextBlockOffset, SizeOf(Integer));
end;
// 如果原本没有记录,则调整TableHeader
if RecTotal = 0 then
begin
IdxTabOffset := DBStream.Size;
FTableHeader.IndexHeader[Idx].IndexOffset := IdxTabOffset;
FDatabase.DBFileIO.WriteTableHeader(TableIdx, FTableHeader);
end;
// 调整FIdxTabBlockOffsets[Idx]
SetLength(FIdxTabBlockOffsets[Idx], Length(FIdxTabBlockOffsets[Idx]) + 1);
FIdxTabBlockOffsets[Idx][High(FIdxTabBlockOffsets[Idx])] := NextBlockOffset;
// 把新的索引表块写入数据库
DBStream.Seek(0, soFromEnd);
NextBlockOffset := 0;
DBStream.Write(NextBlockOffset, SizeOf(Integer));
DBStream.Write(IndexTabAry[0], SizeOf(TIndexTabItem)*Length(IndexTabAry));
end;
// 如果是第一条记录
if RecTotal = 0 then
begin
IdxTabItem.RecIndex := 0;
IdxTabItem.Next := -1;
DBStream.Position := IdxTabOffset + SizeOf(Integer);
DBStream.Write(IdxTabItem, SizeOf(IdxTabItem));
end else
// 如果不是第一条记录
begin
// 如果插入在链表头
if Pos = 0 then
begin
// 构造一个新的IdxTabItem
StartIndex := FTableHeader.IndexHeader[Idx].StartIndex;
IdxTabItem.RecIndex := RecTotal;
IdxTabItem.Next := StartIndex;
// 把新的IdxTabItem写入数据库
DBStream.Position := GetIdxTabItemOffset(Idx, RecTotal);
DBStream.Write(IdxTabItem, SizeOf(IdxTabItem));
// 调整TableHeader
FTableHeader.IndexHeader[Idx].StartIndex := RecTotal;
FDatabase.DBFileIO.WriteTableHeader(TableIdx, FTableHeader);
end else
// 如果不插入在链表头
begin
// 读取插入点的上一个索引项目IdxTabItemA
MemRecTabItem := GetMemRecTabItem(FRecTabLists[Idx+1], Pos - 1);
DBStream.Position := GetIdxTabItemOffset(Idx, MemRecTabItem.RecIndex);
BakFilePos := DBStream.Position;
DBStream.Read(IdxTabItemA, SizeOf(IdxTabItemA));
// 写入新的IdxTabItem
IdxTabItem.RecIndex := RecTotal;
IdxTabItem.Next := IdxTabItemA.Next;
DBStream.Position := GetIdxTabItemOffset(Idx, RecTotal);
DBStream.Write(IdxTabItem, SizeOf(IdxTabItem));
// 将调整后的IdxTabItemA写入数据库
IdxTabItemA.Next := RecTotal;
DBStream.Position := BakFilePos;
DBStream.Write(IdxTabItemA, SizeOf(IdxTabItem));
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// 修改记录时调整数据库索引
// EditPhyRecordIdx: 被修改记录的物理记录号(即在FRecTabLists[0]中的记录号) 0-based
//-----------------------------------------------------------------------------
procedure TTinyTableIO.AdjustIndexesForModify(FieldBuffers: TFieldBuffers;
EditPhyRecordIdx: Integer; OnAdjustIndex: TOnAdjustIndexForModifyEvent);
var
Idx, Pos, FromPos, ToPos, ResultState: Integer;
BakFilePos: Integer;
EditRecordIdx: Integer;
MemRecTabItem, OrgMemRecTabItem: TMemRecTabItem;
IdxTabItem, IdxTabItemA: TIndexTabItem;
IndexOptions: TTDIndexOptions;
EditRecordIdxes: array[0..tdbMaxIndex-1] of Integer;
DBStream: TStream;
begin
DBStream := FDatabase.DBFileIO.DBStream;
for Idx := 0 to High(FRecTabLists) - 1 do
ConvertRecordIdx(-1, EditPhyRecordIdx, Idx, EditRecordIdxes[Idx]);
for Idx := 0 to High(FRecTabLists) - 1 do
begin
IndexOptions := FIndexDefs[Idx].Options;
EditRecordIdx := EditRecordIdxes[Idx];
OrgMemRecTabItem := GetMemRecTabItem(FRecTabLists[Idx+1], EditRecordIdx);
DeleteMemRecTabItem(FRecTabLists[Idx+1], EditRecordIdx);
// 求取插入点
Pos := SearchInsertPos(FieldBuffers, Idx, ResultState);
FromPos := EditRecordIdx;
if Pos <= EditRecordIdx then ToPos := Pos
else ToPos := Pos + 1;
// 还原FRecTabLists[Idx+1]
InsertMemRecTabItem(FRecTabLists[Idx+1], EditRecordIdx, OrgMemRecTabItem);
if FromPos = ToPos then Continue;
if Assigned(OnAdjustIndex) then
OnAdjustIndex(Idx, FromPos, ToPos);
// 调整磁盘数据库文件中的索引数据 ----------------------------
// 先把待移动索引项目从链表中分离出来(IdxTabItem)
// 如果待移动索引项目是链表中的第一个节点
if FromPos = 0 then
begin
DBStream.Position := GetIdxTabItemOffset(Idx, OrgMemRecTabItem.RecIndex);
DBStream.Read(IdxTabItem, SizeOf(IdxTabItem));
FTableHeader.IndexHeader[Idx].StartIndex := IdxTabItem.Next;
FDatabase.DBFileIO.WriteTableHeader(TableIdx, FTableHeader);
end else
// 如果不是链表中的第一个节点
begin
DBStream.Position := GetIdxTabItemOffset(Idx, OrgMemRecTabItem.RecIndex);
DBStream.Read(IdxTabItem, SizeOf(IdxTabItem));
MemRecTabItem := GetMemRecTabItem(FRecTabLists[Idx+1], FromPos - 1);
DBStream.Position := GetIdxTabItemOffset(Idx, MemRecTabItem.RecIndex);
BakFilePos := DBStream.Position;
DBStream.Read(IdxTabItemA, SizeOf(IdxTabItemA));
IdxTabItemA.Next := IdxTabItem.Next;
DBStream.Position := BakFilePos;
DBStream.Write(IdxTabItemA, SizeOf(IdxTabItemA));
end;
// 再把分离出来的索引项目放置到链表中的合适位置
// 如果要放置到链表的第一个节点位置
if ToPos = 0 then
begin
IdxTabItem.Next := FTableHeader.IndexHeader[Idx].StartIndex;
FTableHeader.IndexHeader[Idx].StartIndex := OrgMemRecTabItem.RecIndex;
DBStream.Position := GetIdxTabItemOffset(Idx, OrgMemRecTabItem.RecIndex);
DBStream.Write(IdxTabItem, SizeOf(IdxTabItem));
FDatabase.DBFileIO.WriteTableHeader(TableIdx, FTableHeader);
end else
// 如果要放置的位置不是链表的第一个节点位置
begin
MemRecTabItem := GetMemRecTabItem(FRecTabLists[Idx+1], ToPos - 1);
DBStream.Position := GetIdxTabItemOffset(Idx, MemRecTabItem.RecIndex);
BakFilePos := DBStream.Position;
DBStream.Read(IdxTabItemA, SizeOf(IdxTabItemA));
IdxTabItem.Next := IdxTabItemA.Next;
IdxTabItemA.Next := OrgMemRecTabItem.RecIndex;
DBStream.Position := BakFilePos;
DBStream.Write(IdxTabItemA, SizeOf(IdxTabItemA));
DBStream.Position := GetIdxTabItemOffset(Idx, OrgMemRecTabItem.RecIndex);
DBStream.Write(IdxTabItem, SizeOf(IdxTabItem));
end;
// 调整FRecTabLists[Idx+1]
DeleteMemRecTabItem(FRecTabLists[Idx+1], FromPos);
InsertMemRecTabItem(FRecTabLists[Idx+1], Pos, OrgMemRecTabItem);
end;
end;
//-----------------------------------------------------------------------------
// 删除记录时调整数据库索引
// DeletePhyRecordIdx: 被删除记录的物理记录号(即在FRecTabLists[0]中的记录号) 0-based
//-----------------------------------------------------------------------------
procedure TTinyTableIO.AdjustIndexesForDelete(DeletePhyRecordIdx: Integer);
var
Idx: Integer;
DeleteRecordIdxes: array[0..tdbMaxIndex-1] of Integer;
begin
for Idx := 0 to High(FRecTabLists) - 1 do
ConvertRecordIdx(-1, DeletePhyRecordIdx, Idx, DeleteRecordIdxes[Idx]);
for Idx := 0 to High(FRecTabLists) - 1 do
DeleteMemRecTabItem(FRecTabLists[Idx+1], DeleteRecordIdxes[Idx]);
end;
//-----------------------------------------------------------------------------
// 在数据库中做删除标记
// PhyRecordIdx: 物理记录号 0-based
//-----------------------------------------------------------------------------
procedure TTinyTableIO.WriteDeleteFlag(PhyRecordIdx: Integer);
var
RecTabItemOffset: Integer;
begin
RecTabItemOffset := GetRecTabItemOffset(GetMemRecTabItem(FRecTabLists[0], PhyRecordIdx).RecIndex);
FDatabase.DBFileIO.WriteDeleteFlag(RecTabItemOffset);
end;
//-----------------------------------------------------------------------------
// 调整FieldBuffers,使其中的String字段未用区域为空字符
//-----------------------------------------------------------------------------
procedure TTinyTableIO.AdjustStrFldInBuffer(FieldBuffers: TFieldBuffers);
var
I, DataSize, Len: Integer;
Buffer: PChar;
begin
for I := 0 to FieldBuffers.Count - 1 do
begin
if FieldBuffers.Items[I].FieldType in StringFieldTypes then
begin
Buffer := FieldBuffers.Items[I].Buffer;
DataSize := FieldBuffers.Items[I].FieldSize;
Len := Length(Buffer);
if Len >= DataSize then Len := DataSize - 1;
FillChar(Buffer[Len], DataSize - Len, 0);
end;
end;
end;
procedure TTinyTableIO.ClearAllRecTabLists;
var
I: Integer;
begin
for I := 0 to High(FRecTabLists) do
begin
ClearMemRecTab(FRecTabLists[I]);
FRecTabLists[I].Free;
end;
SetLength(FRecTabLists, 0);
end;
procedure TTinyTableIO.Initialize;
var
IndexCount: Integer;
begin
FDatabase.DBFileIO.Lock;
try
FTableIdx := GetTableIdxByName(FTableName);
if FTableIdx = -1 then
DatabaseErrorFmt(STableNotFound, [FTableName]);
FDatabase.DBFileIO.ReadTableHeader(FTableIdx, FTableHeader);
IndexCount := FTableHeader.IndexCount;
SetLength(FIdxTabBlockOffsets, IndexCount);
InitFieldDefs;
InitIndexDefs;
InitAllRecTabLists;
InitDiskRecInfo;
InitAutoInc;
finally
FDatabase.DBFileIO.Unlock;
end;
end;
procedure TTinyTableIO.Finalize;
begin
FFieldDefs.Clear;
FIndexDefs.Clear;
ClearAllRecTabLists;
end;
procedure TTinyTableIO.Open;
begin
if FRefCount = 0 then Initialize;
Inc(FRefCount);
end;
procedure TTinyTableIO.Close;
begin
Dec(FRefCount);
if FRefCount = 0 then Finalize;
if FRefCount < 0 then FRefCount := 0;
end;
procedure TTinyTableIO.Refresh;
begin
if Active then
begin
Finalize;
Initialize;
end;
end;
//-----------------------------------------------------------------------------
// 将Buffer中的数据新增到数据库中
// FieldBuffers: 将要新增的字段数据(包含所有物理字段)
// Flush: 新增完后是否flush cache
//-----------------------------------------------------------------------------
procedure TTinyTableIO.AppendRecordData(FieldBuffers: TFieldBuffers; Flush: Boolean;
OnAdjustIndex: TOnAdjustIndexForAppendEvent);
var
RecordTab: TRecordTabItem;
RecordTabAry: array of TRecordTabItem;
TableHeaderOffset, RecTabOffset, RecTotal, DataOffset: Integer;
BlobHeader: TBlobFieldHeader;
BlobRestBuf: array[0..tdbBlobSizeUnitNum-1] of Char;
BlobStream, DstBlobStream, DstBlobStream1: TMemoryStream;
MemRecTabItem: TMemRecTabItem;
NextRecTabBlockOffset: Integer;
I, BlobDataPos, DstBlobSize: Integer;
CRC32Value1, CRC32Value2: Longword;
SrcDiskRecBuf, DstDiskRecBuf: PChar;
FieldBuffer: Pointer;
DBStream: TStream;
begin
FDatabase.DBFileIO.Lock;
try
DBStream := FDatabase.DBFileIO.DBStream;
// 检查Primary,Unique字段的唯一性
CheckUniqueFieldForAppend(FieldBuffers);
// 对AutoInc字段做调整
if FAutoIncFieldIdx <> -1 then
begin
FieldBuffer := FieldBuffers.Items[FAutoIncFieldIdx].Buffer;
if PInteger(FieldBuffer)^ = 0 then
begin
Inc(FTableHeader.AutoIncCounter);
PInteger(FieldBuffer)^ := FTableHeader.AutoIncCounter;
end else if PInteger(FieldBuffer)^ > FTableHeader.AutoIncCounter then
begin
FTableHeader.AutoIncCounter := PInteger(FieldBuffer)^;
end;
end;
TableHeaderOffset := FDatabase.DBFileIO.TableTab.TableHeaderOffset[FTableIdx];
RecTabOffset := FTableHeader.RecTabOffset;
RecTotal := FTableHeader.RecordTotal;
// 如果还没有任何记录
if RecTotal = 0 then
begin
RecTabOffset := DBStream.Size;
// 调整FRecTabBlockOffsets
SetLength(FRecTabBlockOffsets, Length(FRecTabBlockOffsets) + 1);
FRecTabBlockOffsets[High(FRecTabBlockOffsets)] := RecTabOffset;
// ..
SetLength(RecordTabAry, tdbRecTabUnitNum);
FillChar(RecordTabAry[0], SizeOf(TRecordTabItem)*tdbRecTabUnitNum, 0);
DataOffset := DBStream.Size + SizeOf(Integer) + SizeOf(TRecordTabItem)*tdbRecTabUnitNum;
RecordTabAry[0].DataOffset := DataOffset;
RecordTabAry[0].DeleteFlag := False;
NextRecTabBlockOffset := 0;
DBStream.Seek(0, soFromEnd);
DBStream.Write(NextRecTabBlockOffset, SizeOf(Integer));
DBStream.Write(RecordTabAry[0], SizeOf(TRecordTabItem)*tdbRecTabUnitNum);
end else
// 如果表中已经存在记录
begin
// 如果已有记录数已经是调整步长的整数倍,则..
if RecTotal mod tdbRecTabUnitNum = 0 then
begin
// 构造一个新的记录表块
SetLength(RecordTabAry, tdbRecTabUnitNum);
FillChar(RecordTabAry[0], SizeOf(TRecordTabItem)*Length(RecordTabAry), 0);
DataOffset := DBStream.Size + SizeOf(Integer) + SizeOf(TRecordTabItem)*Length(RecordTabAry);
RecordTabAry[0].DataOffset := DataOffset;
RecordTabAry[0].DeleteFlag := False;
// 调整上一个记录表块首的Next指针
NextRecTabBlockOffset := DBStream.Size;
DBStream.Position := FRecTabBlockOffsets[High(FRecTabBlockOffsets)];
DBStream.Write(NextRecTabBlockOffset, SizeOf(Integer));
// 调整FRecTabBlockOffsets
SetLength(FRecTabBlockOffsets, Length(FRecTabBlockOffsets) + 1);
FRecTabBlockOffsets[High(FRecTabBlockOffsets)] := NextRecTabBlockOffset;
// 在文件尾增加一个记录表块
DBStream.Seek(0, soFromEnd);
NextRecTabBlockOffset := 0;
DBStream.Write(NextRecTabBlockOffset, SizeOf(Integer));
DBStream.Write(RecordTabAry[0], SizeOf(TRecordTabItem)*Length(RecordTabAry));
end else
// 否则,只需直接修改
begin
DBStream.Position := GetRecTabItemOffset(RecTotal);
DataOffset := DBStream.Size;
RecordTab.DataOffset := DataOffset;
RecordTab.DeleteFlag := False;
DBStream.Write(RecordTab, SizeOf(RecordTab));
end;
end;
// 将调整后的RecTabOffset, RecordTotal写回数据库
Inc(RecTotal);
DBStream.Position := TableHeaderOffset + SizeOf(TTableNameString);
DBStream.Write(RecTabOffset, SizeOf(Integer));
DBStream.Write(RecTotal, SizeOf(Integer));
if FAutoIncFieldIdx <> -1 then DBStream.Write(FTableHeader.AutoIncCounter, SizeOf(Integer));
// 调整FTableHeader
FTableHeader.RecTabOffset := RecTabOffset;
FTableHeader.RecordTotal := RecTotal;
// 写入真正数据
DstBlobStream := TMemoryStream.Create;
DstBlobStream1 := TMemoryStream.Create;
SrcDiskRecBuf := AllocMem(FDiskRecSize);
DstDiskRecBuf := AllocMem(FDiskRecSize);
try
FillChar(BlobHeader, SizeOf(BlobHeader), 0);
// 调整字符串字段
AdjustStrFldInBuffer(FieldBuffers);
// 先写入数据库以占据位置
DBStream.Position := DataOffset;
DBStream.Write(DstDiskRecBuf^, FDiskRecSize);
for I := 0 to FTableHeader.FieldCount - 1 do
begin
FieldBuffer := FieldBuffers.Items[I].Buffer;
// 如果是不定长度数据
if FieldBuffers.Items[I].IsBlob then
begin
BlobStream := TMemoryStream(FieldBuffer);
// 数据编码(压缩、加密)
FDatabase.DBFileIO.EncodeMemoryStream(BlobStream, DstBlobStream, ShouldEncrypt(I), ShouldCompress(I));
DstBlobSize := DstBlobStream.Size;
// 计算BlobHeader
BlobDataPos := DBStream.Position;
BlobHeader.DataOffset := BlobDataPos;
BlobHeader.DataSize := DstBlobSize;
BlobHeader.AreaSize := DstBlobSize + (tdbBlobSizeUnitNum - DstBlobSize mod tdbBlobSizeUnitNum);
// 将BlobHeader写入数据库
Move(BlobHeader, DstDiskRecBuf[FDiskFieldOffsets[I]], SizeOf(BlobHeader));
// 写BLOB数据:
// 如果起用CRC32校检
if FDatabase.CRC32 then
begin
CRC32Value1 := 0;
CRC32Value2 := 0;
repeat
if CRC32Value1 <> CRC32Value2 then
FDatabase.DBFileIO.EncodeMemoryStream(BlobStream, DstBlobStream, ShouldEncrypt(I), ShouldCompress(I));
DstBlobSize := DstBlobStream.Size;
// 计算原始数据的Checksum Value
CRC32Value1 := CheckSumCRC32(BlobStream.Memory^, BlobStream.Size);
// 写入Blob数据
DBStream.Position := BlobDataPos;
DBStream.Write(DstBlobStream.Memory^, DstBlobStream.Size);
// 读入Blob数据
DBStream.Position := BlobDataPos;
DBStream.Read(DstBlobStream.Memory^, DstBlobStream.Size);
// 解码
try
FDatabase.DBFileIO.DecodeMemoryStream(DstBlobStream, DstBlobStream1, ShouldEncrypt(I), ShouldCompress(I));
except
end;
// 计算解码后数据的Checksum Value
CRC32Value2 := CheckSumCRC32(DstBlobStream1.Memory^, DstBlobStream1.Size);
// 如果两次的Checksum Value相等,则说明校检正确,跳出循环
until CRC32Value1 = CRC32Value2;
end else
// 如果不起用CRC32校检
begin
// 直接写入Blob数据
DBStream.Write(DstBlobStream.Memory^, DstBlobStream.Size);
end;
// 填充Blob区域,使得Blob长度为tdbBlobSizeUnitNum的整数倍
DBStream.Write(BlobRestbuf[0], tdbBlobSizeUnitNum - DstBlobSize mod tdbBlobSizeUnitNum);
end else
// 固定长度数据
begin
// 数据编码(加密)
FDatabase.DBFileIO.EncodeMemoryBuffer(FieldBuffer, DstDiskRecBuf + FDiskFieldOffsets[I],
FieldBuffers.Items[I].FieldSize, ShouldEncrypt(I));
end;
end;
// 再次写入数据库
DBStream.Position := DataOffset;
DBStream.Write(DstDiskRecBuf^, FDiskRecSize);
finally
// 释放内存
FreeMem(DstDiskRecBuf, FDiskRecSize);
FreeMem(SrcDiskRecBuf, FDiskRecSize);
DstBlobStream.Free;
DstBlobStream1.Free;
end;
// 调整RecTabLists[0]
MemRecTabItem.DataOffset := DataOffset;
MemRecTabItem.RecIndex := RecTotal - 1;
AddMemRecTabItem(FRecTabLists[0], MemRecTabItem);
// 调整索引
AdjustIndexesForAppend(FieldBuffers, DataOffset, RecTotal - 1, OnAdjustIndex);
if Flush then FDatabase.DBFileIO.Flush;
finally
FDatabase.DBFileIO.Unlock;
end;
end;
//-----------------------------------------------------------------------------
// 将FieldBuffers中的数据写入到数据库的第PhyRecordIdx条记录中
// FieldBuffers: 将要修改的字段数据(包含所有物理字段)
// PhyRecordIdx: 物理记录号(即在FRecTabLists[0]中的记录号) 0-based
// Flush: 修改完后是否flush cache
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ModifyRecordData(FieldBuffers: TFieldBuffers;
PhyRecordIdx: Integer; Flush: Boolean;
OnAdjustIndex: TOnAdjustIndexForModifyEvent);
var
I, DataOffset: Integer;
BakPos, BlobDataPos: Integer;
DstBlobSize: Integer;
BlobHeader, NewBlobHeader: TBlobFieldHeader;
BlobRestBuf: array[0..tdbBlobSizeUnitNum-1] of Char;
BlobStream, DstBlobStream, DstBlobStream1: TMemoryStream;
CRC32Value1, CRC32Value2: Longword;
DiskRecBuf: PChar;
DBStream: TStream;
FieldBuffer: Pointer;
begin
FDatabase.DBFileIO.Lock;
try
DBStream := FDatabase.DBFileIO.DBStream;
DstBlobStream := TMemoryStream.Create;
DstBlobStream1 := TMemoryStream.Create;
DiskRecBuf := AllocMem(FDiskRecSize);
try
// 检查Primary,Unique字段的唯一性
CheckUniqueFieldForModify(FieldBuffers, PhyRecordIdx);
FillChar(BlobRestBuf, SizeOf(BlobRestBuf), 0);
FillChar(BlobHeader, SizeOf(BlobHeader), 0);
DataOffset := GetMemRecTabItem(FRecTabLists[0], PhyRecordIdx).DataOffset;
DBStream.Position := DataOffset;
DBStream.Read(DiskRecBuf^, FDiskRecSize);
for I := 0 to FieldBuffers.Count - 1 do
begin
if not FieldBuffers.Items[I].Active then Continue;
FieldBuffer := FieldBuffers.Items[I].Buffer;
// ----------如果是不定长度数据------------
if FieldBuffers.Items[I].IsBlob then
begin
BlobStream := TMemoryStream(FieldBuffer);
// 数据编码(压缩、加密)
FDatabase.DBFileIO.EncodeMemoryStream(BlobStream, DstBlobStream, ShouldEncrypt(I), ShouldCompress(I));
DstBlobSize := DstBlobStream.Size;
// 读取原来的BlobHeader数据
BlobHeader := PBlobFieldHeader(DiskRecBuf + FDiskFieldOffsets[I])^;
NewBlobHeader := BlobHeader;
// if DstBlobSize <= BlobHeader.AreaSize then
if DstBlobSize < BlobHeader.AreaSize then // modified by haoxg 2004.11.14
begin
BlobDataPos := BlobHeader.DataOffset;
NewBlobHeader.DataOffset := BlobDataPos;
NewBlobHeader.DataSize := DstBlobSize;
NewBlobHeader.AreaSize := BlobHeader.AreaSize;
end else
begin
// 如果Blob数据在文件末尾
if BlobHeader.DataOffset + BlobHeader.AreaSize = DBStream.Size then
begin
BlobDataPos := BlobHeader.DataOffset;
NewBlobHeader.DataOffset := BlobDataPos;
end else
// 如果Blob数据不在文件末尾
begin
BlobDataPos := DBStream.Size;
NewBlobHeader.DataOffset := BlobDataPos;
end;
NewBlobHeader.DataSize := DstBlobSize;
NewBlobHeader.AreaSize := DstBlobSize + (tdbBlobSizeUnitNum - DstBlobSize mod tdbBlobSizeUnitNum);
end;
// 如果起用CRC32校检
if FDatabase.CRC32 then
begin
CRC32Value1 := 0;
CRC32Value2 := 0;
repeat
if CRC32Value1 <> CRC32Value2 then
FDatabase.DBFileIO.EncodeMemoryStream(BlobStream, DstBlobStream, ShouldEncrypt(I), ShouldCompress(I));
DstBlobSize := DstBlobStream.Size;
// 计算原始数据的Checksum Value
CRC32Value1 := CheckSumCRC32(BlobStream.Memory^, BlobStream.Size);
// 写入Blob数据
DBStream.Position := BlobDataPos;
DBStream.Write(DstBlobStream.Memory^, DstBlobStream.Size);
// 读入Blob数据
DBStream.Position := BlobDataPos;
DBStream.Read(DstBlobStream.Memory^, DstBlobStream.Size);
// 解码
try
FDatabase.DBFileIO.DecodeMemoryStream(DstBlobStream, DstBlobStream1, ShouldEncrypt(I), ShouldCompress(I));
except
end;
// 计算解码后数据的Checksum Value
CRC32Value2 := CheckSumCRC32(DstBlobStream1.Memory^, DstBlobStream1.Size);
// 如果两次的Checksum Value相等,则说明校检正确,跳出循环
until CRC32Value1 = CRC32Value2;
end else
// 如果不起用CRC32校检
begin
// 直接写入Blob数据
DBStream.Position := BlobDataPos;
DBStream.Write(DstBlobStream.Memory^, DstBlobStream.Size);
end;
// 填充Blob区域,使得Blob长度为TDBlobSizeUnitNum的整数倍
DBStream.Write(BlobRestBuf[0], tdbBlobSizeUnitNum - DstBlobSize mod tdbBlobSizeUnitNum);
// 写入调整后的BlobHeader
PBlobFieldHeader(DiskRecBuf + FDiskFieldOffsets[I])^ := NewBlobHeader;
// -------------如果是AutoInc字段-----------------------
end else if FieldBuffers.Items[I].FieldType = ftAutoInc then
begin
// 作改变
if PInteger(FieldBuffer)^ <> 0 then
begin
// 数据编码(加密)
FDatabase.DBFileIO.EncodeMemoryBuffer(FieldBuffer, DiskRecBuf + FDiskFieldOffsets[I],
FieldBuffers.Items[I].FieldSize, ShouldEncrypt(I));
// 调整AutoIncCounter
if PInteger(FieldBuffer)^ > FTableHeader.AutoIncCounter then
begin
FTableHeader.AutoIncCounter := PInteger(FieldBuffer)^;
BakPos := DBStream.Position;
DBStream.Position := FDatabase.DBFileIO.TableTab.TableHeaderOffset[FTableIdx] + SizeOf(TTableNameString) + SizeOf(Integer) * 2;
DBStream.Write(FTableHeader.AutoIncCounter, SizeOf(Integer));
DBStream.Position := BakPos;
end;
end;
end else
// -------------其他固定长度数据-------------------------
begin
// 数据编码(加密)
FDatabase.DBFileIO.EncodeMemoryBuffer(FieldBuffer, DiskRecBuf + FDiskFieldOffsets[I],
FieldBuffers.Items[I].FieldSize, ShouldEncrypt(I));
end;
end;
// 写入数据库
DBStream.Position := DataOffset;
DBStream.Write(DiskRecBuf^, FDiskRecSize);
finally
// 释放内存
FreeMem(DiskRecBuf, FDiskRecSize);
DstBlobStream.Free;
DstBlobStream1.Free;
end;
// 调整索引
AdjustIndexesForModify(FieldBuffers, PhyRecordIdx, OnAdjustIndex);
if Flush then FDatabase.DBFileIO.Flush;
finally
FDatabase.DBFileIO.Unlock;
end;
end;
//-----------------------------------------------------------------------------
// 删除记录
// PhyRecordIdx: 物理记录号(即在FRecTabLists[0]中的记录号) 0-based
// Flush: 修改完后是否flush cache
//-----------------------------------------------------------------------------
procedure TTinyTableIO.DeleteRecordData(PhyRecordIdx: Integer; Flush: Boolean);
begin
FDatabase.DBFileIO.Lock;
try
// 在数据库中做删除标记
WriteDeleteFlag(PhyRecordIdx);
// 调整索引
AdjustIndexesForDelete(PhyRecordIdx);
// 删除FRecTabLists[0]中的对应项目
DeleteMemRecTabItem(FRecTabLists[0], PhyRecordIdx);
if Flush then FDatabase.DBFileIO.Flush;
finally
FDatabase.DBFileIO.Unlock;
end;
end;
//-----------------------------------------------------------------------------
// 删除所有记录
//-----------------------------------------------------------------------------
procedure TTinyTableIO.DeleteAllRecords;
var
I: Integer;
begin
FDatabase.DBFileIO.Lock;
try
// 调整FTableHeader
FTableHeader.RecTabOffset := 0;
FTableHeader.RecordTotal := 0;
FTableHeader.AutoIncCounter := 0;
for I := 0 to tdbMaxIndex - 1 do
begin
FTableHeader.IndexHeader[I].StartIndex := 0;
FTableHeader.IndexHeader[I].IndexOffset := 0;
end;
FDatabase.DBFileIO.WriteTableHeader(TableIdx, FTableHeader);
FDatabase.DBFileIO.Flush;
// 清空FRecTabLists
for I := 0 to High(FRecTabLists) do
ClearMemRecTab(FRecTabLists[I]);
// 清空FRecTabBlockOffsets和FIdxTabBlockOffsets
SetLength(FRecTabBlockOffsets, 0);
for I := 0 to High(FIdxTabBlockOffsets) do
SetLength(FIdxTabBlockOffsets[I], 0);
finally
FDatabase.DBFileIO.Unlock;
end;
end;
//-----------------------------------------------------------------------------
// 读取一条记录中某个字段的数据
// DstStream: 结果数据
// DiskRecIndex: 这条记录在文件中RecordTab中的下标号(0-based)
// FieldIdx: 物理字段号(0-based)
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ReadFieldData(DstStream: TMemoryStream; DiskRecIndex, FieldIdx: Integer);
var
FieldOffset, FieldSize: Integer;
RecTabItemOffset: Integer;
FieldType: TFieldType;
begin
// 取记录表中的第RecIndex个RecTabItem的偏移
RecTabItemOffset := GetRecTabItemOffset(DiskRecIndex);
FieldOffset := FDiskFieldOffsets[FieldIdx];
FieldType := FTableHeader.FieldTab[FieldIdx].FieldType;
if FieldType in BlobFieldTypes then
FieldSize := SizeOf(TBlobFieldHeader)
else
FieldSize := GetFieldSize(FieldType, FTableHeader.FieldTab[FieldIdx].FieldSize);
FDatabase.DBFileIO.ReadFieldData(DstStream, RecTabItemOffset, FieldOffset, FieldSize,
FieldType in BlobFieldTypes, ShouldEncrypt(FieldIdx), ShouldCompress(FieldIdx));
end;
//-----------------------------------------------------------------------------
// 读取记录数据到FieldBuffers中
// RecTabList: 记录集,用于限定RecIndex
// RecIndex: 这条记录在参数RecTabList中的下标号(0-based)
// 注意:
// FieldBuffer必须事先指定好FieldType, FieldSize, Buffer等信息.
// 如果某些字段不用读取, 可以把对应FieldBufferItem中的Active设为False.
//-----------------------------------------------------------------------------
procedure TTinyTableIO.ReadRecordData(FieldBuffers: TFieldBuffers; RecTabList: TList; RecordIdx: Integer);
var
SrcDiskRecBuf: PChar;
RecDataOffset: Integer;
I, FldSize, DiskOfs: Integer;
BlobStream: TMemoryStream;
begin
FDatabase.DBFileIO.Lock;
SrcDiskRecBuf := AllocMem(FDiskRecSize);
try
RecDataOffset := GetMemRecTabItem(RecTabList, RecordIdx).DataOffset;
FDatabase.DBFileIO.ReadBuffer(SrcDiskRecBuf[0], RecDataOffset, FDiskRecSize);
for I := 0 to FieldBuffers.Count - 1 do
begin
if FieldBuffers.Items[I].Active then
begin
DiskOfs := FDiskFieldOffsets[I];
if not FieldBuffers.Items[I].IsBlob then
begin
FldSize := FieldBuffers.Items[I].FFieldSize;
FDatabase.DBFileIO.DecodeMemoryBuffer(SrcDiskRecBuf + DiskOfs, FieldBuffers.Items[I].Buffer,
FldSize, ShouldEncrypt(I) );
end else
begin
// 从Buffer中取出BlobStream
BlobStream := TMemoryStream(FieldBuffers.Items[I].Buffer);
// 初始化BlobStream
(BlobStream as TOptimBlobStream).Init(RecDataOffset + DiskOfs, ShouldEncrypt(I), ShouldCompress(I));
end;
end;
end;
finally
FreeMem(SrcDiskRecBuf);
FDatabase.DBFileIO.Unlock;
end;
end;
{ TTDEDataSet }
constructor TTDEDataSet.Create(AOwner: TComponent);
begin
inherited;
ShowNagScreen(Self); // Show nag-screen.
FDatabaseName := '';
FMediumType := mtDisk;
FCurRec := -1;
FRecordSize := 0;
FFilterParser := TFilterParser.Create(Self);
end;
destructor TTDEDataSet.Destroy;
begin
FFilterParser.Free;
inherited;
end;
function TTDEDataSet.GetActiveRecBuf(var RecBuf: PChar): Boolean;
begin
case State of
dsBrowse: if IsEmpty then RecBuf := nil else RecBuf := ActiveBuffer;
dsEdit, dsInsert: RecBuf := ActiveBuffer;
dsSetKey: RecBuf := FKeyBuffer;
dsCalcFields: RecBuf := CalcBuffer;
dsFilter: RecBuf := FFilterBuffer;
dsNewValue: RecBuf := ActiveBuffer;
else
RecBuf := nil;
end;
Result := RecBuf <> nil;
end;
procedure TTDEDataSet.ActivateFilters;
begin
end;
procedure TTDEDataSet.DeactivateFilters;
begin
end;
procedure TTDEDataSet.ReadRecordData(Buffer: PChar; RecordIdx: Integer);
begin
end;
function TTDEDataSet.GetFieldOffsetByFieldNo(FieldNo: Integer): Integer;
begin
Result := FFieldOffsets[FieldNo - 1];
end;
procedure TTDEDataSet.ReadFieldData(DstStream: TMemoryStream; FieldDataOffset, FieldSize: Integer;
IsBlob: Boolean; ShouldEncrypt, ShouldCompress: Boolean);
begin
Database.DBFileIO.ReadFieldData(DstStream, FieldDataOffset, FieldSize, IsBlob, ShouldEncrypt, ShouldCompress);
end;
function TTDEDataSet.GetRecordCount: Longint;
begin
Result := 0;
end;
procedure TTDEDataSet.SetMediumType(Value: TTinyDBMediumType);
var
ADatabase: TTinyDatabase;
begin
if FMediumType <> Value then
begin
CheckInactive;
FMediumType := Value;
ADatabase := DBSession.FindDatabase(FDatabaseName);
if ADatabase <> nil then
ADatabase.MediumType := FMediumType;
end;
end;
procedure TTDEDataSet.SetPassword(const Value: string);
var
ADatabase: TTinyDatabase;
begin
ADatabase := OpenDatabase(False);
if ADatabase <> nil then
ADatabase.SetPassword(Value);
end;
procedure TTDEDataSet.SetCRC32(Value: Boolean);
var
ADatabase: TTinyDatabase;
begin
ADatabase := OpenDatabase(False);
if ADatabase <> nil then
ADatabase.CRC32 := Value;
end;
function TTDEDataSet.GetCRC32: Boolean;
begin
Result := (Database <> nil) and Database.CRC32;
end;
function TTDEDataSet.GetCanAccess: Boolean;
begin
Result := (Database <> nil) and Database.CanAccess;
end;
procedure TTDEDataSet.InitRecordSize;
var
I: Integer;
begin
// 初始化FRecordSize
FRecordSize := 0;
for I := 0 to Fields.Count - 1 do
begin
if Fields[I].FieldNo > 0 then
begin
if Fields[I].IsBlob then
Inc(FRecordSize, SizeOf(PMemoryStream))
else
Inc(FRecordSize, Fields[I].DataSize);
end;
end;
// 初始化FRecBufSize
FRecBufSize := FRecordSize + CalcFieldsSize + SizeOf(TRecInfo);
end;
procedure TTDEDataSet.InitFieldOffsets;
var
I, Offset, MaxNo: Integer;
begin
Offset := 0;
MaxNo := 0;
for I := 0 to Fields.Count - 1 do
if MaxNo < Fields[I].FieldNo then
MaxNo := Fields[I].FieldNo;
SetLength(FFieldOffsets, MaxNo);
for I := 0 to Fields.Count - 1 do
begin
if Fields[I].FieldNo > 0 then
begin
FFieldOffsets[Fields[I].FieldNo - 1] := Offset;
if Fields[I].IsBlob then
Inc(Offset, SizeOf(PMemoryStream))
else
Inc(Offset, Fields[I].DataSize);
end;
end;
end;
function TTDEDataSet.FiltersAccept: Boolean;
function FuncFilter: Boolean;
begin
Result := True;
if Assigned(OnFilterRecord) then
OnFilterRecord(Self, Result);
end;
function ExprFilter: Boolean;
begin
Result := True;
if Filter <> '' then
Result := FFilterParser.Calculate(TStrCompOptions(FilterOptions)) <> 0;
end;
begin
Result := FuncFilter;
if Result then Result := ExprFilter;
end;
procedure TTDEDataSet.SetFilterData(const Text: string; Options: TFilterOptions);
var
Changed: Boolean;
SaveText: string;
begin
Changed := False;
SaveText := Filter;
if Active then
begin
CheckBrowseMode;
if Text <> '' then FFilterParser.Parse(Text);
if (Filter <> Text) or (FilterOptions <> Options) then Changed := True;
end;
inherited SetFilterText(Text);
inherited SetFilterOptions(Options);
try
if Changed then
if Filtered then
begin
DeactivateFilters;
ActivateFilters;
end;
except
inherited SetFilterText(SaveText);
raise;
end;
end;
procedure TTDEDataSet.AllocKeyBuffers;
var
KeyIndex: TTDKeyIndex;
begin
try
for KeyIndex := Low(TTDKeyIndex) to High(TTDKeyIndex) do
begin
FKeyBuffers[KeyIndex] := AllocRecordBuffer;
InitKeyBuffer(KeyIndex);
end;
except
FreeKeyBuffers;
raise;
end;
end;
procedure TTDEDataSet.FreeKeyBuffers;
var
KeyIndex: TTDKeyIndex;
begin
for KeyIndex := Low(TTDKeyIndex) to High(TTDKeyIndex) do
FreeRecordBuffer(FKeyBuffers[KeyIndex]);
end;
procedure TTDEDataSet.InitKeyBuffer(KeyIndex: TTDKeyIndex);
begin
InternalInitRecord(FKeyBuffers[KeyIndex]);
end;
//-----------------------------------------------------------------------------
// TDataSet calls this method to allocate the record buffer. Here we use
// FRecBufSize which is equal to the size of the data plus the size of the
// TRecInfo structure.
//-----------------------------------------------------------------------------
function TTDEDataSet.AllocRecordBuffer: PChar;
var
I, FieldOffset: Integer;
BlobStream: TMemoryStream;
begin
Result := AllocMem(FRecBufSize);
for I := 0 to Fields.Count - 1 do
begin
if Fields[I].IsBlob then
begin
FieldOffset := GetFieldOffsetByFieldNo(Fields[I].FieldNo);
BlobStream := TOptimBlobStream.Create(Self);
PMemoryStream(@Result[FieldOffset])^ := BlobStream;
end;
end;
end;
//-----------------------------------------------------------------------------
// Again, TDataSet calls this method to free the record buffer.
// Note: Make sure the value of FRecBufSize does not change before all
// allocated buffers are freed.
//-----------------------------------------------------------------------------
procedure TTDEDataSet.FreeRecordBuffer(var Buffer: PChar);
var
I, FieldOffset: Integer;
BlobStream: TMemoryStream;
begin
if Buffer = nil then Exit;
for I := 0 to Fields.Count - 1 do
begin
if Fields[I].IsBlob then
begin
FieldOffset := GetFieldOffsetByFieldNo(Fields[I].FieldNo);
BlobStream := PMemoryStream(@Buffer[FieldOffset])^;
if Assigned(BlobStream) then
begin
BlobStream.Free;
end;
end;
end;
FreeMem(Buffer, FRecBufSize);
Buffer := nil;
end;
procedure TTDEDataSet.GetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PInteger(Data)^ := PRecInfo(Buffer + FRecordSize + CalcFieldsSize).Bookmark;
end;
//-----------------------------------------------------------------------------
// Bookmark flags are used to indicate if a particular record is the first
// or last record in the dataset. This is necessary for "crack" handling.
// If the bookmark flag is bfBOF or bfEOF then the bookmark is not actually
// used; InternalFirst, or InternalLast are called instead by TDataSet.
//-----------------------------------------------------------------------------
function TTDEDataSet.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag;
begin
Result := PRecInfo(Buffer + FRecordSize + CalcFieldsSize).BookmarkFlag;
end;
//-----------------------------------------------------------------------------
// This method returns the size of just the data in the record buffer.
// Do not confuse this with RecBufSize which also includes any additonal
// structures stored in the record buffer (such as TRecInfo).
//-----------------------------------------------------------------------------
function TTDEDataSet.GetRecordSize: Word;
begin
Result := FRecordSize;
end;
//-----------------------------------------------------------------------------
// This routine is called to initialize a record buffer. In this sample,
// we fill the buffer with zero values, but we might have code to initialize
// default values or do other things as well.
//-----------------------------------------------------------------------------
procedure TTDEDataSet.InternalInitRecord(Buffer: PChar);
var
I, FieldOffset: Integer;
BlobStream: TMemoryStream;
TempDateTime: TDateTime;
TempTimeStamp: TTimeStamp;
TempDouble: Double;
TempInteger: Integer;
begin
for I := 0 to Fields.Count - 1 do
begin
if Fields[I].FieldNo > 0 then
begin
FieldOffset := GetFieldOffsetByFieldNo(Fields[I].FieldNo);
if Fields[I].IsBlob then
begin
BlobStream := PMemoryStream(@Buffer[FieldOffset])^;
BlobStream.Clear;
end else
if Fields[I].DataType = ftDateTime then
begin
TempDateTime := 0; //Now;
TempTimeStamp := DateTimeToTimeStamp(TempDateTime);
TempDouble := TimeStampToMSecs(TempTimeStamp);
Move(TempDouble, Buffer[FieldOffset], Fields[I].DataSize);
end else
if Fields[I].DataType = ftDate then
begin
TempInteger := DateTimeToTimeStamp(SysUtils.Date).Date;
Move(TempInteger, Buffer[FieldOffset], Fields[I].DataSize);
end else
if Fields[I].DataType = ftTime then
begin
TempInteger := DateTimeToTimeStamp(SysUtils.Time).Time;
Move(TempInteger, Buffer[FieldOffset], Fields[I].DataSize);
end else
begin
FillChar(Buffer[FieldOffset], Fields[I].DataSize, 0);
end;
end else {fkCalculated, fkLookup}
begin
FieldOffset := FRecordSize + Fields[I].Offset;
FillChar(Buffer[FieldOffset], 1, 0);
if Fields[I].IsBlob then
begin
BlobStream := PMemoryStream(@Buffer[FieldOffset + 1])^;
BlobStream.Clear;
end else
begin
FillChar(Buffer[FieldOffset + 1], Fields[I].DataSize, 0);
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// This method is called by TDataSet.First. Crack behavior is required.
// That is we must position to a special place *before* the first record.
// Otherwise, we will actually end up on the second record after Resync
// is called.
//-----------------------------------------------------------------------------
procedure TTDEDataSet.InternalFirst;
begin
FCurRec := -1;
end;
//-----------------------------------------------------------------------------
// Again, we position to the crack *after* the last record here.
//-----------------------------------------------------------------------------
procedure TTDEDataSet.InternalLast;
begin
FCurRec := RecordCount;
end;
//-----------------------------------------------------------------------------
// This is the exception handler which is called if an exception is raised
// while the component is being stream in or streamed out. In most cases this
// should be implemented useing the application exception handler as follows. }
//-----------------------------------------------------------------------------
procedure TTDEDataSet.InternalHandleException;
begin
Application.HandleException(Self);
end;
//-----------------------------------------------------------------------------
// This function does the same thing as InternalGotoBookmark, but it takes
// a record buffer as a parameter instead
//-----------------------------------------------------------------------------
procedure TTDEDataSet.InternalSetToRecord(Buffer: PChar);
begin
InternalGotoBookmark(@PRecInfo(Buffer + FRecordSize + CalcFieldsSize).Bookmark);
end;
procedure TTDEDataSet.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag);
begin
PRecInfo(Buffer + FRecordSize + CalcFieldsSize).BookmarkFlag := Value;
end;
procedure TTDEDataSet.SetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PRecInfo(Buffer + FRecordSize + CalcFieldsSize).Bookmark := PInteger(Data)^;
end;
procedure TTDEDataSet.SetFieldData(Field: TField; Buffer: Pointer);
var
RecBuf: PChar;
FieldOffset: Integer;
begin
if not GetActiveRecBuf(RecBuf) then Exit;
if Field.FieldNo > 0 then
begin
if Buffer <> nil then
begin
FieldOffset := GetFieldOffsetByFieldNo(Field.FieldNo);
if Field.IsBlob then
begin
DatabaseError(SGeneralError);
end else
begin
Move(Buffer^, RecBuf[FieldOffset], Field.DataSize);
end;
DataEvent(deFieldChange, Longint(Field));
end;
end else {fkCalculated, fkLookup}
begin
Inc(RecBuf, FRecordSize + Field.Offset);
Boolean(RecBuf[0]) := LongBool(Buffer);
if Boolean(RecBuf[0]) then Move(Buffer^, RecBuf[1], Field.DataSize);
end;
if (State <> dsCalcFields) and (State <> dsFilter) then
DataEvent(deFieldChange, Longint(Field));
end;
//-----------------------------------------------------------------------------
// This property is used while opening the dataset.
// It indicates if data is available even though the
// current state is still dsInActive.
//-----------------------------------------------------------------------------
function TTDEDataSet.IsCursorOpen: Boolean;
begin
Result := False;
end;
procedure TTDEDataSet.DataConvert(Field: TField; Source, Dest: Pointer; ToNative: Boolean);
{ DateTime Conversions }
function NativeToDateTime(DataType: TFieldType; Data: TDateTimeRec): TDateTime;
var
TimeStamp: TTimeStamp;
begin
case DataType of
ftDate:
begin
TimeStamp.Time := 0;
TimeStamp.Date := Data.Date;
end;
ftTime:
begin
TimeStamp.Time := Data.Time;
TimeStamp.Date := DateDelta;
end;
else
try
TimeStamp := MSecsToTimeStamp(Data.DateTime);
except
TimeStamp.Time := 0;
TimeStamp.Date := 0;
end;
end;
try
Result := TimeStampToDateTime(TimeStamp);
except
Result := 0;
end;
end;
function DateTimeToNative(DataType: TFieldType; Data: TDateTime): TDateTimeRec;
var
TimeStamp: TTimeStamp;
begin
TimeStamp := DateTimeToTimeStamp(Data);
case DataType of
ftDate: Result.Date := TimeStamp.Date;
ftTime: Result.Time := TimeStamp.Time;
else
Result.DateTime := TimeStampToMSecs(TimeStamp);
end;
end;
begin
case Field.DataType of
ftDate, ftTime, ftDateTime:
if ToNative then
TDateTimeRec(Dest^) := DateTimeToNative(Field.DataType, TDateTime(Source^)) else
TDateTime(Dest^) := NativeToDateTime(Field.DataType, TDateTimeRec(Source^));
else
inherited;
end;
end;
function TTDEDataSet.GetRecNo: Longint;
begin
UpdateCursorPos;
if (FCurRec = -1) and (RecordCount > 0) then
Result := 1
else
Result := FCurRec + 1;
end;
procedure TTDEDataSet.SetRecNo(Value: Integer);
begin
CheckBrowseMode;
if (Value >= 0) and (Value <= RecordCount) and (Value <> RecNo) then
begin
DoBeforeScroll;
FCurRec := Value - 1;
Resync([]);
DoAfterScroll;
end;
end;
function TTDEDataSet.GetCanModify: Boolean;
begin
Result := FCanModify;
end;
procedure TTDEDataSet.SetFiltered(Value: Boolean);
begin
if Active then
begin
CheckBrowseMode;
if Filtered <> Value then
begin
if Value then ActivateFilters
else DeactivateFilters;
inherited SetFiltered(Value);
end;
First;
end else
inherited SetFiltered(Value);
end;
procedure TTDEDataSet.SetFilterOptions(Value: TFilterOptions);
begin
SetFilterData(Filter, Value);
end;
procedure TTDEDataSet.SetFilterText(const Value: string);
begin
SetFilterData(Value, FilterOptions);
end;
procedure TTDEDataSet.DoAfterOpen;
begin
if Filtered then ActivateFilters;
inherited;
end;
function TTDEDataSet.FindRecord(Restart, GoForward: Boolean): Boolean;
var
RecIdx, Step, StartIdx, EndIdx: Integer;
SaveCurRec: Integer;
Accept: Boolean;
begin
CheckBrowseMode;
DoBeforeScroll;
SetFound(False);
UpdateCursorPos;
CursorPosChanged;
if GoForward then
begin
Step := 1;
if Restart then StartIdx := 0
else StartIdx := FCurRec + 1;
EndIdx := RecordCount - 1;
end else
begin
Step := -1;
if Restart then StartIdx := RecordCount - 1
else StartIdx := FCurRec - 1;
EndIdx := 0;
end;
if Filter <> '' then FFilterParser.Parse(Filter);
SaveCurRec := FCurRec;
SetTempState(dsFilter);
try
Accept := False;
RecIdx := StartIdx;
while (GoForward and (RecIdx <= EndIdx)) or
(not GoForward and (RecIdx >= EndIdx)) do
begin
FCurRec := RecIdx;
FFilterBuffer := ActiveBuffer;
ReadRecordData(FFilterBuffer, FCurRec);
Accept := FiltersAccept;
if Accept then Break;
Inc(RecIdx, Step);
end;
finally
RestoreState(dsBrowse);
end;
if Accept then
begin
SetFound(True);
end else
begin
FCurRec := SaveCurRec;
end;
Resync([rmExact, rmCenter]);
Result := Found;
if Result then DoAfterScroll;
end;
function TTDEDataSet.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
begin
Result := TTinyBlobStream.Create(Field as TBlobField, Mode);
end;
//-----------------------------------------------------------------------------
// 从RecordBuffer中取出字段值
// 返回:
// True: 成功,且值不为空
// False: 失败,或者值为空
//-----------------------------------------------------------------------------
function TTDEDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
var
RecBuf: PChar;
FieldOffset: Integer;
begin
Result := GetActiveRecBuf(RecBuf);
if not Result then Exit;
if Field.FieldNo > 0 then
begin
if Buffer <> nil then
begin
FieldOffset := GetFieldOffsetByFieldNo(Field.FieldNo);
if Field.IsBlob then
begin
DatabaseError(SGeneralError);
end else
begin
Move(RecBuf[FieldOffset], Buffer^, Field.DataSize);
end;
Result := True;
end;
end else {fkCalculated, fkLookup}
begin
FieldOffset := FRecordSize + Field.Offset;
Result := Boolean(RecBuf[FieldOffset]);
if Result and (Buffer <> nil) then
Move((RecBuf + FieldOffset + 1)^, Buffer^, Field.DataSize);
end;
end;
{ TTDBDataSet }
constructor TTDBDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if AOwner is TTinyDatabase then
begin
DatabaseName := TTinyDatabase(AOwner).DatabaseName;
SessionName := TTinyDatabase(AOwner).SessionName;
end;
end;
procedure TTDBDataSet.CheckDBSessionName;
var
S: TTinySession;
Database: TTinyDatabase;
begin
if (SessionName <> '') and (DatabaseName <> '') then
begin
S := Sessions.FindSession(SessionName);
if Assigned(S) and not Assigned(S.DoFindDatabase(DatabaseName, Self)) then
begin
Database := DefaultSession.DoFindDatabase(DatabaseName, Self);
if Assigned(Database) then Database.CheckSessionName(True);
end;
end;
end;
procedure TTDBDataSet.OpenCursor(InfoQuery: Boolean);
begin
CheckDBSessionName;
FDatabase := OpenDatabase(True);
FDatabase.RegisterClient(Self);
FDatabase.CheckCanAccess;
inherited;
end;
procedure TTDBDataSet.CloseCursor;
begin
inherited;
if FDatabase <> nil then
begin
FDatabase.UnregisterClient(Self);
FDatabase.Session.CloseDatabase(FDatabase);
FDatabase := nil;
end;
end;
function TTDBDataSet.OpenDatabase(IncRef: Boolean): TTinyDatabase;
begin
with Sessions.List[FSessionName] do
Result := DoOpenDatabase(FDatabasename, Self.Owner, Self, IncRef);
end;
procedure TTDBDataSet.CloseDatabase(Database: TTinyDatabase);
begin
if Assigned(Database) then
Database.Session.CloseDatabase(Database);
end;
procedure TTDBDataSet.Disconnect;
begin
Close;
end;
function TTDBDataSet.GetDBSession: TTinySession;
begin
if (FDatabase <> nil) then
Result := FDatabase.Session
else
Result := Sessions.FindSession(SessionName);
if Result = nil then Result := DefaultSession;
end;
procedure TTDBDataSet.SetDatabaseName(const Value: string);
begin
if csReading in ComponentState then
FDatabaseName := Value
else if FDatabaseName <> Value then
begin
CheckInactive;
if FDatabase <> nil then DatabaseError(SDatabaseOpen, Self);
FDatabaseName := Value;
DataEvent(dePropertyChange, 0);
end;
end;
procedure TTDBDataSet.SetSessionName(const Value: string);
begin
CheckInactive;
FSessionName := Value;
DataEvent(dePropertyChange, 0);
end;
{ TTinyTable }
constructor TTinyTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTableName := '';
FIndexName := '';
FIndexIdx := -1;
FUpdateCount := 0;
FIndexDefs := TIndexDefs.Create(Self);
FMasterLink := TMasterDataLink.Create(Self);
FMasterLink.OnMasterChange := MasterChanged;
FMasterLink.OnMasterDisable := MasterDisabled;
end;
destructor TTinyTable.Destroy;
begin
FIndexDefs.Free;
FMasterLink.Free;
inherited Destroy;
end;
function TTinyTable.GetRecordCount: Integer;
begin
if FRecTabList = nil then
Result := 0
else
Result := FRecTabList.Count;
end;
function TTinyTable.GetCanModify: Boolean;
begin
Result := inherited GetCanModify and not ReadOnly and not Database.DBFileIO.FileIsReadOnly;
end;
function TTinyTable.GetDataSource: TDataSource;
begin
Result := FMasterLink.DataSource;
end;
procedure TTinyTable.SetDatabaseName(const Value: string);
begin
inherited;
FTableName := '';
FIndexName := '';
end;
procedure TTinyTable.DoAfterOpen;
begin
CheckMasterRange;
inherited;
end;
procedure TTinyTable.SetTableName(const Value: string);
begin
if FTableName <> Value then
begin
CheckInactive;
FTableName := Value;
end;
end;
procedure TTinyTable.SetIndexName(const Value: string);
begin
if Value = '' then
begin
FIndexName := Value;
FIndexIdx := -1;
end else
begin
FIndexName := Value;
end;
if Active then
begin
CheckBrowseMode;
FIndexIdx := FTableIO.IndexDefs.IndexOf(FIndexName);
if FIndexIdx = -1 then
FIndexIdx := FTableIO.CheckPrimaryFieldExists;
SwitchToIndex(FIndexIdx);
CheckMasterRange;
First;
end;
end;
procedure TTinyTable.SetReadOnly(Value: Boolean);
begin
FReadOnly := Value;
end;
procedure TTinyTable.SetMasterFields(const Value: string);
var
SaveValue: string;
begin
SaveValue := FMasterLink.FieldNames;
try
FMasterLink.FieldNames := Value;
except
FMasterLink.FieldNames := SaveValue;
raise;
end;
end;
procedure TTinyTable.SetDataSource(Value: TDataSource);
begin
if IsLinkedTo(Value) then DatabaseError(SCircularDataLink, Self);
FMasterLink.DataSource := Value;
end;
function TTinyTable.GetTableIdx: Integer;
begin
if FTableIO <> nil then
Result := FTableIO.TableIdx
else
Result := -1;
end;
function TTinyTable.GetMasterFields: string;
begin
Result := FMasterLink.FieldNames;
end;
procedure TTinyTable.InitIndexDefs;
var
I, J: Integer;
IndexName, Fields: string;
Options: TIndexOptions;
List: TStrings;
begin
List := TStringList.Create;
FIndexDefs.Clear;
for I := 0 to FTableIO.IndexDefs.Count - 1 do
begin
IndexName := FTableIO.IndexDefs[I].Name;
List.Clear;
for J := 0 to High(FTableIO.IndexDefs[I].FieldIdxes) do
List.Add(FTableIO.FieldDefs[FTableIO.IndexDefs[I].FieldIdxes[J]].Name);
Fields := List.CommaText;
Options := [];
if tiPrimary in FTableIO.IndexDefs[I].Options then Include(Options, ixPrimary);
if tiUnique in FTableIO.IndexDefs[I].Options then Include(Options, ixUnique);
if tiDescending in FTableIO.IndexDefs[I].Options then Include(Options, ixDescending);
if tiCaseInsensitive in FTableIO.IndexDefs[I].Options then Include(Options, ixCaseInsensitive);
FIndexDefs.Add(IndexName, Fields, Options);
end;
List.Free;
end;
procedure TTinyTable.InitCurRecordTab;
begin
FIndexIdx := FTableIO.IndexDefs.IndexOf(FIndexName);
if FIndexIdx = -1 then
FIndexIdx := FTableIO.CheckPrimaryFieldExists;
SwitchToIndex(FIndexIdx);
end;
procedure TTinyTable.ClearMemRecTab(AList: TList);
var
I: Integer;
begin
if not Assigned(AList) then Exit;
for I := 0 to AList.Count - 1 do
Dispose(PMemRecTabItem(AList.Items[I]));
AList.Clear;
end;
procedure TTinyTable.AddMemRecTabItem(AList: TList; Value: TMemRecTabItem);
var
MemRecTabItemPtr: PMemRecTabItem;
begin
New(MemRecTabItemPtr);
MemRecTabItemPtr^ := Value;
AList.Add(MemRecTabItemPtr);
end;
procedure TTinyTable.InsertMemRecTabItem(AList: TList; Index: Integer; Value: TMemRecTabItem);
var
MemRecTabItemPtr: PMemRecTabItem;
begin
New(MemRecTabItemPtr);
MemRecTabItemPtr^ := Value;
AList.Insert(Index, MemRecTabItemPtr);
end;
procedure TTinyTable.DeleteMemRecTabItem(AList: TList; Index: Integer);
var
F: PMemRecTabItem;
begin
F := AList.Items[Index];
Dispose(F);
AList.Delete(Index);
end;
function TTinyTable.GetMemRecTabItem(AList: TList; Index: Integer): TMemRecTabItem;
begin
Result := PMemRecTabItem(AList.Items[Index])^;
end;
//-----------------------------------------------------------------------------
// 切换索引
// IndexIdx: 索引号 0-based
//-----------------------------------------------------------------------------
procedure TTinyTable.SwitchToIndex(IndexIdx: Integer);
var
I: Integer;
MemRecTabItemPtr: PMemRecTabItem;
begin
FTableIO.InitRecTabList(IndexIdx + 1);
ClearMemRecTab(FRecTabList);
for I := 0 to FTableIO.RecTabLists[IndexIdx + 1].Count - 1 do
begin
New(MemRecTabItemPtr);
MemRecTabItemPtr^ := PMemRecTabItem(FTableIO.RecTabLists[IndexIdx + 1].Items[I])^;
FRecTabList.Add(MemRecTabItemPtr);
end;
FCanModify := True;
end;
//-----------------------------------------------------------------------------
// 读取记录数据到Buffer中
// RecordIdx: 在当前记录集中的记录号 0-based
// 注:Buffer中数据存放格式按照TDataSet.ActiveBuffer定义
// 非Blob字段按顺序排列,Blob字段用PMemoryStream代替
//-----------------------------------------------------------------------------
procedure TTinyTable.ReadRecordData(Buffer: PChar; RecordIdx: Integer);
var
FieldBuffers: TFieldBuffers;
begin
if (RecordIdx < 0) or (RecordIdx >= RecordCount) then Exit;
FieldBuffers := TFieldBuffers.Create;
RecordBufferToFieldBuffers(Buffer, FieldBuffers);
FTableIO.ReadRecordData(FieldBuffers, FRecTabList, RecordIdx);
FieldBuffers.Free;
end;
//-----------------------------------------------------------------------------
// AppendRecordData的回调函数
//-----------------------------------------------------------------------------
procedure TTinyTable.OnAdjustIndexForAppend(IndexIdx, InsertPos: Integer; MemRecTabItem: TMemRecTabItem);
var
Pos, ResultState: Integer;
begin
if not Filtered and not FSetRanged then
begin
if FIndexIdx = IndexIdx then
begin
if FIndexIdx = -1 then
begin
AddMemRecTabItem(FRecTabList, MemRecTabItem);
end else
begin
// 调整FRecTabList
InsertMemRecTabItem(FRecTabList, InsertPos, MemRecTabItem);
// 调整FCurRec
FCurRec := InsertPos;
end;
end;
end else
begin
if FIndexIdx = IndexIdx then
begin
if FIndexIdx = -1 then
begin
AddMemRecTabItem(FRecTabList, MemRecTabItem);
end else
begin
// 查找应插入的位置
Pos := SearchInsertPos(IndexIdx, ResultState);
// 调整FRecTabList
InsertMemRecTabItem(FRecTabList, Pos, MemRecTabItem);
// 调整FCurRec
FCurRec := Pos;
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// 将Buffer中的数据新增到数据库中
// 注:Buffer 中数据格式的定义同ReadRecordData
//-----------------------------------------------------------------------------
procedure TTinyTable.AppendRecordData(Buffer: PChar);
var
FieldBuffers: TFieldBuffers;
begin
FieldBuffers := TFieldBuffers.Create;
try
RecordBufferToFieldBuffers(Buffer, FieldBuffers);
FTableIO.AppendRecordData(FieldBuffers, (FUpdateCount = 0) and Database.FlushCacheAlways, OnAdjustIndexForAppend);
finally
FieldBuffers.Free;
end;
end;
//-----------------------------------------------------------------------------
// ModifyRecordData的回调函数
//-----------------------------------------------------------------------------
procedure TTinyTable.OnAdjustIndexForModify(IndexIdx, FromRecIdx, ToRecIdx: Integer);
var
MemRecTabItem: TMemRecTabItem;
Pos, ResultState: Integer;
begin
if not Filtered and not FSetRanged then
begin
// 如果是当前索引
if FIndexIdx = IndexIdx then
begin
// 因为在对FRecTabList Insert之前先要做Delete,故ToRecIdx需要调整。
if ToRecIdx > FromRecIdx then Dec(ToRecIdx);
// 调整FRecTabList
MemRecTabItem := GetMemRecTabItem(FRecTabList, FromRecIdx);
DeleteMemRecTabItem(FRecTabList, FromRecIdx);
InsertMemRecTabItem(FRecTabList, ToRecIdx, MemRecTabItem);
// 调整FCurRec
FCurRec := ToRecIdx;
end;
end else
begin
// 如果是当前索引
if FIndexIdx = IndexIdx then
begin
// 调整FRecTabList
MemRecTabItem := GetMemRecTabItem(FRecTabList, FCurRec);
DeleteMemRecTabItem(FRecTabList, FCurRec);
// 查找应插入的位置
Pos := SearchInsertPos(IndexIdx, ResultState);
InsertMemRecTabItem(FRecTabList, Pos, MemRecTabItem);
// 调整FCurRec
FCurRec := Pos;
end;
end;
end;
//-----------------------------------------------------------------------------
// 将Buffer中的数据写入到数据库的第RecordIdx条记录中
// RecordIdx: 当前记录集中的记录号 0-based
// 注:Buffer 中数据格式的定义同ReadRecordData
//-----------------------------------------------------------------------------
procedure TTinyTable.ModifyRecordData(Buffer: PChar; RecordIdx: Integer);
var
FieldBuffers: TFieldBuffers;
PhyRecordIdx: Integer;
begin
if (RecordIdx < 0) or (RecordIdx >= RecordCount) then Exit;
FTableIO.ConvertRecIdxForPhy(FRecTabList, RecordIdx, PhyRecordIdx);
FieldBuffers := TFieldBuffers.Create;
try
RecordBufferToFieldBuffers(Buffer, FieldBuffers);
FTableIO.ModifyRecordData(FieldBuffers, PhyRecordIdx, (FUpdateCount = 0) and Database.FlushCacheAlways, OnAdjustIndexForModify);
finally
FieldBuffers.Free;
end;
end;
//-----------------------------------------------------------------------------
// 删除记录
// RecordIdx: 当前记录集中的记录号 0-based
//-----------------------------------------------------------------------------
procedure TTinyTable.DeleteRecordData(RecordIdx: Integer);
var
PhyRecordIdx: Integer;
begin
if (RecordIdx < 0) or (RecordIdx >= RecordCount) then Exit;
FTableIO.ConvertRecIdxForPhy(FRecTabList, RecordIdx, PhyRecordIdx);
FTableIO.DeleteRecordData(PhyRecordIdx, (FUpdateCount = 0) and Database.FlushCacheAlways);
// 删除FRecTabList中的对应项目
DeleteMemRecTabItem(FRecTabList, RecordIdx);
end;
//-----------------------------------------------------------------------------
// 删除所有记录
//-----------------------------------------------------------------------------
procedure TTinyTable.DeleteAllRecords;
begin
FTableIO.DeleteAllRecords;
ClearMemRecTab(FRecTabList);
FCurRec := -1;
end;
//-----------------------------------------------------------------------------
// 根据索引查找离指定数据最近的位置(二分法)
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号 0-based
// ResultState: 存放搜索结果状态
// 0: 待查找的值 = 查找结果位置的值
// 1: 待查找的值 > 查找结果位置的值
// -1: 待查找的值 < 查找结果位置的值
// -2: 无记录
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// PartialCompare: 字符串的部分匹配
// 返回值:在RecTabList中的记录号(0-based),如果无记录则返回-1
// 注:待查找数据应事先存放于Fields中
//-----------------------------------------------------------------------------
function TTinyTable.SearchIndexedField(RecTabList: TList; IndexIdx: Integer;
var ResultState: Integer; EffFieldCount: Integer; PartialCompare: Boolean): Integer;
var
FieldBuffers: TFieldBuffers;
RecBuf: PChar;
begin
FieldBuffers := TFieldBuffers.Create;
GetActiveRecBuf(RecBuf);
RecordBufferToFieldBuffers(RecBuf, FieldBuffers);
Result := FTableIO.SearchIndexedField(FieldBuffers, RecTabList, IndexIdx, ResultState, EffFieldCount, PartialCompare);
FieldBuffers.Free;
end;
//-----------------------------------------------------------------------------
// 根据索引查找离指定数据的边界位置(二分法)
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号 0-based
// LowBound: 为True时查找低边界,为False时查找高边界
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// PartialCompare: 字符串的部分匹配
// 返回值:在RecTabList中的记录号(0-based),如果无记录则返回-1
// 注:
// 1.待查找数据应事先存放于Fields中
//-----------------------------------------------------------------------------
function TTinyTable.SearchIndexedFieldBound(RecTabList: TList; IndexIdx: Integer;
LowBound: Boolean; var ResultState: Integer; EffFieldCount: Integer; PartialCompare: Boolean): Integer;
var
FieldBuffers: TFieldBuffers;
RecBuf: PChar;
begin
FieldBuffers := TFieldBuffers.Create;
GetActiveRecBuf(RecBuf);
RecordBufferToFieldBuffers(RecBuf, FieldBuffers);
Result := FTableIO.SearchIndexedFieldBound(FieldBuffers, RecTabList, IndexIdx, LowBound, ResultState, EffFieldCount, PartialCompare);
FieldBuffers.Free;
end;
//-----------------------------------------------------------------------------
// 根据索引求取SubRangeStart的位置
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// 返回值:求得结果,在RecTabList中的记录号(0-based)
// 注:1.待查找的记录数据应事先存放于Fields中
//-----------------------------------------------------------------------------
function TTinyTable.SearchRangeStart(RecTabList: TList; IndexIdx: Integer;
var ResultState: Integer; EffFieldCount: Integer): Integer;
var
SaveState: TDataSetState;
SaveKeyBuffer: PChar;
begin
SaveState := SetTempState(dsSetKey);
SaveKeyBuffer := FKeyBuffer;
FKeyBuffer := FKeyBuffers[tkRangeStart];
try
Result := SearchIndexedFieldBound(RecTabList, IndexIdx, True, ResultState, EffFieldCount);
if ResultState = 1 then Inc(Result);
finally
RestoreState(SaveState);
FKeyBuffer := SaveKeyBuffer;
end;
end;
//-----------------------------------------------------------------------------
// 根据索引求取RangeEnd的位置
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// ResultState: 存放搜索结果状态,定义同SearchIndexedField
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// 返回值:求得结果,在RecTabList中的记录号(0-based)
// 注:1.待查找的记录数据应事先存放于Fields中
//-----------------------------------------------------------------------------
function TTinyTable.SearchRangeEnd(RecTabList: TList; IndexIdx: Integer;
var ResultState: Integer; EffFieldCount: Integer): Integer;
var
SaveState: TDataSetState;
SaveKeyBuffer: PChar;
begin
SaveState := SetTempState(dsSetKey);
SaveKeyBuffer := FKeyBuffer;
FKeyBuffer := FKeyBuffers[tkRangeEnd];
try
Result := SearchIndexedFieldBound(RecTabList, IndexIdx, False, ResultState, EffFieldCount);
if ResultState = -1 then Dec(Result);
finally
RestoreState(SaveState);
FKeyBuffer := SaveKeyBuffer;
end;
end;
//-----------------------------------------------------------------------------
// 根据索引查找记录
// RecTabList: 要查找的记录集,注意:必须是已排序的记录集
// IndexIdx: 索引号(0-based),应对应于RecTabList的排序索引
// EffFieldCount: Fields中有效字段个数。缺省为0时表示按复合索引中实际字段数计算
// GotoKey和GotoNearest要用到此函数
//-----------------------------------------------------------------------------
function TTinyTable.SearchKey(RecTabList: TList; IndexIdx: Integer;
EffFieldCount: Integer; Nearest: Boolean): Boolean;
var
Pos, ResultState, CurRec: Integer;
SaveState: TDataSetState;
begin
Result := False;
if IndexIdx = -1 then Exit;
SaveState := SetTempState(dsSetKey);
try
Pos := SearchIndexedField(RecTabList, IndexIdx, ResultState, EffFieldCount, True);
FTableIO.ConvertRecordIdx(RecTabList, Pos, FRecTabList, CurRec);
if ResultState = -2 then // 无记录,返回False
begin
Result := False;
end else if (ResultState = 0) and (CurRec <> -1) then // 找到
begin
FCurRec := CurRec;
Result := True;
end else // 找到相似记录
begin
if Nearest then
if CurRec <> -1 then
FCurRec := CurRec;
Result := Nearest;
end;
finally
RestoreState(SaveState);
end;
end;
function TTinyTable.SearchInsertPos(IndexIdx: Integer; var ResultState: Integer): Integer;
begin
Result := SearchIndexedField(FRecTabList, IndexIdx, ResultState);
if ResultState in [0, 1] then Inc(Result)
else if ResultState = -2 then Result := 0;
end;
//-----------------------------------------------------------------------------
// FindKey, SetRange要用到此过程
//-----------------------------------------------------------------------------
procedure TTinyTable.SetKeyFields(KeyIndex: TTDKeyIndex; const Values: array of const);
begin
if FIndexIdx = -1 then DatabaseError(SNoFieldIndexes, Self);
SetKeyFields(FIndexIdx, KeyIndex, Values);
end;
procedure TTinyTable.SetKeyFields(IndexIdx: Integer; KeyIndex: TTDKeyIndex; const Values: array of const);
var
I, FieldIdx: Integer;
SaveState: TDataSetState;
begin
SaveState := SetTempState(dsSetKey);
try
InitKeyBuffer(KeyIndex);
FKeyBuffer := FKeyBuffers[KeyIndex];
for I := 0 to High(FTableIO.IndexDefs[IndexIdx].FieldIdxes) do
begin
FieldIdx := FTableIO.IndexDefs[IndexIdx].FieldIdxes[I];
if I <= High(Values) then
begin
Fields[FieldIdx].AssignValue(Values[I]);
end else
Fields[FieldIdx].Clear;
end;
finally
RestoreState(SaveState);
end;
end;
function TTinyTable.LocateRecord(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions; SyncCursor: Boolean): Boolean;
function SearchOrderly(AFields: TList): Integer;
var
DataStream: TMemoryStream;
RecIdx, FieldIdx, CompRes, I: Integer;
MemRecTabItem: TMemRecTabItem;
FieldType: TFieldType;
RecBuf: PChar;
begin
Result := -1;
DataStream := TMemoryStream.Create;
try
GetActiveRecBuf(RecBuf);
for RecIdx := 0 to RecordCount - 1 do
begin
MemRecTabItem := GetMemRecTabItem(FRecTabList, RecIdx);
CompRes := 0;
for I := 0 to AFields.Count - 1 do
begin
FieldIdx := TField(AFields[I]).FieldNo - 1;
FieldType := TField(AFields[I]).DataType;
FTableIO.ReadFieldData(DataStream, MemRecTabItem.RecIndex, FieldIdx);
CompRes := FTableIO.CompFieldData(RecBuf + FFieldOffsets[FieldIdx],
DataStream.Memory, FieldType, loCaseInsensitive in Options, loPartialKey in Options);
if CompRes <> 0 then Break;
end;
if CompRes = 0 then
begin
Result := RecIdx;
Break;
end;
end;
finally
DataStream.Free;
end;
end;
function SearchByIndex(AFields: TList; IndexIdx: Integer): Integer;
var
ResultState: Integer;
RecIdx, DstRecIdx: Integer;
begin
Result := -1;
RecIdx := SearchIndexedField(FTableIO.RecTabLists[IndexIdx+1], IndexIdx, ResultState, 0, loPartialKey in Options);
if (RecIdx <> -1) and (ResultState = 0) then
begin
FTableIO.ConvertRecIdxForCur(IndexIdx, RecIdx, FRecTabList, DstRecIdx);
if (DstRecIdx >= 0) and (DstRecIdx < RecordCount) then
Result := DstRecIdx;
end;
end;
var
I, FieldCount, RecIdx, IndexIdx: Integer;
Buffer: PChar;
Fields: TList;
begin
CheckBrowseMode;
CursorPosChanged;
Buffer := TempBuffer;
Fields := TList.Create;
SetTempState(dsFilter);
FFilterBuffer := Buffer;
try
GetFieldList(Fields, KeyFields);
FieldCount := Fields.Count;
if FieldCount = 1 then
begin
if VarIsArray(KeyValues) then
TField(Fields.First).Value := KeyValues[0] else
TField(Fields.First).Value := KeyValues;
end else
for I := 0 to FieldCount - 1 do
TField(Fields[I]).Value := KeyValues[I];
IndexIdx := MapsToIndexForSearch(Fields, loCaseInsensitive in Options);
if IndexIdx = -1 then
RecIdx := SearchOrderly(Fields)
else
RecIdx := SearchByIndex(Fields, IndexIdx);
Result := RecIdx <> -1;
if Result then
begin
ReadRecordData(Buffer, RecIdx);
if SyncCursor then FCurRec := RecIdx;
end;
finally
RestoreState(dsBrowse);
Fields.Free;
end;
end;
//-----------------------------------------------------------------------------
// 检查即将要查找的Fields是否和某个索引匹配
// 返回:如果找到匹配则返回索引号(0-based),没有则返回-1
//-----------------------------------------------------------------------------
function TTinyTable.MapsToIndexForSearch(Fields: TList; CaseInsensitive: Boolean): Integer;
var
I, J: Integer;
HasStr, Ok: Boolean;
begin
Result := -1;
HasStr := False;
for I := 0 to Fields.Count - 1 do
begin
HasStr := TField(Fields[I]).DataType in [ftString, ftFixedChar, ftWideString];
if HasStr then Break;
end;
for I := 0 to FTableIO.IndexDefs.Count - 1 do
begin
Ok := True;
if not HasStr or (CaseInsensitive = (tiCaseInsensitive in FTableIO.IndexDefs[I].Options)) then
begin
if Fields.Count = Length(FTableIO.IndexDefs[I].FieldIdxes) then
begin
for J := 0 to High(FTableIO.IndexDefs[I].FieldIdxes) do
begin
if TField(Fields[J]).FieldNo - 1 <> FTableIO.IndexDefs[I].FieldIdxes[J] then
begin
Ok := False;
Break;
end;
end;
end else
Ok := False;
end else
Ok := False;
if Ok then
begin
Result := I;
Break;
end;
end;
end;
//-----------------------------------------------------------------------------
// 检查Filter是否可以匹配索引,以便作优化处理
//-----------------------------------------------------------------------------
function TTinyTable.CheckFilterMapsToIndex: Boolean;
var
Node: TExprNode;
I, FieldIdx: Integer;
Exists: Boolean;
begin
Result := True;
if Assigned(OnFilterRecord) then
begin
Result := False;
Exit;
end;
Node := FFilterParser.FExprNodes.FNodes;
while Node <> nil do
begin
if Node.FKind = enField then
begin
FieldIdx := FTableIO.FieldDefs.IndexOf(Node.FData);
if FieldIdx = -1 then
begin
Result := False;
Break;
end else
begin
Exists := False;
for I := 0 to FTableIO.IndexDefs.Count - 1 do
if (Length(FTableIO.IndexDefs[I].FFieldIdxes) = 1) and
(FTableIO.IndexDefs[I].FFieldIdxes[0] = FieldIdx) then
begin
Exists := True;
Break;
end;
if Exists = False then
begin
Result := False;
Break;
end;
end;
end;
if Node.FOperator in [toLIKE] then
begin
Result := False;
Break;
end;
Node := Node.FNext;
end;
end;
procedure TTinyTable.MasterChanged(Sender: TObject);
begin
SetLinkRange(FMasterLink.Fields);
end;
procedure TTinyTable.MasterDisabled(Sender: TObject);
begin
CancelRange;
end;
procedure TTinyTable.SetLinkRange(MasterFields: TList);
function GetIndexField(Index: Integer): TField;
var
I: Integer;
begin
I := FTableIO.IndexDefs[FIndexIdx].FieldIdxes[Index];
Result := Fields[I];
end;
var
SaveState: TDataSetState;
StartIdx, EndIdx: Integer;
I, ResultState: Integer;
RecTabList: TList;
begin
if FIndexIdx = -1 then Exit;
if Filtered then Filtered := False;
// if FSetRanged then CancelRange;
// 设置范围前初始化Fields中的值
CheckBrowseMode;
SaveState := SetTempState(dsSetKey);
try
FKeyBuffer := FKeyBuffers[tkRangeStart];
InitKeyBuffer(tkRangeStart);
for I := 0 to MasterFields.Count - 1 do
GetIndexField(I).Assign(TField(MasterFields[I]));
FKeyBuffer := FKeyBuffers[tkRangeEnd];
InitKeyBuffer(tkRangeEnd);
for I := 0 to MasterFields.Count - 1 do
GetIndexField(I).Assign(TField(MasterFields[I]));
finally
RestoreState(SaveState);
end;
// 设置范围
CheckBrowseMode;
FEffFieldCount := MasterFields.Count;
StartIdx := SearchRangeStart(FTableIO.RecTabLists[FIndexIdx+1], FIndexIdx, ResultState, FEffFieldCount);
if ResultState = -2 then Exit;
EndIdx := SearchRangeEnd(FTableIO.RecTabLists[FIndexIdx+1], FIndexIdx, ResultState, FEffFieldCount);
if ResultState = -2 then Exit;
RecTabList := TList.Create;
for I := StartIdx to EndIdx do
AddMemRecTabItem(RecTabList, GetMemRecTabItem(FTableIO.RecTabLists[FIndexIdx+1], I));
ClearMemRecTab(FRecTabList);
for I := 0 to RecTabList.Count - 1 do
AddMemRecTabItem(FRecTabList, GetMemRecTabItem(RecTabList, I));
ClearMemRecTab(RecTabList);
RecTabList.Free;
FSetRanged := True;
//FCanModify := False;
First;
end;
procedure TTinyTable.CheckMasterRange;
begin
if FMasterLink.Active and (FMasterLink.Fields.Count > 0) then
begin
SetLinkRange(FMasterLink.Fields);
end;
end;
//-----------------------------------------------------------------------------
// RecordBuffer格式到FieldBuffers的转换
// 只是让FieldBuffers中的指针指向RecordBuffer中的各个字段偏移处,而没有复制数据.
//-----------------------------------------------------------------------------
procedure TTinyTable.RecordBufferToFieldBuffers(RecordBuffer: PChar; FieldBuffers: TFieldBuffers);
var
I: Integer;
Field: TField;
begin
FieldBuffers.Clear;
for I := 0 to FTableIO.FieldDefs.Count - 1 do
begin
Field := FieldByNumber(I + 1);
if Field = nil then
begin
FieldBuffers.Add(nil, ftUnknown, 0);
FieldBuffers.Items[FieldBuffers.Count - 1].Active := False;
end else
begin
FieldBuffers.Add(RecordBuffer + FFieldOffsets[I], Field.DataType, Field.DataSize);
end;
end;
end;
function TTinyTable.FieldDefsStored: Boolean;
begin
Result := FieldDefs.Count > 0;
end;
function TTinyTable.IndexDefsStored: Boolean;
begin
Result := IndexDefs.Count > 0;
end;
procedure TTinyTable.ActivateFilters;
var
I: Integer;
Accept: Boolean;
RecTabList: TList;
begin
RecTabList := TList.Create;
SetTempState(dsFilter);
if DBSession.SQLHourGlass then Screen.Cursor := crSQLWait;
try
if Filter <> '' then FFilterParser.Parse(Filter);
FFilterMapsToIndex := CheckFilterMapsToIndex;
//if FFilterMapsToIndex then
//begin
//showmessage('yes, maps to index.');
// FiltersAccept;
//end else
//begin
FFilterBuffer := ActiveBuffer;
for I := 0 to RecordCount - 1 do
begin
FCurRec := I;
ReadRecordData(FFilterBuffer, FCurRec);
Accept := FiltersAccept;
if Accept then
AddMemRecTabItem(RecTabList, GetMemRecTabItem(FRecTabList, I));
if Assigned(FOnFilterProgress) then
FOnFilterProgress(Self, Trunc(I/RecordCount*100));
end;
if FRecTabList.Count <> RecTabList.Count then
begin
ClearMemRecTab(FRecTabList);
for I := 0 to RecTabList.Count - 1 do
AddMemRecTabItem(FRecTabList, GetMemRecTabItem(RecTabList, I));
end;
//end;
finally
Screen.Cursor := crDefault;
RestoreState(dsBrowse);
ClearMemRecTab(RecTabList);
RecTabList.Free;
FCurRec := -1;
First;
//FCanModify := False;
end;
end;
procedure TTinyTable.DeactivateFilters;
begin
InitCurRecordTab;
FCurRec := -1;
First;
FCanModify := True;
end;
procedure TTinyTable.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TTinyTable.EndUpdate;
begin
Dec(FUpdateCount);
end;
//-----------------------------------------------------------------------------
// This method is called by TDataSet.Open and also when FieldDefs need to
// be updated (usually by the DataSet designer). Everything which is
// allocated or initialized in this method should also be freed or
// uninitialized in the InternalClose method.
//-----------------------------------------------------------------------------
procedure TTinyTable.InternalOpen;
begin
FTableIO := Database.TableIOByName(FTableName);
if FTableIO = nil then
DatabaseErrorFmt(STableNotFound, [FTableName], Self);
FTableIO.Open;
FRecTabList := TList.Create;
FUpdateCount := 0;
FCurRec := -1;
BookmarkSize := SizeOf(Integer);
FCanModify := True;
InternalInitFieldDefs;
if DefaultFields then CreateFields;
BindFields(True);
InitIndexDefs;
InitCurRecordTab;
InitRecordSize;
InitFieldOffsets;
AllocKeyBuffers;
end;
procedure TTinyTable.InternalClose;
begin
if FTableIO <> nil then FTableIO.Close;
ClearMemRecTab(FRecTabList);
FRecTabList.Free;
FRecTabList := nil;
FreeKeyBuffers;
{ Destroy the TField components if no persistent fields }
if DefaultFields then DestroyFields;
{ Reset these internal flags }
FCurRec := -1;
FCanModify := False;
end;
//-----------------------------------------------------------------------------
// For this simple example we just create one FieldDef, but a more complete
// TDataSet implementation would create multiple FieldDefs based on the
// actual data.
//-----------------------------------------------------------------------------
procedure TTinyTable.InternalInitFieldDefs;
var
I: Integer;
FieldType: TFieldType;
FieldSize: Integer;
begin
FieldDefs.Clear;
for I := 0 to FTableIO.FieldDefs.Count -1 do
begin
FieldType := FTableIO.FieldDefs[I].FieldType;
if FieldType in StringFieldTypes then
FieldSize := FTableIO.FieldDefs[I].FieldSize
else
FieldSize := 0;
FieldDefs.Add(FTableIO.FieldDefs[I].Name,
FieldType,
FieldSize,
False);
end;
end;
// Bookmarks
//-----------------------------------------------------------------------------
// In this sample the bookmarks are stored in the Object property of the
// TStringList holding the data. Positioning to a bookmark just requires
// finding the offset of the bookmark in the TStrings.Objects and using that
// value as the new current record pointer.
//-----------------------------------------------------------------------------
procedure TTinyTable.InternalGotoBookmark(Bookmark: Pointer);
var
I, Index: Integer;
begin
Index := -1;
for I := 0 to FRecTabList.Count - 1 do
begin
if PInteger(Bookmark)^ = GetMemRecTabItem(FRecTabList, I).RecIndex then
begin
Index := I;
Break;
end;
end;
if Index <> -1 then
FCurRec := Index
else
DatabaseError(SBookmarkNotFound);
end;
//-----------------------------------------------------------------------------
// This multi-purpose function does 3 jobs. It retrieves data for either
// the current, the prior, or the next record. It must return the status
// (TGetResult), and raise an exception if DoCheck is True.
//-----------------------------------------------------------------------------
function TTinyTable.GetRecord(Buffer: PChar; GetMode: TGetMode;
DoCheck: Boolean): TGetResult;
begin
if RecordCount < 1 then
Result := grEOF else
begin
Result := grOK;
case GetMode of
gmNext:
if FCurRec >= RecordCount - 1 then
Result := grEOF else
Inc(FCurRec);
gmPrior:
if FCurRec <= 0 then
Result := grBOF else
Dec(FCurRec);
gmCurrent:
if (FCurRec < 0) or (FCurRec >= RecordCount) then
Result := grError;
end;
if Result = grOK then
begin
ReadRecordData(Buffer, FCurRec);
with PRecInfo(Buffer + FRecordSize + CalcFieldsSize)^ do
begin
BookmarkFlag := bfCurrent;
Bookmark := GetMemRecTabItem(FRecTabList, FCurRec).RecIndex;
end;
GetCalcFields(Buffer);
end else
if (Result = grError) and DoCheck then DatabaseError(SNoRecords);
end;
end;
procedure TTinyTable.SetKeyBuffer(KeyIndex: TTDKeyIndex; Clear: Boolean);
begin
CheckBrowseMode;
FKeyBuffer := FKeyBuffers[KeyIndex];
if Clear then InitKeyBuffer(KeyIndex);
SetState(dsSetKey);
DataEvent(deDataSetChange, 0);
end;
procedure TTinyTable.InternalRefresh;
begin
InitCurRecordTab;
if FSetRanged then ApplyRange;
if Filtered then ActivateFilters;
end;
//-----------------------------------------------------------------------------
// This method is called by TDataSet.Post. Most implmentations would write
// the changes directly to the associated datasource, but here we simply set
// a flag to write the changes when we close the dateset.
//-----------------------------------------------------------------------------
procedure TTinyTable.InternalPost;
var
RecBuf: PChar;
begin
if GetActiveRecBuf(RecBuf) then
begin
//if FUpdateCount = 0 then InitCurRecordTab;
if State = dsEdit then
begin //edit
ModifyRecordData(RecBuf, FCurRec);
end else
begin //insert or append
AppendRecordData(RecBuf);
end;
end;
end;
//-----------------------------------------------------------------------------
// This method is similar to InternalPost above, but the operation is always
// an insert or append and takes a pointer to a record buffer as well.
//-----------------------------------------------------------------------------
procedure TTinyTable.InternalAddRecord(Buffer: Pointer; Append: Boolean);
begin
if Append then InternalLast;
AppendRecordData(Buffer);
end;
//-----------------------------------------------------------------------------
// This method is called by TDataSet.Delete to delete the current record
//-----------------------------------------------------------------------------
procedure TTinyTable.InternalDelete;
begin
DeleteRecordData(FCurRec);
if FCurRec >= RecordCount then
Dec(FCurRec);
end;
//-----------------------------------------------------------------------------
// This property is used while opening the dataset.
// It indicates if data is available even though the
// current state is still dsInActive.
//-----------------------------------------------------------------------------
function TTinyTable.IsCursorOpen: Boolean;
begin
Result := Assigned(FRecTabList);
end;
procedure TTinyTable.Post;
begin
inherited Post;
//When state is dsSetKey, calling CheckBrowseMode will run to here:
if State = dsSetKey then
begin
DataEvent(deCheckBrowseMode, 0);
SetState(dsBrowse);
DataEvent(deDataSetChange, 0);
end;
end;
function TTinyTable.BookmarkValid(Bookmark: TBookmark): Boolean;
var
I, Index: Integer;
begin
Result := IsCursorOpen;
if not Result then Exit;
Index := -1;
for I := 0 to FRecTabList.Count - 1 do
if PInteger(Bookmark)^ = GetMemRecTabItem(FRecTabList, I).RecIndex then
begin
Index := I;
Break;
end;
Result := (Index <> -1);
end;
procedure TTinyTable.SetKey;
begin
SetKeyBuffer(tkLookup, True);
FEffFieldCount := 0;
end;
procedure TTinyTable.EditKey;
begin
SetKeyBuffer(tkLookup, False);
FEffFieldCount := 0;
end;
function TTinyTable.GotoKey: Boolean;
begin
CheckBrowseMode;
DoBeforeScroll;
CursorPosChanged;
Result := SearchKey(FRecTabList, FIndexIdx, FEffFieldCount, False);
if Result then Resync([rmExact, rmCenter]);
if Result then DoAfterScroll;
end;
function TTinyTable.GotoKey(const IndexName: string): Boolean;
var
IndexIdx: Integer;
begin
IndexIdx := FTableIO.IndexDefs.IndexOf(IndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
CheckBrowseMode;
DoBeforeScroll;
CursorPosChanged;
Result := SearchKey(FTableIO.RecTabLists[IndexIdx+1], IndexIdx, FEffFieldCount, False);
if Result then Resync([rmExact, rmCenter]);
if Result then DoAfterScroll;
end;
procedure TTinyTable.GotoNearest;
var
Result: Boolean;
begin
CheckBrowseMode;
DoBeforeScroll;
CursorPosChanged;
Result := SearchKey(FRecTabList, FIndexIdx, FEffFieldCount, True);
Resync([rmExact, rmCenter]);
if Result then DoAfterScroll;
end;
procedure TTinyTable.GotoNearest(const IndexName: string);
var
IndexIdx: Integer;
Result: Boolean;
begin
IndexIdx := FTableIO.IndexDefs.IndexOf(IndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
CheckBrowseMode;
DoBeforeScroll;
CursorPosChanged;
Result := SearchKey(FTableIO.RecTabLists[IndexIdx+1], IndexIdx, FEffFieldCount, True);
Resync([rmExact, rmCenter]);
if Result then DoAfterScroll;
end;
function TTinyTable.FindKey(const KeyValues: array of const): Boolean;
begin
CheckBrowseMode;
FEffFieldCount := Length(KeyValues);
SetKeyFields(tkLookup, KeyValues);
Result := GotoKey;
end;
function TTinyTable.FindKey(const IndexName: string; const KeyValues: array of const): Boolean;
var
IndexIdx: Integer;
begin
IndexIdx := FTableIO.IndexDefs.IndexOf(IndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
CheckBrowseMode;
FEffFieldCount := Length(KeyValues);
SetKeyFields(IndexIdx, tkLookup, KeyValues);
Result := GotoKey(IndexName);
end;
procedure TTinyTable.FindNearest(const KeyValues: array of const);
begin
CheckBrowseMode;
FEffFieldCount := Length(KeyValues);
SetKeyFields(tkLookup, KeyValues);
GotoNearest;
end;
procedure TTinyTable.FindNearest(const IndexName: string; const KeyValues: array of const);
var
IndexIdx: Integer;
begin
IndexIdx := FTableIO.IndexDefs.IndexOf(IndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
CheckBrowseMode;
FEffFieldCount := Length(KeyValues);
SetKeyFields(IndexIdx, tkLookup, KeyValues);
GotoNearest(IndexName);
end;
procedure TTinyTable.SetRangeStart;
begin
SetKeyBuffer(tkRangeStart, True);
FEffFieldCount := 0;
end;
procedure TTinyTable.SetRangeEnd;
begin
SetKeyBuffer(tkRangeEnd, True);
FEffFieldCount := 0;
end;
procedure TTinyTable.EditRangeStart;
begin
SetKeyBuffer(tkRangeStart, False);
FEffFieldCount := 0;
end;
procedure TTinyTable.EditRangeEnd;
begin
SetKeyBuffer(tkRangeEnd, False);
FEffFieldCount := 0;
end;
procedure TTinyTable.ApplyRange;
var
StartIdx, EndIdx: Integer;
I, ResultState: Integer;
RecTabList: TList;
begin
CheckBrowseMode;
if FIndexIdx = -1 then DatabaseError(SNoFieldIndexes, Self);
if RecordCount = 0 then Exit;
StartIdx := SearchRangeStart(FRecTabList, FIndexIdx, ResultState, FEffFieldCount);
if ResultState = -2 then Exit;
EndIdx := SearchRangeEnd(FRecTabList, FIndexIdx, ResultState, FEffFieldCount);
if ResultState = -2 then Exit;
RecTabList := TList.Create;
for I := StartIdx to EndIdx do
AddMemRecTabItem(RecTabList, GetMemRecTabItem(FRecTabList, I));
ClearMemRecTab(FRecTabList);
for I := 0 to RecTabList.Count - 1 do
AddMemRecTabItem(FRecTabList, GetMemRecTabItem(RecTabList, I));
ClearMemRecTab(RecTabList);
RecTabList.Free;
//FCanModify := False;
First;
FSetRanged := True;
end;
procedure TTinyTable.ApplyRange(const IndexName: string);
var
IndexIdx: Integer;
StartIdx, EndIdx: Integer;
I, J, RecIndex, ResultState: Integer;
RecTabList: TList;
begin
IndexIdx := FTableIO.IndexDefs.IndexOf(IndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
CheckBrowseMode;
if RecordCount = 0 then Exit;
StartIdx := SearchRangeStart(FTableIO.RecTabLists[IndexIdx+1], IndexIdx, ResultState, FEffFieldCount);
if ResultState = -2 then Exit;
EndIdx := SearchRangeEnd(FTableIO.RecTabLists[IndexIdx+1], IndexIdx, ResultState, FEffFieldCount);
if ResultState = -2 then Exit;
RecTabList := TList.Create;
for I := 0 to FRecTabList.Count - 1 do
begin
RecIndex := GetMemRecTabItem(FRecTabList, I).RecIndex;
for J := StartIdx to EndIdx do
if RecIndex = GetMemRecTabItem(FTableIO.RecTabLists[IndexIdx+1], J).RecIndex then
begin
AddMemRecTabItem(RecTabList, GetMemRecTabItem(FRecTabList, I));
Break;
end;
end;
ClearMemRecTab(FRecTabList);
for I := 0 to RecTabList.Count - 1 do
AddMemRecTabItem(FRecTabList, GetMemRecTabItem(RecTabList, I));
ClearMemRecTab(RecTabList);
RecTabList.Free;
//FCanModify := False;
First;
end;
procedure TTinyTable.SetRange(const StartValues, EndValues: array of const);
begin
CheckBrowseMode;
FEffFieldCount := Min(Length(StartValues), Length(EndValues));
SetKeyFields(tkRangeStart, StartValues);
SetKeyFields(tkRangeEnd, EndValues);
ApplyRange;
end;
procedure TTinyTable.SetRange(const IndexName: string; const StartValues, EndValues: array of const);
var
IndexIdx: Integer;
begin
IndexIdx := FTableIO.IndexDefs.IndexOf(IndexName);
if IndexIdx = -1 then
DatabaseErrorFmt(SInvalidIndexName, [IndexName]);
CheckBrowseMode;
FEffFieldCount := Min(Length(StartValues), Length(EndValues));
SetKeyFields(IndexIdx, tkRangeStart, StartValues);
SetKeyFields(IndexIdx, tkRangeEnd, EndValues);
ApplyRange(IndexName);
end;
procedure TTinyTable.CancelRange;
begin
CheckBrowseMode;
UpdateCursorPos;
InitCurRecordTab;
Resync([]);
First;
FCanModify := True;
if Filtered then ActivateFilters;
FSetRanged := False;
FEffFieldCount := 0;
end;
function TTinyTable.Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean;
begin
DoBeforeScroll;
Result := LocateRecord(KeyFields, KeyValues, Options, True);
if Result then
begin
Resync([rmExact, rmCenter]);
DoAfterScroll;
end;
end;
function TTinyTable.Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;
begin
Result := Null;
if LocateRecord(KeyFields, KeyValues, [], False) then
begin
SetTempState(dsCalcFields);
try
CalculateFields(TempBuffer);
Result := FieldValues[ResultFields];
finally
RestoreState(dsBrowse);
end;
end;
end;
procedure TTinyTable.EmptyTable;
begin
if Active then
begin
CheckBrowseMode;
DeleteAllRecords;
ClearBuffers;
DataEvent(deDataSetChange, 0);
end else
begin
DeleteAllRecords;
end;
end;
procedure TTinyTable.CreateTable;
var
ADatabase: TTinyDatabase;
FieldItems: array of TFieldItem;
IndexFieldNames: array of string;
TempList: TStrings;
IndexName: string;
IndexOptions: TTDIndexOptions;
I, J: Integer;
IndexExists: Boolean;
begin
ADatabase := OpenDatabase(False);
if ADatabase <> nil then
begin
SetLength(FieldItems, FieldDefs.Count);
for I := 0 to FieldDefs.Count - 1 do
begin
FieldItems[I].FieldName := FieldDefs[I].Name;
FieldItems[I].FieldType := FieldDefs[I].DataType;
FieldItems[I].DataSize := FieldDefs[I].Size;
FieldItems[I].DPMode := fdDefault;
end;
ADatabase.CreateTable(TableName, FieldItems);
for I := 0 to IndexDefs.Count - 1 do
begin
IndexName := IndexDefs[I].Name;
IndexOptions := [];
if ixPrimary in IndexDefs[I].Options then Include(IndexOptions, tiPrimary);
if ixUnique in IndexDefs[I].Options then Include(IndexOptions, tiUnique);
if ixDescending in IndexDefs[I].Options then Include(IndexOptions, tiDescending);
if ixCaseInsensitive in IndexDefs[I].Options then Include(IndexOptions, tiCaseInsensitive);
TempList := TStringList.Create;
TempList.CommaText := IndexDefs[I].Fields;
SetLength(IndexFieldNames, TempList.Count);
for J := 0 to TempList.Count - 1 do
IndexFieldNames[J] := TempList[J];
TempList.Free;
IndexExists := tiPrimary in IndexOptions;
if not IndexExists then
ADatabase.CreateIndex(TableName, IndexName, IndexOptions, IndexFieldNames);
end;
end;
end;
{ TTinyQuery }
constructor TTinyQuery.Create(AOwner: TComponent);
begin
inherited;
FSQL := TStringList.Create;
FSQLParser := TSQLParser.Create(Self);
end;
destructor TTinyQuery.Destroy;
begin
SQL.Free;
FSQLParser.Free;
inherited;
end;
procedure TTinyQuery.ExecSQL;
begin
FSQLParser.Parse(SQL.Text);
FSQLParser.Execute;
end;
procedure TTinyQuery.SetQuery(Value: TStrings);
begin
if SQL.Text <> Value.Text then
begin
SQL.BeginUpdate;
try
SQL.Assign(Value);
finally
SQL.EndUpdate;
end;
end;
end;
function TTinyQuery.GetRowsAffected: Integer;
begin
Result := FSQLParser.RowsAffected;
end;
procedure TTinyQuery.InternalOpen;
begin
end;
procedure TTinyQuery.InternalClose;
begin
end;
{ TTinyDatabase }
constructor TTinyDatabase.Create(AOwner: TComponent);
begin
inherited;
FDataSets := TList.Create;
if FSession = nil then
if AOwner is TTinySession then
FSession := TTinySession(AOwner) else
FSession := DefaultSession;
SessionName := FSession.SessionName;
FSession.AddDatabase(Self);
FTableDefs := TTinyTableDefs.Create(Self);
FKeepConnection := False;
FAutoFlushInterval := tdbDefAutoFlushInterval; // 60秒
FAutoFlushTimer := TTimer.Create(nil);
FAutoFlushTimer.OnTimer := AutoFlushTimer;
end;
destructor TTinyDatabase.Destroy;
begin
Destroying;
if FSession <> nil then
FSession.RemoveDatabase(Self);
SetConnected(False);
FreeAndNil(FDataSets);
FTableDefs.Free;
FAutoFlushTimer.Free;
inherited;
end;
procedure TTinyDatabase.Open;
begin
SetConnected(True);
end;
procedure TTinyDatabase.Close;
begin
SetConnected(False);
end;
procedure TTinyDatabase.CloseDataSets;
begin
while DataSetCount <> 0 do TTDBDataSet(DataSets[DataSetCount-1]).Disconnect;
end;
procedure TTinyDatabase.FlushCache;
begin
if FDBFileIO <> nil then FDBFileIO.Flush;
end;
procedure TTinyDatabase.DoConnect;
begin
CheckDatabaseName;
CheckSessionName(True);
if FDBFileIO = nil then
FDBFileIO := TTinyDBFileIO.Create(Self);
try
FDBFileIO.Open(GetDBFileName, FMediumType, FExclusive);
except
FDBFileIO.Close;
FDBFileIO.Free;
FDBFileIO := nil;
raise;
end;
FCanAccess := not FDBFileIO.FDBOptions.Encrypt;
if not FCanAccess and FPasswordModified then
FCanAccess := FDBFileIO.SetPassword(FPassword);
InitTableDefs;
InitTableIOs;
end;
procedure TTinyDatabase.DoDisconnect;
begin
if FDBFileIO <> nil then
begin
FDBFileIO.Close;
FDBFileIO.Free;
FDBFileIO := nil;
Session.DBNotification(dbClose, Self);
CloseDataSets;
FRefCount := 0;
FCanAccess := False;
FPassword := '';
FPasswordModified := False;
FreeTableIOs;
FTableDefs.Clear;
end;
FCanAccess := False;
end;
procedure TTinyDatabase.CheckCanAccess;
var
TempPassword: string;
I: Integer;
begin
if not FCanAccess then
begin
// check passwords from session
if Session.FPasswords.Count > 0 then
begin
for I := 0 to Session.FPasswords.Count - 1 do
begin
Password := Session.FPasswords[I];
if FCanAccess then Break;
end;
end;
if not FCanAccess then
begin
if not FPasswordModified then
begin
if ShowLoginDialog(GetDBFileName, TempPassword) then
begin
Password := TempPassword;
if not FCanAccess then DatabaseError(SAccessDenied);
end else
Abort;
end else
begin
Password := FPassword;
if not FCanAccess then DatabaseError(SAccessDenied);
end;
end;
end;
end;
function TTinyDatabase.GetDataSet(Index: Integer): TTDEDataSet;
begin
Result := FDataSets[Index];
end;
function TTinyDatabase.GetDataSetCount: Integer;
begin
Result := FDataSets.Count;
end;
procedure TTinyDatabase.RegisterClient(Client: TObject; Event: TConnectChangeEvent = nil);
begin
if Client is TTDBDataSet then
FDataSets.Add(Client);
end;
procedure TTinyDatabase.UnRegisterClient(Client: TObject);
begin
if Client is TTDBDataSet then
FDataSets.Remove(Client);
end;
procedure TTinyDatabase.SendConnectEvent(Connecting: Boolean);
var
I: Integer;
begin
for I := 0 to FDataSets.Count - 1 do
TTDBDataSet(FDataSets[I]).DataEvent(deConnectChange, Integer(Connecting));
end;
function TTinyDatabase.GetConnected: Boolean;
begin
Result := (FDBFileIO <> nil) and (FDBFileIO.IsOpen);
end;
function TTinyDatabase.GetEncrypted: Boolean;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.FDBOptions.Encrypt;
end;
function TTinyDatabase.GetEncryptAlgoName: string;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.FDBOptions.EncryptAlgoName;
end;
function TTinyDatabase.GetCompressed: Boolean;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.FDBOptions.CompressBlob;
end;
function TTinyDatabase.GetCompressLevel: TCompressLevel;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.FDBOptions.CompressLevel;
end;
function TTinyDatabase.GetCompressAlgoName: string;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.FDBOptions.CompressAlgoName;
end;
function TTinyDatabase.GetCRC32: Boolean;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.FDBOptions.CRC32;
end;
function TTinyDatabase.GetTableIOs(Index: Integer): TTinyTableIO;
begin
Result := TTinyTableIO(FTableIOs[Index]);
end;
function TTinyDatabase.GetFileSize: Integer;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
Result := FDBFileIO.DBStream.Size;
end;
function TTinyDatabase.GetFileDate: TDateTime;
var
FileDate: Integer;
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
if FMediumType = mtDisk then
begin
FileDate := FileGetDate((FDBFileIO.FDBStream as TFileStream).Handle);
Result := FileDateToDateTime(FileDate);
end else
Result := Now;
end;
function TTinyDatabase.GetFileIsReadOnly: Boolean;
begin
Result := DBFileIO.FileIsReadOnly;
end;
function TTinyDatabase.TableIOByName(const Name: string): TTinyTableIO;
var
I: Integer;
begin
for I := 0 to FTableIOs.Count - 1 do
if AnsiCompareText(Name, TTinyTableIO(FTableIOs[I]).TableName) = 0 then
begin
Result := TTinyTableIO(FTableIOs[I]);
Exit;
end;
Result := nil;
end;
procedure TTinyDatabase.SetDatabaseName(const Value: string);
begin
if FDatabaseName <> Value then
begin
CheckInactive;
ValidateName(Value);
FDatabaseName := Value;
end;
end;
procedure TTinyDatabase.SetFileName(const Value: string);
begin
if FFileName <> Value then
begin
CheckInactive;
FFileName := Value;
end;
end;
procedure TTinyDatabase.SetMediumType(const Value: TTinyDBMediumType);
var
I: Integer;
begin
if FMediumType <> Value then
begin
CheckInactive;
FMediumType := Value;
for I := 0 to FDataSets.Count - 1 do
if TObject(FDataSets[I]) is TTDEDataSet then
TTDEDataSet(FDataSets[I]).MediumType := FMediumType;
end;
end;
procedure TTinyDatabase.SetExclusive(const Value: Boolean);
begin
CheckInactive;
FExclusive := Value;
end;
procedure TTinyDatabase.SetKeepConnection(const Value: Boolean);
begin
if FKeepConnection <> Value then
begin
FKeepConnection := Value;
if not Value and (FRefCount = 0) then Close;
end;
end;
procedure TTinyDatabase.SetSessionName(const Value: string);
begin
if csReading in ComponentState then
FSessionName := Value
else
begin
CheckInactive;
if FSessionName <> Value then
begin
FSessionName := Value;
CheckSessionName(False);
end;
end;
end;
procedure TTinyDatabase.SetConnected(const Value: Boolean);
begin
if (csReading in ComponentState) and Value then
FStreamedConnected := True
else
begin
if Value = GetConnected then Exit;
if Value then
begin
if Assigned(BeforeConnect) then BeforeConnect(Self);
DoConnect;
SendConnectEvent(True);
if Assigned(AfterConnect) then AfterConnect(Self);
end else
begin
if Assigned(BeforeDisconnect) then BeforeDisconnect(Self);
SendConnectEvent(False);
DoDisconnect;
if Assigned(AfterDisconnect) then AfterDisconnect(Self);
end;
end;
end;
procedure TTinyDatabase.SetPassword(Value: string);
begin
FPasswordModified := True;
FPassword := Value;
if Connected then
FCanAccess := FDBFileIO.SetPassword(Value);
end;
procedure TTinyDatabase.SetCRC32(Value: Boolean);
begin
if FDBFileIO = nil then DatabaseError(SDatabaseClosed, Self);
FDBFileIO.FDBOptions.CRC32 := Value;
end;
procedure TTinyDatabase.SetAutoFlush(Value: Boolean);
begin
if FAutoFlush <> Value then
begin
FAutoFlush := Value;
if Value then
FAutoFlushTimer.Interval := FAutoFlushInterval;
FAutoFlushTimer.Enabled := Value;
end;
end;
procedure TTinyDatabase.SetAutoFlushInterval(Value: Integer);
begin
if FAutoFlushInterval <> Value then
begin
FAutoFlushInterval := Value;
if FAutoFlushTimer.Enabled then
FAutoFlushTimer.Interval := FAutoFlushInterval;
end;
end;
function TTinyDatabase.CreateLoginDialog(const ADatabaseName: string): TForm;
var
BackPanel: TPanel;
begin
Result := TTinyDBLoginForm.CreateNew(Application);
with Result do
begin
BiDiMode := Application.BiDiMode;
BorderStyle := bsDialog;
Canvas.Font := Font;
Width := 281;
Height := 154;
Position := poScreenCenter;
Scaled := False;
Caption := 'Database Login';
BackPanel := TPanel.Create(Result);
with BackPanel do
begin
Name := 'BackPanel';
Parent := Result;
Caption := '';
BevelInner := bvRaised;
BevelOuter := bvLowered;
SetBounds(8, 8, Result.ClientWidth - 16, 75);
end;
with TLabel.Create(Result) do
begin
Name := 'DatabaseLabel';
Parent := BackPanel;
Caption := 'Database:';
BiDiMode := Result.BiDiMode;
Left := 12;
Top := 15;
end;
with TLabel.Create(Result) do
begin
Name := 'PasswordLabel';
Parent := BackPanel;
Caption := 'Password:';
BiDiMode := Result.BiDiMode;
Left := 12;
Top := 45;
end;
with TEdit.Create(Result) do
begin
Name := 'DatabaseEdit';
Parent := BackPanel;
BiDiMode := Result.BiDiMode;
SetBounds(86, 12, BackPanel.ClientWidth - 86 - 12, 21);
ReadOnly := True;
Color := clBtnFace;
TabStop := False;
Text := ADatabaseName;
end;
with TEdit.Create(Result) do
begin
Name := 'PasswordEdit';
Parent := BackPanel;
BiDiMode := Result.BiDiMode;
SetBounds(86, 42, BackPanel.ClientWidth - 86 - 12, 21);
PasswordChar := '*';
TabOrder := 0;
Text := '';
end;
with TButton.Create(Result) do
begin
Name := 'OkButton';
Parent := Result;
Caption := '&OK';
Default := True;
ModalResult := mrOk;
Left := 109;
Top := 94;
end;
with TButton.Create(Result) do
begin
Name := 'CancelButton';
Parent := Result;
Caption := '&Cancel';
Cancel := True;
ModalResult := mrCancel;
Left := 191;
Top := 94;
end;
end;
end;
function TTinyDatabase.ShowLoginDialog(const ADatabaseName: string; var APassword: string): Boolean;
begin
with CreateLoginDialog(ADatabaseName) as TTinyDBLoginForm do
begin
Result := ShowModal = mrOk;
if Result then
APassword := (FindComponent('PasswordEdit') as TEdit).Text;
Free;
end;
end;
function TTinyDatabase.GetDBFileName: string;
begin
if FFileName <> '' then
Result := FFileName
else
Result := FDatabaseName;
end;
procedure TTinyDatabase.CheckSessionName(Required: Boolean);
var
NewSession: TTinySession;
begin
if Required then
NewSession := Sessions.List[FSessionName]
else
NewSession := Sessions.FindSession(FSessionName);
if (NewSession <> nil) and (NewSession <> FSession) then
begin
if (FSession <> nil) then FSession.RemoveDatabase(Self);
FSession := NewSession;
FSession.FreeNotification(Self);
FSession.AddDatabase(Self);
try
ValidateName(FDatabaseName);
except
FDatabaseName := '';
raise;
end;
end;
if Required then FSession.Active := True;
end;
procedure TTinyDatabase.CheckInactive;
begin
if FDBFileIO <> nil then
if csDesigning in ComponentState then
Close
else
DatabaseError(SDatabaseOpen, Self);
end;
procedure TTinyDatabase.CheckDatabaseName;
begin
if (FDatabaseName = '') and not Temporary then
DatabaseError(SDatabaseNameMissing, Self);
end;
procedure TTinyDatabase.InitTableIOs;
var
I: Integer;
TableIO: TTinyTableIO;
TableNames: TStringList;
begin
FreeTableIOs;
FTableIOs := TList.Create;
TableNames := TStringList.Create;
try
GetTableNames(TableNames);
for I := 0 to TableNames.Count - 1 do
begin
TableIO := TTinyTableIO.Create(Self);
TableIO.TableName := TableNames[I];
FTableIOs.Add(TableIO);
end;
finally
TableNames.Free;
end;
end;
procedure TTinyDatabase.FreeTableIOs;
var
I: Integer;
begin
if FTableIOs <> nil then
begin
for I := 0 to FTableIOs.Count - 1 do
TTinyTableIO(FTableIOs[I]).Free;
FTableIOs.Clear;
FTableIOs.Free;
FTableIOs := nil;
end;
end;
procedure TTinyDatabase.AddTableIO(const TableName: string);
var
TableIO: TTinyTableIO;
begin
TableIO := TTinyTableIO.Create(Self);
TableIO.TableName := TableName;
FTableIOs.Add(TableIO);
end;
procedure TTinyDatabase.DeleteTableIO(const TableName: string);
var
I: Integer;
begin
for I := 0 to FTableIOs.Count - 1 do
if AnsiCompareText(TTinyTableIO(FTableIOs[I]).TableName, TableName) = 0 then
begin
TTinyTableIO(FTableIOs[I]).Free;
FTableIOs.Delete(I);
Break;
end;
end;
procedure TTinyDatabase.RenameTableIO(const OldTableName, NewTableName: string);
var
I: Integer;
begin
for I := 0 to FTableIOs.Count - 1 do
if AnsiCompareText(TTinyTableIO(FTableIOs[I]).TableName, OldTableName) = 0 then
begin
TTinyTableIO(FTableIOs[I]).TableName := NewTableName;
Break;
end;
end;
procedure TTinyDatabase.RefreshAllTableIOs;
var
I: Integer;
begin
if FTableIOs <> nil then
begin
for I := 0 to FTableIOs.Count - 1 do
TTinyTableIO(FTableIOs[I]).Refresh;
end;
end;
procedure TTinyDatabase.RefreshAllDataSets;
var
I: Integer;
begin
for I := 0 to DataSetCount - 1 do
DataSets[I].Refresh;
end;
procedure TTinyDatabase.InitTableDefs;
var
I: Integer;
List: TStrings;
begin
List := TStringList.Create;
try
FTableDefs.Clear;
GetTableNames(List);
for I := 0 to List.Count - 1 do
with TTinyTableDef(FTableDefs.Add) do
begin
Name := List[I];
TableIdx := I;
end;
finally
List.Free;
end;
end;
procedure TTinyDatabase.AutoFlushTimer(Sender: TObject);
begin
if FDBFileIO <> nil then
begin
if not FDBFileIO.Flushed then
FlushCache;
end;
end;
procedure TTinyDatabase.Loaded;
begin
inherited Loaded;
try
if FStreamedConnected then SetConnected(True);
except
on E: Exception do
if csDesigning in ComponentState then
ShowException(E, ExceptAddr) else
raise;
end;
if not StreamedConnected then CheckSessionName(False);
end;
procedure TTinyDatabase.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FSession) and
(FSession <> DefaultSession) then
begin
Close;
SessionName := '';
end;
end;
procedure TTinyDatabase.ValidateName(const Name: string);
var
Database: TTinyDatabase;
begin
if (Name <> '') and (FSession <> nil) then
begin
Database := FSession.FindDatabase(Name);
if (Database <> nil) and (Database <> Self) and
not (Database.HandleShared and HandleShared) then
begin
if not Database.Temporary or (Database.FRefCount <> 0) then
DatabaseErrorFmt(SDuplicateDatabaseName, [Name]);
Database.Free;
end;
end;
end;
procedure TTinyDatabase.GetTableNames(List: TStrings);
begin
if Connected then
DBFileIO.GetTableNames(List);
end;
procedure TTinyDatabase.GetFieldNames(const TableName: string; List: TStrings);
begin
if Connected then
DBFileIO.GetFieldNames(TableName, List);
end;
procedure TTinyDatabase.GetIndexNames(const TableName: string; List: TStrings);
begin
if Connected then
DBFileIO.GetIndexNames(TableName, List);
end;
function TTinyDatabase.TableExists(const TableName: string): Boolean;
var
Tables: TStrings;
begin
Tables := TStringList.Create;
try
try
GetTableNames(Tables);
except
end;
Result := (Tables.IndexOf(TableName) <> -1);
finally
Tables.Free;
end;
end;
class function TTinyDatabase.GetCompressAlgoNames(List: TStrings): Integer;
begin
List.Assign(FCompressClassList);
Result := List.Count;
end;
class function TTinyDatabase.GetEncryptAlgoNames(List: TStrings): Integer;
begin
List.Assign(FEncryptClassList);
Result := List.Count;
end;
class function TTinyDatabase.IsTinyDBFile(const FileName: string): Boolean;
begin
try
Result := TTinyDBFileIO.CheckValidTinyDB(FileName);
except
Result := False;
end;
end;
function TTinyDatabase.CreateDatabase(const DBFileName: string): Boolean;
begin
Result := CreateDatabase(DBFileName, False, clNormal, '', False, '', '', False);
end;
function TTinyDatabase.CreateDatabase(const DBFileName: string;
CompressBlob: Boolean; CompressLevel: TCompressLevel; const CompressAlgoName: string;
Encrypt: Boolean; const EncryptAlgoName, Password: string; CRC32: Boolean = False): Boolean;
var
TempDBFile: TTinyDBFileIO;
begin
TempDBFile := TTinyDBFileIO.Create(Self);
try
Result := TempDBFile.CreateDatabase(DBFileName, CompressBlob, CompressLevel,
CompressAlgoName, Encrypt, EncryptAlgoName, Password, CRC32);
finally
TempDBFile.Free;
end;
end;
function TTinyDatabase.CreateTable(const TableName: string; Fields: array of TFieldItem): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.CreateTable(TableName, Fields);
if Result then
begin
InitTableDefs;
AddTableIO(TableName);
end;
end;
function TTinyDatabase.DeleteTable(const TableName: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.DeleteTable(TableName);
if Result then
begin
InitTableDefs;
DeleteTableIO(TableName);
end;
end;
function TTinyDatabase.CreateIndex(const TableName, IndexName: string; IndexOptions: TTDIndexOptions; FieldNames: array of string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.CreateIndex(TableName, IndexName, IndexOptions, FieldNames);
end;
function TTinyDatabase.DeleteIndex(const TableName, IndexName: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.DeleteIndex(TableName, IndexName);
end;
function TTinyDatabase.RenameTable(const OldTableName, NewTableName: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.RenameTable(OldTableName, NewTableName);
if Result then
begin
InitTableDefs;
RenameTableIO(OldTableName, NewTableName);
end;
end;
function TTinyDatabase.RenameField(const TableName, OldFieldName, NewFieldName: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.RenameField(TableName, OldFieldName, NewFieldName);
end;
function TTinyDatabase.RenameIndex(const TableName, OldIndexName, NewIndexName: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.RenameIndex(TableName, OldIndexName, NewIndexName);
end;
function TTinyDatabase.Compact: Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.Compact(FPassword);
if Result then
begin
RefreshAllTableIOs;
RefreshAllDataSets;
end;
end;
function TTinyDatabase.Repair: Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.Repair(FPassword);
if Result then
begin
RefreshAllTableIOs;
RefreshAllDataSets;
end;
end;
function TTinyDatabase.ChangePassword(const NewPassword: string; Check: Boolean = True): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.ChangePassword(FPassword, NewPassword, Check);
if Result then
begin
Password := NewPassword;
RefreshAllTableIOs;
RefreshAllDataSets;
end;
end;
function TTinyDatabase.ChangeEncrypt(NewEncrypt: Boolean; const NewEncAlgo, NewPassword: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.ChangeEncrypt(NewEncrypt, NewEncAlgo, FPassword, NewPassword);
if Result then
begin
Password := NewPassword;
RefreshAllTableIOs;
RefreshAllDataSets;
end;
end;
function TTinyDatabase.SetComments(const Value: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.SetComments(Value, FPassword);
end;
function TTinyDatabase.GetComments(var Value: string): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.GetComments(Value, FPassword);
end;
function TTinyDatabase.SetExtData(Buffer: PChar; Size: Integer): Boolean;
begin
if not Connected then Open;
CheckCanAccess;
Result := FDBFileIO.SetExtData(Buffer, Size);
end;
function TTinyDatabase.GetExtData(Buffer: PChar): Boolean;
begin
if not Connected then Open;
// Here, CheckCanAccess is not needed.
Result := FDBFileIO.GetExtData(Buffer);
end;
{ TTinySession }
constructor TTinySession.Create(AOwner: TComponent);
begin
ValidateAutoSession(AOwner, False);
inherited Create(AOwner);
FDatabases := TList.Create;
FKeepConnections := False;
FSQLHourGlass := True;
FLockRetryCount := tdbDefaultLockRetryCount;
FLockWaitTime := tdbDefaultLockWaitTime;
FPasswords := TStringList.Create;
Sessions.AddSession(Self);
end;
destructor TTinySession.Destroy;
begin
SetActive(False);
Sessions.FSessions.Remove(Self);
FPasswords.Free;
inherited Destroy;
FDatabases.Free;
end;
procedure TTinySession.Open;
begin
SetActive(True);
end;
procedure TTinySession.Close;
begin
SetActive(False);
end;
procedure TTinySession.Loaded;
begin
inherited Loaded;
try
if AutoSessionName then SetSessionNames;
if FStreamedActive then SetActive(True);
except
if csDesigning in ComponentState then
Application.HandleException(Self)
else
raise;
end;
end;
procedure TTinySession.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if AutoSessionName and (Operation = opInsert) then
if AComponent is TTDBDataSet then
TTDBDataSet(AComponent).FSessionName := Self.SessionName
else if AComponent is TTinyDatabase then
TTinyDatabase(AComponent).FSession := Self;
end;
procedure TTinySession.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
if FAutoSessionName then UpdateAutoSessionName;
end;
function TTinySession.OpenDatabase(const DatabaseName: string): TTinyDatabase;
begin
Result := DoOpenDatabase(DatabaseName, nil, nil, True);
end;
procedure TTinySession.CloseDatabase(Database: TTinyDatabase);
begin
with Database do
begin
if FRefCount <> 0 then Dec(FRefCount);
if (FRefCount = 0) and not KeepConnection then
if not Temporary then Close else
if not (csDestroying in ComponentState) then Free;
end;
end;
function TTinySession.FindDatabase(const DatabaseName: string): TTinyDatabase;
var
I: Integer;
begin
for I := 0 to FDatabases.Count - 1 do
begin
Result := FDatabases[I];
if ((Result.DatabaseName <> '') or Result.Temporary) and
(AnsiCompareText(Result.DatabaseName, DatabaseName) = 0) then Exit;
end;
Result := nil;
end;
procedure TTinySession.DropConnections;
var
I: Integer;
begin
for I := FDatabases.Count - 1 downto 0 do
with TTinyDatabase(FDatabases[I]) do
if Temporary and (FRefCount = 0) then Free;
end;
procedure TTinySession.GetDatabaseNames(List: TStrings);
var
I: Integer;
begin
for I := 0 to FDatabases.Count - 1 do
with TTinyDatabase(FDatabases[I]) do
List.Add(DatabaseName);
end;
procedure TTinySession.GetTableNames(const DatabaseName: string; List: TStrings);
var
Database: TTinyDatabase;
begin
List.BeginUpdate;
try
List.Clear;
Database := OpenDatabase(DatabaseName);
try
Database.GetTableNames(List);
finally
CloseDatabase(Database);
end;
finally
List.EndUpdate;
end;
end;
procedure TTinySession.GetFieldNames(const DatabaseName, TableName: string; List: TStrings);
var
Database: TTinyDatabase;
begin
List.BeginUpdate;
try
List.Clear;
Database := OpenDatabase(DatabaseName);
try
Database.GetFieldNames(TableName, List);
finally
CloseDatabase(Database);
end;
finally
List.EndUpdate;
end;
end;
procedure TTinySession.GetIndexNames(const DatabaseName, TableName: string; List: TStrings);
var
Database: TTinyDatabase;
begin
List.BeginUpdate;
try
List.Clear;
Database := OpenDatabase(DatabaseName);
try
Database.GetIndexNames(TableName, List);
finally
CloseDatabase(Database);
end;
finally
List.EndUpdate;
end;
end;
procedure TTinySession.AddPassword(const Password: string);
begin
LockSession;
try
if GetPasswordIndex(Password) = -1 then
FPasswords.Add(Password);
finally
UnlockSession;
end;
end;
procedure TTinySession.RemovePassword(const Password: string);
var
I: Integer;
begin
LockSession;
try
I := GetPasswordIndex(Password);
if I <> -1 then FPasswords.Delete(I);
finally
UnlockSession;
end;
end;
procedure TTinySession.RemoveAllPasswords;
begin
LockSession;
try
FPasswords.Clear;
finally
UnlockSession;
end;
end;
procedure TTinySession.CheckInactive;
begin
if Active then
DatabaseError(SSessionActive, Self);
end;
function TTinySession.GetActive: Boolean;
begin
Result := FActive;
end;
function TTinySession.GetDatabase(Index: Integer): TTinyDatabase;
begin
Result := FDatabases[Index];
end;
function TTinySession.GetDatabaseCount: Integer;
begin
Result := FDatabases.Count;
end;
procedure TTinySession.SetActive(Value: Boolean);
begin
if csReading in ComponentState then
FStreamedActive := Value
else
if Active <> Value then
StartSession(Value);
end;
procedure TTinySession.SetAutoSessionName(Value: Boolean);
begin
if Value <> FAutoSessionName then
begin
if Value then
begin
CheckInActive;
ValidateAutoSession(Owner, True);
FSessionNumber := -1;
EnterCriticalSection(FSessionCSect);
try
with Sessions do
begin
FSessionNumber := FSessionNumbers.OpenBit;
FSessionNumbers[FSessionNumber] := True;
end;
finally
LeaveCriticalSection(FSessionCSect);
end;
UpdateAutoSessionName;
end
else
begin
if FSessionNumber > -1 then
begin
EnterCriticalSection(FSessionCSect);
try
Sessions.FSessionNumbers[FSessionNumber] := False;
finally
LeaveCriticalSection(FSessionCSect);
end;
end;
end;
FAutoSessionName := Value;
end;
end;
procedure TTinySession.SetSessionName(const Value: string);
var
Ses: TTinySession;
begin
if FAutoSessionName and not FUpdatingAutoSessionName then
DatabaseError(SAutoSessionActive, Self);
CheckInActive;
if Value <> '' then
begin
Ses := Sessions.FindSession(Value);
if not ((Ses = nil) or (Ses = Self)) then
DatabaseErrorFmt(SDuplicateSessionName, [Value], Self);
end;
FSessionName := Value
end;
procedure TTinySession.SetSessionNames;
var
I: Integer;
Component: TComponent;
begin
if Owner <> nil then
for I := 0 to Owner.ComponentCount - 1 do
begin
Component := Owner.Components[I];
if (Component is TTDBDataSet) and
(AnsiCompareText(TTDBDataSet(Component).SessionName, Self.SessionName) <> 0) then
TTDBDataSet(Component).SessionName := Self.SessionName
else if (Component is TTinyDataBase) and
(AnsiCompareText(TTinyDataBase(Component).SessionName, Self.SessionName) <> 0) then
TTinyDataBase(Component).SessionName := Self.SessionName
end;
end;
procedure TTinySession.SetLockRetryCount(Value: Integer);
begin
if Value < 0 then Value := 0;
if Value <> FLockRetryCount then
FLockRetryCount := Value;
end;
procedure TTinySession.SetLockWaitTime(Value: Integer);
begin
if Value < 0 then Value := 0;
if Value <> FLockWaitTime then
FLockWaitTime := Value;
end;
function TTinySession.SessionNameStored: Boolean;
begin
Result := not FAutoSessionName;
end;
procedure TTinySession.ValidateAutoSession(AOwner: TComponent; AllSessions: Boolean);
var
I: Integer;
Component: TComponent;
begin
if AOwner <> nil then
for I := 0 to AOwner.ComponentCount - 1 do
begin
Component := AOwner.Components[I];
if (Component <> Self) and (Component is TTinySession) then
if AllSessions then DatabaseError(SAutoSessionExclusive, Self)
else if TTinySession(Component).AutoSessionName then
DatabaseErrorFmt(SAutoSessionExists, [Component.Name]);
end;
end;
function TTinySession.DoFindDatabase(const DatabaseName: string; AOwner: TComponent): TTinyDatabase;
var
I: Integer;
begin
if AOwner <> nil then
for I := 0 to FDatabases.Count - 1 do
begin
Result := FDatabases[I];
if (Result.Owner = AOwner) and (Result.HandleShared) and
(AnsiCompareText(Result.DatabaseName, DatabaseName) = 0) then Exit;
end;
Result := FindDatabase(DatabaseName);
end;
function TTinySession.DoOpenDatabase(const DatabaseName: string;
AOwner: TComponent; ADataSet: TTDBDataSet; IncRef: Boolean): TTinyDatabase;
var
TempDatabase: TTinyDatabase;
begin
Result := nil;
LockSession;
try
TempDatabase := nil;
try
Result := DoFindDatabase(DatabaseName, AOwner);
if Result = nil then
begin
TempDatabase := TTinyDatabase.Create(Self);
if ADataSet <> nil then
TempDatabase.MediumType := (ADataSet as TTDEDataSet).MediumType;
TempDatabase.DatabaseName := DatabaseName;
TempDatabase.KeepConnection := FKeepConnections;
TempDatabase.Temporary := True;
Result := TempDatabase;
end;
Result.Open;
if IncRef then Inc(Result.FRefCount);
except
TempDatabase.Free;
raise;
end;
finally
UnLockSession;
end;
end;
procedure TTinySession.AddDatabase(Value: TTinyDatabase);
begin
FDatabases.Add(Value);
DBNotification(dbAdd, Value);
end;
procedure TTinySession.RemoveDatabase(Value: TTinyDatabase);
begin
FDatabases.Remove(Value);
DBNotification(dbRemove, Value);
end;
procedure TTinySession.DBNotification(DBEvent: TTinyDatabaseEvent; const Param);
begin
if Assigned(FOnDBNotify) then FOnDBNotify(DBEvent, Param);
end;
procedure TTinySession.LockSession;
begin
if FLockCount = 0 then
begin
EnterCriticalSection(FSessionCSect);
Inc(FLockCount);
if not Active then SetActive(True);
end
else
Inc(FLockCount);
end;
procedure TTinySession.UnlockSession;
begin
Dec(FLockCount);
if FLockCount = 0 then
LeaveCriticalSection(FSessionCSect);
end;
procedure TTinySession.StartSession(Value: Boolean);
var
I: Integer;
begin
EnterCriticalSection(FSessionCSect);
try
if Value then
begin
if Assigned(FOnStartup) then FOnStartup(Self);
if FSessionName = '' then DatabaseError(SSessionNameMissing, Self);
if (DefaultSession <> Self) then DefaultSession.Active := True;
end else
begin
for I := FDatabases.Count - 1 downto 0 do
with TTinyDatabase(FDatabases[I]) do
if Temporary then Free else Close;
end;
FActive := Value;
finally
LeaveCriticalSection(FSessionCSect);
end;
end;
procedure TTinySession.UpdateAutoSessionName;
begin
FUpdatingAutoSessionName := True;
try
SessionName := Format('%s_%d', [Name, FSessionNumber + 1]);
finally
FUpdatingAutoSessionName := False;
end;
SetSessionNames;
end;
function TTinySession.GetPasswordIndex(const Password: string): Integer;
var
I: Integer;
begin
for I := 0 to FPasswords.Count - 1 do
if FPasswords[I] = Password then
begin
Result := I;
Exit;
end;
Result := -1;
end;
{ TTinySessionList }
constructor TTinySessionList.Create;
begin
inherited Create;
FSessions := TThreadList.Create;
FSessionNumbers := TBits.Create;
InitializeCriticalSection(FSessionCSect);
end;
destructor TTinySessionList.Destroy;
begin
CloseAll;
DeleteCriticalSection(FSessionCSect);
FSessionNumbers.Free;
FSessions.Free;
inherited Destroy;
end;
procedure TTinySessionList.AddSession(ASession: TTinySession);
var
List: TList;
begin
List := FSessions.LockList;
try
if List.Count = 0 then ASession.FDefault := True;
List.Add(ASession);
finally
FSessions.UnlockList;
end;
end;
procedure TTinySessionList.CloseAll;
var
I: Integer;
List: TList;
begin
List := FSessions.LockList;
try
for I := List.Count-1 downto 0 do
TTinySession(List[I]).Free;
finally
FSessions.UnlockList;
end;
end;
function TTinySessionList.GetCount: Integer;
var
List: TList;
begin
List := FSessions.LockList;
try
Result := List.Count;
finally
FSessions.UnlockList;
end;
end;
function TTinySessionList.GetSession(Index: Integer): TTinySession;
var
List: TList;
begin
List := FSessions.LockList;
try
Result := TTinySession(List[Index]);
finally
FSessions.UnlockList;
end;
end;
function TTinySessionList.GetSessionByName(const SessionName: string): TTinySession;
begin
if SessionName = '' then
Result := Session
else
Result := FindSession(SessionName);
if Result = nil then
DatabaseErrorFmt(SInvalidSessionName, [SessionName]);
end;
function TTinySessionList.FindSession(const SessionName: string): TTinySession;
var
I: Integer;
List: TList;
begin
if SessionName = '' then
Result := Session
else
begin
List := FSessions.LockList;
try
for I := 0 to List.Count - 1 do
begin
Result := List[I];
if AnsiCompareText(Result.SessionName, SessionName) = 0 then Exit;
end;
Result := nil;
finally
FSessions.UnlockList;
end;
end;
end;
procedure TTinySessionList.GetSessionNames(List: TStrings);
var
I: Integer;
SList: TList;
begin
List.BeginUpdate;
try
List.Clear;
SList := FSessions.LockList;
try
for I := 0 to SList.Count - 1 do
with TTinySession(SList[I]) do
List.Add(SessionName);
finally
FSessions.UnlockList;
end;
finally
List.EndUpdate;
end;
end;
function TTinySessionList.OpenSession(const SessionName: string): TTinySession;
begin
Result := FindSession(SessionName);
if Result = nil then
begin
Result := TTinySession.Create(nil);
Result.SessionName := SessionName;
end;
Result.SetActive(True);
end;
{ TTinyDBLoginForm }
constructor TTinyDBLoginForm.CreateNew(AOwner: TComponent);
var
NonClientMetrics: TNonClientMetrics;
begin
inherited CreateNew(AOwner);
NonClientMetrics.cbSize := sizeof(NonClientMetrics);
if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then
Font.Handle := CreateFontIndirect(NonClientMetrics.lfMessageFont);
end;
initialization
Sessions := TTinySessionList.Create;
Session := TTinySession.Create(nil);
Session.SessionName := 'Default'; { Do not localize }
finalization
FCompressClassList.Free;
FEncryptClassList.Free;
Sessions.Free;
Sessions := nil;
end.
|
{ *********************************************************************** }
{ }
{ Copyright (c) 2003 Borland Software Corporation }
{ }
{ Written by: Rick Beerendonk (rick@beerendonk.com) }
{ Microloon BV }
{ The Netherlands }
{ }
{ I'd like to thank Mike Bax, Patrick van Logchem, Hans Veltman, }
{ Arjan Jansen, Arnim Mulder, Micha Somers, Bob Swart (www.drbob42.net),}
{ Jeetinder Ramlal, Mark Sleper, Fred de Wagenaar & Piet Weijers }
{ }
{ ----------------------------------------------------------------------- }
{ THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY }
{ KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE }
{ IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A }
{ PARTICULAR PURPOSE. }
{ }
{ *********************************************************************** }
unit Borland.Examples.Delphi.RichTextBox.Info;
interface
uses
System.Collections,
System.ComponentModel,
System.Data,
System.Drawing,
System.Resources,
System.Windows.Forms;
type
TInfoBox = class(System.Windows.Forms.Form)
{$REGION 'Designer Managed Code'}
strict private
/// <summary>
/// Required designer variable.
/// </summary>
Components: System.ComponentModel.Container;
ProductLabel: System.Windows.Forms.Label;
CopyrightLabel: System.Windows.Forms.Label;
OKButton: System.Windows.Forms.Button;
WebsiteLabel: System.Windows.Forms.LinkLabel;
OperatingSystemLabel: System.Windows.Forms.Label;
PictureBox1: System.Windows.Forms.PictureBox;
Panel1: System.Windows.Forms.Panel;
DotNetFrameworkVersion: System.Windows.Forms.Label;
WrittenByLabel: System.Windows.Forms.Label;
WrittenByEMail: System.Windows.Forms.LinkLabel;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure InitializeComponent;
procedure WebsiteLabel_LinkClicked(sender: System.Object; e: System.Windows.Forms.LinkLabelLinkClickedEventArgs);
procedure WrittenByEMail_LinkClicked(sender: System.Object; e: System.Windows.Forms.LinkLabelLinkClickedEventArgs);
{$ENDREGION}
strict protected
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure Dispose(Disposing: Boolean); override;
public
constructor Create;
end;
[assembly: RuntimeRequiredAttribute(TypeOf(TInfoBox))]
implementation
uses
System.Diagnostics,
System.Globalization;
{$REGION 'Windows Form Designer generated code'}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TInfoBox.InitializeComponent;
var
resources: System.Resources.ResourceManager;
begin
resources := System.Resources.ResourceManager.Create(TypeOf(TInfoBox));
Self.ProductLabel := System.Windows.Forms.Label.Create;
Self.CopyrightLabel := System.Windows.Forms.Label.Create;
Self.OKButton := System.Windows.Forms.Button.Create;
Self.WebsiteLabel := System.Windows.Forms.LinkLabel.Create;
Self.OperatingSystemLabel := System.Windows.Forms.Label.Create;
Self.PictureBox1 := System.Windows.Forms.PictureBox.Create;
Self.Panel1 := System.Windows.Forms.Panel.Create;
Self.DotNetFrameworkVersion := System.Windows.Forms.Label.Create;
Self.WrittenByLabel := System.Windows.Forms.Label.Create;
Self.WrittenByEMail := System.Windows.Forms.LinkLabel.Create;
Self.SuspendLayout;
//
// ProductLabel
//
Self.ProductLabel.AutoSize := True;
Self.ProductLabel.Location := System.Drawing.Point.Create(72, 24);
Self.ProductLabel.Name := 'ProductLabel';
Self.ProductLabel.Size := System.Drawing.Size.Create(293, 16);
Self.ProductLabel.TabIndex := 1;
Self.ProductLabel.Text := 'Delphi™ Rich Text Box Control Demo for Microsoft® .NET';
//
// CopyrightLabel
//
Self.CopyrightLabel.AutoSize := True;
Self.CopyrightLabel.Location := System.Drawing.Point.Create(72, 48);
Self.CopyrightLabel.Name := 'CopyrightLabel';
Self.CopyrightLabel.Size := System.Drawing.Size.Create(81, 16);
Self.CopyrightLabel.TabIndex := 2;
Self.CopyrightLabel.Text := 'CopyrightLabel';
//
// OKButton
//
Self.OKButton.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom
or System.Windows.Forms.AnchorStyles.Right)));
Self.OKButton.DialogResult := System.Windows.Forms.DialogResult.OK;
Self.OKButton.Location := System.Drawing.Point.Create(296, 200);
Self.OKButton.Name := 'OKButton';
Self.OKButton.TabIndex := 0;
Self.OKButton.Text := 'OK';
//
// WebsiteLabel
//
Self.WebsiteLabel.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom
or System.Windows.Forms.AnchorStyles.Left)));
Self.WebsiteLabel.AutoSize := True;
Self.WebsiteLabel.Location := System.Drawing.Point.Create(8, 200);
Self.WebsiteLabel.Name := 'WebsiteLabel';
Self.WebsiteLabel.Size := System.Drawing.Size.Create(94, 16);
Self.WebsiteLabel.TabIndex := 6;
Self.WebsiteLabel.TabStop := True;
Self.WebsiteLabel.Text := 'www.borland.com';
Include(Self.WebsiteLabel.LinkClicked, Self.WebsiteLabel_LinkClicked);
//
// OperatingSystemLabel
//
Self.OperatingSystemLabel.AutoSize := True;
Self.OperatingSystemLabel.Location := System.Drawing.Point.Create(72, 160);
Self.OperatingSystemLabel.Name := 'OperatingSystemLabel';
Self.OperatingSystemLabel.Size := System.Drawing.Size.Create(120, 16);
Self.OperatingSystemLabel.TabIndex := 5;
Self.OperatingSystemLabel.Text := 'OperatingSystemLabel';
//
// PictureBox1
//
Self.PictureBox1.Image := (System.Drawing.Image(resources.GetObject('PictureBox1.Image')));
Self.PictureBox1.Location := System.Drawing.Point.Create(16, 16);
Self.PictureBox1.Name := 'PictureBox1';
Self.PictureBox1.Size := System.Drawing.Size.Create(43, 48);
Self.PictureBox1.SizeMode := System.Windows.Forms.PictureBoxSizeMode.AutoSize;
Self.PictureBox1.TabIndex := 5;
Self.PictureBox1.TabStop := False;
//
// Panel1
//
Self.Panel1.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right)));
Self.Panel1.BorderStyle := System.Windows.Forms.BorderStyle.Fixed3D;
Self.Panel1.Location := System.Drawing.Point.Create(72, 120);
Self.Panel1.Name := 'Panel1';
Self.Panel1.Size := System.Drawing.Size.Create(296, 4);
Self.Panel1.TabIndex := 3;
//
// DotNetFrameworkVersion
//
Self.DotNetFrameworkVersion.AutoSize := True;
Self.DotNetFrameworkVersion.Location := System.Drawing.Point.Create(72, 136);
Self.DotNetFrameworkVersion.Name := 'DotNetFrameworkVersion';
Self.DotNetFrameworkVersion.Size := System.Drawing.Size.Create(135, 16);
Self.DotNetFrameworkVersion.TabIndex := 4;
Self.DotNetFrameworkVersion.Text := 'DotNetFrameworkVersion';
//
// WrittenByLabel
//
Self.WrittenByLabel.AutoSize := True;
Self.WrittenByLabel.Location := System.Drawing.Point.Create(72, 72);
Self.WrittenByLabel.Name := 'WrittenByLabel';
Self.WrittenByLabel.Size := System.Drawing.Size.Create(55, 16);
Self.WrittenByLabel.TabIndex := 7;
Self.WrittenByLabel.Text := 'Written by';
//
// WrittenByEMail
//
Self.WrittenByEMail.AutoSize := True;
Self.WrittenByEMail.Location := System.Drawing.Point.Create(128, 72);
Self.WrittenByEMail.Name := 'WrittenByEMail';
Self.WrittenByEMail.Size := System.Drawing.Size.Create(90, 16);
Self.WrittenByEMail.TabIndex := 8;
Self.WrittenByEMail.TabStop := True;
Self.WrittenByEMail.Text := 'Rick Beerendonk';
Include(Self.WrittenByEMail.LinkClicked, Self.WrittenByEMail_LinkClicked);
//
// TInfoBox
//
Self.AcceptButton := Self.OKButton;
Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13);
Self.CancelButton := Self.OKButton;
Self.ClientSize := System.Drawing.Size.Create(378, 232);
Self.ControlBox := False;
Self.Controls.Add(Self.WrittenByEMail);
Self.Controls.Add(Self.WrittenByLabel);
Self.Controls.Add(Self.DotNetFrameworkVersion);
Self.Controls.Add(Self.OperatingSystemLabel);
Self.Controls.Add(Self.WebsiteLabel);
Self.Controls.Add(Self.CopyrightLabel);
Self.Controls.Add(Self.ProductLabel);
Self.Controls.Add(Self.Panel1);
Self.Controls.Add(Self.PictureBox1);
Self.Controls.Add(Self.OKButton);
Self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedSingle;
Self.MaximizeBox := False;
Self.MinimizeBox := False;
Self.Name := 'TInfoBox';
Self.ShowInTaskbar := False;
Self.StartPosition := System.Windows.Forms.FormStartPosition.CenterParent;
Self.Text := 'Info Rich Text Box Control Demo';
Self.ResumeLayout(False);
end;
{$ENDREGION}
procedure TInfoBox.Dispose(Disposing: Boolean);
begin
if Disposing then
begin
if Components <> nil then
Components.Dispose();
end;
inherited Dispose(Disposing);
end;
constructor TInfoBox.Create;
begin
inherited Create;
//
// Required for Windows Form Designer support
//
InitializeComponent;
//
// TODO: Add any constructor code after InitializeComponent call
//
CopyrightLabel.Text := System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath).LegalCopyright;
DotNetFrameworkVersion.Text := 'Microsoft® .NET Framework: ' + Environment.Version.ToString;
OperatingSystemLabel.Text := 'Operating System: ' + Environment.OSVersion.ToString;
end;
procedure TInfoBox.WrittenByEMail_LinkClicked(sender: System.Object; e: System.Windows.Forms.LinkLabelLinkClickedEventArgs);
begin
Process.Create.Start('mailto:rick@beerendonk.com?subject=Delphi Example "Rich Text Box Demo"');
end;
procedure TInfoBox.WebsiteLabel_LinkClicked(sender: System.Object; e: System.Windows.Forms.LinkLabelLinkClickedEventArgs);
begin
Process.Create.Start('http://www.borland.com');
end;
end.
|
// **************************************************************************************************
// Delphi Aio Library.
// Unit Hub
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
//
// The Original Code is Hub.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit Hub;
interface
uses Classes, SysUtils, SyncObjs, {$IFDEF LOCK_FREE} PasMP, {$ENDIF}
{$IFDEF FPC} fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF},
GarbageCollector, GInterfaces;
type
THub = class(TCustomHub)
strict private
type
TTaskKind = (tkMethod, tkIntfMethod, tkProc);
{ TTask }
TTask = record
Kind: TTaskKind;
Method: TThreadMethod;
Intf: IInterface;
Proc: TTaskProc;
Arg: Pointer;
procedure Init(const Method: TThreadMethod); overload;
procedure Init(Intf: IInterface; const Method: TThreadMethod); overload;
procedure Init(const Proc: TTaskProc; Arg: Pointer); overload;
{$IFDEF FPC}
class operator = (const a,b : TTask): Boolean;
{$ENDIF}
end;
TQueue = {$IFDEF DCC}TList<TTask>{$ELSE}TFPGList<TTask>{$ENDIF};
procedure GetAddresses(const Task: TThreadMethod; out Obj: TObject;
out MethodAddr: Pointer); inline;
var
FQueue: TQueue;
FAccumQueue: TQueue;
FLoopExit: Boolean;
FName: string;
FLock: SyncObjs.TCriticalSection;
FLS: Pointer;
FGC: Pointer;
FIsSuspended: Boolean;
{$IFDEF LOCK_FREE}
FLockFreeQueue: TPasMPUnboundedQueue;
{$ENDIF}
procedure Clean;
procedure Swap(var A1, A2: TQueue);
protected
procedure Lock; inline;
procedure Unlock; inline;
function TryLock: Boolean; inline;
function ServeTaskQueue: Boolean; dynamic;
procedure AfterSwap; dynamic;
public
constructor Create;
destructor Destroy; override;
property Name: string read FName write FName;
property IsSuspended: Boolean read FIsSuspended write FIsSuspended;
function HLS(const Key: string): TObject; override;
procedure HLS(const Key: string; Value: TObject); override;
function GC(A: TObject): IGCObject; override;
procedure EnqueueTask(const Task: TThreadMethod); override;
procedure EnqueueTask(const Task: TTaskProc; Arg: Pointer); override;
procedure Pulse; override;
procedure LoopExit; override;
procedure Loop(const Cond: TExitCondition; Timeout: LongWord = INFINITE); override;
procedure Loop(const Cond: TExitConditionStatic; Timeout: LongWord = INFINITE); override;
procedure Switch; override;
end;
TSingleThreadHub = class(THub)
type
TMultiplexorEvent = (meError, meEvent, meSync, meIO, meWinMsg,
meTimer, meWaitTimeout);
TMultiplexorEvents = set of TMultiplexorEvent;
const
ALL_EVENTS: TMultiplexorEvents = [Low(TMultiplexorEvent)..High(TMultiplexorEvent)];
private
type
TTimeoutRoutine = function(Timeout: LongWord): Boolean of object;
var
FEvents: Pointer;
FReadFiles: Pointer;
FWriteFiles: Pointer;
FTimeouts: Pointer;
FWakeMainThread: TNotifyEvent;
FThreadId: LongWord;
FTimerFlag: Boolean;
FIOFlag: Boolean;
FIsDef: Boolean;
FProcessWinMsg: Boolean;
FSyncEvent: TEvent;
FServeRoutine: TTimeoutRoutine;
procedure SetTriggerFlag(const TimerFlag, IOFlag: Boolean);
procedure WakeUpThread(Sender: TObject);
procedure SetupEnviron;
procedure BeforeServe;inline;
procedure AfterServe; inline;
function ServeAsDefHub(Timeout: LongWord): Boolean;
function ServeHard(Timeout: LongWord): Boolean;
protected
function ServeMultiplexor(TimeOut: LongWord): TMultiplexorEvent; dynamic;
public
constructor Create;
destructor Destroy; override;
// IO files, sockets, com-ports, pipes, etc.
procedure Cancel(Fd: THandle); override;
function Write(Fd: THandle; Buf: Pointer; Len: LongWord; const Cb: TIOCallback; Data: Pointer; Offset: Int64 = -1): Boolean; override;
function WriteTo(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean; override;
function Read(Fd: THandle; Buf: Pointer; Len: LongWord; const Cb: TIOCallback; Data: Pointer; Offset: Int64 = -1): Boolean; override;
function ReadFrom(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean; override;
// IO timeouts and timers
function CreateTimer(const Cb: TInervalCallback; Data: Pointer; Interval: LongWord): THandle; override;
procedure DestroyTimer(Id: THandle); override;
function CreateTimeout(const Cb: TInervalCallback; Data: Pointer; Interval: LongWord): THandle; override;
procedure DestroyTimeout(Id: THandle); override;
// Event objects
function AddEvent(Ev: THandle; const Cb: TEventCallback; Data: Pointer): Boolean; override;
procedure RemEvent(Ev: THandle); override;
// services
function Serve(TimeOut: LongWord): Boolean; override;
function Wait(TimeOut: LongWord; const Events: TMultiplexorEvents=[];
const ProcessWinMsg: Boolean = True): TMultiplexorEvent;
procedure Pulse; override;
end;
function GetCurrentHub: TCustomHub;
function DefHub(ThreadID: LongWord = 0): TSingleThreadHub; overload;
function DefHub(Thread: TThread): TSingleThreadHub; overload;
var
HubInfrasctuctureEnable: Boolean;
{$IFDEF DEBUG}
IOEventTupleCounter: Integer;
IOFdTupleCounter: Integer;
IOTimeTupleCounter: Integer;
{$ENDIF}
implementation
uses Math, GreenletsImpl, Greenlets, sock,
{$IFDEF MSWINDOWS}
{$IFDEF DCC}Winapi.Windows{$ELSE}windows{$ENDIF}
{$ELSE}
// TODO
{$ENDIF};
const
NANOSEC_PER_MSEC = 1000000;
type
TObjMethodStruct = packed record
Code: Pointer;
Data: TObject;
end;
THubMap = {$IFDEF DCC}TDictionary{$ELSE}TFPGMap{$ENDIF}<LongWord, TSingleThreadHub>;
TEventTuple = record
Event: THandle;
Cb: TEventCallback;
Data: Pointer;
Hub: THub;
procedure Trigger(const Aborted: Boolean);
end;
PEvents = ^TEvents;
TEvents = record
const
MAX_EV_COUNT = 1024;
var
SyncEvent: TEvent;
FBuf: array[0..MAX_EV_COUNT-1] of THandle;
FCb: array[0..MAX_EV_COUNT-1] of TEventCallback;
FData: array[0..MAX_EV_COUNT-1] of Pointer;
FHub: array[0..MAX_EV_COUNT-1] of THub;
FBufSize: Integer;
procedure Enqueue(Hnd: THandle; const Cb: TEventCallback;
Data: Pointer; Hub: THub);
procedure DequeueByIndex(Index: Integer); overload;
procedure Dequeue(Hnd: THandle); overload;
function Buf: Pointer; inline;
function TupleByIndex(Index: Integer): TEventTuple; inline;
function Find(Hnd: THandle; out Index: Integer): Boolean; inline;
function BufSize: LongWord; inline;
function IsInitialized: Boolean; inline;
procedure Initialize; inline;
procedure DeInitialize; inline;
end;
PFileTuple = ^TFileTuple;
TFileTuple = record
Fd: THandle;
ReadData: Pointer;
WriteData: Pointer;
ReadCb: TIOCallback;
WriteCb: TIOCallback;
Hub: THub;
Active: Boolean;
CleanTime: TTime;
{$IFDEF MSWINDOWS}
Overlap: TOverlapped;
{$ENDIF}
procedure RecalcCleanTime;
procedure Trigger(ErrorCode: Integer; Len: Integer; const Op: TIOOperation);
end;
PFiles = ^TFiles;
TFiles = record
const
TRASH_CLEAR_TIMEOUT_MINS = 30;
type
TMap = {$IFDEF DCC}TDictionary{$ELSE}TFPGMap{$ENDIF}<THandle, PFileTuple>;
FList = {$IFDEF DCC}TList{$ELSE}TFPGList{$ENDIF}<PFileTuple>;
var
FMap: TMap;
// in input-output operations callbacks can come to private
// descriptors. This is found for sockets
FTrash: FList;
FTrashLAstClean: TTime;
procedure TrashClean(const OnlyByTimeout: Boolean = True);
function IsInitialized: Boolean;
procedure Initialize;
procedure Deinitialize;
function Enqueue(Fd: THandle; const Op: TIOOperation;
const Cb: TIOCallback; Data: Pointer; Hub: THub): PFileTuple; overload;
procedure Dequeue(const Fd: THandle);
function Find(Fd: THandle): Boolean; overload;
function Find(Id: THandle; out Tup: PFileTuple): Boolean; overload;
end;
PTimeoutTuple = ^TTimeoutTuple;
TTimeoutTuple = record
Id: THandle;
Cb: TInervalCallback;
Data: Pointer;
Hub: THub;
procedure Trigger;
end;
TRawGreenletPImpl = class(TRawGreenletImpl);
PTimeouts = ^TTimeouts;
TTimeouts = record
type
TMap = {$IFDEF DCC}TDictionary{$ELSE}TFPGMap{$ENDIF}<THandle, PTimeoutTuple>;
var
FMap: TMap;
function IsInitialized: Boolean;
procedure Initialize;
procedure Deinitialize;
public
function Enqueue(Id: THandle; const Cb: TInervalCallback;
Data: Pointer; Hub: THub): PTimeoutTuple;
procedure Dequeue(Id: THandle);
function Find(Id: THandle): Boolean; overload;
end;
threadvar
CurrentHub: THub;
var
DefHubsLock: SyncObjs.TCriticalSection;
DefHubs: THubMap;
{$IFDEF MSWINDOWS}
{$I iocpwin.inc}
var
WsaDataOnce: TWSADATA;
function GetCurrentProcessorNumber: DWORD; external kernel32 name 'GetCurrentProcessorNumber';
{$ENDIF}
function GetCurrentHub: TCustomHub;
begin
if Assigned(CurrentHub) then
Result := CurrentHub
else
Result := DefHub;
end;
function DefHub(ThreadID: LongWord): TSingleThreadHub;
var
ID: LongWord;
CintainsKey: Boolean;
{$IFNDEF DCC}
Index: Integer;
{$ENDIF}
begin
if not Assigned(DefHubs) then
Exit(nil);
if ThreadID = 0 then
ID := TThread.CurrentThread.ThreadID
else
ID := ThreadID;
DefHubsLock.Acquire;
try
{$IFDEF DCC}
CintainsKey := DefHubs.ContainsKey(ID);
{$ELSE}
CintainsKey := DefHubs.Find(ID, Index);
{$ENDIF}
if CintainsKey then
Result := DefHubs[ID]
else begin
Result := TSingleThreadHub.Create;
Result.FIsDef := True;
Result.FThreadId := ID;
DefHubs.Add(ID, Result);
end;
finally
DefHubsLock.Release
end;
end;
function DefHub(Thread: TThread): TSingleThreadHub;
begin
Result := DefHub(Thread.ThreadID)
end;
{$IFDEF MSWINDOWS}
procedure STFileIOCompletionReadRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioRead);
end;
procedure STFlaggedFileIOCompletionReadRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped; Flags: DWORD); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioRead);
end;
procedure STFileIOCompletionWriteRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioWrite);
end;
procedure STFlaggedFileIOCompletionWriteRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped; Flags: DWORD); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioWrite);
end;
procedure STTimerAPCProc(lpArgToCompletionRoutine: Pointer;
dwTimerLowValue: DWORD; dwTimerHighValue: DWORD); stdcall;
var
Tuple: PTimeoutTuple;
begin
Tuple := lpArgToCompletionRoutine;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(True, False);
Tuple.Trigger;
end;
{$ENDIF}
function GetEvents(Hub: TSingleThreadHub): PEvents; inline;
begin
Result := PEvents(Hub.FEvents)
end;
function GetReadFiles(Hub: TSingleThreadHub): PFiles; inline;
begin
Result := PFiles(Hub.FReadFiles)
end;
function GetWriteFiles(Hub: TSingleThreadHub): PFiles; inline;
begin
Result := PFiles(Hub.FWriteFiles)
end;
function GetTimeouts(Hub: TSingleThreadHub): PTimeouts; inline;
begin
Result := PTimeouts(Hub.FTimeouts)
end;
{ THub }
procedure THub.AfterSwap;
begin
end;
function THub.ServeTaskQueue: Boolean;
var
I: Integer;
Arg: Pointer;
Proc: TTaskProc;
OldHub: THub;
Tsk: TTask;
procedure Process(var Tsk: TTask);
begin
case Tsk.Kind of
tkMethod: begin
Tsk.Method();
end;
tkIntfMethod: begin
if Assigned(Tsk.Intf) then begin
Tsk.Method();
Tsk.Intf := nil;
end;
end;
tkProc: begin
Proc := Tsk.Proc;
Arg := Tsk.Arg;
Proc(Arg)
end;
end;
end;
begin
Result := False;
OldHub := CurrentHub;
try
CurrentHub := Self;
{$IFDEF MSWINDOWS}
if TThread.CurrentThread.ThreadID = MainThreadID then begin
Result := CheckSynchronize(0)
end;
{$ENDIF}
{$IFDEF LOCK_FREE}
try
while FLockFreeQueue.Dequeue(Tsk) do begin
Result := True;
Process(Tsk)
end;
finally
while FLockFreeQueue.Dequeue(Tsk) do ;
end;
{$ELSE}
// transaction commit to write and transfer data
// in transaction for reading - to reduce problems with race condition
Swap(FQueue, FAccumQueue);
Result := Result or (FQueue.Count > 0);
if FQueue.Count > 0 then
try
for I := 0 to FQueue.Count-1 do begin
Tsk := FQueue[I];
Process(Tsk);
end;
finally
// obligatory it is necessary to clean, differently at Abort or Exception
// on the iteration trace. queues will come up with "outdated" calls
FQueue.Clear;
end;
{$ENDIF}
finally
CurrentHub := OldHub;
end;
end;
procedure THub.Clean;
procedure CleanQueue(A: TQueue);
var
I: Integer;
begin
for I := 0 to A.Count-1 do
with A[I] do begin
case Kind of
tkIntfMethod: begin
//Intf._Release;
end;
tkMethod:;
tkProc: ;
end;
end;
A.Clear;
end;
begin
Lock;
try
CleanQueue(FAccumQueue);
CleanQueue(FQueue);
finally
Unlock
end;
end;
procedure THub.Swap(var A1, A2: TQueue);
var
Tmp: TQueue;
begin
Lock;
try
Tmp := A1;
A1 := A2;
A2 := Tmp;
finally
AfterSwap;
Unlock;
end;
end;
procedure THub.Lock;
begin
{$IFDEF DCC}
TMonitor.Enter(FLock);
{$ELSE}
FLock.Acquire;
{$ENDIF}
end;
procedure THub.Unlock;
begin
{$IFDEF DCC}
TMonitor.Exit(FLock);
{$ELSE}
FLock.Release;
{$ENDIF}
end;
function THub.TryLock: Boolean;
begin
{$IFDEF DCC}
Result := TMonitor.TryEnter(FLock);
{$ELSE}
Result := FLock.TryEnter
{$ENDIF}
end;
constructor THub.Create;
begin
inherited Create;
FQueue := TQueue.Create;
FAccumQueue := TQueue.Create;
FLock := SyncObjs.TCriticalSection.Create;
FLS := TLocalStorage.Create;
FGC := TGarbageCollector.Create;
GetJoiner(Self);
{$IFDEF LOCK_FREE}
FLockFreeQueue := TPasMPUnboundedQueue.Create(SizeOf(TTask));
{$ENDIF}
end;
destructor THub.Destroy;
begin
Clean;
FQueue.Free;
FAccumQueue.Free;
TLocalStorage(FLS).Free;
TGarbageCollector(FGC).Free;
FLock.Free;
{$IFDEF LOCK_FREE}
FLockFreeQueue.Free;
{$ENDIF}
inherited;
end;
function THub.HLS(const Key: string): TObject;
begin
Result := TLocalStorage(FLS).GetValue(Key);
end;
procedure THub.HLS(const Key: string; Value: TObject);
var
Obj: TObject;
begin
if TLocalStorage(FLS).IsExists(Key) then begin
Obj := TLocalStorage(FLS).GetValue(Key);
Obj.Free;
TLocalStorage(FLS).UnsetValue(Key);
end;
if Assigned(Value) then
TLocalStorage(FLS).SetValue(Key, Value)
end;
function THub.GC(A: TObject): IGCObject;
var
G: TGarbageCollector;
begin
G := TGarbageCollector(FGC);
Result := G.SetValue(A);
end;
procedure THub.EnqueueTask(const Task: TTaskProc; Arg: Pointer);
var
Tsk: TTask;
{$IFDEF LOCK_FREE}
Q: TPasMPUnboundedQueue;
{$ENDIF}
begin
Tsk.Init(Task, Arg);
{$IFDEF LOCK_FREE}
FLockFreeQueue.Enqueue(Tsk);
{$ELSE}
Lock;
try
FAccumQueue.Add(Tsk);
finally
Unlock
end;
{$ENDIF}
Pulse;
end;
procedure THub.EnqueueTask(const Task: TThreadMethod);
var
Obj: TObject;
MethodAddr: Pointer;
Intf: IInterface;
Tsk: TTask;
{$IFDEF LOCK_FREE}
Q: TPasMPUnboundedQueue;
{$ENDIF}
begin
GetAddresses(Task, Obj, MethodAddr);
{$IFDEF DEBUG}
Assert(not Obj.InheritsFrom(TRawGreenletImpl), 'Enqueue Greenlet methods only by Proxy');
{$ENDIF}
if Obj.GetInterface(IInterface, Intf) then
Tsk.Init(Intf, Task)
else
Tsk.Init(Task);
{$IFDEF LOCK_FREE}
if Assigned(Intf) then
Intf._AddRef;
FLockFreeQueue.Enqueue(Tsk);
{$ELSE}
Lock;
try
// write transaction
FAccumQueue.Add(Tsk);
finally
Unlock;
end;
{$ENDIF}
Pulse;
end;
procedure THub.GetAddresses(const Task: TThreadMethod; out Obj: TObject;
out MethodAddr: Pointer);
var
Struct: TObjMethodStruct absolute Task;
begin
Obj := Struct.Data;
MethodAddr := Struct.Code;
end;
procedure THub.Loop(const Cond: TExitCondition; Timeout: LongWord);
var
Stop: TTime;
begin
FLoopExit := False;
Stop := Now + TimeOut2Time(Timeout);
while not Cond() and (Now < Stop) and (not FLoopExit) do
Serve(Time2TimeOut(Stop - Now))
end;
procedure THub.Loop(const Cond: TExitConditionStatic; Timeout: LongWord);
var
Stop: TTime;
begin
FLoopExit := False;
Stop := Now + TimeOut2Time(Timeout);
while not Cond() and (Now < Stop) and (not FLoopExit) do
Serve(Time2TimeOut(Stop - Now))
end;
procedure THub.Switch;
begin
if Greenlets.GetCurrent <> nil then begin
TRawGreenletPImpl.Switch2RootContext
end;
end;
procedure THub.LoopExit;
begin
FLoopExit := True;
Pulse;
end;
procedure THub.Pulse;
begin
end;
{ TSingleThreadHub }
function TSingleThreadHub.AddEvent(Ev: THandle; const Cb: TEventCallback;
Data: Pointer): Boolean;
var
Index: Integer;
Tup: TEventTuple;
begin
{$IFDEF MSWINDOWS}
Result := GetEvents(Self).BufSize < (MAXIMUM_WAIT_OBJECTS-1);
{$ELSE}
Result := True;
{$ENDIF}
if GetEvents(Self).Find(Ev, Index) then begin
Tup := GetEvents(Self).TupleByIndex(Index);
if (@Tup.Cb <> @Cb) or (Tup.Data <> Data) then
raise EHubError.CreateFmt('Handle %d already exists in demultiplexor queue', [Ev]);
end;
if Result then begin
GetEvents(Self).Enqueue(Ev, Cb, Data, Self);
Pulse;
end;
end;
procedure TSingleThreadHub.AfterServe;
begin
if Assigned(FWakeMainThread) then
Classes.WakeMainThread := FWakeMainThread;
if not FIsDef then
FThreadId := 0;
end;
procedure TSingleThreadHub.BeforeServe;
begin
if FIsDef then begin
if FThreadId <> TThread.CurrentThread.ThreadID then
raise EHubError.Create('Def Hub must be serving inside owner thread');
end
else begin
if FThreadId <> 0 then
raise EHubError.Create('Hub already serving by other thread');
FThreadId := TThread.CurrentThread.ThreadID;
end;
SetupEnviron;
if TThread.CurrentThread.ThreadID = MainThreadID then begin
FWakeMainThread := Classes.WakeMainThread;
Classes.WakeMainThread := Self.WakeUpThread;
end;
end;
procedure TSingleThreadHub.Cancel(Fd: THandle);
var
R, W: Boolean;
begin
R := GetReadFiles(Self).Find(Fd);
W := GetWriteFiles(Self).Find(Fd);
if W or R then begin
{$IFDEF MSWINDOWS}
CancelIo(Fd);
{$ELSE}
{$ENDIF}
end;
if R then
GetReadFiles(Self).Dequeue(Fd);
if W then
GetWriteFiles(Self).Dequeue(Fd);
end;
constructor TSingleThreadHub.Create;
begin
inherited Create;
SetupEnviron;
FServeRoutine := ServeHard;
end;
function TSingleThreadHub.CreateTimeout(const Cb: TInervalCallback;
Data: Pointer; Interval: LongWord): THandle;
var
DueTime: Int64;
TuplePtr: PTimeoutTuple;
begin
{$IFDEF MSWINDOWS}
Result := CreateWaitableTimer(nil, False, '');
DueTime := Interval*(NANOSEC_PER_MSEC div 100);
DueTime := DueTime * -1;
TuplePtr := GetTimeouts(Self).Enqueue(Result, Cb, Data, Self);
if not SetWaitableTimer(Result, DueTime, 0, @STTimerAPCProc, TuplePtr, False) then begin
GetTimeouts(Self).Dequeue(Result);
end;
{$ELSE}
{$ENDIF}
end;
function TSingleThreadHub.CreateTimer(const Cb: TInervalCallback; Data: Pointer;
Interval: LongWord): THandle;
var
DueTime: Int64;
TuplePtr: PTimeoutTuple;
begin
{$IFDEF MSWINDOWS}
Result := CreateWaitableTimer(nil, False, '');
DueTime := Interval*(NANOSEC_PER_MSEC div 100);
DueTime := DueTime * -1;
TuplePtr := GetTimeouts(Self).Enqueue(Result, Cb, Data, Self);
if not SetWaitableTimer(Result, DueTime, Interval, @STTimerAPCProc, TuplePtr, False) then begin
GetTimeouts(Self).Dequeue(Result);
end;
{$ELSE}
{$ENDIF}
end;
destructor TSingleThreadHub.Destroy;
var
ContainsKey: Boolean;
{$IFNDEF DCC}
Index: Integer;
{$ENDIF}
begin
if Assigned(FEvents) then begin
GetEvents(Self).DeInitialize;
FreeMem(FEvents, SizeOf(TEvents));
end;
if Assigned(FReadFiles) then begin
GetReadFiles(Self).Deinitialize;
FreeMem(FReadFiles, SizeOf(TFiles));
end;
if Assigned(FWriteFiles) then begin
GetWriteFiles(Self).Deinitialize;
FreeMem(FWriteFiles, SizeOf(TFiles));
end;
if Assigned(FTimeouts) then begin
GetTimeouts(Self).Deinitialize;
FreeMem(FTimeouts, SizeOf(TTimeouts));
end;
if FIsDef then begin
DefHubsLock.Acquire;
try
{$IFDEF DCC}
ContainsKey := DefHubs.ContainsKey(FThreadId);
{$ELSE}
ContainsKey := DefHubs.Find(FThreadId, Index);
{$ENDIF}
if ContainsKey then
DefHubs.Remove(FThreadId);
finally
DefHubsLock.Release
end;
end;
TRawGreenletPImpl.ClearContexts;
CurrentHub := nil;
inherited;
end;
procedure TSingleThreadHub.DestroyTimeout(Id: THandle);
begin
{$IFDEF MSWINDOWS}
if GetTimeouts(Self).Find(Id) then begin
CancelWaitableTimer(Id);
GetTimeouts(Self).Dequeue(Id);
end
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.DestroyTimer(Id: THandle);
begin
{$IFDEF MSWINDOWS}
if GetTimeouts(Self).Find(Id) then begin
CancelWaitableTimer(Id);
GetTimeouts(Self).Dequeue(Id);
end;
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.Pulse;
begin
FSyncEvent.SetEvent;
end;
function TSingleThreadHub.ReadFrom(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean;
var
TuplePtr: PFileTuple;
Flags: DWORD;
Buf_: WSABUF;
RetValue: LongWord;
begin
TuplePtr := GetReadFiles(Self).Enqueue(Fd, ioRead, Cb, Data, Self);
Flags := MSG_PARTIAL;
Buf_.len := Len;
Buf_.buf := Buf;
WSARecvFrom(Fd, @Buf_, 1, nil, Flags, Addr.AddrPtr,
@Addr.AddrLen, @TuplePtr.Overlap, @STFlaggedFileIOCompletionReadRoutine);
RetValue := WSAGetLastError;
Result := RetValue = WSA_IO_PENDING;
if not Result then begin
GetReadFiles(Self).Dequeue(Fd);
end;
end;
function TSingleThreadHub.Read(Fd: THandle; Buf: Pointer; Len: LongWord;
const Cb: TIOCallback; Data: Pointer; Offset: Int64): Boolean;
var
TuplePtr: PFileTuple;
begin
TuplePtr := GetReadFiles(Self).Enqueue(Fd, ioRead, Cb, Data, Self);
{$IFDEF MSWINDOWS}
if Offset <> -1 then begin
TuplePtr^.Overlap.Offset := Offset and $FFFFFFFF;
TuplePtr^.Overlap.OffsetHigh := Offset shr 32;
end;
Result := ReadFileEx(Fd, Buf, Len, @TuplePtr^.Overlap, @STFileIOCompletionReadRoutine);
if not Result then
GetReadFiles(Self).Dequeue(Fd);
{$IFDEF DEBUG}
//raise EHubError.CreateFmt('Error Message: %s', [SysErrorMessage(GetLastError)]);
{$ENDIF}
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.RemEvent(Ev: THandle);
begin
GetEvents(Self).Dequeue(Ev);
end;
function TSingleThreadHub.ServeAsDefHub(Timeout: LongWord): Boolean;
var
Stop: TTime;
MxEvent: TMultiplexorEvent;
begin
Stop := Now + TimeOut2Time(TimeOut);
repeat
if ServeTaskQueue then
Exit(True)
else begin
FProcessWinMsg := True;
MxEvent := ServeMultiplexor(Time2TimeOut(Stop - Now));
Result := MxEvent <> meWaitTimeout;
Result := Result or ServeTaskQueue;
end;
until (Now >= Stop) or Result;
end;
function TSingleThreadHub.ServeHard(Timeout: LongWord): Boolean;
begin
BeforeServe;
try
Result := ServeAsDefHub(Timeout);
finally
AfterServe
end;
if FIsDef then
FServeRoutine := ServeAsDefHub
end;
function TSingleThreadHub.Serve(TimeOut: LongWord): Boolean;
begin
Result := FServeRoutine(TimeOut);
end;
function TSingleThreadHub.ServeMultiplexor(TimeOut: LongWord): TMultiplexorEvent;
const
WM_QUIT = $0012;
WM_CLOSE = $0010;
WM_DESTROY = $0002;
MWMO_ALERTABLE = $0002;
MWMO_INPUTAVAILABLE = $0004;
var
MultiplexorCode: LongWord;
Event: TEventTuple;
{$IFDEF MSWINDOWS}
Msg: TMsg;
function ProcessMultiplexorAnswer(Code: LongWord): TMultiplexorEvent;
var
Cnt: Integer;
begin
Result := meError;
if Code = WAIT_FAILED then begin
Cnt := GetEvents(Self).BufSize;
if Cnt = 0 then
raise EHubError.CreateFmt('Events.Count = 0', [])
else
raise EHubError.CreateFmt('IO.Serve with error: %s', [SysErrorMessage(GetLastError)]);
end;
if Code = 0 then begin
Result := meSync;
end
else if InRange(Code, WAIT_OBJECT_0+1, WAIT_OBJECT_0+GetEvents(Self).BufSize-1) then begin
Event := GetEvents(Self).TupleByIndex(Code);
GetEvents(Self).DequeueByIndex(Code);
Event.Trigger(False);
Result := meEvent;
end
else if InRange(Code, WAIT_ABANDONED_0+1, WAIT_ABANDONED_0+GetEvents(Self).BufSize-1) then begin
Event := GetEvents(Self).TupleByIndex(Code);
GetEvents(Self).DequeueByIndex(Code);
Event.Trigger(True);
Result := meEvent;
end;
end;
{$ENDIF}
begin
Result := meError;
{$IFDEF MSWINDOWS}
if IsConsole or (TThread.CurrentThread.ThreadID <> MainThreadID) then begin
MultiplexorCode := WaitForMultipleObjectsEx(GetEvents(Self).BufSize,
{$IFDEF DCC}PWOHandleArray{$ELSE}LPHANDLE{$ENDIF}(GetEvents(Self).Buf),
False, Timeout, True);
end
else begin
MultiplexorCode := MsgWaitForMultipleObjectsEx(GetEvents(Self).BufSize, GetEvents(Self).Buf^,
Timeout, QS_ALLEVENTS or QS_ALLINPUT, MWMO_ALERTABLE or MWMO_INPUTAVAILABLE);
end;
case MultiplexorCode of
WAIT_TIMEOUT:
Result := meWaitTimeout;
WAIT_IO_COMPLETION: begin
if FTimerFlag then
Result := meTimer
else if FIOFlag then
Result := meIO
end;
else begin
if MultiplexorCode = GetEvents(Self).BufSize then
Result := meWinMsg
else
Result := ProcessMultiplexorAnswer(MultiplexorCode);
end;
end;
if Result = meWinMsg then begin
if FProcessWinMsg then begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
if Msg.message in [WM_QUIT, WM_CLOSE, WM_DESTROY] then begin
CloseWindow(GetWindow(GetCurrentProcess, GW_HWNDFIRST));
//Abort
end
end;
end
end;
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.SetTriggerFlag(const TimerFlag, IOFlag: Boolean);
begin
FTimerFlag := TimerFlag;
FIOFlag := IOFlag;
end;
procedure TSingleThreadHub.SetupEnviron;
begin
if not Assigned(FEvents) then begin
FEvents := AllocMem(SizeOf(TEvents));
FillChar(FEvents^, SizeOF(TEvents), 0);
end;
if not GetEvents(Self).IsInitialized then begin
GetEvents(Self).Initialize;
FSyncEvent := GetEvents(Self).SyncEvent;
end;
if not Assigned(FReadFiles) then begin
FReadFiles := AllocMem(SizeOf(TFiles));
FillChar(FReadFiles^, SizeOF(TFiles), 0);
end;
if not GetReadFiles(Self).IsInitialized then begin
GetReadFiles(Self).Initialize;
end;
if not Assigned(FWriteFiles) then begin
FWriteFiles := AllocMem(SizeOf(TFiles));
FillChar(FWriteFiles^, SizeOF(TFiles), 0);
end;
if not GetWriteFiles(Self).IsInitialized then begin
GetWriteFiles(Self).Initialize;
end;
if not Assigned(FTimeouts) then begin
FTimeouts := AllocMem(SizeOf(TTimeouts));
FillChar(FTimeouts^, SizeOF(TTimeouts), 0);
end;
if not GetTimeouts(Self).IsInitialized then begin
GetTimeouts(Self).Initialize;
end;
end;
function TSingleThreadHub.Wait(TimeOut: LongWord;
const Events: TMultiplexorEvents; const ProcessWinMsg: Boolean): TMultiplexorEvent;
var
Stop: TTime;
LocalEvents: TMultiplexorEvents;
IsTimeout: Boolean;
begin
FProcessWinMsg := ProcessWinMsg;
IsTimeout := False;
if Events = [] then
LocalEvents := ALL_EVENTS
else
LocalEvents := Events;
BeforeServe;
try
Stop := Now + TimeOut2Time(TimeOut);
repeat
Result := ServeMultiplexor(Time2TimeOut(Stop - Now));
IsTimeout := (TimeOut <> INFINITE) and (Now >= Stop);
until IsTimeout or (Result in LocalEvents);
finally
if IsTimeout then
Result := meWaitTimeout;
AfterServe
end;
end;
procedure TSingleThreadHub.WakeUpThread(Sender: TObject);
begin
GetEvents(Self).SyncEvent.SetEvent;
end;
function TSingleThreadHub.WriteTo(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean;
var
TuplePtr: PFileTuple;
Flags: DWORD;
BufWsa: WSABUF;
RetValue: LongWord;
SentSz: LongWord;
begin
TuplePtr := GetWriteFiles(Self).Enqueue(Fd, ioWrite, Cb, Data, Self);
Flags := 0;
BufWsa.buf := Buf;
BufWsa.len := Len;
SentSz := 0;
WSASendTo(Fd, @BufWsa, 1, SentSz, Flags, Addr.AddrPtr,
Addr.AddrLen, @TuplePtr.Overlap, @STFlaggedFileIOCompletionWriteRoutine);
RetValue := WSAGetLastError;
Result := RetValue = WSA_IO_PENDING;
if not Result then begin
GetWriteFiles(Self).Dequeue(Fd);
end;
end;
function TSingleThreadHub.Write(Fd: THandle; Buf: Pointer; Len: LongWord;
const Cb: TIOCallback; Data: Pointer; Offset: Int64): Boolean;
var
TuplePtr: PFileTuple;
begin
TuplePtr := GetWriteFiles(Self).Enqueue(Fd, ioWrite, Cb, Data, Self);
{$IFDEF MSWINDOWS}
if Offset <> -1 then begin
TuplePtr^.Overlap.Offset := Offset and $FFFFFFFF;
TuplePtr^.Overlap.OffsetHigh := Offset shr 32;
end;
Result := WriteFileEx(Fd, Buf, Len, TuplePtr^.Overlap, @STFileIOCompletionWriteRoutine);
if not Result then begin
GetWriteFiles(Self).Dequeue(Fd);
{$IFDEF DEBUG}
//raise EHubError.CreateFmt('Error Message: %s', [SysErrorMessage(GetLastError)]);
{$ENDIF}
end;
{$ELSE}
{$ENDIF}
end;
{ TEvents }
function TEvents.Buf: Pointer;
begin
Result := @FBuf;
end;
function TEvents.BufSize: LongWord;
begin
Result := FBufSize
end;
procedure TEvents.DeInitialize;
begin
if not IsInitialized then
Exit;
Dequeue(THandle(SyncEvent.Handle));
FreeAndNil(SyncEvent);
end;
procedure TEvents.Dequeue(Hnd: THandle);
var
Index, I: Integer;
begin
Index := -1;
for I := 0 to FBufSize-1 do
if FBuf[I] = Hnd then begin
Index := I;
Break;
end;
if Index <> -1 then begin
DequeueByIndex(Index);
end;
end;
procedure TEvents.DequeueByIndex(Index: Integer);
begin
if Index >= FBufSize then
Exit;
if Index = FBufSize-1 then
Dec(FBufSize)
else begin
Move(FBuf[Index+1], FBuf[Index], (FBufSize-Index-1)*SizeOf(THandle));
Move(FCb[Index+1], FCb[Index], (FBufSize-Index-1)*SizeOf(TEventCallback));
Move(FData[Index+1], FData[Index], (FBufSize-Index-1)*SizeOf(Pointer));
Dec(FBufSize);
end;
{$IFDEF DEBUG}
AtomicDecrement(IOEventTupleCounter);
{$ENDIF}
end;
procedure TEvents.Enqueue(Hnd: THandle; const Cb: TEventCallback;
Data: Pointer; Hub: THub);
begin
if not Assigned(Cb) then
Exit;
FBuf[FBufSize] := Hnd;
FCb[FBufSize] := Cb;
FData[FBufSize] := Data;
FHub[FBufSize] := Data;
Inc(FBufSize);
{$IFDEF DEBUG}
AtomicIncrement(IOEventTupleCounter);
{$ENDIF}
end;
function TEvents.Find(Hnd: THandle; out Index: Integer): Boolean;
var
I: Integer;
begin
Result := False;
Index := -1;
for I := 0 to BufSize-1 do
if FBuf[I] = Hnd then begin
Index := I;
Exit(True)
end;
end;
procedure TEvents.Initialize;
begin
if IsInitialized then
Exit;
SyncEvent := TEvent.Create(nil, False, False, '');
FBufSize := 1;
FBuf[0] := THandle(SyncEvent.Handle);
{$IFDEF DEBUG}
AtomicIncrement(IOEventTupleCounter);
{$ENDIF}
end;
function TEvents.IsInitialized: Boolean;
begin
Result := Assigned(SyncEvent)
end;
function TEvents.TupleByIndex(Index: Integer): TEventTuple;
begin
Result.Event := FBuf[Index];
Result.Cb := FCb[Index];
Result.Data := FData[Index];
Result.Hub := FHub[Index]
end;
{ TEvents.TTuple }
procedure TEventTuple.Trigger(const Aborted: Boolean);
var
OldHub: THub;
begin
OldHub := CurrentHub;
try
CurrentHub := Self.Hub;
Self.Cb(Event, Data, Aborted)
finally
CurrentHub := OldHub;
end;
end;
{ TFilesTuple }
procedure TFileTuple.Trigger(ErrorCode, Len: Integer; const Op: TIOOperation);
var
OldHub: THub;
begin
OldHub := CurrentHub;
try
CurrentHub := Hub;
case Op of
ioRead:
ReadCb(Fd, Op, ReadData, ErrorCode, Len);
ioWrite:
WriteCb(Fd, Op, WriteData, ErrorCode, Len);
end;
finally
CurrentHub := OldHub;
end;
end;
procedure TFileTuple.RecalcCleanTime;
begin
CleanTime := Now + EncodeTime(0, TFiles.TRASH_CLEAR_TIMEOUT_MINS, 0, 0)
end;
{ TFiles }
procedure TFiles.Deinitialize;
var
Fd: THandle;
{$IFNDEF DCC}I: Integer;{$ENDIF}
begin
if not IsInitialized then
Exit;
{$IFDEF MSWINDOWS}
{$IFDEF DCC}
for Fd in FMap.Keys do begin
CancelIo(Fd);
Dequeue(Fd);
end;
{$ELSE}
for I := 0 to FMap.Count-1 do begin
Fd := FMap.Keys[I];
CancelIo(Fd);
Dequeue(Fd);
end;
{$ENDIF}
{$ELSE}
{$ENDIF}
FMap.Free;
TrashClean(False);
FTrash.Free;
end;
procedure TFiles.Dequeue(const Fd: THandle);
var
TuplePtr: PFileTuple;
begin
if Find(Fd) then begin
TuplePtr := FMap[Fd];
TuplePtr.Active := False;
TuplePtr.RecalcCleanTime;
FMap.Remove(Fd);
FTrash.Add(TuplePtr);
{$IFDEF DEBUG}
AtomicDecrement(IOFdTupleCounter);
{$ENDIF}
end;
if Now > FTrashLAstClean then
TrashClean;
end;
function TFiles.Enqueue(Fd: THandle; const Op: TIOOperation;
const Cb: TIOCallback; Data: Pointer; Hub: THub): PFileTuple;
begin
if Find(Fd) then begin
Result := FMap[Fd]
end
else begin
New(Result);
FMap.Add(Fd, Result);
FillChar(Result^, SizeOf(TFileTuple), 0);
{$IFDEF DEBUG}
AtomicIncrement(IOFdTupleCounter);
{$ENDIF}
end;
Result.Fd := Fd;
case Op of
ioRead: begin
Result.ReadCb := Cb;
Result.ReadData := Data;
end;
ioWrite: begin
Result.WriteCb := Cb;
Result.WriteData := Data;
end;
end;
Result.Hub := Hub;
Result.Active := True;
{$IFDEF MSWINDOWS}
Result.Overlap.hEvent := NativeUInt(Result);
{$ENDIF}
if Now > FTrashLAstClean then
TrashClean;
end;
function TFiles.Find(Id: THandle; out Tup: PFileTuple): Boolean;
begin
Result := Find(Id);
if Result then
Tup := FMap[Id]
end;
function TFiles.Find(Fd: THandle): Boolean;
begin
{$IFDEF DCC}
Result := FMap.ContainsKey(Fd);
{$ELSE}
Result := FMap.IndexOf(Fd) >= 0;
{$ENDIF}
end;
procedure TFiles.Initialize;
begin
if IsInitialized then
Exit;
FMap := TMap.Create;
FTrash := FList.Create;
end;
procedure TFiles.TrashClean(const OnlyByTimeout: Boolean);
var
I: Integer;
begin
if OnlyByTimeout then begin
I := 0;
while I < FTrash.Count do begin
if FTrash[I].CleanTime < Now then begin
Dispose(FTrash[I]);
FTrash.Delete(I);
end
else
Inc(I)
end;
end
else begin
for I := 0 to FTrash.Count-1 do begin
Dispose(FTrash[I]);
end;
FTrash.Clear;
end;
FTrashLAstClean := Now;
end;
function TFiles.IsInitialized: Boolean;
begin
Result := Assigned(FMap);
end;
{ TTimeouts }
procedure TTimeouts.Deinitialize;
var
Id: NativeUInt;
{$IFNDEF DCC}
I: Integer;
Fd: THandle;
{$ENDIF}
begin
if not IsInitialized then
Exit;
{$IFDEF MSWINDOWS}
{$IFDEF DCC}
for Id in FMap.Keys do begin
CancelWaitableTimer(Id);
Dequeue(Id);
end;
{$ELSE}
for I := 0 to FMap.Count-1 do begin
Fd := FMap.Keys[I];
CancelIo(Fd);
Dequeue(Fd);
end;
{$ENDIF}
{$ELSE}
{$ENDIF}
FMap.Free;
end;
procedure TTimeouts.Dequeue(Id: THandle);
var
TuplePtr: PTimeoutTuple;
begin
if Find(Id) then begin
TuplePtr := FMap[Id];
FMap.Remove(Id);
Dispose(TuplePtr);
{$IFDEF DEBUG}
AtomicDecrement(IOTimeTupleCounter);
{$ENDIF}
end;
end;
function TTimeouts.Enqueue(Id: THandle; const Cb: TInervalCallback;
Data: Pointer; Hub: THub): PTimeoutTuple;
begin
if Find(Id) then
Result := FMap[Id]
else begin
New(Result);
FMap.Add(Id, Result);
{$IFDEF DEBUG}
AtomicIncrement(IOTimeTupleCounter);
{$ENDIF}
end;
Result.Cb := Cb;
Result.Data := Data;
Result.Id := Id;
Result.Hub := Hub;
end;
function TTimeouts.Find(Id: THandle): Boolean;
begin
{$IFDEF DCC}
Result := FMap.ContainsKey(Id);
{$ELSE}
Result := FMap.IndexOf(Id) >= 0;
{$ENDIF}
end;
procedure TTimeouts.Initialize;
begin
if IsInitialized then
Exit;
FMap := TMap.Create;
end;
function TTimeouts.IsInitialized: Boolean;
begin
Result := Assigned(FMap);
end;
{ TTimeoutTuple }
procedure TTimeoutTuple.Trigger;
var
OldHub: THub;
begin
OldHub := CurrentHub;
try
CurrentHub := Hub;
Cb(Id, Data)
finally
CurrentHub := OldHub
end;
end;
{ THub.TTask }
procedure THub.TTask.Init(const Method: TThreadMethod);
begin
FillChar(Self, SizeOf(Self), 0);
Self.Method := Method;
Self.Kind := tkMEthod;
end;
procedure THub.TTask.Init(Intf: IInterface; const Method: TThreadMethod);
begin
FillChar(Self, SizeOf(Self), 0);
Self.Method := Method;
Self.Intf := Intf;
Self.Kind := tkIntfMethod;
end;
procedure THub.TTask.Init(const Proc: TTaskProc; Arg: Pointer);
begin
FillChar(Self, SizeOf(Self), 0);
Self.Proc := Proc;
Self.Arg := Arg;
Self.Kind := tkProc;
end;
{$IFDEF FPC}
class operator THub.TTask.=(const a, b: TTask): Boolean;
begin
if a.Kind <> b.Kind then
Exit(False);
case a.Kind of
tkMethod, tkIntfMethod: begin
Result := @a.Method = @b.Method;
end;
tkProc: begin
Result := @a.Proc = @b.Proc
end;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function GetMessagePatched(var lpMsg: TMsg; hWnd: HWND;
wMsgFilterMin, wMsgFilterMax: UINT): BOOL; stdcall;
begin
case DefHub.Wait(INFINITE) of
meError:;
meEvent:
;
meSync:
DefHub.ServeTaskQueue;
meIO:;
meWinMsg:;
meTimer:;
meWaitTimeout:;
end;
Result := False;
end;
procedure FinalizeDefHubList;
var
{$IFDEF DCC}
TID: LongWord;
{$ELSE}
I: Integer;
H: TSingleThreadHub;
{$ENDIF}
begin
DefHubsLock.Acquire;
try
{$IFDEF DCC}
for TID in DefHubs.Keys do begin
DefHubs[TID].FIsDef := False;
DefHubs[TID].Free;
end;
{$ELSE}
for I := 0 to DefHubs.Count-1 do begin
H := DefHubs.Data[I];
H.FIsDef := False;
H.Free;
end;
{$ENDIF}
finally
DefHubsLock.Release;
end;
FreeAndNil(DefHubsLock);
FreeAndNil(DefHubs);
end;
{$ENDIF}
initialization
DefHubsLock := SyncObjs.TCriticalSection.Create;
DefHubs := THubMap.Create;
InitSocketInterface('');
sock.WSAStartup(WinsockLevel, WsaDataOnce);
InitializeStubsEx;
HubInfrasctuctureEnable := True;
finalization
HubInfrasctuctureEnable := False;
sock.WSACleanup;
DestroySocketInterface;
FinalizeDefHubList;
end.
|
unit PE_Def;
interface
(*************************************************************************
DESCRIPTION : Win32 PE file definitions
REQUIREMENTS : TP5-7, D1-D7/9-10, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : o Johannes Plachy: The Portable Executable File Format, available at
http://www.csn.ul.ie/~caolan/publink/winresdump/winresdump/doc/pefile.html
o Matt Pietrek: An In-Depth Look into the Win32 Portable Executable File Format
http://msdn.microsoft.com/msdnmag/issues/02/02/PE/
o delphi-faq\16495.html
o WINNT.H
REMARK : Modifications needed for WIN64
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 08.05.06 W.Ehrhardt Initial version based on delphi-faq\16495.html
0.11 09.05.06 we Some additions, standard formating/names
**************************************************************************)
{$ifdef win32}
uses
windows;
{$else}
type
pdword = ^dword;
dword = longint;
{$endif}
const
IMAGE_UNKNOWN_SIGNATURE = $0;
IMAGE_DOS_SIGNATURE = $5A4D; {MZ}
IMAGE_OS2_SIGNATURE = $454E; {NE}
IMAGE_OS2_SIGNATURE_LE = $454C; {LE}
IMAGE_VXD_SIGNATURE = $454C; {LE}
IMAGE_NT_SIGNATURE = $4550; {PE}
IMAGE_NT_SIGNATURE_L = $00004550; {PE00}
const
NE_IMAGE_DLL = $8000; {File is a DLL}
const
IMAGE_NT_OPTIONAL_HDR_MAGIC = $10B;
IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10B;
IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20B;
IMAGE_ROM_OPTIONAL_HDR_MAGIC = $107;
const
IMAGE_FILE_RELOCS_STRIPPED = $0001; {Relocation info stripd}
IMAGE_FILE_EXECUTABLE_IMAGE = $0002; {File is executable}
IMAGE_FILE_LINE_NUMS_STRIPPED = $0004; {Line numbers stripped}
IMAGE_FILE_LOCAL_SYMS_STRIPPED = $0008; {Local symbols stripped}
IMAGE_FILE_BYTES_REVERSED_LO = $0080; {machine word bytes rev}
IMAGE_FILE_32BIT_MACHINE = $0100; {32 bit word machine}
IMAGE_FILE_DEBUG_STRIPPED = $0200; {Debug info stripped}
IMAGE_FILE_SYSTEM = $1000; {System File}
IMAGE_FILE_DLL = $2000; {File is a DLL}
IMAGE_FILE_BYTES_REVERSED_HI = $8000; {machine word bytes rev}
const
IMAGE_FILE_MACHINE_UNKNOWN = $0;
IMAGE_FILE_MACHINE_I386 = $14c; {Intel 386}
IMAGE_FILE_MACHINE_R3000B = $160; {MIPS big-endian}
IMAGE_FILE_MACHINE_R3000L = $162; {MIPS little-endian}
IMAGE_FILE_MACHINE_R4000 = $166; {MIPS little-endian}
IMAGE_FILE_MACHINE_R10000 = $168; {MIPS little-endian}
IMAGE_FILE_MACHINE_ALPHA = $184; {Alpha_AXP}
IMAGE_FILE_MACHINE_POWERPC = $1F0; {IBM PowerPC Little-Endian}
const
IMAGE_SIZEOF_SHORT_NAME = 8;
IMAGE_SIZEOF_SECTION_HEADER = 40;
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
IMAGE_RESOURCE_NAME_IS_STRING = $80000000;
IMAGE_RESOURCE_DATA_IS_DIRECTORY = $80000000;
IMAGE_OFFSET_STRIP_HIGH = $7FFFFFFF;
type
PIMAGE_DOS_HEADER = ^TIMAGE_DOS_HEADER;
TIMAGE_DOS_HEADER = packed record {DOS .EXE header}
e_magic : word; {Magic number}
e_cblp : word; {Bytes on last page of file}
e_cp : word; {Pages in file}
e_crlc : word; {Relocations}
e_cparhdr : word; {Size of header in paragraphs}
e_minalloc : word; {Minimum extra paragraphs needed}
e_maxalloc : word; {Maximum extra paragraphs needed}
e_ss : word; {Initial (relative) SS value}
e_sp : word; {Initial SP value}
e_csum : word; {Checksum}
e_ip : word; {Initial IP value}
e_cs : word; {Initial (relative) CS value}
e_lfarlc : word; {File address of relocation table}
e_ovno : word; {Overlay number}
e_res : packed array[0..3] of word; {Reserved words}
e_oemid : word; {OEM identifier (for e_oeminfo)}
e_oeminfo : word; {OEM information; e_oemid specific}
e_res2 : packed array[0..9] of word; {Reserved words}
e_lfanew : longint; {File address of new exe header}
end;
type
PIMAGE_OS2_HEADER = ^TIMAGE_OS2_HEADER;
TIMAGE_OS2_HEADER = packed record
ne_magic : word; {Magic number}
ne_ver : char; {Version number}
ne_rev : char; {Revision number}
ne_enttab : word; {Offset of Entry Table}
ne_cbenttab : word; {Number of bytes in Entry Table}
ne_crc : longint; {Checksum of whole file}
ne_flags : word; {Flag word}
ne_autodata : word; {Automatic data segment number}
ne_heap : word; {Initial heap allocation}
ne_stack : word; {Initial stack allocation}
ne_csip : longint; {Initial CS:IP setting}
ne_sssp : longint; {Initial SS:SP setting}
ne_cseg : word; {Count of file segments}
ne_cmod : word; {Entries in Module Reference Table}
ne_cbnrestab : word; {Size of non-resident name table}
ne_segtab : word; {Offset of Segment Table}
ne_rsrctab : word; {Offset of Resource Table}
ne_restab : word; {Offset of resident name table}
ne_modtab : word; {Offset of Module Reference Table}
ne_imptab : word; {Offset of Imported Names Table}
ne_nrestab : word; {Offset of Non-resident Names Table}
ne_cmovent : word; {Count of movable entries}
ne_align : word; {Segment alignment shift count}
ne_cres : word; {Count of resource segments}
ne_exetyp : word; {Target Operating system}
ne_flagsothers : word; {Other .EXE flags}
ne_pretthunks : word; {offset to return thunks}
ne_psegrefbytes: word; {offset to segment ref. bytes}
ne_swaparea : word; {Minimum code swap area size}
ne_expver : word; {Expected Windows version number}
end;
type
PIMAGE_VXD_HEADER = ^TIMAGE_VXD_HEADER;
TIMAGE_VXD_HEADER = packed record
e32_magic : word; {Magic number}
e32_border : byte; {The byte ordering for the VXD}
e32_worder : byte; {The word ordering for the VXD}
e32_level : dword; {The EXE format level for now = 0}
e32_cpu : word; {The CPU type}
e32_os : word; {The OS type}
e32_ver : dword; {Module version}
e32_mflags : dword; {Module flags}
e32_mpages : dword; {Module # pages}
e32_startobj : dword; {Object # for instruction pointer}
e32_eip : dword; {Extended instruction pointer}
e32_stackobj : dword; {Object # for stack pointer}
e32_esp : dword; {Extended stack pointer}
e32_pagesize : dword; {VXD page size}
e32_lastpagesize: dword; {Last page size in VXD}
e32_fixupsize : dword; {Fixup section size}
e32_fixupsum : dword; {Fixup section checksum}
e32_ldrsize : dword; {Loader section size}
e32_ldrsum : dword; {Loader section checksum}
e32_objtab : dword; {Object table offset}
e32_objcnt : dword; {Number of objects in module}
e32_objmap : dword; {Object page map offset}
e32_itermap : dword; {Object iterated data map offset}
e32_rsrctab : dword; {Offset of Resource Table}
e32_rsrccnt : dword; {Number of resource entries}
e32_restab : dword; {Offset of resident name table}
e32_enttab : dword; {Offset of Entry Table}
e32_dirtab : dword; {Offset of Module Directive Table}
e32_dircnt : dword; {Number of module directives}
e32_fpagetab : dword; {Offset of Fixup Page Table}
e32_frectab : dword; {Offset of Fixup Record Table}
e32_impmod : dword; {Offset of Import Module Name Table}
e32_impmodcnt : dword; {NumEntries in Import Module Name Table}
e32_impproc : dword; {Offset of Import Procedure Name Table}
e32_pagesum : dword; {Offset of Per-Page Checksum Table}
e32_datapage : dword; {Offset of Enumerated Data Pages}
e32_preload : dword; {Number of preload pages}
e32_nrestab : dword; {Offset of Non-resident Names Table}
e32_cbnrestab : dword; {Size of Non-resident Name Table}
e32_nressum : dword; {Non-resident Name Table Checksum}
e32_autodata : dword; {Object # for automatic data object}
e32_debuginfo : dword; {Offset of the debugging information}
e32_debuglen : dword; {length of the debugging info. in bytes}
e32_instpreload : dword; {# of instance pages in preload section}
e32_instdemand : dword; {# of inst pages in demand load section}
e32_heapsize : dword; {Size of heap - for 16-bit apps}
e32_res3 : packed array[0..11] of byte; {Reserved words}
e32_winresoff : dword;
e32_winreslen : dword;
e32_devid : word; {Device ID for VxD}
e32_ddkver : word; {DDK version for VxD}
end;
type
PIMAGE_DATA_DIRECTORY = ^TIMAGE_DATA_DIRECTORY;
TIMAGE_DATA_DIRECTORY = packed record
VirtualAddress : dword;
Size : dword;
end;
type
PIMAGE_FILE_HEADER = ^TIMAGE_FILE_HEADER;
TIMAGE_FILE_HEADER = packed record
Machine : word;
NumberOfSections : word;
TimeDateStamp : dword;
PointerToSymbolTable : dword;
NumberOfSymbols : dword;
SizeOfOptionalHeader : word;
Characteristics : word;
end;
type
PIMAGE_OPTIONAL_HEADER = ^TIMAGE_OPTIONAL_HEADER;
TIMAGE_OPTIONAL_HEADER = packed record
{Standard fields}
Magic : word;
MajorLinkerVersion : byte;
MinorLinkerVersion : byte;
SizeOfCode : dword;
SizeOfInitializedData : dword;
SizeOfUninitializedData : dword;
AddressOfEntryPoint : dword;
BaseOfCode : dword;
BaseOfData : dword;
{NT additional fields}
ImageBase : dword;
SectionAlignment : dword;
FileAlignment : dword;
MajorOperatingSystemVersion: word;
MinorOperatingSystemVersion: word;
MajorImageVersion : word;
MinorImageVersion : word;
MajorSubsystemVersion : word;
MinorSubsystemVersion : word;
Reserved1 : dword;
SizeOfImage : dword;
SizeOfHeaders : dword;
CheckSum : dword;
Subsystem : word;
DllCharacteristics : word;
SizeOfStackReserve : dword;
SizeOfStackCommit : dword;
SizeOfHeapReserve : dword;
SizeOfHeapCommit : dword;
LoaderFlags : dword;
NumberOfRvaAndSizes : dword;
DataDirectory : packed array[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of TIMAGE_DATA_DIRECTORY;
end;
type
PIMAGE_ROM_OPTIONAL_HEADER = ^TIMAGE_ROM_OPTIONAL_HEADER;
TIMAGE_ROM_OPTIONAL_HEADER = packed record
Magic : word;
MajorLinkerVersion : byte;
MinorLinkerVersion : byte;
SizeOfCode : dword;
SizeOfInitializedData : dword;
SizeOfUninitializedData: dword;
AddressOfEntryPoint : dword;
BaseOfCode : dword;
BaseOfData : dword;
BaseOfBss : dword;
GprMask : dword;
CprMask : packed array[0..3] of dword;
GpValue : dword;
end;
type
PIMAGE_SECTION_HEADER = ^TIMAGE_SECTION_HEADER;
TIMAGE_SECTION_HEADER = packed record
Name : packed array[0..IMAGE_SIZEOF_SHORT_NAME-1] of char;
PhysicalAddress : dword;
VirtualAddress : dword;
SizeOfRawData : dword;
PointerToRawData : dword;
PointerToRelocations: dword;
PointerToLinenumbers: dword;
NumberOfRelocations : word;
NumberOfLinenumbers : word;
Characteristics : dword;
end;
type
PSECTION_HDR_ARRAY = ^TSECTION_HDR_ARRAY;
TSECTION_HDR_ARRAY = packed array[1..$FF00 div sizeof(TIMAGE_SECTION_HEADER)] of TIMAGE_SECTION_HEADER;
type
PIMAGE_NT_HEADERS = ^TIMAGE_NT_HEADERS;
TIMAGE_NT_HEADERS = packed record
Signature : dword;
FileHeader : TIMAGE_FILE_HEADER;
OptionalHeader : TIMAGE_OPTIONAL_HEADER;
end;
type
PIMAGE_EXPORT_DIRECTORY = ^TIMAGE_EXPORT_DIRECTORY;
TIMAGE_EXPORT_DIRECTORY = record
Characteristics : dword;
TimeDateStamp : dword;
MajorVersion : word;
MinorVersion : word;
Name : dword;
Base : dword;
NumberOfFunctions : dword;
NumberOfNames : dword;
AddressOfFunctions : pdword;
AddressOfNames : pdword;
AddressOfNameOrdinals : pdword;
end;
implementation
end.
|
unit caTreeView;
{$INCLUDE ca.inc}
interface
uses
// standard Delphi units...
SysUtils,
Classes,
Windows,
Messages,
Graphics,
Controls,
ComCtrls,
CommCtrl,
ExtCtrls,
// ca units...
caClasses,
caUtils,
caLog,
caNodes;
type
//---------------------------------------------------------------------------
// TcaTreeNode
//---------------------------------------------------------------------------
TcaTreeNode = class(TTreeNode)
private
// private members...
FBold: Boolean;
FPartChecked: Boolean;
FFont: TFont;
FEnabled: Boolean;
// property methods...
function GetChecked: Boolean;
procedure SetBold(const Value: Boolean);
procedure SetChecked(const Value: Boolean);
procedure SetPartChecked(const Value: Boolean);
procedure SetFont(const Value: TFont);
procedure SetEnabled(const Value: Boolean);
public
// lifetime...
constructor Create(AOwner: TTreeNodes);
destructor Destroy; override;
// public properties...
property Bold: Boolean read FBold write SetBold;
property Checked: Boolean read GetChecked write SetChecked;
property Enabled: Boolean read FEnabled write SetEnabled;
property Font: TFont read FFont write SetFont;
property PartChecked: Boolean read FPartChecked write SetPartChecked;
end;
//---------------------------------------------------------------------------
// TcaTreeView
//---------------------------------------------------------------------------
TcaTreeViewNodeAddedEvent = procedure(Sender: TObject; ATreeNode: TcaTreeNode; ANode: TcaNode) of object;
TcaTreeViewCheckBoxClickEvent = procedure(Sender: TObject; ATreeNode: TcaTreeNode) of object;
TcaTreeViewNodeHoverEvent = TcaTreeViewCheckBoxClickEvent;
TcaTreeView = class(TTreeView)
private
// private members...
FNodes: IcaNodes;
FHoverTimer: TTimer;
FMousePos: TPoint;
FPrevMousePos: TPoint;
// property fields...
FUseCheckBoxes: Boolean;
FUseLinkedChecking: Boolean;
FUserChange: Boolean;
FUpdatingNodes: Boolean;
// event property fields...
FOnNodeAdded: TcaTreeViewNodeAddedEvent;
FOnCheckBoxClicked: TcaTreeViewCheckBoxClickEvent;
FUseNodeHoverEvents: Boolean;
FOnNodeHover: TcaTreeViewNodeHoverEvent;
// private methods...
procedure AddTreeNode(ANode: TcaNode; ATreeNode: TcaTreeNode);
procedure UpdateChildrenCheckState(ATreeNode: TcaTreeNode);
procedure UpdateParentsCheckState(ATreeNode: TcaTreeNode);
procedure UpdateNodes;
// property methods...
function GetItem(Index: Integer): TcaTreeNode;
procedure SetUseCheckBoxes(const Value: Boolean);
procedure SetUseLinkedChecking(const Value: Boolean);
procedure SetUseNodeHoverEvents(const Value: Boolean);
// windows message handlers...
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
// event handler - THIS IS A HACK because there seems to be no way to
// use the internal virtual methods...
procedure CustomDrawItemEvent(Sender: TCustomTreeView; Node: TTreeNode;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure AdvancedCustomDrawItemEvent(Sender: TCustomTreeView; Node: TTreeNode;
State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean);
// hover timer event
procedure HoverTimerEvent(Sender: TObject);
protected
// protected virtual methods...
function CreateNode: TTreeNode; override;
function IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; override;
procedure Added(Node: TTreeNode); {$IFDEF D7_UP}override{$ELSE}virtual{$ENDIF};
procedure CreateParams(var Params: TCreateParams); override;
procedure DoAddNode(ANode: TcaNode; var AAccept: Boolean); virtual;
procedure DoNodeAdded(ATreeNode: TcaTreeNode; ANode: TcaNode); virtual;
procedure DoCheckBoxClicked; virtual;
procedure DoNodeHover(ATreeNode: TcaTreeNode); virtual;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
// protected static methods...
function GetNodeCheckedState(ATreeNode: TcaTreeNode): Boolean;
procedure RepaintNode(ATreeNode: TcaTreeNode);
procedure SetNodeBoldState(ATreeNode: TcaTreeNode; IsBold: Boolean);
procedure SetNodeCheckedState(ATreeNode: TcaTreeNode; IsChecked: Boolean);
procedure UpdateNodeCheckLinkStates(ATreeNode: TcaTreeNode);
// protected properties...
property UpdatingNodes: Boolean read FUpdatingNodes write FUpdatingNodes;
property UserChange: Boolean read FUserChange;
public
// lifetime...
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// public methods...
procedure SetNodes(const Value: IcaNodes);
// public properties...
property Item[Index: Integer]: TcaTreeNode read GetItem;
property Items;
published
// published properties...
property UseCheckBoxes: Boolean read FUseCheckBoxes write SetUseCheckBoxes;
property UseLinkedChecking: Boolean read FUseLinkedChecking write SetUseLinkedChecking;
property UseNodeHoverEvents: Boolean read FUseNodeHoverEvents write SetUseNodeHoverEvents;
// event properties...
property OnNodeAdded: TcaTreeViewNodeAddedEvent read FOnNodeAdded write FOnNodeAdded;
property OnCheckBoxClicked: TcaTreeViewCheckBoxClickEvent read FOnCheckBoxClicked write FOnCheckBoxClicked;
property OnNodeHover: TcaTreeViewNodeHoverEvent read FOnNodeHover write FOnNodeHover;
end;
implementation
//---------------------------------------------------------------------------
// TcaTreeNode;
//---------------------------------------------------------------------------
// lifetime...
constructor TcaTreeNode.Create(AOwner: TTreeNodes);
begin
inherited Create(AOwner);
FFont := TFont.Create;
end;
destructor TcaTreeNode.Destroy;
begin
FFont.Free;
inherited;
end;
// property methods...
function TcaTreeNode.GetChecked: Boolean;
begin
Result := TcaTreeView(TreeView).GetNodeCheckedState(Self);
end;
procedure TcaTreeNode.SetBold(const Value: Boolean);
begin
if Value <> FBold then
begin
FBold := Value;
TcaTreeView(TreeView).SetNodeBoldState(Self, FBold);
end;
end;
procedure TcaTreeNode.SetChecked(const Value: Boolean);
begin
if Value <> GetChecked then
begin
TcaTreeView(TreeView).SetNodeCheckedState(Self, Value);
if not TcaTreeView(TreeView).UpdatingNodes then
begin
TcaTreeView(TreeView).UpdatingNodes := True;
try
if not TcaTreeView(TreeView).UserChange then
TcaTreeView(TreeView).UpdateNodeCheckLinkStates(Self);
finally
TcaTreeView(TreeView).UpdatingNodes := False;
end;
end;
if Assigned(Data) then
TcaNode(Data).Checked := Value;
end;
end;
procedure TcaTreeNode.SetEnabled(const Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
TcaTreeView(TreeView).RepaintNode(Self);
end;
end;
procedure TcaTreeNode.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
procedure TcaTreeNode.SetPartChecked(const Value: Boolean);
begin
if Value <> FPartChecked then
begin
FPartChecked := Value;
TcaTreeView(TreeView).RepaintNode(Self);
end;
end;
//---------------------------------------------------------------------------
// TcaTreeView
//---------------------------------------------------------------------------
// lifetime...
constructor TcaTreeView.Create(AOwner: TComponent);
begin
inherited;
// HACK - there seems to be no way to use the internal virtual methods...
Self.OnCustomDrawItem := CustomDrawItemEvent;
Self.OnAdvancedCustomDrawItem := AdvancedCustomDrawItemEvent;
FHoverTimer := TTimer.Create(nil);
FHoverTimer.Interval := 200;
FHoverTimer.Enabled := False;
end;
destructor TcaTreeView.Destroy;
begin
FHoverTimer.Free;
inherited;
end;
// public methods...
procedure TcaTreeView.SetNodes(const Value: IcaNodes);
begin
FNodes := Value;
UpdateNodes;
end;
// protected virtual methods...
function TcaTreeView.CreateNode: TTreeNode;
begin
Result := TcaTreeNode.Create(Items);
TcaTreeNode(Result).Enabled := True;
end;
function TcaTreeView.IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean;
begin
Result := inherited IsCustomDrawn(Target, Stage);
end;
procedure TcaTreeView.Added(Node: TTreeNode);
var
ANode: TcaNode;
ParentNode: TcaNode;
ParentTreeNode: TTreeNode;
begin
inherited;
if Assigned(FNodes) then
begin
ANode := nil;
if not FUpdatingNodes then
begin
ParentTreeNode := Node.Parent;
if Assigned(ParentTreeNode) then
begin
ParentNode := TcaNode(ParentTreeNode.Data);
if Assigned(ParentNode) then
ANode := FNodes.AddSub(ParentNode, Node.Text);
end
else
ANode := FNodes.AddRoot(Node.Text);
if Assigned(ANode) then
Node.Data := ANode;
end;
end;
end;
procedure TcaTreeView.CreateParams(var Params: TCreateParams);
begin
inherited;
if FUseCheckBoxes then
Params.Style := Params.Style or TVS_CHECKBOXES;
end;
procedure TcaTreeView.DoAddNode(ANode: TcaNode; var AAccept: Boolean);
begin
AAccept := True;
end;
procedure TcaTreeView.DoNodeAdded(ATreeNode: TcaTreeNode; ANode: TcaNode);
begin
if Assigned(FOnNodeAdded) then FOnNodeAdded(Self, ATreeNode, ANode);
end;
procedure TcaTreeView.DoCheckBoxClicked;
begin
if Assigned(FOnCheckBoxClicked) then
FOnCheckBoxClicked(Self, TcaTreeNode(Selected));
end;
procedure TcaTreeView.DoNodeHover(ATreeNode: TcaTreeNode);
begin
if Assigned(FOnNodeHover) then
FOnNodeHover(Self, ATreeNode);
end;
procedure TcaTreeView.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
FMousePos.X := X;
FMousePos.Y := Y;
end;
// windows message handlers...
procedure TcaTreeView.WMKeyDown(var Message: TWMKeyDown);
var
WasChecked: Boolean;
begin
WasChecked := TcaTreeNode(Selected).Checked;
inherited;
if Message.CharCode = $20 then
begin
if TcaTreeNode(Selected).Enabled then
begin
if FUseLinkedChecking then
begin
FUserChange := True;
UpdateNodeCheckLinkStates(TcaTreeNode(Selected));
FUserChange := False;
end;
DoCheckBoxClicked;
end
else
TcaTreeNode(Selected).Checked := WasChecked;
Message.Result := 0;
end;
end;
procedure TcaTreeView.WMLButtonDown(var Message: TWMLButtonDown);
var
Node: TcaTreeNode;
WasChecked: Boolean;
begin
Node := TcaTreeNode(GetNodeAt(Message.XPos, Message.YPos));
if Assigned(Node) then
begin
WasChecked := Node.Checked;
inherited;
if htOnStateIcon in GetHitTestInfoAt(Message.XPos, Message.YPos) then
begin
if TcaTreeNode(Selected).Enabled then
begin
Node.Focused := True;
Node.Selected := True;
if Node.Checked then
Node.PartChecked := False;
if FUseLinkedChecking then
begin
FUserChange := True;
UpdateNodeCheckLinkStates(TcaTreeNode(Selected));
FUserChange := False;
end;
DoCheckBoxClicked;
end
else
Node.Checked := WasChecked;
end;
end;
end;
// event handlers - THIS IS A HACK because there seems to be no way to
// use the internal virtual methods...
procedure TcaTreeView.CustomDrawItemEvent(Sender: TCustomTreeView; Node: TTreeNode;
State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if UseCheckBoxes then
begin
Canvas.Font.Assign(TcaTreeNode(Node).Font);
if cdsSelected in State then
begin
if TcaTreeNode(Node).Enabled then
begin
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
end
else
begin
Canvas.Brush.Color := clBtnShadow;
Canvas.Font.Color := clBtnFace;
end;
end
else
begin
if not TcaTreeNode(Node).Enabled then
begin
Canvas.Brush.Color := clWindow;
Canvas.Font.Color := clBtnShadow;
end;
end;
end
else
DefaultDraw := True;
end;
procedure TcaTreeView.AdvancedCustomDrawItemEvent(Sender: TCustomTreeView; Node: TTreeNode;
State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean);
var
R: TRect;
procedure DrawUncheckedBox;
begin
R := Node.DisplayRect(False);
R.Left := R.Left + (Node.Level * Indent) + 26;
R.Right := R.Left + 9;
R.Top := R.Top + 4;
R.Bottom := R.Top + 9;
if TcaTreeNode(Node).PartChecked then
begin
if TcaTreeNode(Node).Enabled then
Canvas.Brush.Color := clGray
else
Canvas.Brush.Color := clSilver;
end
else
Canvas.Brush.Color := clWhite;
Canvas.FillRect(R);
DefaultDraw := True;
end;
begin
if UseCheckBoxes then
begin
if (Stage = cdPostPaint) then
begin
if not TcaTreeNode(Node).Checked then
DrawUncheckedBox;
end;
end
else
DefaultDraw := True;
end;
// hover timer event
procedure TcaTreeView.HoverTimerEvent(Sender: TObject);
var
TreeNode: TcaTreeNode;
begin
if (FMousePos.X = FPrevMousePos.X) and (FMousePos.Y = FPrevMousePos.Y) then
begin
TreeNode := TcaTreeNode(GetNodeAt(FMousePos.X, FMousePos.Y));
if Assigned(TreeNode) then
DoNodeHover(TreeNode);
end;
FPrevMousePos := FMousePos;
end;
// protected static methods...
function TcaTreeView.GetNodeCheckedState(ATreeNode: TcaTreeNode): Boolean;
var
tvi: TTVItem;
begin
Result := False;
if Assigned(ATreeNode) then
begin
FillChar(tvi, SizeOf(tvi), 0);
tvi.hItem := ATreeNode.ItemID;
tvi.mask := TVIF_HANDLE or TVIF_STATE;
tvi.stateMask := TVIS_STATEIMAGEMASK;
TreeView_GetItem(ATreeNode.Handle, tvi);
Result := Pred(tvi.state shr 12) > 0;
end;
end;
procedure TcaTreeView.RepaintNode(ATreeNode: TcaTreeNode);
var
R: TRect;
begin
while (ATreeNode <> nil) and not ATreeNode.IsVisible do
ATreeNode := TcaTreeNode(ATreeNode.Parent);
if ATreeNode <> nil then
begin
R := ATreeNode.DisplayRect(False);
InvalidateRect(Handle, @R, True);
end;
end;
procedure TcaTreeView.SetNodeBoldState(ATreeNode: TcaTreeNode; IsBold: Boolean);
var
tvi: TTVItem;
begin
if Assigned(ATreeNode) then
begin
FillChar(tvi, SizeOf(tvi), 0);
tvi.hItem := ATreeNode.ItemID;
tvi.mask := TVIF_STATE;
tvi.stateMask := TVIS_BOLD;
tvi.state := TVIS_BOLD * Ord(IsBold);
TreeView_SetItem(ATreeNode.Handle, tvi);
end;
end;
procedure TcaTreeView.SetNodeCheckedState(ATreeNode: TcaTreeNode; IsChecked: Boolean);
var
tvi: TTVItem;
const
StateIndexes: array[Boolean] of Integer = (1, 2);
begin
if Assigned(ATreeNode) then
begin
FillChar(tvi, SizeOf(tvi), 0);
tvi.hItem := ATreeNode.ItemID;
tvi.mask := TVIF_HANDLE or TVIF_STATE;
tvi.stateMask := TVIS_STATEIMAGEMASK;
tvi.state := IndexToStateImageMask(StateIndexes[IsChecked]);
TreeView_SetItem(ATreeNode.Handle, tvi);
end;
end;
procedure TcaTreeView.UpdateNodeCheckLinkStates(ATreeNode: TcaTreeNode);
begin
Items.BeginUpdate;
try
if Assigned(ATreeNode) then
begin
UpdateChildrenCheckState(ATreeNode);
UpdateParentsCheckState(ATreeNode);
end;
finally
Items.EndUpdate;
end;
end;
// private methods...
procedure TcaTreeView.AddTreeNode(ANode: TcaNode; ATreeNode: TcaTreeNode);
var
TreeNode: TTreeNode;
SubNode: TcaNode;
ShouldAddNode: Boolean;
begin
if not Assigned(ANode) then
if FNodes.RootCount > 0 then
ANode := FNodes.Roots[0];
if Assigned(ANode) then
begin
TreeNode := Items.AddChild(ATreeNode, ANode.Text);
TreeNode.Data := ANode;
TreeNode.ImageIndex := 0;
TreeNode.SelectedIndex := 0;
DoNodeAdded(TcaTreeNode(TreeNode), ANode);
SubNode := ANode.FirstSub;
while Assigned(SubNode) do
begin
DoAddNode(SubNode, ShouldAddNode);
if ShouldAddNode then
AddTreeNode(SubNode, TcaTreeNode(TreeNode));
SubNode := SubNode.NextIso;
end;
end;
end;
procedure TcaTreeView.UpdateChildrenCheckState(ATreeNode: TcaTreeNode);
var
SubTreeNode: TcaTreeNode;
begin
SubTreeNode := TcaTreeNode(ATreeNode.getFirstChild);
while Assigned(SubTreeNode) and SubTreeNode.HasAsParent(ATreeNode) do
begin
SubTreeNode.Checked := ATreeNode.Checked;
SubTreeNode := TcaTreeNode(SubTreeNode.GetNext);
end;
end;
procedure TcaTreeView.UpdateParentsCheckState(ATreeNode: TcaTreeNode);
var
ParentTreeNode: TcaTreeNode;
SubTreeNode: TcaTreeNode;
ChildCount: Integer;
CheckedCount: Integer;
PartCheckedCount: Integer;
begin
ParentTreeNode := TcaTreeNode(ATreeNode.Parent);
while Assigned(ParentTreeNode) do
begin
ChildCount := 0;
CheckedCount := 0;
PartCheckedCount := 0;
SubTreeNode := TcaTreeNode(ParentTreeNode.getFirstChild);
while Assigned(SubTreeNode) do
begin
if SubTreeNode.Parent = ParentTreeNode then
begin
Inc(ChildCount);
if SubTreeNode.Checked then
Inc(CheckedCount);
if SubTreeNode.PartChecked then
Inc(PartCheckedCount);
end;
SubTreeNode := TcaTreeNode(ParentTreeNode.GetNextChild(SubTreeNode));
end;
if ChildCount = 0 then
begin
ParentTreeNode.Checked := False;
ParentTreeNode.PartChecked := False;
end
else
begin
if CheckedCount = ChildCount then
begin
ParentTreeNode.Checked := True;
ParentTreeNode.PartChecked := False;
end
else
begin
if (CheckedCount > 0) or (PartCheckedCount > 0) then
begin
ParentTreeNode.Checked := False;
ParentTreeNode.PartChecked := True;
end
else
begin
ParentTreeNode.Checked := False;
ParentTreeNode.PartChecked := False;
end;
end;
end;
ParentTreeNode := TcaTreeNode(ParentTreeNode.Parent);
end;
end;
procedure TcaTreeView.UpdateNodes;
var
Index: Integer;
RootNode: TcaNode;
ShouldAddNode: Boolean;
begin
if Assigned(FNodes) then
begin
Items.BeginUpdate;
FUpdatingNodes := True;
try
Items.Clear;
for Index := 0 to Pred(FNodes.RootCount) do
begin
RootNode := FNodes.Roots[Index];
DoAddNode(RootNode, ShouldAddNode);
if ShouldAddNode then
AddTreeNode(RootNode, nil);
end;
finally
Items.EndUpdate;
FUpdatingNodes := False;
end;
end;
end;
// property methods...
function TcaTreeView.GetItem(Index: Integer): TcaTreeNode;
begin
Result := TcaTreeNode(Items[Index]);
end;
procedure TcaTreeView.SetUseCheckBoxes(const Value: Boolean);
begin
if Value <> FUseCheckBoxes then
begin
FUseCheckBoxes := Value;
// need to force the CreateParams call...
if not (csDesigning in ComponentState) then
RecreateWnd;
end;
end;
procedure TcaTreeView.SetUseLinkedChecking(const Value: Boolean);
begin
if Value <> FUseLinkedChecking then
begin
FUseLinkedChecking := Value;
if FUseLinkedChecking and (not (csDesigning in ComponentState)) then
UpdateNodeCheckLinkStates(TcaTreeNode(Selected));
end;
end;
procedure TcaTreeView.SetUseNodeHoverEvents(const Value: Boolean);
begin
if Value <> FUseNodeHoverEvents then
begin
FUseNodeHoverEvents := Value;
FHoverTimer.OnTimer := HoverTimerEvent;
FHoverTimer.Enabled := FUseNodeHoverEvents;
end;
end;
end.
|
unit xThreadUDPSendScreen;
interface
uses System.Types,System.Classes, xFunction, system.SysUtils, xUDPServerBase,
xConsts, System.IniFiles, winsock, Graphics,
xThreadBase, xProtocolSendScreen, Vcl.Imaging.jpeg;
type
TThreadUDPSendScreen = class(TThreadBase)
private
FStream1 : TMemoryStream;
FCanClose : Boolean;
FClose : Boolean;
FOnLog: TGetStrProc;
FSendPort : Integer; // 发送端口
FOnGetScreen: TNotifyEvent;
procedure ReadINI;
procedure WriteINI;
procedure GetScreen;
protected
/// <summary>
/// 执行定时命令 (如果定时命令要执行列表需要判断 FIsStop 是佛停止运行,如果挺尸运行需要跳出循环)
/// </summary>
procedure ExecuteTimerOrder; override;
public
constructor Create(CreateSuspended: Boolean); override;
destructor Destroy; override;
procedure Connect;
procedure DisConnect;
/// <summary>
/// 记录时间
/// </summary>
property OnLog : TGetStrProc read FOnLog write FOnLog;
/// <summary>
/// 获取图像事件
/// </summary>
property OnGetScreen : TNotifyEvent read FOnGetScreen write FOnGetScreen;
end;
var
UDPSendScreen : TThreadUDPSendScreen;
implementation
{ TTCPServer }
procedure TThreadUDPSendScreen.Connect;
begin
TUDPServerBase(FCommBase).Connect;
end;
constructor TThreadUDPSendScreen.Create(CreateSuspended: Boolean);
begin
inherited;
FStream1 := TMemoryStream.Create;
FCanClose := True;
FProtocol := TProtocolSendScreen.Create;
ProType := ctUDPServer;
TimerOrderEnable := True;
FClose := False;
ReadINI;
end;
destructor TThreadUDPSendScreen.Destroy;
begin
FClose := True;
WaitForSeconds(2000);
repeat
WaitForSeconds(1);
until (FCanClose);
FStream1.Free;
FProtocol.Free;
WriteINI;
inherited;
end;
procedure TThreadUDPSendScreen.DisConnect;
begin
TUDPServerBase(FCommBase).DisConnect;
end;
procedure TThreadUDPSendScreen.ExecuteTimerOrder;
begin
if FClose then
Exit;
FCanClose := False;
Synchronize(GetScreen);
FStream1.Position := 0;
if FStream1.Size > 0 then
begin
ExecuteOrder(C_SEND_SCREEN, FStream1, '255.255.255.255', FSendPort);
end;
WaitForSeconds(10);
FCanClose := True;
end;
procedure TThreadUDPSendScreen.GetScreen;
begin
if Assigned(FOnGetScreen) then
FOnGetScreen(FStream1);
end;
procedure TThreadUDPSendScreen.ReadINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
TUDPServerBase(FCommBase).ListenPort := ReadInteger('UPDSendScreen', 'ListenPort', 16100);
FSendPort := ReadInteger('UPDSendScreen', 'SendPort', 16101);
Free;
end;
end;
procedure TThreadUDPSendScreen.WriteINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
WriteInteger('UPDSendScreen', 'ListenPort', TUDPServerBase(FCommBase).ListenPort);
WriteInteger('UPDSendScreen', 'SendPort', FSendPort);
Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSProxyWriterRegistry;
interface
uses System.Generics.Collections, System.IniFiles, System.SysUtils;
type
TDSProxyWriterPackageFile = class;
TDSProxyWriterPackageFileList = class;
TDSProxyWriterPackagesLoader = class
private
class procedure Clear(AIniFile: TCustomIniFile;
const AKey: string); static;
class procedure Load(AList: TDSProxyWriterPackageFileList; AIniFile: TCustomIniFile;
const AKey: string); static;
class procedure Save(AList: TDSProxyWriterPackageFileList; AIniFile: TCustomIniFile;
const AKey: string); static;
public
class function LoadPackages(APackageList: TDSProxyWriterPackageFileList): TObject;
class function LoadPackageList: TDSProxyWriterPackageFileList;
class procedure SavePackageList(AList: TDSProxyWriterPackageFileList);
end;
TDSProxyWriterPackageFileList = class
strict private
FList: TDictionary<string, TDSProxyWriterPackageFile>;
FUntitledPackage: string;
function GetList: TArray<TDSProxyWriterPackageFile>;
function GetCount: Integer;
protected
FModified: Boolean;
procedure HandleError(E: Exception; PackageInfo: TDSProxyWriterPackageFile); virtual;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Add(const AName: string; const ADescription: string; ADisabled: Boolean = False); virtual;
procedure Remove(const AFile: string);
function Contains(const AFile: string): Boolean;
property List: TArray<TDSProxyWriterPackageFile> read GetList;
property Count: Integer read GetCount;
property Modified: Boolean read FModified;
end;
TDSProxyWriterPackageFile = class
strict private
FFileName: string;
FDescription: string;
FDisabled: Boolean;
public
constructor Create(const AFileName: string; ADescription: string; ADisabled: Boolean);
property FileName: string read FFileName;
property Description: string read FDescription write FDescription;
property Disabled: Boolean read FDisabled write FDisabled;
end;
const
sProxyWriterPackages = 'Proxy Writer Packages';
sDSProxyGenSettingsKey = 'Software\Embarcadero\DSProxyGen';
implementation
uses
System.Classes,
System.Contnrs,
Vcl.Controls,
Vcl.Dialogs,
Datasnap.DSClientResStrs,
Vcl.Forms,
System.Win.Registry,
System.StrUtils,
System.UITypes,
Winapi.Windows;
type
TDSProxyWriterPackageFileListHandleError = class(TDSProxyWriterPackageFileList)
protected
procedure HandleError(E: Exception; PackageInfo: TDSProxyWriterPackageFile); override;
end;
TBasePackage = class
private
FFilename: string;
FHandle: HMODULE;
protected
function DoLoadPackage(const PackageName: string): HMODULE; virtual;
procedure DoUnloadPackage(Module: HMODULE); virtual;
procedure InternalUnload; virtual;
public
constructor Create(const AFilename: string);
destructor Destroy; override;
function IsLoaded: Boolean;
procedure Load; virtual;
procedure Unload; virtual;
property Filename: string read FFilename;
property Handle: HMODULE read FHandle; // write SetHandle;
end;
TProxyPackage = class(TBasePackage)
public
constructor Create(const AFilename: string; AList: TList);
end;
function ExpandRootMacro(const InString: string; const AdditionalVars: TDictionary<string, string>): string; forward;
{ TDSProxyWriterPackagesLoader }
class function TDSProxyWriterPackagesLoader.LoadPackages(APackageList: TDSProxyWriterPackageFileList): TObject;
var
LPackage: TProxyPackage;
LList: TList;
LPackageFile: TDSProxyWriterPackageFile;
begin
LList := TObjectList.Create(True);
for LPackageFile in APackageList.List do
begin
if not LPackageFile.Disabled then
begin
LPackage := TProxyPackage.Create(ExpandRootMacro(LPackageFile.FileName, nil), LList);
try
LPackage.Load;
except
on E: Exception do
APackageList.HandleError(E, LPackageFile);
end;
end;
end;
Result := LList;
end;
class function TDSProxyWriterPackagesLoader.LoadPackageList: TDSProxyWriterPackageFileList;
var
LIniFile: TCustomIniFile;
begin
LIniFile := TRegistryIniFile.Create(sDSProxyGenSettingsKey);
try
Result := TDSProxyWriterPackageFileListHandleError.Create;
try
Load(Result, LIniFile, sProxyWriterPackages);
except
Result.Free;
raise;
end;
except
LIniFile.Free;
raise;
end;
end;
class procedure TDSProxyWriterPackagesLoader.SavePackageList(AList: TDSProxyWriterPackageFileList);
var
LIniFile: TCustomIniFile;
begin
LIniFile := TRegistryIniFile.Create(sDSProxyGenSettingsKey);
try
Save(AList, LIniFile, sProxyWriterPackages);
except
LIniFile.Free;
raise;
end;
end;
class procedure TDSProxyWriterPackagesLoader.Load(AList: TDSProxyWriterPackageFileList; AIniFile: TCustomIniFile; const AKey: string);
var
I: Integer;
LStrings: TStrings;
LName, LDesc: String;
LDisabled: Boolean;
begin
AList.Clear;
Assert(AKey <> '');
if AIniFile = nil then Exit;
LStrings := TStringList.Create;
try
AIniFile.ReadSectionValues(AKey, LStrings);
for I := 0 to LStrings.Count - 1 do
begin
LName := LStrings.Names[I];
LDesc := LStrings.ValueFromIndex[I];
LDisabled := False;
// If the name starts with an underbar, then it is disabled.
if StartsText('_', LName) then
begin
LDisabled := True;
LName := LName.Substring(1);
end;
AList.Add(LName, LDesc, LDisabled);
end;
finally
LStrings.Free;
end;
AList.FModified := False;
end;
class procedure TDSProxyWriterPackagesLoader.Clear(AIniFile: TCustomIniFile; const AKey: string);
var
LStrings: TStringList;
LName: string;
I: Integer;
begin
LStrings := TStringList.Create;
try
AIniFile.ReadSectionValues(AKey, LStrings);
for I := 0 to LStrings.Count - 1 do
begin
LName := LStrings.Names[I];
AIniFile.DeleteKey(AKey, LName);
end;
finally
LStrings.Free;
end;
end;
class procedure TDSProxyWriterPackagesLoader.Save(AList: TDSProxyWriterPackageFileList; AIniFile: TCustomIniFile; const AKey: string);
var
LPackageFile: TDSProxyWriterPackageFile;
begin
Assert(AKey <> '');
if AIniFile = nil then Exit;
Clear(AIniFile, AKey);
for LPackageFile in AList.List do
begin
if LPackageFile.Disabled then
AIniFile.WriteString(AKey, '_' + LPackageFile.FileName, LPackageFile.Description)
else
AIniFile.WriteString(AKey, LPackageFile.FileName, LPackageFile.Description)
end;
if (AList.Count > 0) and (AIniFile.FileName <> '') then
AIniFile.UpdateFile;
AList.FModified := False;
end;
{ TDSProxyWriterPackageFileList }
constructor TDSProxyWriterPackageFileList.Create;
begin
FList := TObjectDictionary<string, TDSProxyWriterPackageFile>.Create([doOwnsValues]);
FUntitledPackage := sUntitledPackage;
end;
destructor TDSProxyWriterPackageFileList.Destroy;
begin
FList.Free;
inherited Destroy;
end;
function TDSProxyWriterPackageFileList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TDSProxyWriterPackageFileList.GetList: TArray<TDSProxyWriterPackageFile>;
begin
Result := FList.Values.ToArray;
end;
procedure TDSProxyWriterPackageFileList.Add(const AName, ADescription: string; ADisabled: Boolean = False);
var
LLowerCaseName: string;
LFileName: string;
begin
LFileName := AName;
LLowerCaseName := AnsiLowerCase(LFileName);
if not FList.ContainsKey(LLowerCaseName) then
begin
FModified := True;
FList.Add(LLowerCaseName, TDSProxyWriterPackageFile.Create(AName, ADescription, ADisabled));
end
else
begin
FList[LLowerCaseName].Description := ADescription;
FList[LLowerCaseName].Disabled := ADisabled;
FModified := True;
end;
end;
procedure TDSProxyWriterPackageFileList.Clear;
begin
FModified := True;
FList.Clear;
end;
procedure TDSProxyWriterPackageFileList.Remove(const AFile: string);
var
LowerCaseName: string;
begin
LowerCaseName := AnsiLowerCase(AFile);
if FList.ContainsKey(LowerCaseName) then
begin
FList.Remove(LowerCaseName);
FModified := True;
end;
end;
function TDSProxyWriterPackageFileList.Contains(const AFile: string): Boolean;
var
LowerCaseName: string;
begin
LowerCaseName := AnsiLowerCase(AFile);
Result := FList.ContainsKey(LowerCaseName);
end;
procedure TDSProxyWriterPackageFileList.HandleError(E: Exception; PackageInfo: TDSProxyWriterPackageFile);
begin
end;
{ TDSProxyWriterPackageFileListHandleError }
procedure TDSProxyWriterPackageFileListHandleError.HandleError(E: Exception; PackageInfo: TDSProxyWriterPackageFile);
var
Msg: string;
Buttons: TMsgDlgButtons;
Buffer: array[0..1023] of Char;
begin
if (E is EOutOfMemory) then
Application.ShowException(E)
else
begin
Buttons := [mbYes, mbNo];
if E.HelpContext <> 0 then Include(Buttons, mbHelp);
SetString(Msg, Buffer, ExceptionErrorMessage(E, ExceptAddr, Buffer, Length(Buffer)));
if Msg.IndexOf(ExtractFileName(ChangeFileExt(PackageInfo.FileName, ''))) = -1 then
Msg := string.Format(sErrorLoadingPackage, [PackageInfo.FileName, Msg]);
Msg := Msg + sLineBreak + sLoadPackageNextTime;
if MessageDlg(Msg, mtError, Buttons, E.HelpContext) = mrNo then
begin
PackageInfo.Disabled := True;
FModified := True;
end;
end;
end;
{ TBasePackage }
constructor TBasePackage.Create(const AFilename: string);
begin
FHandle := 0;
FFilename := AFilename;
end;
destructor TBasePackage.Destroy;
begin
Unload;
inherited Destroy;
end;
function TBasePackage.DoLoadPackage(const PackageName: string): HMODULE;
begin
Result := LoadPackage(PackageName);
end;
procedure TBasePackage.DoUnloadPackage(Module: HMODULE);
begin
try
UnloadPackage(Module);
except
On E:Exception do
begin
System.Classes.ApplicationShowException(E);
FreeLibrary(Module);
end;
end;
end;
procedure TBasePackage.InternalUnload;
begin
if (FHandle <> 0) then
begin
DoUnloadPackage(FHandle);
if FHandle <> 0 then
begin
// Make sure that we have a valid handle. This
FHandle := GetModuleHandle(PChar(FileName));
end;
end;
end;
function TBasePackage.IsLoaded: Boolean;
begin
Result := FHandle <> 0;
end;
procedure TBasePackage.Load;
begin
if FHandle = 0 then
FHandle := DoLoadPackage(FFileName)
else
DoLoadPackage(FFileName); // simply add a ref-count
end;
procedure TBasePackage.Unload;
begin
InternalUnload;
end;
{ TProxyPackage }
constructor TProxyPackage.Create(const AFilename: string;
AList: TList);
begin
inherited Create(AFileName);
if AList <> nil then
AList.Add(Self);
end;
{ TDSProxyWriterPackageFileList }
constructor TDSProxyWriterPackageFile.Create(const AFileName: string; ADescription: string;
ADisabled: Boolean);
begin
FFileName := AFileName;
FDescription := ADescription;
FDisabled := ADisabled;
end;
function ExpandEnvStrings(InString: string): string;
var
DollarPos, EndEnvVarPos: Integer;
OrigStr: string;
Depth: Integer; //depth is used to avoid infinite looping (only 1000 levels deep allowed)
P: array[0..4096] of char;
begin
Result := '$(' + InString + ')'; // do not localize
DollarPos := AnsiPos('$(', Result); // do not localize
EndEnvVarPos := AnsiPos(')', Result);
Depth := 0;
while (DollarPos <> 0) and (EndEnvVarPos > DollarPos) and (Depth < 1000) do
begin
if EndEnvVarPos > DollarPos then
begin
OrigStr := Result.Substring(DollarPos - 1, EndEnvVarPos - DollarPos + 1);
ExpandEnvironmentStrings(PChar('%' + Result.Substring(DollarPos + 1, EndEnvVarPos - DollarPos - 2) + '%'), P, SizeOf(P));
Result := Result.Replace(OrigStr, P);
DollarPos := AnsiPos('$(', Result); // do not localize
EndEnvVarPos := AnsiPos(')', Result);
Inc(Depth);
end;
end;
end;
function ExpandRootMacro(const InString: string; const AdditionalVars: TDictionary<string, string>): string;
var
I, Len, Start: Integer;
NewS, S: string;
P: PChar;
begin
Result := InString;
I := Result.IndexOf('$(') + 1;
if I = 0 then
Exit;
Len := Result.Length;
while I <= Len do
begin
if (I < Len - 1) and (Result.Chars[I-1] = '$') and (Result.Chars[I] = '(') then
begin
Start := I;
Inc(I);
while (I <= Len) and (Result.Chars[I-1] <> ')') do
Inc(I);
if I <= Len then
begin
S := Result.Substring(Start + 1, I - Start - 2);
if (AdditionalVars = nil)
or not AdditionalVars.TryGetValue(S, NewS) then
NewS := ExpandEnvStrings(S);
Result := Result.Remove(Start - 1, I - Start + 1);
Result := Result.Insert(Start - 1, NewS);
I := Start + NewS.Length;
Len := Result.Length;
end;
end;
Inc(I);
P := PChar(Pointer(Result)) + I - 1;
while (I <= Len) and (P^ <> '$') do // fast forward
begin
Inc(P);
Inc(I);
end;
end;
end;
end.
|
unit GdsData;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls, ExtCtrls, Grids, DBGrids, DB, DBTables, Mask,
DBCtrls, GdsStd;
type
TStdDataForm = class(TGDSStdForm)
StdCtrlPanel: TPanel;
FilterOnRadioGroup: TRadioGroup;
Orders: TTable;
Cust: TTable;
OrdersSource: TDataSource;
OrdersOrderNo: TFloatField;
OrdersCustNo: TFloatField;
OrdersSaleDate: TDateTimeField;
OrdersShipDate: TDateTimeField;
OrdersEmpNo: TIntegerField;
OrdersShipToContact: TStringField;
OrdersShipToAddr1: TStringField;
OrdersShipToAddr2: TStringField;
OrdersShipToCity: TStringField;
OrdersShipToState: TStringField;
OrdersShipToZip: TStringField;
OrdersShipToCountry: TStringField;
OrdersShipToPhone: TStringField;
OrdersShipVIA: TStringField;
OrdersPO: TStringField;
OrdersTerms: TStringField;
OrdersPaymentMethod: TStringField;
OrdersItemsTotal: TCurrencyField;
OrdersTaxRate: TFloatField;
OrdersFreight: TCurrencyField;
OrdersCustName: TStringField;
OrdersAmountDue: TCurrencyField;
OrdersAmountPaid: TCurrencyField;
GroupBox1: TGroupBox;
FilterOnLabel: TLabel;
FilterCriteria: TEdit;
FilterCheckBox: TCheckBox;
NextBtn: TButton;
PriorBtn: TButton;
OrdersTaxAmount: TCurrencyField;
procedure FilterOnRadioGroupClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OrdersFilterOnDate(DataSet: TDataSet; var Accept: Boolean);
procedure OrdersFilterOnAmount(DataSet: TDataSet; var Accept: Boolean);
procedure OrdersCalcFields(DataSet: TDataSet);
procedure FilterCheckBoxClick(Sender: TObject);
procedure PriorBtnClick(Sender: TObject);
procedure NextBtnClick(Sender: TObject);
procedure FilterCriteriaExit(Sender: TObject);
procedure FilterCriteriaKeyPress(Sender: TObject; var Key: Char);
protected
FLastAmount: Double;
FLastDate: TDateTime;
function CalcAmountDue: Double;
procedure ConvertFilterCriteria;
end;
var
StdDataForm: TStdDataForm;
implementation
{$R *.dfm}
procedure TStdDataForm.FilterOnRadioGroupClick(Sender: TObject);
begin
inherited;
with FilterOnRadioGroup do
begin
FilterOnLabel.Caption := Format('Records where %S >=', [Items[ItemIndex]]);
case ItemIndex of
0: begin
Orders.OnFilterRecord := OrdersFilterOnDate;
FilterCriteria.Text := DateToStr(FLastDate);
end;
1: begin
Orders.OnFilterRecord := OrdersFilterOnAmount;
FilterCriteria.Text := FloatToStr(FLastAmount);
end;
end;
ActiveControl := FilterCriteria;
end;
if Orders.Filtered then Orders.Refresh;
end;
procedure TStdDataForm.FormCreate(Sender: TObject);
begin
inherited;
FLastDate := EncodeDate(1995, 1, 1);
FLastAmount := 1000;
FilterOnRadioGroup.ItemIndex := 0;
end;
{ Calculate the value of AmountDue. Used in the OnCalcFields
and OnFilterRecord event handlers. }
function TStdDataForm.CalcAmountDue: Double;
begin
Result :=
OrdersItemsTotal.Value * (1.0 + OrdersTaxRate.Value / 100) +
OrdersFreight.Value - OrdersAmountPaid.Value;
end;
{ Convert the FilterCriteria text into a Date or Float. This value
will be used in the OnFilterRecord callback instead of using the
FilterCriteria directly, so that the string does not need to be
converted each time the event is triggered. }
procedure TStdDataForm.ConvertFilterCriteria;
begin
if FilterCriteria.Text <> '' then
case FilterOnRadioGroup.ItemIndex of
0: FLastDate := StrToDate(FilterCriteria.Text);
1: FLastAmount := StrToFloat(FilterCriteria.Text);
end;
if Orders.Filtered then Orders.Refresh;
end;
{ Try to convert the filter criteria whenever the edit control
looses focus, or the user presses enter }
procedure TStdDataForm.FilterCriteriaExit(Sender: TObject);
begin
inherited;
ConvertFilterCriteria;
end;
procedure TStdDataForm.FilterCriteriaKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
begin
ConvertFilterCriteria;
Key := #0
end;
end;
{ Calculate this order's total on the fly. Include in the dataset
if its amount is greater than or equal to the specified filter
criteria. Note that calculated and lookup fields are undefined
in an OnFilterRecord event handler. }
procedure TStdDataForm.OrdersFilterOnAmount(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
Accept := CalcAmountDue >= FLastAmount;
end;
{ Include this order in the dataset if its date is greater
than or equal to the specified filter criteria. }
procedure TStdDataForm.OrdersFilterOnDate(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
Accept := OrdersSaleDate.Value >= FLastDate;
end;
procedure TStdDataForm.OrdersCalcFields(DataSet: TDataSet);
begin
inherited;
OrdersTaxAmount.Value := OrdersItemsTotal.Value * (OrdersTaxRate.Value / 100);
OrdersAmountDue.Value := CalcAmountDue;
end;
{ Store contents of filter criteria from edit control }
procedure TStdDataForm.FilterCheckBoxClick(Sender: TObject);
begin
inherited;
ConvertFilterCriteria;
Orders.Filtered := FilterCheckBox.Checked;
NextBtn.Enabled := not FilterCheckBox.Checked;
PriorBtn.Enabled := not FilterCheckBox.Checked;
end;
{ Button handlers for new filter-oriented dataset navigation methods }
procedure TStdDataForm.PriorBtnClick(Sender: TObject);
begin
inherited;
ConvertFilterCriteria;
Orders.FindPrior;
end;
procedure TStdDataForm.NextBtnClick(Sender: TObject);
begin
inherited;
ConvertFilterCriteria;
Orders.FindNext;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{ osc1.c
Objects oscillating (or being squeezed and expanded, rather) at
different frequencies.
(c) Mahesh Venkitachalam 1999. http://home.att.net/~bighesh
}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Dialogs,
SysUtils, OpenGL;
type
TfrmGL = 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;
uTimerId : uint;
theta : Integer;
fRot : Boolean;
nf : Integer;
procedure Init;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
const
ell = 1;
cyl = 2;
light_pos : Array [0..3] of GLfloat = (100.0, 100.0, 100.0, 0.0);
var
frmGL: TfrmGL;
implementation
uses mmSystem;
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.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);
mat_shininess : Array [0..0] of GLfloat = (50.0);
var
qobj : GLUquadricObj;
begin
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);
glLightfv(GL_LIGHT0,GL_POSITION, @light_pos);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glClearColor(1.0, 1.0, 1.0, 0.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
// glu stuff
qobj := gluNewQuadric;
glNewList(ell,GL_COMPILE);
gluSphere(qobj,1.0,20,20);
glEndList;
glNewList(cyl,GL_COMPILE);
glPushMatrix;
glRotatef(180.0,1.0,0.0,0.0);
gluDisk(qobj,0.0,1.0,20,20);
glPopMatrix;
gluCylinder(qobj,1.0,1.0,4.0,20,20);
glPushMatrix;
glTranslatef(0.0,0.0,4.0);
gluDisk(qobj,0.0,1.0,20,20);
glPopMatrix;
glEndList;
gluDeleteQuadric (qobj);
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
a,b,c1,c2,c3 : GLfloat;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
a := 10.0*(1.0 + abs(sin(2.0*PI*nf/100.0)));
b := 10.0*(1.0 + abs(sin(2.0*PI*nf/10.0)));
c1 := 10.0*(1.0 + abs(sin(2.0*PI*nf/50.0)));
c2 := 10.0*(1.0 + abs(sin(2.0*PI*nf/50.0 + PI/4.0)));
c3 := 10.0*(1.0 + abs(sin(2.0*PI*nf/50.0 + PI/8.0)));
glLoadIdentity;
// viewing transform
glTranslatef(0.0,0.0,-200.0);
If fRot then
glRotatef(theta,0.0,0.0,1.0);
// modelling transforms
glPushMatrix;
glColor3f(1.0,0.0,0.0);
glPushMatrix;
glTranslatef(-40.0,-40.0,40.0);
glScalef(c1,c2,c3);
glCallList(ell);
glPopMatrix;
glColor3f(1.0,1.0,0.0);
glPushMatrix;
glRotatef(60.0,1.0,0.0,0.0);
glScalef(10.0,10.0,a);
glCallList(cyl);
glPopMatrix;
glColor3f(0.0,1.0,0.0);
glPushMatrix;
glTranslatef(20.0,40.0,20.0);
glRotatef(30.0,1.0,0.0,0.0);
glScalef(b,10.0,10.0);
glCallList(cyl);
glPopMatrix;
glPopMatrix;
SwapBuffers(DC); // конец работы
EndPaint(Handle, ps);
end;
{=======================================================================
Обработка таймера}
procedure FNTimeCallBack(uTimerID, uMessage: UINT;dwUser, dw1, dw2: DWORD) stdcall;
begin
With frmGL do begin
nf := nf + 1;
theta := theta + 4;
If theta = 360 then theta := 0;
InvalidateRect(Handle, nil, False);
end;
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
nf := 0;
theta := 0;
fRot := FALSE;
Init;
uTimerID := timeSetEvent (30, 0, @FNTimeCallBack, 0, TIME_PERIODIC);
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.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 TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(50.0, 1.0, 10.0, 500.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
timeKillEvent(uTimerID);
glDeleteLists (ell, 2);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If Key = VK_INSERT then fRot := not fRot;
end;
end.
|
unit uTelegramAPI;
interface
uses
uTelegramAPI.Interfaces, uConsts, System.Net.HttpClientComponent,
System.SysUtils, System.Classes, System.Net.Mime, System.JSON,
uClassMessageDTO, Rest.JSON, Rest.JSON.Types;
// UnixToDateTime(1605808194) DateUtils
type
TTelegramAPI = Class(TInterfacedObject, iTelegramAPI)
private
FHTTPClient: TNetHTTPClient;
FBotToken: String;
FUserID: String;
FResult: String;
FProcErrorException: TProcErrorException;
function _POST(AUrl: String; AData: TStrings): String; overload;
function _POST(AUrl: String; AData: TMultipartFormData): String; overload;
function _GET(AUrl: String): String;
function GetURL(APath: String = ''): String;
function Ready(): Boolean;
public
constructor Create();
destructor Destroy(); override;
class function New(): iTelegramAPI;
function SetBotToken(AToken: String): iTelegramAPI;
function SetUserID(AUserID: String): iTelegramAPI;
function SendFile(AFileName: String): iTelegramAPI;
function SendMsg(AMsg: String): iTelegramAPI;
function SendMsgWithButtons(AMsg: String; AButtons: TTelegramButtons)
: iTelegramAPI;
function OnError(AValue: TProcErrorException): iTelegramAPI;
function GetResult: String;
function GetUpdates(var AValue: TChatMessageDTOList): iTelegramAPI;
function SendLocation(ALatitude, ALongitude: String): iTelegramAPI;
end;
const
urlBase = 'https://api.telegram.org/{BOT_TOKEN}';
implementation
{ TTelegramAPI }
constructor TTelegramAPI.Create;
begin
FHTTPClient := TNetHTTPClient.Create(nil);
FHTTPClient.ConnectionTimeout := 5000;
FHTTPClient.ResponseTimeout := 5000;
end;
destructor TTelegramAPI.Destroy;
begin
FreeAndNil(FHTTPClient);
inherited;
end;
class function TTelegramAPI.New: iTelegramAPI;
begin
Result := Self.Create;
end;
function TTelegramAPI.OnError(AValue: TProcErrorException): iTelegramAPI;
begin
Result := Self;
FProcErrorException := AValue;
end;
function TTelegramAPI.Ready: Boolean;
begin
Result := True;
if FBotToken.IsEmpty then
begin
if Assigned(FProcErrorException) then
FProcErrorException(Exception.Create('BotToken is Empty!'));
Result := False;
end
else if FUserID.IsEmpty then
begin
if Assigned(FProcErrorException) then
FProcErrorException(Exception.Create('UserID is Empty!'));
Result := False;
end;
end;
function TTelegramAPI.GetResult: String;
begin
Result := FResult;
end;
function TTelegramAPI.GetUpdates(var AValue: TChatMessageDTOList): iTelegramAPI;
var
pArrJSON: TJSONArray;
I: Byte;
begin
Result := Self;
if FBotToken.IsEmpty then
begin
if Assigned(FProcErrorException) then
FProcErrorException(Exception.Create('BotToken is Empty!'));
Exit;
end;
try
FResult := _GET(GetURL('/getUpdates'));
pArrJSON := ((TJSONObject.ParseJSONValue(FResult) as TJSONObject)
.GetValue('result') as TJSONArray);
if pArrJSON.Count <= 0 then Exit;
for I := 0 to Pred(pArrJSON.Count) do
AValue.Add(TJSON.JsonToObject<TChatMessageDTO>(pArrJSON.Items[I].ToJSON));
except
on E: Exception do
begin
if Assigned(FProcErrorException) then
FProcErrorException(E);
end;
end;
end;
function TTelegramAPI.GetURL(APath: String = ''): String;
begin
Result := EmptyStr;
try
Result := urlBase.Replace('{BOT_TOKEN}', FBotToken + APath);
except
end;
end;
function TTelegramAPI.SendFile(AFileName: String): iTelegramAPI;
var
pData: TMultipartFormData;
begin
Result := Self;
FHTTPClient.ContentType := 'multipart/form-data';
pData := TMultipartFormData.Create;
pData.AddFile('document', AFileName);
pData.AddField('chat_id', FUserID);
FResult := _POST(GetURL('/sendDocument'), pData);
end;
function TTelegramAPI.SendLocation(ALatitude, ALongitude: String): iTelegramAPI;
var
pData: TStrings;
begin
Result := Self;
FHTTPClient.ContentType := 'application/json';
pData := TStringList.Create;
pData.AddPair('chat_id', FUserID);
pData.AddPair('latitude', ALatitude);
pData.AddPair('longitude', ALongitude);
FResult := _POST(GetURL('/sendLocation'), pData);
end;
function TTelegramAPI.SendMsg(AMsg: String): iTelegramAPI;
var
pData: TStrings;
begin
Result := Self;
FHTTPClient.ContentType := 'application/json';
pData := TStringList.Create;
pData.AddPair('chat_id', FUserID);
pData.AddPair('text', AMsg);
FResult := _POST(GetURL('/sendMessage'), pData);
end;
function TTelegramAPI.SendMsgWithButtons(AMsg: String;
AButtons: TTelegramButtons): iTelegramAPI;
var
pData: TStrings;
pJsonArr: TJSONArray;
begin
Result := Self;
if AButtons.Count <= 0 then
Exit;
pJsonArr := TJSONArray.Create;
for var Enum in AButtons do
begin
pJsonArr.AddElement(TJSONObject.Create.AddPair('text', Enum.Key)
.AddPair('url', Enum.Value));
end;
FHTTPClient.ContentType := 'application/json';
pData := TStringList.Create;
pData.AddPair('chat_id', FUserID);
pData.AddPair('text', AMsg);
pData.AddPair('reply_markup', '{"inline_keyboard":[' +
pJsonArr.ToJSON + ']}');
FResult := _POST(GetURL('/sendMessage'), pData);
end;
function TTelegramAPI.SetBotToken(AToken: String): iTelegramAPI;
begin
Result := Self;
FBotToken := 'bot' + AToken;
end;
function TTelegramAPI.SetUserID(AUserID: String): iTelegramAPI;
begin
Result := Self;
FUserID := AUserID;
end;
function TTelegramAPI._GET(AUrl: String): String;
begin
Result := EmptyStr;
try
Result := FHTTPClient.Get(AUrl).ContentAsString(TEncoding.UTF8);
except
on E: Exception do
begin
if Assigned(FProcErrorException) then
FProcErrorException(E);
end;
end;
end;
function TTelegramAPI._POST(AUrl: String; AData: TMultipartFormData): String;
begin
Result := EmptyStr;
if not Ready() then
Exit;
try
Result := FHTTPClient.Post(AUrl, AData).ContentAsString(TEncoding.UTF8);
except
on E: Exception do
begin
if Assigned(FProcErrorException) then
FProcErrorException(E);
end;
end;
end;
function TTelegramAPI._POST(AUrl: String; AData: TStrings): String;
begin
Result := EmptyStr;
if not Ready() then
Exit;
try
Result := FHTTPClient.Post(AUrl, AData).ContentAsString(TEncoding.UTF8);
except
on E: Exception do
begin
if Assigned(FProcErrorException) then
FProcErrorException(E);
end;
end;
end;
end.
|
{ This file is part of CodeSharkFC
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
}
unit SetTool;
{$MODE Delphi}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, ComCtrls,
Dialogs, ExtCtrls, StdCtrls;
type
{ TSetToolFRM }
TSetToolFRM = class(TForm)
ClearanceEdt: TLabeledEdit;
FinalDepthEdt: TLabeledEdit;
HorzFeedEdt: TLabeledEdit;
Label1: TLabel;
Label2: TLabel;
{$IFDEF FPC}
Label3: TLabel;
Label4: TLabel;
StartXEdt: TLabeledEdit;
StartYEdt: TLabeledEdit;
StartZEdt: TLabeledEdit;
{$ENDIF}
OffsetExtraEdt: TLabeledEdit;
Panel1: TPanel;
Panel2: TPanel;
Panel4: TPanel;
Panel3: TPanel;
RadiusEdt: TLabeledEdit;
RapidSafeSpaceEdt: TLabeledEdit;
rbCW: TRadioButton;
rbCCW: TRadioButton;
rbLeftofLine: TRadioButton;
rbOnLine: TRadioButton;
rbRightofLine: TRadioButton;
StartDepthEdt: TLabeledEdit;
StepdownEdt: TLabeledEdit;
VertFeedEdt: TLabeledEdit;
procedure GenericEditExit(Sender: TObject);
procedure GenericEditExitP(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
SetToolFRM: TSetToolFRM;
implementation
{$R *.lfm}
{ TSetToolFRM }
// use val function procedure Val(Const S: string; var V; var Code: Word) to validate tool values
procedure TSetToolFRM.GenericEditExit(Sender: TObject);
Var
Value : Double;
begin
with Sender as TLabeledEdit do
begin
if Not(TryStrToFloat(Text, Value)) then
Begin
ShowMessage('Value Entered for ' + EditLabel.Caption + ': ' + Text + ' Is Invalid, Retry');
Setfocus;
End;
end;
end;
procedure TSetToolFRM.GenericEditExitP(Sender: TObject);
Var
Value : Double;
begin
with Sender as TLabeledEdit do
begin
if Not(TryStrToFloat(Text, Value)) then
Begin
ShowMessage('Value Entered for ' + EditLabel.Caption + ': ' + Text + ' Is Invalid, Retry');
Setfocus;
End
Else
if Value < 0 then
Begin
ShowMessage('Value Entered for ' + EditLabel.Caption + ': ' + Text + ' Cannot Be Negative, Retry');
Setfocus;
End
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit XMLSchemaHelper;
interface
{$DEFINE SAFE_TYPE_ACCESS}
{$DEFINE SAFE_DATATYPE_ACCESS}
uses XMLIntf, XMLDoc, xmldom, XmlSchema, WSDLModelIntf
{$IFDEF VISITOR_CONTEXT_TTREENODE}
, ComCtrls
{$ENDIF}
;
type
{$IFDEF VISITOR_CONTEXT_TTREENODE}
XMLVisitorContext = TTreeNode;
{$ELSE}
XMLVisitorContext = IWSDLType;
{$ENDIF}
{ Similar to TCompositorType but caters for global elements }
TElementType = (etGlobal, etAll, etChoice, etSequence, etElementGroup);
TElementTypes = set of TElementType;
{ To be implemented by class that wants to traverse elements of a schema }
IXMLSchemaVisitor = interface
['{BA640BF8-8364-49FF-829E-81B74A3394F9}']
function Start(const SchemaDef: IXMLSchemaDef; const SchemaLoc: String): XMLVisitorContext;
function Visit(const Item: IXMLAttributeDef; const Context: XMLVisitorContext): XMLVisitorContext; overload;
function Visit(const Item: IXMLElementDef; const ElementTypes: TElementTypes;
const CompositorId: Integer;
const Context: XMLVisitorContext): XMLVisitorContext; overload;
function Visit(const Item: IXMLSimpleTypeDef; const Context: XMLVisitorContext): XMLVisitorContext; overload;
function Visit(const Item: IXMLComplexTypeDef; const Context: XMLVisitorContext): XMLVisitorContext; overload;
function Visit(const Item: IXMLAttributeGroup; const Context: XMLVisitorContext): XMLVisitorContext; overload;
function Visit(const Item: IXMLElementGroup; const Context: XMLVisitorContext): XMLVisitorContext; overload;
function VisitAny(const Item: IXMLNode; const Context: XMLVisitorContext): XMLVisitorContext;
procedure Skipping(const SchemaLoc: String);
procedure Done(const SchemaLoc: String);
procedure Error(const SchemaLoc: String; const Msg: String);
end;
{ Tour guide that takes visitor to each element of a schema }
IXMLSchemaGuide = interface
['{B8037BC1-EAC0-45D6-B6B2-207AC2D347B9}']
procedure ShowSchema(const SchemaDef: IXMLSchemaDef; const SchemaLoc: String;
const Tracker: IProcessedTracker;
const OuterTNS: DOMString);
end;
ArrayOfXMLNode = array of IXMLNode;
TDataTypeTie = (dtUnknown, dtRef, dtType);
{ Method to visit every element of a schema - note handles import and include of other schemas }
function VisitSchema(const SchemaDef: IXMLSchemaDef;
const SchemaLoc: String;
const Visitor: IXMLSchemaVisitor;
const Tracker: IProcessedTracker): Boolean;
function GetNamespaceOf(const Item: IXMLAttributeGroup): DOMString; overload;
function GetNamespaceOf(const Item: IXMLElementDef): DOMString; overload;
function GetNamespaceOf(const Item: IXMLSimpleTypeDef): DOMString; overload;
function GetNamespaceOf(const Item: IXMLComplexTypeDef): DOMString; overload;
function GetNamespaceOf(const Item: IXMLSchemaItem): DOMString; overload;
function GetNameOf(const Item: IXMLTypedSchemaItem): DOMString; overload;
function GetNameOf(const Item: IXMLTypeDef; const DefaultName: DOMString): DOMString; overload;
function GetNameOf(const Item: IXMLAttributeGroup): DOMString; overload;
function GetDataTypeName(const Item: IXMLTypedSchemaItem): DOMString;
function GetDataTypeNamespace(const Item: IXMLTypedSchemaItem): DOMString;
function GetDataTypeTie(const Item: IXMLTypedSchemaItem): TDataTypeTie;
function HasRefAttr(const Item: IXMLTypedSchemaItem): Boolean;
function IsKnownType(const Item: IXMLSimpleTypeDef): Boolean;
{ Returns whether an Element is defined inline or not }
function ElementDefinedInline(const TypeDef: IXMLElementDef): Boolean;
function AttributeDefinedInline(const TypeDef: IXMLAttributeDef): Boolean;
function AttributeGroupDefinedInline(const TypeDef: IXMLAttributeGroup): Boolean;
{ Odd helper thrown here because .... ?? }
function GetChildNodesOfName(const Node: IXMLNode; const NodeName: String): ArrayOfXMLNode;
{ ---------------------------------------------------------------------------
Pure collection is a complex type that contains just one element with
'maxOccurs="unbounded"'.
---------------------------------------------------------------------------}
function IsPureCollection(const ComplexType: IXMLComplexTypeDef;
var TypeName: DOMString;
var TypeNamespace: DOMString): Boolean; overload;
function IsPureCollection(const ComplexType: IXMLComplexTypeDef;
var IsInline: Boolean): Boolean; overload;
function IsPureCollection(const WSDLType: IWSDLType): Boolean; overload;
{ ---------------------------------------------------------------------------
Retrieve documentation attached to type
---------------------------------------------------------------------------}
function GetDocumentation(const ComplexType: IXMLComplexTypeDef): DOMString;
{ ---------------------------------------------------------------------------
Routine that attempts to determine whether a complex type represents
a SOAP array.
---------------------------------------------------------------------------}
function SOAPArray(const ComplexType: IXMLComplexTypeDef;
var TypeName: DOMString;
var TypeNamespace: DOMString;
var Dimension: Integer): Boolean;
function GetProcessedTracker: IProcessedTracker;
const
DerivationMethodStr: array[TDerivationMethod] of string = ('dmNone',
'dmComplexExtension',
'dmComplexRestriction',
'dmSimpleExtension',
'dmSimpleRestriction'
);
implementation
uses SOAPConst, XMLSchemaTags, WSDLIntf, HTTPUtil, Classes, SysUtils, Variants;
type
{ Implements Items Processed }
TProcessedTracker = class(TInterfacedObject, IProcessedTracker)
FProcessedList: TDOMStrings;
public
constructor Create;
destructor Destroy; override;
function ProcessedAlready(const Name: DOMString): Boolean;
procedure AddProcessed(const Name: DOMString);
procedure Clear;
function GetCount: Integer;
function GetItem(Index: Integer): DOMString;
end;
function GetProcessedTracker: IProcessedTracker;
begin
Result := TProcessedTracker.Create;
end;
{ TProcessedTracker }
procedure TProcessedTracker.AddProcessed(const Name: DOMString);
begin
FProcessedList.Add(Name);
end;
procedure TProcessedTracker.Clear;
begin
FProcessedList.Clear;
end;
constructor TProcessedTracker.Create;
begin
FProcessedList := TDOMStrings.Create;
end;
destructor TProcessedTracker.Destroy;
begin
FProcessedList.Free;
end;
function TProcessedTracker.GetCount: Integer;
begin
Result := FProcessedList.Count;
end;
function TProcessedTracker.GetItem(Index: Integer): DOMString;
begin
Result := FProcessedList[Index];
end;
function TProcessedTracker.ProcessedAlready(const Name: DOMString): Boolean;
begin
Result := FProcessedList.IndexOfIgnoreCase(Name) <> -1;
end;
{ Returns children nodes of the specified named }
function GetChildNodesOfName(const Node: IXMLNode; const NodeName: String): ArrayOfXMLNode;
var
I, Len: Integer;
begin
Len := 0;
SetLength(Result, 0);
if Node.HasChildNodes then
begin
for I := 0 to Node.ChildNodes.Count - 1 do
begin
if Node.ChildNodes[I].NodeName = NodeName then
begin
Inc(Len);
SetLength(Result, Len);
Result[Len-1] := Node.ChildNodes[I];
end;
end;
end;
end;
function HasChildrenNode(Node: IXMLNode; Names: array of DOMString): Boolean;
var
I: Integer;
Name: DOMString;
begin
Result := False;
if (Node.HasChildNodes) then
begin
for Name in Names do
begin
Result := Node.ChildNodes.FindNode(Name) <> nil;
if Result then
Exit;
end;
for I := 0 to Node.ChildNodes.Count - 1 do
begin
Result := HasChildrenNode(Node.ChildNodes[I], Names);
if Result then
Exit;
end;
end;
end;
{ Returns whether an Element is defined inline or not }
function ElementDefinedInline(const TypeDef: IXMLElementDef): Boolean;
begin
{$IFDEF SAFE_TYPE_ACCESS}
Result := (Typedef.HasAttribute(SRef) = False) and
(Typedef.HasAttribute(SType) = False) and
HasChildrenNode(TypeDef, [SComplexType, SSimpleType]);
{$ELSE}
Result := (TypeDef.Ref = nil) and (TypeDef.DataType.IsAnonymous);
{$ENDIF}
end;
function AttributeDefinedInline(const TypeDef: IXMLAttributeDef): Boolean;
begin
{$IFDEF SAFE_TYPE_ACCESS}
Result := (Typedef.HasAttribute(SRef) = False) and
(Typedef.HasAttribute(SType) = False);
{$ELSE}
Result := (TypeDef.Ref = nil) and (TypeDef.DataType.IsAnonymous);
{$ENDIF}
end;
{ Returns whether an <attributeGroup...> is defined inline or not }
function AttributeGroupDefinedInline(const TypeDef: IXMLAttributeGroup): Boolean;
const
SAttributeGroup = 'attributeGroup';
SAttribute = 'attribute';
begin
Result := (Typedef.HasAttribute(SRef) = False) and
HasChildrenNode(TypeDef, [SAttribute, SAttributeGroup]);
end;
{ ---------------------------------------------------------------------------
Retrieve documentation attached to type
---------------------------------------------------------------------------}
function GetDocumentation(const ComplexType: IXMLComplexTypeDef): DOMString;
begin
Result := '';
try
Result := XMLSchema.GetDocumentation(ComplexType);
except
{ RAID: 242581: There's a bug in XMLSchema.GetDocumentation that does not handle
Ebay's style annotation, such as the following:
<xs:complexType xmlns:xs="http://www.w3.org/2001/XMLSchema" name="GetApiAccessRulesRequestType">
<xs:annotation>
<xs:documentation>
<!-- see in/out docs for description -->
</xs:documentation>
<xs:appinfo>
<Summary xmlns="urn:ebay:apis:eBLBaseComponents">
Retrieves the access rules for various calls and shows how many calls your
application has made in the past day and hour.
</Summary>
<SeeLink xmlns="urn:ebay:apis:eBLBaseComponents">
<URL>http://developer.ebay.com/help/certification</URL>
<Title>Certification</Title>
</SeeLink>
</xs:appinfo>
</xs:annotation>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
I've informed ME of the issue and is waiting for a reply.
In the meantime I'll ignore exceptions from XMLSchema.GetDocumetation(xxx) }
end;
end;
function GetArrayDimension(const Name: DOMString; var Dim: integer): DOMString;
var
SepPos, I, Strlen: Integer;
begin
Dim := 1; { Safe Start! }
Result := Name;
StrLen := Length(Name);
SepPos := Pos('[', Name);
{ Extract dimensions }
if SepPos > 0 then
begin
Dim := 0;
for I := SepPos to StrLen do
begin
if (Name[I] = '[') or (Name[I] = ',') then
Inc(Dim);
end;
{ Extract Name }
Result := Copy(Name, Low(Integer), SepPos-1)
end;
end;
{ ---------------------------------------------------------------------------
The way each SOAP Stack declares arrays is frightening. This routine
attempts to detect the flavors that exists out there.
NOTE: This is work in progress...
---------------------------------------------------------------------------}
function SOAPArray(const ComplexType: IXMLComplexTypeDef;
var TypeName: DOMString;
var TypeNamespace: DOMString;
var Dimension: Integer): Boolean;
var
BaseType: string;
URI: DOMString;
AttributeDef: IXMLAttributeDef;
HasValue: Boolean;
V: OleVariant;
begin
Result := False;
Dimension := 1;
{ Some schemas - WASP' for example - declare arrrays as:
<complexType name="ArrayOfstring" base="SOAP-ENC:Array">
<sequence>
<element name="arg" type="xsd:string" />
</sequence>
</complexType> }
{ Check for Base of SOAP-ENC:Array }
if ComplexType.HasAttribute(SBase) then
begin
BaseType := ComplexType.Attributes[SBase];
if IsPrefixed(BaseType) and (ExtractLocalName(BaseType) = SArray) then
begin
URI := ComplexType.FindNamespaceURI(ExtractPrefix(BaseType));
if (URI = Soapns) or (URI = SSoap11EncodingS5) then
begin
if (ComplexType.ElementDefs.Count = 1) then
begin
TypeName := GetDataTypeName(ComplexType.ElementDefList[0]);
TypeNamespace := GetDataTypeNamespace(ComplexType.ElementDefList[0]);
Result := True;
end;
end;
end;
end;
{ Here we check for the more typical Array Schema }
{
<xs:complexType name="ArrayOfint">
<xs:complexContent>
<xs:restriction base="soapenc:Array">
<xs:sequence/>
<xs:attribute ref="soapenc:arrayType" n1:arrayType="xs:int[]"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
NOTE this variation:
<complexType name="ArrayOfstring">
<complexContent>
<restriction base="SOAP-ENC:Array">
<sequence>
<element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
<attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="xsd:string[]"/>
</restriction>
</complexContent>
</complexType>
}
if (not Result) then
begin
if (ComplexType.DerivationMethod = dmComplexRestriction) and
(ComplexType.ElementDefs.Count <= 1) and
(ComplexType.AttributeDefs.Count = 1) then
begin
AttributeDef := ComplexType.AttributeDefs[0];
HasValue := AttributeDef.HasAttribute(SArrayType, Wsdlns);
if (HasValue) then
begin
V := AttributeDef.GetAttributeNS(SArrayType, Wsdlns);
TypeName := V;
if IsPrefixed(TypeName) then
begin
TypeNamespace := ExtractPrefix(TypeName);
TypeNamespace := AttributeDef.FindNamespaceURI(TypeNamespace);
TypeName := ExtractLocalName(TypeName);
end
else
TypeNamespace := AttributeDef.NamespaceURI;
TypeName := GetArrayDimension(TypeName, Dimension);
Result := True;
end;
end;
end;
end;
{ ---------------------------------------------------------------------------
Pure collection is a complex type that contains just one element with
'maxOccurs="unbounded"'.
---------------------------------------------------------------------------}
function IsPureCollection(const ComplexType: IXMLComplexTypeDef; var IsInline: Boolean): Boolean; overload;
begin
Result := (ComplexType.ElementDefList.Count = 1) and
ComplexType.ElementDefList[0].IsRepeating;
if (Result) then
begin
IsInline := ElementDefinedInline(ComplexType.ElementDefs[0]);
end;
end;
{ ---------------------------------------------------------------------------
Pure collection is a complex type that contains just one element with
'maxOccurs="unbounded"'.
---------------------------------------------------------------------------}
function IsPureCollection(const ComplexType: IXMLComplexTypeDef; var TypeName: DOMString;
var TypeNamespace: DOMString): Boolean; overload;
begin
Result := (ComplexType.ElementDefList.Count = 1) and
ComplexType.ElementDefList[0].IsRepeating;
if Result then
begin
TypeName := GetDataTypeName(ComplexType.ElementDefList[0]);
TypeNamespace := GetDataTypeNamespace(ComplexType.ElementDefList[0]);
end;
end;
{ ---------------------------------------------------------------------------
Pure collection is a complex type that contains just one element with
'maxOccurs="unbounded"'.
---------------------------------------------------------------------------}
function IsPureCollection(const WSDLType: IWSDLType): Boolean; overload;
begin
Result := False;
if (WSDLType.DataKind = wtClass) then
begin
if (Length(WSDLType.Members) = 1) and (pfUnbounded in WSDLType.Members[0].PartFlags) then
Result := True;
end;
end;
function FindDefaultNamespace(Node: IXMLNode): DOMString;
begin
Result := '';
while (Result = '') and Assigned(Node) do
begin
if (Node.HasAttribute(SXMLNS)) then
begin
Result := Node.Attributes[SXMLNS];
Break;
end;
Node := Node.ParentNode;
end;
end;
function GetNameOf(const Item: IXMLAttributeGroup): DOMString;
begin
if Item.HasAttribute(SRef) then
begin
Result := Item.Attributes[SRef];
if IsPrefixed(Result) then
Result := ExtractLocalName(Result);
Exit;
end;
Result := Item.Name;
end;
function GetNameOf(const Item: IXMLTypedSchemaItem): DOMString;
begin
{ Whenever there's a ref="xxxx", the logic in XMLSchema may go into
an endless loop (eventually stack overlflow) in trying to resolve
the ref; so we take the easy way out to avoid the crash }
if Item.HasAttribute(SRef) then
begin
Result := Item.Attributes[SRef];
if IsPrefixed(Result) then
Result := ExtractLocalName(Result);
Exit;
end;
Result := Item.Name;
end;
function GetNameOf(const Item: IXMLTypeDef; const DefaultName: DOMString): DOMString;
begin
try
Result := Item.Name;
except
Result := DefaultName;
end;
end;
function GetNamespaceOf(const Item: IXMLSimpleTypeDef): DOMString;
var
V: OleVariant;
begin
if IsKnownType(Item) then
Result := XMLSchema.SXMLSchemaURI_2001
else
begin
V := Item.SchemaDef.TargetNamespace;
if not VarIsNull(V) then
Result := V
else
Result := FindDefaultNamespace(Item);
end;
end;
function GetNamespaceOf(const Item: IXMLAttributeGroup): DOMString;
var
V: OleVariant;
begin
V := Item.SchemaDef.TargetNamespace;
if not VarIsNull(V) then
Result := V
else
Result := FindDefaultNamespace(Item);
end;
function GetNamespaceOf(const Item: IXMLElementDef): DOMString;
var
V: OleVariant;
begin
V := Item.SchemaDef.TargetNamespace;
if not VarIsNull(V) then
Result := V
else
Result := FindDefaultNamespace(Item);
end;
function GetNamespaceOf(const Item: IXMLComplexTypeDef): DOMString;
var
V: OleVariant;
begin
V := Item.SchemaDef.TargetNamespace;
if not VarIsNull(V) then
Result := V
else
Result := FindDefaultNamespace(Item);
end;
function GetNamespaceOf(const Item: IXMLSchemaItem): DOMString;
var
V: OleVariant;
begin
if Supports(Item, IXMLSimpleTypeDef) then
Result := GetNamespaceOf(Item as IXMLSimpleTypeDef)
else
begin
V := Item.SchemaDef.TargetNamespace;
if not VarIsNull(V) then
Result := V
else
Result := FindDefaultNamespace(Item);
end;
end;
function GetDataTypeSafely(const Item: IXMLTypedSchemaItem): IXMLTypeDef;
begin
Result := nil;
try
Result := Item.DataType;
except
on E: ESchemaParse do
begin
raise ESchemaParse.CreateFmt('Unable to resolve DataType of "%s"' + sLineBreak +
'Error ''%s''',
[Item.XML, E.Message]);
end;
end;
end;
function GetDataTypeTie(const Item: IXMLTypedSchemaItem): TDataTypeTie;
begin
if Item.HasAttribute(SType) then
begin
Result := dtType;
end
else if Item.HasAttribute(SRef) then
begin
Result := dtRef;
end
else
Result := dtUnknown;
end;
function GetDataTypeName(const Item: IXMLTypedSchemaItem): DOMString;
begin
case GetDataTypeTie(Item) of
dtType:
begin
Result := Item.Attributes[SType];
if IsPrefixed(Result) then
begin
Result := ExtractLocalName(Result);
end;
end;
dtRef:
begin
Result := Item.Attributes[SRef];
if IsPrefixed(Result) then
begin
Result := ExtractLocalName(Result);
end;
end;
end;
{ Last Resort }
if Result = '' then
Result := GetDataTypeSafely(Item).Name;
end;
function GetDataTypeNamespace(const Item: IXMLTypedSchemaItem): DOMString;
var
TypeName: DOMString;
ElementDef: IXMLElementDef;
begin
case GetDataTypeTie(Item) of
dtType:
begin
TypeName := Item.Attributes[SType];
if IsPrefixed(TypeName) then
begin
{ Namespace}
TypeName := ExtractPrefix(TypeName);
Result := Item.FindNamespaceURI(TypeName);
end;
end;
dtRef:
begin
TypeName := Item.Attributes[SRef];
if IsPrefixed(TypeName) then
begin
{ Namespace}
TypeName := ExtractPrefix(TypeName);
Result := Item.FindNamespaceURI(TypeName);
end
else
begin
Result := GetNamespaceOf(Item);
end;
end;
end;
{ Last Resort }
if Result = '' then
{$IFNDEF SAFE_DATATYPE_ACCESS}
Result := GetNamespaceOf(Item.DataType);
{$ELSE}
try
ElementDef := nil;
if Supports(Item, IXMLElementDef) then
begin
ElementDef := Item as IXMLElementDef;
end;
Result := GetNamespaceOf(GetDataTypeSafely(Item));
except
on E: ESchemaParse do
begin
if (ElementDef <> nil) then
Result := FindDefaultNamespace(item);
if Result = '' then
raise;
end;
end;
{$ENDIF}
end;
function HasRefAttr(const Item: IXMLTypedSchemaItem): Boolean;
begin
Result := Item.HasAttribute(SRef);
end;
function IsKnownType(const Item: IXMLSimpleTypeDef): Boolean;
begin
Result := Item.IsBuiltInType;
end;
type
TXMLSchemaGuide = class(TInterfacedObject, IXMLSchemaGuide)
FXMLVisitor: IXMLSchemaVisitor;
public
constructor Create(XMLVisitor: IXMLSchemaVisitor);
procedure HandleSchema(FileName: DOMString);
procedure ShowSchema(const SchemaDef: IXMLSchemaDef; const SchemaLoc: String;
const Tracker: IProcessedTracker;
const OuterTNS: DOMString); overload;
procedure Show(Items: IXMLElementGroups; ElementTypes: TElementTypes; Context: XMLVisitorContext); overload;
procedure Show(Items: IXMLAttributeGroups; Context: XMLVisitorContext); overload;
procedure Show(Items: IXMLAttributeDefs; Context: XMLVisitorContext); overload;
procedure Show(Items: IXMLElementDefs; ElementTypes: TElementTypes; CompositorId: Integer;
Context: XMLVisitorContext); overload;
procedure Show(Items: IXMLSimpleTypeDefs; Context: XMLVisitorContext); overload;
procedure Show(Items: IXMLComplexTypeDefs; Context: XMLVisitorContext); overload;
procedure Show(Item: IXMLElementCompositor; CompositorId: Integer; Context: XMLVisitorContext); overload;
procedure ShowAny(Item: IXMLNode; Context: XMLVisitorContext);
function Show(Item: IXMLAttributeGroup; Context: XMLVisitorContext): XMLVisitorContext; overload;
function Show(Item: IXMLElementGroup; ElementTypes: TElementTypes; Context: XMLVisitorContext): XMLVisitorContext; overload;
function Show(Item: IXMLComplexTypeDef; Context: XMLVisitorContext): XMLVisitorContext; overload;
function Show(Item: IXMLSimpleTypeDef; Context: XMLVisitorContext): XMLVisitorContext; overload;
function Show(Item: IXMLElementDef; ElementTypes: TElementTypes; CompositorId: Integer; Context: XMLVisitorContext): XMLVisitorContext; overload;
function Show(Item: IXMLAttributeDef; Context: XMLVisitorContext): XMLVisitorContext; overload;
end;
function VisitSchema(const SchemaDef: IXMLSchemaDef;
const SchemaLoc: String;
const Visitor: IXMLSchemaVisitor;
const Tracker: IProcessedTracker): Boolean;
var
Guide: IXMLSchemaGuide;
begin
Guide := TXMLSchemaGuide.Create(Visitor);
Guide.ShowSchema(SchemaDef, SchemaLoc, Tracker, '');
Result := True;
end;
function isHTTP(const Name: DOMString): boolean;
const
sHTTPPrefix = 'http://';
sHTTPsPrefix= 'https://';
begin
Result := SameText(Copy(Name, 1, Length(sHTTPPrefix)), sHTTPPrefix) or
SameText(Copy(Name, 1, Length(sHTTPsPrefix)),sHTTPsPrefix);
end;
{ Returns path of SchemaLoc relative to its Referer }
function GetRelativePath(const Referer, SchemaLoc: DOMString): DOMString;
const
sPathSep: WideChar = '/';
var
HTTPRef: Boolean;
Path: DOMString;
Len: Integer;
begin
if IsHTTP(SchemaLoc) then
begin
Result := SchemaLoc;
Exit;
end;
HTTPRef := IsHTTP(Referer);
if (HTTPRef) then
begin
Len := Length(Referer);
while (Len > 0) do
begin
if (Referer[Len] = sPathSep) then
begin
Path := Copy(Referer, 0, Len);
Result := Path + SchemaLoc;
Exit;
end;
Dec(Len);
end;
end;
if FileExists(SchemaLoc) then
begin
Result := SchemaLoc;
Path := ExpandFileName(SchemaLoc);
if Path <> '' then
Result := Path;
Exit;
end;
Path := ExtractFilePath(SchemaLoc);
if Path = '' then
begin
Path := ExtractFilePath(Referer);
if Path <> '' then
begin
Result := ExpandFileName(Path + SchemaLoc);
Exit;
end;
end;
Result := SchemaLoc;
end;
{ TXMLSchemaGuide }
constructor TXMLSchemaGuide.Create(XMLVisitor: IXMLSchemaVisitor);
begin
FXMLVisitor := XMLVisitor;
end;
procedure TXMLSchemaGuide.HandleSchema(FileName: DOMString);
begin
end;
procedure TXMLSchemaGuide.ShowSchema(const SchemaDef: IXMLSchemaDef;
const SchemaLoc: String;
const Tracker: IProcessedTracker;
const OuterTNS: DOMString);
var
I: Integer;
UpdatedSchemaLoc: String;
Context: XMLVisitorContext;
TargetNS: DOMString;
begin
if Tracker.ProcessedAlready(SchemaLoc) then
begin
FXMLVisitor.Skipping(SchemaLoc);
Exit;
end;
Tracker.AddProcessed(SchemaLoc);
{ For included items, we patch the targetnamespace to that of the outer
that included the file unless a target namespace is already set }
if not VarIsNull(SchemaDef.TargetNamespace) then
TargetNS := SchemaDef.TargetNamespace
else
begin
if OuterTNS <> '' then
begin
SchemaDef.SetTargetNamespace(OuterTNS, 'tns');
if not VarIsNull(SchemaDef.TargetNamespace) then
TargetNS := SchemaDef.TargetNamespace
end;
end;
Context := FXMLVisitor.Start(SchemaDef, SchemaLoc);
try
// Handle <include ... >
try
for I := 0 to SchemaDef.SchemaIncludes.Count - 1 do
begin
UpdatedSchemaLoc := SchemaDef.SchemaIncludes[I].SchemaLocation;
if (Length(UpdatedSchemaLoc) > 0) then
begin
UpdatedSchemaLoc := GetRelativePath(SchemaLoc, UpdatedSchemaLoc);
SchemaDef.SchemaIncludes[i].SchemaLocation := UpdatedSchemaLoc;
try
ShowSchema(SchemaDef.SchemaIncludes[I].SchemaRef, UpdatedSchemaLoc, Tracker, TargetNS);
except
on E:Exception do
begin
FXMLVisitor.Error(UpdatedSchemaLoc, E.Message);
end;
end;
end;
end;
// Handle <import ...>
for I := 0 to SchemaDef.SchemaImports.Count - 1 do
begin
UpdatedSchemaLoc := SchemaDef.SchemaImports[I].SchemaLocation;
if (Length(UpdatedSchemaLoc) > 0) then
begin
UpdatedSchemaLoc := GetRelativePath(SchemaLoc, UpdatedSchemaLoc);
SchemaDef.SchemaImports[i].SchemaLocation := UpdatedSchemaLoc;
try
{ NOTE: Accessing the SchemaRef causes the schema to be loaded }
ShowSchema(SchemaDef.SchemaImports[I].SchemaRef, UpdatedSchemaLoc, Tracker, '');
except
on E:Exception do
begin
FXMLVisitor.Error(UpdatedSchemaLoc, E.Message);
end;
end;
end;
end;
finally
// Now handle our types
Show(SchemaDef.ElementGroups, [etGlobal, etElementGroup], Context);
Show(SchemaDef.AttributeGroups, Context);
Show(SchemaDef.ComplexTypes, Context);
Show(SchemaDef.SimpleTypes, Context);
Show(SchemaDef.ElementDefs, [etGlobal], -1, Context);
Show(SchemaDef.AttributeDefs, Context);
end;
finally
FXMLVisitor.Done(SchemaLoc);
end;
end;
procedure TXMLSchemaGuide.Show(Items: IXMLElementGroups;
ElementTypes: TElementTypes;
Context: XMLVisitorContext);
var
I: Integer;
Item: IXMLElementGroup;
begin
for I := 0 to Items.Count-1 do
begin
Item := Items[I];
Show(Item, ElementTypes, Context);
end;
end;
procedure TXMLSchemaGuide.Show(Items: IXMLAttributeGroups;
Context: XMLVisitorContext);
var
I: Integer;
Item: IXMLAttributeGroup;
begin
for I := 0 to Items.Count-1 do
begin
Item := Items[I];
Show(Item, Context);
end;
end;
procedure TXMLSchemaGuide.Show(Items: IXMLSimpleTypeDefs; Context: XMLVisitorContext);
var
I: Integer;
begin
for I := 0 to Items.Count-1 do
begin
Show(Items[I], Context);
end;
end;
procedure TXMLSchemaGuide.Show(Items: IXMLComplexTypeDefs; Context: XMLVisitorContext);
var
I: Integer;
Item: IXMLComplexTypeDef;
begin
for I := 0 to Items.Count-1 do
begin
Item := Items[I];
Show(Item, Context);
end;
end;
procedure TXMLSchemaGuide.Show(Items: IXMLAttributeDefs; Context: XMLVisitorContext);
var
I: Integer;
begin
for I := 0 to Items.Count-1 do
begin
Show(Items[I], Context);
end;
end;
procedure TXMLSchemaGuide.Show(Items: IXMLElementDefs;
ElementTypes: TElementTypes;
CompositorId: Integer;
Context: XMLVisitorContext);
var
I: Integer;
Item: IXMLElementDef;
begin
for I := 0 to Items.Count-1 do
begin
Item := Items[I];
Show(Item, ElementTypes, CompositorId, Context);
end;
end;
procedure TXMLSchemaGuide.Show(Item: IXMLElementCompositor;
CompositorId: Integer;
Context: XMLVisitorContext);
function ElementTypeFromCompositorType(const CT: TCompositorType): TElementType;
begin
Result := etGlobal;
case CT of
ctAll: Result := etAll;
ctChoice: Result := etChoice;
ctSequence: Result := etSequence;
end;
end;
function GetAnyNode(const Item: IXMLElementCompositor): IXMLNode;
begin
Result := Item.ChildNodes.FindNode(SAny, XMLSchemaNamespace);
end;
var
I, Count: Integer;
Nodes: array of IXMLNode;
Processed: array of Boolean;
Node: IXMLNode;
ElemTypes: TElementTypes;
begin
ElemTypes := [ElementTypeFromCompositorType(Item.CompositorType)];
if (Item.Compositors.Count < 1) and (Item.ElementGroups.Count < 1) then
begin
Show(Item.ElementDefs, ElemTypes, CompositorId, Context);
end
else
begin
{ Here we might have <element> and <compositorNodes> mixed - so we have to
walk down and make sure we go in Depth-first order }
Count := Item.ChildNodes.Count;
SetLength(Nodes, Count);
SetLength(Processed, Count);
for I := 0 to Count-1 do
Nodes[I] := Item.ChildNodes[I];
for I := 0 to Length(Nodes)-1 do
begin
if Supports(Nodes[I], IXMLElementCompositor) then
begin
Show(Nodes[I] as IXMLElementCompositor, CompositorId, Context);
Processed[I] := True;
end
else if Supports(Nodes[I], IXMLElementGroup) then
begin
Show(Nodes[I] as IXMLElementGroup, ElemTypes + [etElementGroup], Context);
Processed[I] := True;
end
else if Supports(Nodes[I], IXMLElementDef) then
begin
Show(Nodes[I] as IXMLElementDef, ElemTypes, CompositorId, Context);
Processed[I] := True;
end
else
Processed[I] := False;
end;
end;
Node := GetAnyNode(Item);
if (Node <> nil) then
ShowAny(Node, Context);
end;
{$DEFINE USE_COMPOSITOR_NODE}
//{$DEFINE WALK_COMPLEXTYPE_NODES}
function TXMLSchemaGuide.Show(Item: IXMLComplexTypeDef; Context: XMLVisitorContext): XMLVisitorContext;
function ElementTypeFromContentModel(CM: TContentModel): TElementType;
begin
Result := etGlobal;
// cmALL, cmChoice, cmSequence, cmGroupRef, cmEmpty
case CM of
cmAll: Result := etAll;
cmChoice: Result := etChoice;
cmSequence: Result := etSequence;
cmGroupRef, cmEmpty: ;
else
Assert(False, 'Unexpected content model');
end;
end;
{$IFDEF WALK_COMPLEXTYPE_NODES}
var
I, Count: Integer;
Node: IXMLNode;
XMLElementCompositor: IXMLElementCompositor;
XMLAttribute: IXMLAttributeDef;
XMLAttributeGroup: IXMLAttributeGroup;
XMLBaseTypeIndicator: IXMLBaseTypeIndicator;
{$ENDIF}
begin
Result := FXMLVisitor.Visit(Item, Context);
{$IFDEF WALK_COMPLEXTYPE_NODES}
Count := Item.ChildNodes.Count;
for I := 0 to Count-1 do
begin
Node := Item.ChildNodes[I];
if Supports(Node, IXMLElementCompositor, XMLElementCompositor) then
Show(XMLelementCompositor, I, Result)
else if Supports(Node, IXMLAttributeDef, XMLAttribute) then
Show(XMLAttribute, Result)
else if Item.ContentModel
end;
{$ELSE}
Show(Item.AttributeDefs, Result);
Show(Item.AttributeGroups, Result);
{$IFDEF USE_COMPOSITOR_NODE}
Show(Item.CompositorNode, 0, Result);
{$ELSE}
Show(Item.ElementDefs, ElementTypeFromContentModel(Item.ContentModel), Result);
{$ENDIF}
{$ENDIF}
end;
function TXMLSchemaGuide.Show(Item: IXMLAttributeGroup; Context: XMLVisitorContext): XMLVisitorContext;
begin
Result := FXMLVisitor.Visit(Item, Context);
{ XMLSchema's TXMLAttributeGroup.GetAttributeDefs will follow 'ref'
something we do not want - so we check first }
if not Item.HasAttribute(SRef) then
begin
Show(Item.AttributeDefs, Result);
end;
end;
function TXMLSchemaGuide.Show(Item: IXMLElementGroup; ElementTypes: TElementTypes; Context: XMLVisitorContext): XMLVisitorContext;
begin
Result := FXMLVisitor.Visit(Item, Context);
Show(Item.ElementDefs, ElementTypes + [etElementGroup], 0, Result);
end;
function TXMLSchemaGuide.Show(Item: IXMLSimpleTypeDef; Context: XMLVisitorContext): XMLVisitorContext;
begin
Result := FXMLVisitor.Visit(Item, Context);
end;
function TXMLSchemaGuide.Show(Item: IXMLElementDef; ElementTypes: TElementTypes;
CompositorId: Integer; Context: XMLVisitorContext): XMLVisitorContext;
begin
Result := FXMLVisitor.Visit(Item, ElementTypes, CompositorId, Context);
if ElementDefinedInline(Item) then
begin
if Item.DataType.IsComplex then
Show(Item.DataType as IXMLComplexTypeDef, Result)
else
Show(Item.DataType as IXMLSimpleTypeDef, Result);
end
end;
function TXMLSchemaGuide.Show(Item: IXMLAttributeDef; Context: XMLVisitorContext): XMLVisitorContext;
begin
Result := FXMLVisitor.Visit(Item, Context);
end;
procedure TXMLSchemaGuide.ShowAny(Item: IXMLNode; Context: XMLVisitorContext);
begin
FXMLVisitor.VisitAny(Item, Context);
end;
end.
|
unit Dm.Acesso;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TDmAcesso = class(TDataModule)
QryPais: TFDQuery;
QryTatica: TFDQuery;
QryTecnico: TFDQuery;
QryJogador: TFDQuery;
QryClube: TFDQuery;
QryPaisPAI_CODIGO: TIntegerField;
QryPaisPAI_NOME: TStringField;
QryTaticaTAT_CODIGO: TIntegerField;
QryTaticaTAT_DESCRICAO: TStringField;
QryTaticaTAT_ESQUEMA: TStringField;
QryTecnicoTEC_CODIGO: TIntegerField;
QryTecnicoPAI_CODIGO: TIntegerField;
QryTecnicoTEC_NOME: TStringField;
QryJogadorCLB_CODIGO: TIntegerField;
QryJogadorJOG_NUMERO: TIntegerField;
QryJogadorPAI_CODIGO: TIntegerField;
QryJogadorJOG_NOME: TStringField;
QryJogadorJOG_POSICAO: TStringField;
QryJogadorJOG_IDADE: TIntegerField;
QryJogadorJOG_LADO: TStringField;
QryJogadorJOG_TITULAR: TStringField;
QryJogadorJOG_CARACTERISTICA: TStringField;
QryClubeCLB_CODIGO: TIntegerField;
QryClubeTAT_CODIGO: TIntegerField;
QryClubeTEC_CODIGO: TIntegerField;
QryClubePAI_CODIGO: TIntegerField;
QryClubeCLB_NOME: TStringField;
QryClubeCLB_ESTADIO: TStringField;
QryClubeCLB_DTFUNDACAO: TDateField;
DsMestreClube: TDataSource;
QryClubeTAT_NOME: TStringField;
QryClubeTEC_NOME: TStringField;
QryClubePAI_NOME: TStringField;
QryTecnicoPAI_NOME: TStringField;
procedure QryJogadorAfterInsert(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DmAcesso: TDmAcesso;
implementation
uses
Dm.conexao;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDmAcesso.QryJogadorAfterInsert(DataSet: TDataSet);
begin
QryJogadorCLB_CODIGO.AsInteger := QryClubeCLB_CODIGO.AsInteger;
end;
end.
|
unit Model.Base.Impl;
interface
uses
System.Classes, Model.Base.Intf;
type
TModelBase = class(TInterfacedObject, IModelBase)
private
FGUID: TGUID;
public
constructor Create;
function GetId: TGUID;
procedure DefinirID(const AID: TGUID);
end;
implementation
uses
System.SysUtils;
constructor TModelBase.Create;
begin
CreateGUID(FGUID)
end;
procedure TModelBase.DefinirID(const AID: TGUID);
begin
FGUID := AID;
end;
function TModelBase.GetId: TGUID;
begin
Result := FGUID;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSound<p>
Base classes and interface for GLScene Sound System<p>
<b>History : </b><font size=-1><ul>
<li>24/04/11 - Yar - Bugfixed TGLSoundSample.Assign (thanks to Anonymous)
<li>06/06/10 - Yar - Fixed warnings
<li>06/05/09 - DanB - Split TGLSMWaveOut to GLSMWaveOut.pas, to remove windows dependancy
<li>16/10/08 - UweR - Compatibility fix for Delphi 2009
<li>22/07/02 - EG - SetMute/SetPause fix (Sternas Stefanos)
<li>02/07/02 - EG - Persistence fix (MP3 / Sternas Stefanos)
<li>05/03/02 - EG - TGLBSoundEmitter.Loaded
<li>27/02/02 - EG - Added 3D Factors, special listener-is-camera support
<li>13/01/01 - EG - Added CPUUsagePercent
<li>09/06/00 - EG - Various enhancements
<li>04/06/00 - EG - Creation
</ul></font>
}
unit GLSound;
interface
uses
System.Classes, System.SysUtils, System.Types,
GLSoundFileObjects, GLScene, XCollection, GLVectorGeometry,
GLCadencer, GLBaseClasses, GLCrossPlatform, GLUtils;
{$I GLScene.inc}
type
// TGLSoundSample
//
{: Stores a single PCM coded sound sample. }
TGLSoundSample = class(TCollectionItem)
private
{ Private Declarations }
FName: string;
FData: TGLSoundFile;
FTag: Integer;
protected
{ Protected Declarations }
procedure DefineProperties(Filer: TFiler); override;
procedure ReadData(Stream: TStream); virtual;
procedure WriteData(Stream: TStream); virtual;
function GetDisplayName: string; override;
procedure SetData(const val: TGLSoundFile);
public
{ Public Declarations }
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromFile(const fileName: string);
procedure PlayOnWaveOut;
function Sampling: TGLSoundSampling;
function LengthInBytes: Integer;
function LengthInSamples: Integer;
function LengthInSec: Single;
//: This Tag is reserved for sound manager use only
property ManagerTag: Integer read FTag write FTag;
published
{ Published Declarations }
property Name: string read FName write FName;
property Data: TGLSoundFile read FData write SetData stored False;
end;
// TGLSoundSamples
//
TGLSoundSamples = class(TCollection)
protected
{ Protected Declarations }
owner: TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index: Integer; const val: TGLSoundSample);
function GetItems(index: Integer): TGLSoundSample;
public
{ Public Declarations }
constructor Create(AOwner: TComponent);
function Add: TGLSoundSample;
function FindItemID(ID: Integer): TGLSoundSample;
property Items[index: Integer]: TGLSoundSample read GetItems write SetItems;
default;
function GetByName(const aName: string): TGLSoundSample;
function AddFile(const fileName: string; const sampleName: string = ''):
TGLSoundSample;
end;
// TGLSoundLibrary
//
TGLSoundLibrary = class(TComponent)
private
{ Private Declarations }
FSamples: TGLSoundSamples;
protected
{ Protected Declarations }
procedure SetSamples(const val: TGLSoundSamples);
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
property Samples: TGLSoundSamples read FSamples write SetSamples;
end;
// TGLSoundSource
//
TGLSoundSourceChange = (sscTransformation, sscSample, sscStatus);
TGLSoundSourceChanges = set of TGLSoundSourceChange;
TGLBSoundEmitter = class;
// TGLBaseSoundSource
//
{: Base class for origin of sound playback. }
TGLBaseSoundSource = class(TCollectionItem)
private
{ Private Declarations }
FBehaviourToNotify: TGLBSoundEmitter;
// private only, NOT persistent, not assigned
FPriority: Integer;
FOrigin: TGLBaseSceneObject; // NOT persistent
FVolume: Single;
FMinDistance, FMaxDistance: Single;
FInsideConeAngle, FOutsideConeAngle: Single;
FConeOutsideVolume: Single;
FSoundLibraryName: string; // used for persistence
FSoundLibrary: TGLSoundLibrary; // persistence via name
FSoundName: string;
FMute: Boolean;
FPause: Boolean;
FChanges: TGLSoundSourceChanges; // NOT persistent, not assigned
FNbLoops: Integer;
FTag: PtrUInt; // NOT persistent, not assigned
FFrequency: Integer;
protected
{ Protected Declarations }
procedure WriteToFiler(writer: TWriter);
procedure ReadFromFiler(reader: TReader);
function GetDisplayName: string; override;
procedure SetPriority(const val: Integer);
procedure SetOrigin(const val: TGLBaseSceneObject);
procedure SetVolume(const val: Single);
procedure SetMinDistance(const val: Single);
procedure SetMaxDistance(const val: Single);
procedure SetInsideConeAngle(const val: Single);
procedure SetOutsideConeAngle(const val: Single);
procedure SetConeOutsideVolume(const val: Single);
function GetSoundLibrary: TGLSoundLibrary;
procedure SetSoundLibrary(const val: TGLSoundLibrary);
procedure SetSoundName(const val: string);
procedure SetMute(const val: Boolean);
procedure SetPause(const val: Boolean);
procedure SetNbLoops(const val: Integer);
procedure SetFrequency(const val: Integer);
public
{ Public Declarations }
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property Changes: TGLSoundSourceChanges read FChanges;
function Sample: TGLSoundSample;
//: This Tag is reserved for sound manager use only
property ManagerTag: PtrUInt read FTag write FTag;
{: Origin object for the sound sources.<p>
Absolute object position/orientation are taken into account, the
object's TGLBInertia is considered if any.<p>
If origin is nil, the source is assumed to be static at the origin.<p>
<b>Note :</b> since TCollectionItem do not support the "Notification"
scheme, it is up to the Origin object to take care of updating this
property prior to release/destruction. }
property Origin: TGLBaseSceneObject read FOrigin write SetOrigin;
published
{ Published Declarations }
property SoundLibrary: TGLSoundLibrary read GetSoundLibrary write
SetSoundLibrary;
property SoundName: string read FSoundName write SetSoundName;
{: Volume of the source, [0.0; 1.0] range }
property Volume: Single read FVolume write SetVolume;
{: Nb of playing loops. }
property NbLoops: Integer read FNbLoops write SetNbLoops default 1;
property Mute: Boolean read FMute write SetMute default False;
property Pause: Boolean read FPause write SetPause default False;
{: Sound source priority, the higher the better.<p>
When maximum number of sound sources is reached, only the sources
with the highest priority will continue to play, however, even
non-playing sources should be tracked by the manager, thus allowing
an "unlimited" amount of sources from the application point of view. }
property Priority: Integer read FPriority write SetPriority default 0;
{: Min distance before spatial attenuation occurs.<p>
1.0 by default }
property MinDistance: Single read FMinDistance write SetMinDistance;
{: Max distance, if source is further away, it will not be heard.<p>
100.0 by default }
property MaxDistance: Single read FMaxDistance write SetMaxDistance;
{: Inside cone angle, [0°; 360°].<p>
Sound volume is maximal within this cone.<p>
See DirectX SDK for details. }
property InsideConeAngle: Single read FInsideConeAngle write
SetInsideConeAngle;
{: Outside cone angle, [0°; 360°].<p>
Between inside and outside cone, sound volume decreases between max
and cone outside volume.<p>
See DirectX SDK for details. }
property OutsideConeAngle: Single read FOutsideConeAngle write
SetOutsideConeAngle;
{: Cone outside volume, [0.0; 1.0] range.<p>
See DirectX SDK for details. }
property ConeOutsideVolume: Single read FConeOutsideVolume write
SetConeOutsideVolume;
{: Sample custom playback frequency.<p>
Values null or negative are interpreted as 'default frequency'. }
property Frequency: Integer read FFrequency write SetFrequency default -1;
end;
// TGLSoundSource
//
{: Origin of sound playback.<p>
Just publishes the 'Origin' property.<p>
Note that the "orientation" is the the source's Direction, ie. the "Z"
vector. }
TGLSoundSource = class(TGLBaseSoundSource)
public
{ Public Declarations }
destructor Destroy; override;
published
{ Published Declarations }
property Origin;
end;
// TGLSoundSources
//
TGLSoundSources = class(TCollection)
protected
{ Protected Declarations }
owner: TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index: Integer; const val: TGLSoundSource);
function GetItems(index: Integer): TGLSoundSource;
function Add: TGLSoundSource;
function FindItemID(ID: Integer): TGLSoundSource;
public
{ Public Declarations }
constructor Create(AOwner: TComponent);
property Items[index: Integer]: TGLSoundSource read GetItems write SetItems;
default;
end;
// TGLSoundEnvironment
//
{: EAX standard sound environments. }
TGLSoundEnvironment = (seDefault, sePaddedCell, seRoom, seBathroom,
seLivingRoom, seStoneroom, seAuditorium,
seConcertHall, seCave, seArena, seHangar,
seCarpetedHallway, seHallway, seStoneCorridor,
seAlley, seForest, seCity, seMountains, seQuarry,
sePlain, seParkingLot, seSewerPipe, seUnderWater,
seDrugged, seDizzy, sePsychotic);
// TGLSoundManager
//
{: Base class for sound manager components.<p>
The sound manager component is the interface to a low-level audio API
(like DirectSound), there can only be one active manager at any time
(this class takes care of this).<p>
Subclass should override the DoActivate and DoDeActivate protected methods
to "initialize/unitialize" their sound layer, actual data releases should
occur in destructor however. }
TGLSoundManager = class(TGLCadenceAbleComponent)
private
{ Private Declarations }
FActive: Boolean;
FMute: Boolean;
FPause: Boolean;
FMasterVolume: Single;
FListener: TGLBaseSceneObject;
FLastListenerPosition: TVector;
FSources: TGLSoundSources;
FMaxChannels: Integer;
FOutputFrequency: Integer;
FUpdateFrequency: Single;
FDistanceFactor: Single;
FRollOffFactor: Single;
FDopplerFactor: Single;
FSoundEnvironment: TGLSoundEnvironment;
FLastUpdateTime, FLastDeltaTime: Single;
// last time UpdateSources was fired, not persistent
FCadencer: TGLCadencer;
procedure SetActive(const val: Boolean);
procedure SetMute(const val: Boolean);
procedure SetPause(const val: Boolean);
procedure WriteDoppler(writer: TWriter);
procedure ReadDoppler(reader: TReader);
protected
{ Protected Declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure SetSources(const val: TGLSoundSources);
procedure SetMasterVolume(const val: Single);
procedure SetListener(const val: TGLBaseSceneObject);
procedure SetMaxChannels(const val: Integer);
procedure SetOutputFrequency(const val: Integer);
procedure SetUpdateFrequency(const val: Single);
function StoreUpdateFrequency: Boolean;
procedure SetCadencer(const val: TGLCadencer);
procedure SetDistanceFactor(const val: Single);
function StoreDistanceFactor: Boolean;
procedure SetRollOffFactor(const val: Single);
function StoreRollOffFactor: Boolean;
procedure SetDopplerFactor(const val: Single);
procedure SetSoundEnvironment(const val: TGLSoundEnvironment);
procedure Loaded; override;
procedure DefineProperties(Filer: TFiler); override;
procedure ListenerCoordinates(var position, velocity, direction, up:
TVector);
function DoActivate: Boolean; dynamic;
//: Invoked AFTER all sources have been stopped
procedure DoDeActivate; dynamic;
{: Effect mute of all sounds.<p>
Default implementation call MuteSource for all non-muted sources
with "True" as parameter. }
function DoMute: Boolean; dynamic;
{: Effect un-mute of all sounds.<p>
Default implementation call MuteSource for all non-muted sources
with "False" as parameter. }
procedure DoUnMute; dynamic;
{: Effect pause of all sounds.<p>
Default implementation call PauseSource for all non-paused sources
with "True" as parameter. }
function DoPause: Boolean; dynamic;
{: Effect un-pause of all sounds.<p>
Default implementation call PauseSource for all non-paused sources
with "True" as parameter. }
procedure DoUnPause; dynamic;
procedure NotifyMasterVolumeChange; dynamic;
procedure Notify3DFactorsChanged; dynamic;
procedure NotifyEnvironmentChanged; dynamic;
//: Called when a source will be freed
procedure KillSource(aSource: TGLBaseSoundSource); virtual;
{: Request to update source's data in low-level sound API.<p>
Default implementation just clears the "Changes" flags. }
procedure UpdateSource(aSource: TGLBaseSoundSource); virtual;
procedure MuteSource(aSource: TGLBaseSoundSource; muted: Boolean); virtual;
procedure PauseSource(aSource: TGLBaseSoundSource; paused: Boolean);
virtual;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{: Manual request to update all sources to reflect changes.<p>
Default implementation invokes UpdateSource for all known sources. }
procedure UpdateSources; virtual;
{: Stop and free all sources. }
procedure StopAllSources;
{: Progress notification for time synchronization.<p>
This method will call UpdateSources depending on the last time
it was performed and the value of the UpdateFrequency property. }
procedure DoProgress(const progressTime: TProgressTimes); override;
{: Sound manager API reported CPU Usage.<p>
Returns -1 when unsupported. }
function CPUUsagePercent: Single; virtual;
{: True if EAX is supported. }
function EAXSupported: Boolean; dynamic;
published
{ Published Declarations }
{: Activation/deactivation of the low-level sound API }
property Active: Boolean read FActive write SetActive default False;
{: Maximum number of sound output channels.<p>
While some drivers will just ignore this value, others cannot
dynamically adjust the maximum number of channels (you need to
de-activate and re-activate the manager for this property to be
taken into account). }
property MaxChannels: Integer read FMaxChannels write SetMaxChannels default
8;
{: Sound output mixing frequency.<p>
Commonly used values ar 11025, 22050 and 44100.<p>
Note that most driver cannot dynamically adjust the output frequency
(you need to de-ativate and re-activate the manager for this property
to be taken into account). }
property OutputFrequency: Integer read FOutputFrequency write
SetOutputFrequency default 44100;
{: Request to mute all sounds.<p>
All sound requests should be handled as if sound is unmuted though,
however drivers should try to take a CPU advantage of mute over
MasterVolume=0 }
property Mute: Boolean read FMute write SetMute default False;
{: Request to pause all sound, sound output should be muted too.<p>
When unpausing, all sound should resume at the point they were paused. }
property Pause: Boolean read FPause write SetPause default False;
{: Master Volume adjustement in the [0.0; 1.0] range.<p>
Driver should take care of properly clamping the master volume. }
property MasterVolume: Single read FMasterVolume write SetMasterVolume;
{: Scene object that materializes the listener.<p>
The sceneobject's AbsolutePosition and orientation are used to define
the listener coordinates, velocity is automatically calculated
(if you're using DoProgress or connected the manager to a cadencer).<p>
If this property is nil, the listener is assumed to be static at
the NullPoint coordinate, facing Z axis, with up being Y (ie. the
default GLScene orientation). }
property Listener: TGLBaseSceneObject read FListener write SetListener;
{: Currently active and playing sound sources. }
property Sources: TGLSoundSources read FSources write SetSources;
{: Update frequency for time-based control (DoProgress).<p>
Default value is 10 Hz (frequency is clamped in the 1Hz-60Hz range). }
property UpdateFrequency: Single read FUpdateFrequency write
SetUpdateFrequency stored StoreUpdateFrequency;
{: Cadencer for time-based control.<p> }
property Cadencer: TGLCadencer read FCadencer write SetCadencer;
{: Engine relative distance factor, compared to 1.0 meters.<p>
Equates to 'how many units per meter' your engine has. }
property DistanceFactor: Single read FDistanceFactor write SetDistanceFactor
stored StoreDistanceFactor;
{: Sets the global attenuation rolloff factor.<p>
Normally volume for a sample will scale at 1 / distance.
This gives a logarithmic attenuation of volume as the source gets
further away (or closer).<br>
Setting this value makes the sound drop off faster or slower.
The higher the value, the faster volume will fall off. }
property RollOffFactor: Single read FRollOffFactor write SetRollOffFactor
stored StoreRollOffFactor;
{: Engine relative Doppler factor, compared to 1.0 meters.<p>
Equates to 'how many units per meter' your engine has. }
property DopplerFactor: Single read FDopplerFactor write SetDopplerFactor
stored False;
{: Sound environment (requires EAX compatible soundboard). }
property Environment: TGLSoundEnvironment read FSoundEnvironment write
SetSoundEnvironment default seDefault;
end;
// TGLBSoundEmitter
//
{: A sound emitter behaviour, plug it on any object to make it noisy.<p>
This behaviour is just an interface to a TGLSoundSource, for editing
convenience. }
TGLBSoundEmitter = class(TGLBehaviour)
private
{ Private Declarations }
FPlaying: Boolean; // used at design-time ONLY
FSource: TGLBaseSoundSource;
FPlayingSource: TGLSoundSource;
protected
{ Protected Declarations }
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
procedure Loaded; override;
procedure SetSource(const val: TGLBaseSoundSource);
procedure SetPlaying(const val: Boolean);
function GetPlaying: Boolean;
procedure NotifySourceDestruction(aSource: TGLSoundSource);
public
{ Public Declarations }
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function FriendlyName: string; override;
class function FriendlyDescription: string; override;
class function UniqueItem: Boolean; override;
procedure DoProgress(const progressTime: TProgressTimes); override;
property PlayingSource: TGLSoundSource read FPlayingSource;
published
{ Published Declarations }
property Source: TGLBaseSoundSource read FSource write SetSource;
property Playing: Boolean read GetPlaying write SetPlaying default False;
end;
function ActiveSoundManager: TGLSoundManager;
function GetSoundLibraryByName(const aName: string): TGLSoundLibrary;
function GetOrCreateSoundEmitter(behaviours: TGLBehaviours): TGLBSoundEmitter;
overload;
function GetOrCreateSoundEmitter(obj: TGLBaseSceneObject): TGLBSoundEmitter;
overload;
var
// If this variable is true, errors in GLSM may be displayed to the user
vVerboseGLSMErrors: Boolean = True;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
var
vActiveSoundManager: TGLSoundManager;
vSoundLibraries: TList;
// ActiveSoundManager
//
function ActiveSoundManager: TGLSoundManager;
begin
Result := vActiveSoundManager;
end;
// GetSoundLibraryByName
//
function GetSoundLibraryByName(const aName: string): TGLSoundLibrary;
var
i: Integer;
begin
Result := nil;
if Assigned(vSoundLibraries) then
for i := 0 to vSoundLibraries.Count - 1 do
if TGLSoundLibrary(vSoundLibraries[i]).Name = aName then
begin
Result := TGLSoundLibrary(vSoundLibraries[i]);
Break;
end;
end;
// GetOrCreateSoundEmitter (TGLBehaviours)
//
function GetOrCreateSoundEmitter(behaviours: TGLBehaviours): TGLBSoundEmitter;
var
i: Integer;
begin
i := behaviours.IndexOfClass(TGLBSoundEmitter);
if i >= 0 then
Result := TGLBSoundEmitter(behaviours[i])
else
Result := TGLBSoundEmitter.Create(behaviours);
end;
// GetOrCreateSoundEmitter (TGLBaseSceneObject)
//
function GetOrCreateSoundEmitter(obj: TGLBaseSceneObject): TGLBSoundEmitter;
begin
Result := GetOrCreateSoundEmitter(obj.Behaviours);
end;
// ------------------
// ------------------ TGLSoundSample ------------------
// ------------------
// Create
//
constructor TGLSoundSample.Create(Collection: TCollection);
begin
inherited Create(Collection);
end;
// Destroy
//
destructor TGLSoundSample.Destroy;
begin
FData.Free;
inherited Destroy;
end;
// Assign
//
procedure TGLSoundSample.Assign(Source: TPersistent);
begin
if Source is TGLSoundSample then
begin
FName := TGLSoundSample(Source).Name;
FData.Free;
FData := TGLSoundFile(TGLSoundSample(Source).Data.CreateCopy(Self));
end
else
inherited Assign(Source); // Assign error
end;
// DefineProperties
//
procedure TGLSoundSample.DefineProperties(Filer: TFiler);
begin
Filer.DefineBinaryProperty('BinData', ReadData, WriteData, Assigned(FData));
end;
// ReadData
//
procedure TGLSoundSample.ReadData(Stream: TStream);
var
n: Integer;
clName: AnsiString;
begin
with Stream do
begin
Read(n, SizeOf(Integer));
SetLength(clName, n);
if n > 0 then
Read(clName[1], n);
FData := TGLSoundFileClass(FindClass(string(clName))).Create(Self);
FData.LoadFromStream(Stream);
end;
end;
// WriteData
//
procedure TGLSoundSample.WriteData(Stream: TStream);
var
n: Integer;
buf: AnsiString;
begin
with Stream do
begin
n := Length(FData.ClassName);
Write(n, SizeOf(Integer));
buf := AnsiString(FData.ClassName);
if n > 0 then
Write(buf[1], n);
FData.SaveToStream(Stream);
end;
end;
// GetDisplayName
//
function TGLSoundSample.GetDisplayName: string;
var
s: string;
begin
if Assigned(FData) then
begin
if Data.Sampling.NbChannels > 1 then
s := 's'
else
s := '';
Result := Format('%s (%d Hz, %d bits, %d channel%s, %.2f sec)',
[Name, Data.Sampling.Frequency,
Data.Sampling.BitsPerSample,
Data.Sampling.NbChannels, s, LengthInSec])
end
else
Result := Format('%s (empty)', [Name]);
end;
// LoadFromFile
//
procedure TGLSoundSample.LoadFromFile(const fileName: string);
var
sfc: TGLSoundFileClass;
begin
FData.Free;
sfc := GetGLSoundFileFormats.FindExt(ExtractFileExt(fileName));
if Assigned(sfc) then
begin
FData := sfc.Create(Self);
FData.LoadFromFile(fileName);
end
else
FData := nil;
Assert(Data <> nil, 'Could not load ' + fileName +
', make sure you include the unit required to load this format in your uses clause.');
Name := ExtractFileName(fileName);
end;
// PlayOnWaveOut
//
procedure TGLSoundSample.PlayOnWaveOut;
begin
if Assigned(FData) then
FData.PlayOnWaveOut;
end;
// TGLSoundSample
//
function TGLSoundSample.Sampling: TGLSoundSampling;
begin
if Assigned(FData) then
Result := FData.Sampling
else
Result := nil;
end;
// LengthInBytes
//
function TGLSoundSample.LengthInBytes: Integer;
begin
if Assigned(FData) then
Result := FData.LengthInBytes
else
Result := 0;
end;
// LengthInSamples
//
function TGLSoundSample.LengthInSamples: Integer;
begin
if Assigned(FData) then
Result := FData.LengthInSamples
else
Result := 0;
end;
// LengthInSec
//
function TGLSoundSample.LengthInSec: Single;
begin
if Assigned(FData) then
Result := FData.LengthInSec
else
Result := 0;
end;
// SetData
//
procedure TGLSoundSample.SetData(const val: TGLSoundFile);
begin
FData.Free;
if Assigned(val) then
FData := TGLSoundFile(val.CreateCopy(Self))
else
FData := nil;
end;
// ------------------
// ------------------ TGLSoundSamples ------------------
// ------------------
constructor TGLSoundSamples.Create(AOwner: TComponent);
begin
Owner := AOwner;
inherited Create(TGLSoundSample);
end;
function TGLSoundSamples.GetOwner: TPersistent;
begin
Result := Owner;
end;
procedure TGLSoundSamples.SetItems(index: Integer; const val: TGLSoundSample);
begin
inherited Items[index] := val;
end;
function TGLSoundSamples.GetItems(index: Integer): TGLSoundSample;
begin
Result := TGLSoundSample(inherited Items[index]);
end;
function TGLSoundSamples.Add: TGLSoundSample;
begin
Result := (inherited Add) as TGLSoundSample;
end;
function TGLSoundSamples.FindItemID(ID: Integer): TGLSoundSample;
begin
Result := (inherited FindItemID(ID)) as TGLSoundSample;
end;
// GetByName
//
function TGLSoundSamples.GetByName(const aName: string): TGLSoundSample;
var
i: Integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if CompareText(Items[i].Name, aName) = 0 then
begin
Result := Items[i];
Break;
end;
end;
// AddFile
//
function TGLSoundSamples.AddFile(const fileName: string; const sampleName: string
= ''): TGLSoundSample;
begin
Result := Add;
Result.LoadFromFile(fileName);
if sampleName <> '' then
Result.Name := sampleName;
end;
// ------------------
// ------------------ TGLSoundLibrary ------------------
// ------------------
constructor TGLSoundLibrary.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSamples := TGLSoundSamples.Create(Self);
vSoundLibraries.Add(Self);
end;
destructor TGLSoundLibrary.Destroy;
begin
vSoundLibraries.Remove(Self);
FSamples.Free;
inherited Destroy;
end;
// Notification
//
procedure TGLSoundLibrary.Notification(AComponent: TComponent; Operation:
TOperation);
begin
inherited;
end;
// SetSamples
//
procedure TGLSoundLibrary.SetSamples(const val: TGLSoundSamples);
begin
FSamples.Assign(val);
end;
// ------------------
// ------------------ TGLBaseSoundSource ------------------
// ------------------
// Create
//
constructor TGLBaseSoundSource.Create(Collection: TCollection);
begin
inherited Create(Collection);
FChanges := [sscTransformation, sscSample, sscStatus];
FVolume := 1.0;
FMinDistance := 1.0;
FMaxDistance := 100.0;
FInsideConeAngle := 360;
FOutsideConeAngle := 360;
FConeOutsideVolume := 0.0;
FNbLoops := 1;
FFrequency := -1;
end;
// Destroy
//
destructor TGLBaseSoundSource.Destroy;
begin
inherited Destroy;
end;
// GetDisplayName
//
function TGLBaseSoundSource.GetDisplayName: string;
begin
Result := Format('%s', [FSoundName]);
end;
// Assign
//
procedure TGLBaseSoundSource.Assign(Source: TPersistent);
begin
if Source is TGLBaseSoundSource then
begin
FPriority := TGLBaseSoundSource(Source).FPriority;
FOrigin := TGLBaseSoundSource(Source).FOrigin;
FVolume := TGLBaseSoundSource(Source).FVolume;
FMinDistance := TGLBaseSoundSource(Source).FMinDistance;
FMaxDistance := TGLBaseSoundSource(Source).FMaxDistance;
FInsideConeAngle := TGLBaseSoundSource(Source).FInsideConeAngle;
FOutsideConeAngle := TGLBaseSoundSource(Source).FOutsideConeAngle;
FConeOutsideVolume := TGLBaseSoundSource(Source).FConeOutsideVolume;
FSoundLibraryName := TGLBaseSoundSource(Source).FSoundLibraryName;
FSoundLibrary := TGLBaseSoundSource(Source).FSoundLibrary;
FSoundName := TGLBaseSoundSource(Source).FSoundName;
FMute := TGLBaseSoundSource(Source).FMute;
FPause := TGLBaseSoundSource(Source).FPause;
FChanges := [sscTransformation, sscSample, sscStatus];
FNbLoops := TGLBaseSoundSource(Source).FNbLoops;
FFrequency := TGLBaseSoundSource(Source).FFrequency;
end
else
inherited Assign(Source);
end;
// WriteToFiler
//
procedure TGLBaseSoundSource.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteInteger(0); // Archive Version 0
WriteInteger(FPriority);
WriteFloat(FVolume);
WriteFloat(FMinDistance);
WriteFloat(FMaxDistance);
WriteFloat(FInsideConeAngle);
WriteFloat(FOutsideConeAngle);
WriteFloat(FConeOutsideVolume);
if Assigned(FSoundLibrary) then
WriteString(FSoundLibrary.Name)
else
WriteString(FSoundLibraryName);
WriteString(FSoundName);
WriteBoolean(FMute);
WriteBoolean(FPause);
WriteInteger(FNbLoops);
// WriteInteger(FFrequency);
end;
end;
// ReadFromFiler
//
procedure TGLBaseSoundSource.ReadFromFiler(reader: TReader);
begin
inherited;
with reader do
begin
ReadInteger; // ignore archiveVersion
FPriority := ReadInteger;
FVolume := ReadFloat;
FMinDistance := ReadFloat;
FMaxDistance := ReadFloat;
FInsideConeAngle := ReadFloat;
FOutsideConeAngle := ReadFloat;
FConeOutsideVolume := ReadFloat;
FSoundLibraryName := ReadString;
FSoundLibrary := nil;
FSoundName := ReadString;
FMute := ReadBoolean;
FPause := ReadBoolean;
FChanges := [sscTransformation, sscSample, sscStatus];
FNbLoops := ReadInteger;
// FFrequency:=ReadInteger;
end;
end;
// Sample
//
function TGLBaseSoundSource.Sample: TGLSoundSample;
begin
if SoundLibrary <> nil then
Result := FSoundLibrary.Samples.GetByName(FSoundName)
else
Result := nil;
end;
// SetPriority
//
procedure TGLBaseSoundSource.SetPriority(const val: Integer);
begin
if val <> FPriority then
begin
FPriority := val;
Include(FChanges, sscStatus);
end;
end;
// SetOrigin
//
procedure TGLBaseSoundSource.SetOrigin(const val: TGLBaseSceneObject);
begin
if val <> FOrigin then
begin
FOrigin := val;
Include(FChanges, sscTransformation);
end;
end;
// SetVolume
//
procedure TGLBaseSoundSource.SetVolume(const val: Single);
begin
if val <> FVolume then
begin
FVolume := ClampValue(val, 0, 1);
Include(FChanges, sscStatus);
end;
end;
// SetMinDistance
//
procedure TGLBaseSoundSource.SetMinDistance(const val: Single);
begin
if val <> FMinDistance then
begin
FMinDistance := ClampValue(val, 0);
Include(FChanges, sscStatus);
end;
end;
// SetMaxDistance
//
procedure TGLBaseSoundSource.SetMaxDistance(const val: Single);
begin
if val <> FMaxDistance then
begin
FMaxDistance := ClampValue(val, 0);
Include(FChanges, sscStatus);
end;
end;
// SetInsideConeAngle
//
procedure TGLBaseSoundSource.SetInsideConeAngle(const val: Single);
begin
if val <> FInsideConeAngle then
begin
FInsideConeAngle := ClampValue(val, 0, 360);
Include(FChanges, sscStatus);
end;
end;
// SetOutsideConeAngle
//
procedure TGLBaseSoundSource.SetOutsideConeAngle(const val: Single);
begin
if val <> FOutsideConeAngle then
begin
FOutsideConeAngle := ClampValue(val, 0, 360);
Include(FChanges, sscStatus);
end;
end;
// SetConeOutsideVolume
//
procedure TGLBaseSoundSource.SetConeOutsideVolume(const val: Single);
begin
if val <> FConeOutsideVolume then
begin
FConeOutsideVolume := ClampValue(val, 0, 1);
Include(FChanges, sscStatus);
end;
end;
// GetSoundLibrary
//
function TGLBaseSoundSource.GetSoundLibrary: TGLSoundLibrary;
begin
if (FSoundLibrary = nil) and (FSoundLibraryName <> '') then
FSoundLibrary := GetSoundLibraryByName(FSoundLibraryName);
Result := FSoundLibrary;
end;
// SetSoundLibrary
//
procedure TGLBaseSoundSource.SetSoundLibrary(const val: TGLSoundLibrary);
begin
if val <> FSoundLibrary then
begin
FSoundLibrary := val;
if Assigned(FSoundLibrary) then
FSoundLibraryName := FSoundLibrary.Name
else
FSoundLibraryName := '';
Include(FChanges, sscSample);
end;
end;
// SetSoundName
//
procedure TGLBaseSoundSource.SetSoundName(const val: string);
begin
if val <> FSoundName then
begin
FSoundName := val;
Include(FChanges, sscSample);
end;
end;
// SetPause
//
procedure TGLBaseSoundSource.SetPause(const val: Boolean);
begin
if val <> FPause then
begin
FPause := val;
if Collection <> nil then
TGLSoundManager(TGLSoundSources(Collection).owner).PauseSource(Self,
FPause);
end;
end;
// SetNbLoops
//
procedure TGLBaseSoundSource.SetNbLoops(const val: Integer);
begin
if val <> FNbLoops then
begin
FNbLoops := val;
Include(FChanges, sscSample);
end;
end;
// SetFrequency
//
procedure TGLBaseSoundSource.SetFrequency(const val: integer);
begin
if val <> FFrequency then
begin
FFrequency := val;
Include(FChanges, sscStatus);
end;
end;
// SetMute
//
procedure TGLBaseSoundSource.SetMute(const val: Boolean);
begin
if val <> FMute then
begin
FMute := val;
if Collection <> nil then
TGLSoundManager(TGLSoundSources(Collection).owner).MuteSource(Self,
FMute);
end;
end;
// ------------------
// ------------------ TGLSoundSource ------------------
// ------------------
// Destroy
//
destructor TGLSoundSource.Destroy;
begin
if Assigned(FBehaviourToNotify) then
FBehaviourToNotify.NotifySourceDestruction(Self);
if Collection <> nil then
((Collection as TGLSoundSources).Owner as TGLSoundManager).KillSource(Self);
inherited;
end;
// ------------------
// ------------------ TGLSoundSources ------------------
// ------------------
constructor TGLSoundSources.Create(AOwner: TComponent);
begin
Owner := AOwner;
inherited Create(TGLSoundSource);
end;
function TGLSoundSources.GetOwner: TPersistent;
begin
Result := Owner;
end;
procedure TGLSoundSources.SetItems(index: Integer; const val: TGLSoundSource);
begin
inherited Items[index] := val;
end;
function TGLSoundSources.GetItems(index: Integer): TGLSoundSource;
begin
Result := TGLSoundSource(inherited Items[index]);
end;
function TGLSoundSources.Add: TGLSoundSource;
begin
Result := (inherited Add) as TGLSoundSource;
end;
function TGLSoundSources.FindItemID(ID: Integer): TGLSoundSource;
begin
Result := (inherited FindItemID(ID)) as TGLSoundSource;
end;
// ------------------
// ------------------ TGLSoundManager ------------------
// ------------------
// Create
//
constructor TGLSoundManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSources := TGLSoundSources.Create(Self);
FMasterVolume := 1.0;
FOutputFrequency := 44100;
FMaxChannels := 8;
FUpdateFrequency := 10;
FLastUpdateTime := -1e30;
FDistanceFactor := 1.0;
FRollOffFactor := 1.0;
FDopplerFactor := 1.0;
end;
// Destroy
//
destructor TGLSoundManager.Destroy;
begin
Active := False;
Listener := nil;
FSources.Free;
inherited Destroy;
end;
// Notification
//
procedure TGLSoundManager.Notification(AComponent: TComponent; Operation:
TOperation);
begin
if Operation = opRemove then
begin
if AComponent = FListener then
Listener := nil;
if AComponent = FCadencer then
Cadencer := nil;
end;
inherited;
end;
// SetActive
//
procedure TGLSoundManager.SetActive(const val: Boolean);
begin
if (csDesigning in ComponentState) or (csLoading in ComponentState) then
FActive := val
else if val <> FActive then
begin
if val then
begin
if Assigned(vActiveSoundManager) then
vActiveSoundManager.Active := False;
if DoActivate then
begin
FActive := True;
vActiveSoundManager := Self;
end;
end
else
begin
try
StopAllSources;
DoDeActivate;
finally
FActive := val;
vActiveSoundManager := nil;
end;
end;
end;
end;
// Activate
//
function TGLSoundManager.DoActivate: Boolean;
begin
Result := True;
end;
// DeActivate
//
procedure TGLSoundManager.DoDeActivate;
begin
StopAllSources;
end;
// SetMute
//
procedure TGLSoundManager.SetMute(const val: Boolean);
begin
if val <> FMute then
begin
if val then
begin
if DoMute then
FMute := True
end
else
begin
DoUnMute;
FMute := False;
end;
end;
end;
// DoMute
//
function TGLSoundManager.DoMute: Boolean;
var
i: Integer;
begin
for i := 0 to Sources.Count - 1 do
if not Sources[i].Mute then
MuteSource(Sources[i], True);
Result := True;
end;
// DoUnMute
//
procedure TGLSoundManager.DoUnMute;
var
i: Integer;
begin
for i := 0 to Sources.Count - 1 do
if not Sources[i].Mute then
MuteSource(Sources[i], False);
end;
// SetPause
//
procedure TGLSoundManager.SetPause(const val: Boolean);
begin
if val <> FPause then
begin
if val then
begin
if DoPause then
FPause := True
end
else
begin
DoUnPause;
FPause := False;
end;
end;
end;
// Loaded
//
procedure TGLSoundManager.Loaded;
begin
inherited;
if Active and (not (csDesigning in ComponentState)) then
begin
FActive := False;
Active := True;
end;
end;
// DefineProperties
//
procedure TGLSoundManager.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('Doppler', ReadDoppler, WriteDoppler, (DopplerFactor <>
1));
end;
// WriteDoppler
//
procedure TGLSoundManager.WriteDoppler(writer: TWriter);
begin
writer.WriteFloat(DopplerFactor);
end;
// ReadDoppler
//
procedure TGLSoundManager.ReadDoppler(reader: TReader);
begin
FDopplerFactor := reader.ReadFloat;
end;
// DoPause
//
function TGLSoundManager.DoPause: Boolean;
var
i: Integer;
begin
for i := 0 to Sources.Count - 1 do
if not Sources[i].Pause then
PauseSource(Sources[i], True);
Result := True;
end;
// DoUnPause
//
procedure TGLSoundManager.DoUnPause;
var
i: Integer;
begin
for i := 0 to Sources.Count - 1 do
if not Sources[i].Pause then
PauseSource(Sources[i], False);
end;
// SetMasterVolume
//
procedure TGLSoundManager.SetMasterVolume(const val: Single);
begin
if val < 0 then
FMasterVolume := 0
else if val > 1 then
FMasterVolume := 1
else
FMasterVolume := val;
NotifyMasterVolumeChange;
end;
// SetMaxChannels
//
procedure TGLSoundManager.SetMaxChannels(const val: Integer);
begin
if val <> FMaxChannels then
begin
if val < 1 then
FMaxChannels := 1
else
FMaxChannels := val;
end;
end;
// SetOutputFrequency
//
procedure TGLSoundManager.SetOutputFrequency(const val: Integer);
begin
if val <> FOutputFrequency then
begin
if val < 11025 then
FOutputFrequency := 11025
else
FOutputFrequency := val;
end;
end;
// SetUpdateFrequency
//
procedure TGLSoundManager.SetUpdateFrequency(const val: Single);
begin
FUpdateFrequency := ClampValue(val, 1, 60);
end;
// StoreUpdateFrequency
//
function TGLSoundManager.StoreUpdateFrequency: Boolean;
begin
Result := (FUpdateFrequency <> 10);
end;
// SetCadencer
//
procedure TGLSoundManager.SetCadencer(const val: TGLCadencer);
begin
if val <> FCadencer then
begin
if Assigned(FCadencer) then
FCadencer.UnSubscribe(Self);
FCadencer := val;
if Assigned(FCadencer) then
FCadencer.Subscribe(Self);
end;
end;
// SetDistanceFactor
//
procedure TGLSoundManager.SetDistanceFactor(const val: Single);
begin
if val <= 0 then
FDistanceFactor := 1
else
FDistanceFactor := val;
Notify3DFactorsChanged;
end;
// StoreDistanceFactor
//
function TGLSoundManager.StoreDistanceFactor: Boolean;
begin
Result := (FDistanceFactor <> 1);
end;
// SetRollOffFactor
//
procedure TGLSoundManager.SetRollOffFactor(const val: Single);
begin
if val <= 0 then
FRollOffFactor := 1
else
FRollOffFactor := val;
Notify3DFactorsChanged;
end;
// StoreRollOffFactor
//
function TGLSoundManager.StoreRollOffFactor: Boolean;
begin
Result := (FRollOffFactor <> 1);
end;
// SetDopplerFactor
//
procedure TGLSoundManager.SetDopplerFactor(const val: Single);
begin
if val < 0 then
FDopplerFactor := 0
else if val > 10 then
FDopplerFactor := 10
else
FDopplerFactor := val;
Notify3DFactorsChanged;
end;
// SetSoundEnvironment
//
procedure TGLSoundManager.SetSoundEnvironment(const val: TGLSoundEnvironment);
begin
if val <> FSoundEnvironment then
begin
FSoundEnvironment := val;
NotifyEnvironmentChanged;
end;
end;
// ListenerCoordinates
//
procedure TGLSoundManager.ListenerCoordinates(var position, velocity, direction,
up: TVector);
var
right: TVector;
begin
if Listener <> nil then
begin
position := Listener.AbsolutePosition;
if FLastDeltaTime <> 0 then
begin
velocity := VectorSubtract(position, FLastListenerPosition);
ScaleVector(velocity, 1 / FLastDeltaTime);
end;
FLastListenerPosition := position;
if (Listener is TGLCamera) and (TGLCamera(Listener).TargetObject <> nil)
then
begin
// special case of the camera targeting something
direction := TGLCamera(Listener).AbsoluteVectorToTarget;
NormalizeVector(direction);
up := Listener.AbsoluteYVector;
right := VectorCrossProduct(direction, up);
up := VectorCrossProduct(right, direction);
end
else
begin
direction := Listener.AbsoluteZVector;
up := Listener.AbsoluteYVector;
end;
end
else
begin
position := NullHmgPoint;
velocity := NullHmgVector;
direction := ZHmgVector;
up := YHmgVector;
end;
end;
// NotifyMasterVolumeChange
//
procedure TGLSoundManager.NotifyMasterVolumeChange;
begin
// nothing
end;
// Notify3DFactorsChanged
//
procedure TGLSoundManager.Notify3DFactorsChanged;
begin
// nothing
end;
// NotifyEnvironmentChanged
//
procedure TGLSoundManager.NotifyEnvironmentChanged;
begin
// nothing
end;
// SetListener
//
procedure TGLSoundManager.SetListener(const val: TGLBaseSceneObject);
begin
if Assigned(FListener) then
FListener.RemoveFreeNotification(Self);
FListener := val;
if Assigned(FListener) then
FListener.FreeNotification(Self);
end;
// SetSources
//
procedure TGLSoundManager.SetSources(const val: TGLSoundSources);
begin
FSources.Assign(val);
end;
// KillSource
//
procedure TGLSoundManager.KillSource(aSource: TGLBaseSoundSource);
begin
// nothing
end;
// UpdateSource
//
procedure TGLSoundManager.UpdateSource(aSource: TGLBaseSoundSource);
begin
aSource.FChanges := [];
end;
// MuteSource
//
procedure TGLSoundManager.MuteSource(aSource: TGLBaseSoundSource; muted:
Boolean);
begin
// nothing
end;
// PauseSource
//
procedure TGLSoundManager.PauseSource(aSource: TGLBaseSoundSource; paused:
Boolean);
begin
// nothing
end;
// UpdateSources
//
procedure TGLSoundManager.UpdateSources;
var
i: Integer;
begin
for i := Sources.Count - 1 downto 0 do
UpdateSource(Sources[i]);
end;
// StopAllSources
//
procedure TGLSoundManager.StopAllSources;
var
i: Integer;
begin
for i := Sources.Count - 1 downto 0 do
Sources.Delete(i);
end;
// DoProgress
//
procedure TGLSoundManager.DoProgress(const progressTime: TProgressTimes);
begin
if not Active then
Exit;
with progressTime do
if newTime - FLastUpdateTime > 1 / FUpdateFrequency then
begin
FLastDeltaTime := newTime - FLastUpdateTime;
FLastUpdateTime := newTime;
UpdateSources;
end;
end;
// CPUUsagePercent
//
function TGLSoundManager.CPUUsagePercent: Single;
begin
Result := -1;
end;
// EAXSupported
//
function TGLSoundManager.EAXSupported: Boolean;
begin
Result := False;
end;
// ------------------
// ------------------ TGLBSoundEmitter ------------------
// ------------------
// Create
//
constructor TGLBSoundEmitter.Create(aOwner: TXCollection);
begin
inherited Create(aOwner);
FSource := TGLSoundSource.Create(nil);
end;
// Destroy
//
destructor TGLBSoundEmitter.Destroy;
begin
if Assigned(FPlayingSource) then
FPlayingSource.Free;
FSource.Free;
inherited Destroy;
end;
// Assign
//
procedure TGLBSoundEmitter.Assign(Source: TPersistent);
begin
if Source is TGLBSoundEmitter then
begin
FSource.Assign(TGLBSoundEmitter(Source).FSource);
end;
inherited Assign(Source);
end;
// WriteToFiler
//
procedure TGLBSoundEmitter.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteInteger(0); // Archive Version 0
FSource.WriteToFiler(writer);
WriteBoolean(FPlaying);
end;
end;
// ReadFromFiler
//
procedure TGLBSoundEmitter.ReadFromFiler(reader: TReader);
begin
inherited;
with reader do
begin
ReadInteger; // ignore archiveVersion
FSource.ReadFromFiler(reader);
FPlaying := ReadBoolean;
end;
end;
// Loaded
//
procedure TGLBSoundEmitter.Loaded;
begin
inherited;
if not (csDesigning in OwnerBaseSceneObject.ComponentState) then
SetPlaying(FPlaying);
end;
// FriendlyName
//
class function TGLBSoundEmitter.FriendlyName: string;
begin
Result := 'Sound Emitter';
end;
// FriendlyDescription
//
class function TGLBSoundEmitter.FriendlyDescription: string;
begin
Result := 'A simple sound emitter behaviour';
end;
// UniqueBehaviour
//
class function TGLBSoundEmitter.UniqueItem: Boolean;
begin
Result := False;
end;
// DoProgress
//
procedure TGLBSoundEmitter.DoProgress(const progressTime: TProgressTimes);
begin
// nothing, yet
end;
// SetSource
//
procedure TGLBSoundEmitter.SetSource(const val: TGLBaseSoundSource);
begin
FSource.Assign(val);
end;
// SetPlaying
//
procedure TGLBSoundEmitter.SetPlaying(const val: Boolean);
begin
if csDesigning in OwnerBaseSceneObject.ComponentState then
FPlaying := val
else if ActiveSoundManager <> nil then
begin
if val <> Playing then
begin
if val then
begin
FPlayingSource := ActiveSoundManager.Sources.Add;
FPlayingSource.FBehaviourToNotify := Self;
FPlayingSource.Assign(FSource);
FPlayingSource.Origin := OwnerBaseSceneObject;
end
else
FPlayingSource.Free;
end;
end
else if vVerboseGLSMErrors then
InformationDlg('No Active Sound Manager.'#13#10'Make sure manager is created before emitter');
end;
// GetPlaying
//
function TGLBSoundEmitter.GetPlaying: Boolean;
begin
if csDesigning in OwnerBaseSceneObject.ComponentState then
Result := FPlaying
else
Result := Assigned(FPlayingSource);
end;
// NotifySourceDestruction
//
procedure TGLBSoundEmitter.NotifySourceDestruction(aSource: TGLSoundSource);
begin
Assert(FPlayingSource = aSource);
FPlayingSource := nil;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TGLSoundLibrary]);
RegisterXCollectionItemClass(TGLBSoundEmitter);
vSoundLibraries := TList.Create;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
finalization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
if Assigned(vActiveSoundManager) then
vActiveSoundManager.Active := False;
vSoundLibraries.Free;
vSoundLibraries := nil;
UnregisterXCollectionItemClass(TGLBSoundEmitter);
end.
|
UNIT LD_INT;
INTERFACE
TYPE
lista = ^reg;
reg = record
d : integer;
ant : lista;
sig : lista;
end;
VAR
c : Char;
p : ^Integer;
{appends the element to the end of the list}
procedure L_ADD(var L:lista; e: integer);
{appends the element at given position}
procedure L_ADD_POS(var L:lista; i: integer; e: integer);
{return the element at the specified position in the list.}
function L_GET(var L: lista; pos: integer): integer;
{remove the element at the specified position}
procedure L_REMOVE(var L: lista; i: integer);
{remove all list values, and dispose from memory}
procedure L_REMOVE_ALL(var L: lista);
{removes the first occurrence of element}
function L_REMOVE_INT(var L: lista; e: integer): Boolean;
{return the index in this list of the first occurence, or -1 if list does not contain element}
function L_INDEXOF(var L: lista; e: integer): integer;
{return true if the list contains no elements.}
function L_ISEMPTY(var L: lista): Boolean;
{returns the index of the las ocurrence, or -1 if list does not contain element}
function L_LASTINDEXOF(var L: lista; e: integer): integer;
{return the number of elements}
function L_SIZE(var L: lista): integer;
IMPLEMENTATION
{add first element}
procedure L_NEW_ADD(var L: lista; e: integer);
var
auxL: lista;
begin
new(L);
L^.d:= e;
L^.sig:= NIL;
L^.ant:= NIL;
end;
{remove all list values, and dispose from memory}
procedure L_REMOVE_ALL(var L: lista);
Begin
end;
{appends the element to the end of the list}
procedure L_ADD(var L:lista; e: integer);
var
auxL : lista;
tmpL : lista;
Begin
{check if initialized}
if L <> NIL
then begin
{prepare data and add to last pos}
new(auxL);
auxL:= L;
while auxL^.sig <> NIL do auxL := auxL^.sig;
new(tmpL);
tmpL^.d:= e;
tmpL^.sig:= NIL;
tmpL^.ant:= auxL;
auxL^.sig:= tmpL;
end
else L_NEW_ADD(L,e);
end;
{appends the element at given position}
procedure L_ADD_POS(var L:lista; i: integer; e: integer);
var
auxL,tmpL: lista;
auxi: integer;
Begin
{check out of bounds}
if ((i < 0) AND (i > L_SIZE(l))) then RunError(201);
i:=i-1; {hack to scape for if pos = 0}
new(tmpL);
tmpL:= L;
for auxi:=0 to i do tmpL:= tmpL^.sig;
new(auxL);
auxL^.d:= e;
auxL^.sig:= tmpL;
auxL^.ant:= tmpL^.ant;
tmpL^.ant^.sig:= auxL;
tmpL^.ant:= auxL;
end;
{return the element at the specified position in the list.}
function L_GET(var L: lista; pos: integer): integer;
var
i: integer;
tmpL: lista;
Begin
pos:= pos - 1; {hack to scape for if pos = 0}
new(tmpL);
tmpL:= L;
for i:=0 to pos do tmpL:= tmpL^.sig;
L_GET:= tmpL^.d;
end;
{remove the element at the specified position}
procedure L_REMOVE(var L: lista; i: integer);
Begin
end;
{removes the first occurrence of element}
function L_REMOVE_INT(var L: lista; e: integer): Boolean;
Begin
end;
{return the index in this list of the first occurence, or -1 if list does not contain element}
function L_INDEXOF(var L: lista; e: integer): integer;
Begin
end;
{return true if the list contains no elements.}
function L_ISEMPTY(var L: lista): Boolean;
Begin
end;
{returns the index of the las ocurrence, or -1 if list does not contain element}
function L_LASTINDEXOF(var L: lista; e: integer): integer;
Begin
end;
{return the number of elements}
function L_SIZE(var L: lista): integer;
var
auxL: lista;
i: integer;
Begin
if L <> NIL
then begin
new(auxL);
auxL:= L;
i:= 1;
while auxL <> NIL
do begin
auxL := auxL^.sig;
inc(i);
end;
dec(i);
L_SIZE:= i;
end
else L_SIZE:= -1;
end;
END.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.VirtualKeyboard.Types;
interface
uses
System.Classes, System.SysUtils;
type
{ TfgButtonsCollection }
TfgButtonsCollectionItem = class;
TfgButtonsCollection = class(TCollection)
protected
[Weak] FOwner: TPersistent;
FOnChanged: TProc;
function GetOwner: TPersistent; override;
procedure DoChanged;
procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override;
public
constructor Create(const AOwner: TPersistent; const AOnChanged: TProc);
destructor Destroy; override;
function GetButton(const Index: Integer): TfgButtonsCollectionItem;
end;
{ TfgButtonsCollectionItem }
TfgButtonsCollectionItem = class(TCollectionItem)
public const
DefaultVisible = True;
private
FCaption: string;
FVisible: Boolean;
FOnInternalChanged: TProc;
FOnClick: TNotifyEvent;
procedure SetCaption(const Value: string);
procedure SetOnClick(const Value: TNotifyEvent);
procedure SetVisible(const Value: Boolean);
protected
procedure AssignTo(Dest: TPersistent); override;
function Collection: TfgButtonsCollection; virtual;
function GetDisplayName: string; override;
procedure NotifyAboutChanges; virtual;
property OnInternalChanged: TProc read FOnInternalChanged write FOnInternalChanged;
public
constructor Create(Collection: TCollection); override;
published
property Caption: string read FCaption write SetCaption;
property Visible: Boolean read FVisible write SetVisible default DefaultVisible;
property OnClick: TNotifyEvent read FOnClick write SetOnClick;
end;
implementation
uses
FGX.Asserts;
{ TfgButtonsCollection }
constructor TfgButtonsCollection.Create(const AOwner: TPersistent; const AOnChanged: TProc);
begin
inherited Create(TfgButtonsCollectionItem);
FOwner := AOwner;
FOnChanged := AOnChanged;
end;
destructor TfgButtonsCollection.Destroy;
begin
FOnChanged := nil;
inherited Destroy;
end;
procedure TfgButtonsCollection.DoChanged;
begin
if Assigned(FOnChanged) then
FOnChanged;
end;
function TfgButtonsCollection.GetButton(const Index: Integer): TfgButtonsCollectionItem;
begin
AssertInRange(Index, 0, Count - 1);
Result := Items[Index] as TfgButtonsCollectionItem;
end;
function TfgButtonsCollection.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TfgButtonsCollection.Notify(Item: TCollectionItem; Action: TCollectionNotification);
begin
AssertIsClass(Item, TfgButtonsCollectionItem);
inherited Notify(Item, Action);
if Action = TCollectionNotification.cnAdded then
(Item as TfgButtonsCollectionItem).OnInternalChanged := DoChanged;
DoChanged;
end;
{ TfgButtonsCollectionItem }
procedure TfgButtonsCollectionItem.AssignTo(Dest: TPersistent);
var
DestAction: TfgButtonsCollectionItem;
begin
if Dest is TfgButtonsCollectionItem then
begin
DestAction := Dest as TfgButtonsCollectionItem;
DestAction.Caption := Caption;
DestAction.OnClick := OnClick;
DestAction.Visible := Visible;
end
else
inherited AssignTo(Dest);
end;
function TfgButtonsCollectionItem.Collection: TfgButtonsCollection;
begin
AssertIsNotNil(Collection);
Result := Collection as TfgButtonsCollection;
end;
constructor TfgButtonsCollectionItem.Create(Collection: TCollection);
begin
AssertIsNotNil(Collection);
AssertIsClass(Collection, TfgButtonsCollection);
inherited Create(Collection);
FVisible := DefaultVisible;
end;
function TfgButtonsCollectionItem.GetDisplayName: string;
begin
if Caption.IsEmpty then
Result := inherited GetDisplayName
else
Result := Caption;
end;
procedure TfgButtonsCollectionItem.NotifyAboutChanges;
begin
if Assigned(FOnInternalChanged) then
FOnInternalChanged;
end;
procedure TfgButtonsCollectionItem.SetCaption(const Value: string);
begin
if FCaption <> Value then
begin
FCaption := Value;
NotifyAboutChanges;
end;
end;
procedure TfgButtonsCollectionItem.SetOnClick(const Value: TNotifyEvent);
begin
FOnClick := Value;
NotifyAboutChanges;
end;
procedure TfgButtonsCollectionItem.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
NotifyAboutChanges;
end;
end;
end.
|
unit RootObject;
interface
type
// общий предок всех классов переключаемых в рантайме объектов:
// TVclCanvas, TGdiPlusCanvas, TStraightWalker, TCurveWalker
TRootObject = class(TInterfacedObject)
constructor Create; virtual; abstract;
end;
TRootClass = class of TRootObject;
implementation
end.
|
unit CurrencyUnit;
interface
uses
CurrencyInterface, System.Classes, System.Generics.Collections;
type
TMyCurrency = class(TObject, ICurrency)
strict private
private
class var Instance: TMyCurrency;
var
FDictionary: TDictionary<Cardinal, Double>;
FRefCount: Integer;
function GetKey(CurrencyID: Integer; ADate: TDateTime): Cardinal;
public
constructor Create;
destructor Destroy; override;
function GetCourses(CurrencyID: Integer; ADate: TDateTime): Double; stdcall;
class function NewInstance: TObject; override;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
implementation
uses
System.SysUtils, HttpUnit, Winapi.Windows, System.Contnrs;
var
SingletonList: TObjectList;
constructor TMyCurrency.Create;
begin
if FDictionary <> nil then
Exit;
FDictionary := TDictionary<Cardinal, Double>.Create;
end;
destructor TMyCurrency.Destroy;
begin
FreeAndNil(FDictionary);
inherited;
end;
function TMyCurrency.GetCourses(CurrencyID: Integer; ADate: TDateTime): Double;
var
ACources: TArray<Double>;
Key: Cardinal;
begin
Assert((CurrencyID >= 2) and (CurrencyID <= 3));
Key := GetKey(CurrencyID, ADate);
if not FDictionary.ContainsKey(Key) then
begin
// Пытаемся получить курс доллара и евро с сайта
ACources := TCBRHttp.GetCourses(['Доллар США', 'Евро'], ADate);
// Запоминаем курс доллара на дату
FDictionary.Add(GetKey(2, ADate), ACources[0]);
// Запоминаем курс евро на дату
FDictionary.Add(GetKey(3, ADate), ACources[1]);
end;
Result := FDictionary[Key];
end;
function TMyCurrency.GetKey(CurrencyID: Integer; ADate: TDateTime): Cardinal;
Var
Day: Word;
Month: Word;
Year: Word;
begin
DecodeDate(ADate, Year, Month, Day);
Result := CurrencyID * 1000000000 + Year * 10000 + Month * 100 + Day;
end;
class function TMyCurrency.NewInstance: TObject;
begin
if not Assigned(Instance) then
begin
Instance := TMyCurrency(inherited NewInstance);
SingletonList.Add(Instance);
end;
Result := Instance;
end;
function TMyCurrency.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TMyCurrency._AddRef: Integer;
begin
Result := InterlockedIncrement(FRefCount);
end;
function TMyCurrency._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
// Пусть синлтон существует, даже если на него нет ни одной ссылки
// if Result = 0 then
// Destroy;
end;
initialization
SingletonList := TObjectList.Create(True);
finalization
FreeAndNil(SingletonList);
end.
|
unit BufferList;
interface
procedure Register;
implementation
uses Windows, Classes, SysUtils, ToolsAPI, Menus, Forms, Dialogs, Controls,
BufferListForm, BaseBindings, SaveKeyMacro, ActiveX;
type
TBufferList = class(TNotifierObject, IUnknown, IOTANotifier,
IOTAKeyboardBinding)
procedure BufferListProc(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
function GetBindingType: TBindingType;
function GetDisplayName: string;
function GetName: string;
procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices);
end;
TClassicBinding = class(TBaseBindings, IOTAKeyboardBinding)
protected
procedure AdjustBlockCase(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure AdjustWordCase(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure BackspaceDelete(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicBlockDelete(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicDeleteLine(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkWord(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkToViewBottom(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkToViewTop(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkToBOF(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkToBOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkToEOF(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMarkToEOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicMoveBlock(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ClassicToggleCase(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure CopyBlock(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure CursorLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure CursorRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteChar(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteToEOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteWordLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteWordRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure EndCursor(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure GotoBookmark(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure HomeCursor(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure IndentBlock(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertCharacter(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertFile(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertLiteralKey(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertTab(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure LineDown(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure LineUp(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure LiteralKeyProc(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure LoadKeyMacro(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkBlockBegin(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkBlockEnd(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkLine(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkToPageDown(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkToPageUp(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkToRelativeHoriz(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkToRelativeVert(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkToWordLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MarkToWordRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorHorizontal(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToBOF(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToBOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToEOF(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToEOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToLastEdit(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToMarkBegin(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToMarkEnd(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorVertical(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveLineViewBottom(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveLineViewTop(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure PageDown(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure PageUp(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure SetBookmark(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure Scroll(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ToggleBlock(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ToggleInsertMode(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ToggleMacroRecord(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure WordLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure WordRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
public
function GetBindingType: TBindingType;
function GetDisplayName: string;
function GetName: string;
procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices);
end;
resourcestring
sBufferList = 'Buffer List';
sNewIDEClassic = 'New IDE Classic';
procedure Register;
begin
(BorlandIDEServices as IOTAKeyBoardServices).AddKeyboardBinding(TBufferList.Create);
(BorlandIDEServices as IOTAKeyBoardServices).AddKeyboardBinding(TClassicBinding.Create);
end;
{ TBufferList }
procedure TBufferList.BindKeyboard(const BindingServices: IOTAKeyBindingServices);
begin
BindingServices.AddKeyBinding([ShortCut(Ord('B'), [ssCtrl])], BufferListProc, nil);
end;
procedure TBufferList.BufferListProc(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
I: Integer;
InterfaceList: IInterfaceList;
Iter: IOTAEditBufferIterator;
Buffer: IOTAEditBuffer;
begin
with TBufferListFrm.Create(Application) do
try
InterfaceList := TInterfaceList.Create;
Context.KeyboardServices.EditorServices.GetEditBufferIterator(Iter);
for I := 0 to Iter.Count - 1 do
begin
Buffer := Iter.EditBuffers[I];
InterfaceList.Add(Buffer);
BufferListBox.Items.Add(Buffer.FileName);
end;
if BufferListBox.Items.Count > 1 then
BufferListBox.ItemIndex := 1
else BufferListBox.ItemIndex := 0;
Iter := nil;
if ShowModal = mrOK then
(InterfaceList[BufferListBox.ItemIndex] as IOTAEditBuffer).Show;
finally
Free;
end;
BindingResult := krHandled;
end;
function TBufferList.GetBindingType: TBindingType;
begin
Result := btPartial;
end;
function TBufferList.GetDisplayName: string;
begin
Result := sBufferList;
end;
function TBufferList.GetName: string;
begin
Result := 'Borland.BufferList'; //do not localize
end;
{ TClassicBinding }
{ Do no localize the following strings }
procedure TClassicBinding.BindKeyboard(const BindingServices: IOTAKeyBindingServices);
begin
BindingServices.AddKeyBinding([ShortCut(VK_F5, [ssAlt])], DebugInspect, nil);
BindingServices.AddKeyBinding([ShortCut(VK_F1, [ssCtrl])], HelpKeyword, nil);
BindingServices.AddKeyBinding([ShortCut(VK_F7, [ssCtrl])], AddWatchAtCursor, nil);
BindingServices.AddMenuCommand(mcAddWatchAtCursor, AddWatchAtCursor, nil);
BindingServices.AddMenuCommand(mcInspectAtCursor, DebugInspect, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('A'), [ssCtrl])], WordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('C'), [ssCtrl])], PageDown, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('D'), [ssCtrl])], CursorRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('E'), [ssCtrl])], LineUp, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('F'), [ssCtrl])], WordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('G'), [ssCtrl])], DeleteChar, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('H'), [ssCtrl])], BackSpaceDelete, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('I'), [ssCtrl])], InsertTab, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('J'), [ssCtrl])], CodeTemplate, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('L'), [ssCtrl])], SearchAgain, nil, kfImplicits, '', 'SearchAgainItem');
BindingServices.AddKeyBinding([ShortCut(Ord('R'), [ssCtrl])], PageUp, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('S'), [ssCtrl])], CursorLeft, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('T'), [ssCtrl])], DeleteWordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('V'), [ssCtrl])], ToggleInsertMode, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('W'), [ssCtrl])], Scroll, Pointer(-1));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl])], LineDown, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Y'), [ssCtrl])], ClassicDeleteLine, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Z'), [ssCtrl])], Scroll, Pointer(1));
BindingServices.AddMenuCommand(mcRepeatSearch, SearchAgain, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('B'), [ssCtrl])], MarkBlockBegin, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('C'), [ssCtrl])], CopyBlock, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('E'), [ssCtrl])], AdjustWordCase, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('F'), [ssCtrl])], AdjustWordCase, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('H'), [ssCtrl])], ToggleBlock, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('I'), [ssCtrl])], IndentBlock, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('K'), [ssCtrl])], MarkBlockEnd, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('L'), [ssCtrl])], MarkLine, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('N'), [ssCtrl])], AdjustBlockCase, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('O'), [ssCtrl])], AdjustBlockCase, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('P'), [ssCtrl])], Print, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('R'), [ssCtrl])], InsertFile, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('T'), [ssCtrl])], ClassicMarkWord, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('U'), [ssCtrl])], IndentBlock, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('V'), [ssCtrl])], ClassicMoveBlock, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('W'), [ssCtrl])], BlockSave, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('Y'), [ssCtrl])], ClassicBlockDelete, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('0'), [])], SetBookmark, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('1'), [])], SetBookmark, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('2'), [])], SetBookmark, Pointer(2));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('3'), [])], SetBookmark, Pointer(3));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('4'), [])], SetBookmark, Pointer(4));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('5'), [])], SetBookmark, Pointer(5));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('6'), [])], SetBookmark, Pointer(6));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('7'), [])], SetBookmark, Pointer(7));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('8'), [])], SetBookmark, Pointer(8));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('9'), [])], SetBookmark, Pointer(9));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('0'), [ssCtrl])], SetBookmark, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('1'), [ssCtrl])], SetBookmark, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('2'), [ssCtrl])], SetBookmark, Pointer(2));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('3'), [ssCtrl])], SetBookmark, Pointer(3));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('4'), [ssCtrl])], SetBookmark, Pointer(4));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('5'), [ssCtrl])], SetBookmark, Pointer(5));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('6'), [ssCtrl])], SetBookmark, Pointer(6));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('7'), [ssCtrl])], SetBookmark, Pointer(7));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('8'), [ssCtrl])], SetBookmark, Pointer(8));
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl]), ShortCut(Ord('9'), [ssCtrl])], SetBookmark, Pointer(9));
BindingServices.AddKeyBinding([ShortCut(Ord('N'), [ssCtrl])], OpenLine, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('A'), [ssCtrl])], OpenFileAtCursor, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('B'), [ssCtrl])], BrowseSymbolAtCursor, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('C'), [ssCtrl])], SetBlockStyle, Pointer(btColumn));
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('G'), [ssCtrl])], GotoLine, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('I'), [ssCtrl])], SetBlockStyle, Pointer(btInclusive));
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('K'), [ssCtrl])], SetBlockStyle, Pointer(btNonInclusive));
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('L'), [ssCtrl])], SetBlockStyle, Pointer(btLine));
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('O'), [ssCtrl])], InsertCompilerOptions, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('O'), [ssCtrl]), ShortCut(Ord('U'), [ssCtrl])], ClassicToggleCase, nil);
BindingServices.AddMenuCommand(mcGotoLine, GotoLine, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('P'), [ssCtrl])], InsertLiteralKey, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('A'), [ssCtrl])], SearchReplace, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('B'), [ssCtrl])], MoveCursorToMarkBegin, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('C'), [ssCtrl])], MoveCursorToEOF, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('D'), [ssCtrl])], MoveCursorToEOL, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('E'), [ssCtrl])], HomeCursor, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('F'), [ssCtrl])], SearchFind, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('G'), [ssCtrl])], NullCmd, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('H'), [ssCtrl])], NullCmd, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('I'), [ssCtrl])], NullCmd, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('J'), [ssCtrl])], NullCmd, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('K'), [ssCtrl])], MoveCursorToMarkEnd, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('P'), [ssCtrl])], MoveCursorToLastEdit, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('R'), [ssCtrl])], MoveCursorToBOF, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('S'), [ssCtrl])], MoveCursorToBOL, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('T'), [ssCtrl])], MoveLineViewTop, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('U'), [ssCtrl])], MoveLineViewBottom, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('X'), [ssCtrl])], EndCursor, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('Y'), [ssCtrl])], DeleteToEOL, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('0'), [])], GotoBookmark, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('1'), [])], GotoBookmark, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('2'), [])], GotoBookmark, Pointer(2));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('3'), [])], GotoBookmark, Pointer(3));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('4'), [])], GotoBookmark, Pointer(4));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('5'), [])], GotoBookmark, Pointer(5));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('6'), [])], GotoBookmark, Pointer(6));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('7'), [])], GotoBookmark, Pointer(7));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('8'), [])], GotoBookmark, Pointer(8));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('9'), [])], GotoBookmark, Pointer(9));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('0'), [ssCtrl])], GotoBookmark, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('1'), [ssCtrl])], GotoBookmark, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('2'), [ssCtrl])], GotoBookmark, Pointer(2));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('3'), [ssCtrl])], GotoBookmark, Pointer(3));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('4'), [ssCtrl])], GotoBookmark, Pointer(4));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('5'), [ssCtrl])], GotoBookmark, Pointer(5));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('6'), [ssCtrl])], GotoBookmark, Pointer(6));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('7'), [ssCtrl])], GotoBookmark, Pointer(7));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('8'), [ssCtrl])], GotoBookmark, Pointer(8));
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('9'), [ssCtrl])], GotoBookmark, Pointer(9));
BindingServices.AddMenuCommand(mcReplace, SearchReplace, nil);
BindingServices.AddMenuCommand(mcGetFindString, SearchFind, nil);
BindingServices.AddMenuCommand(mcMoveToMark0, GotoBookmark, nil);
BindingServices.AddMenuCommand(mcMoveToMark1, GotoBookmark, Pointer(1));
BindingServices.AddMenuCommand(mcMoveToMark2, GotoBookmark, Pointer(2));
BindingServices.AddMenuCommand(mcMoveToMark3, GotoBookmark, Pointer(3));
BindingServices.AddMenuCommand(mcMoveToMark4, GotoBookmark, Pointer(4));
BindingServices.AddMenuCommand(mcMoveToMark5, GotoBookmark, Pointer(5));
BindingServices.AddMenuCommand(mcMoveToMark6, GotoBookmark, Pointer(6));
BindingServices.AddMenuCommand(mcMoveToMark7, GotoBookmark, Pointer(7));
BindingServices.AddMenuCommand(mcMoveToMark8, GotoBookmark, Pointer(8));
BindingServices.AddMenuCommand(mcMoveToMark9, GotoBookmark, Pointer(9));
BindingServices.AddMenuCommand(mcSetMark0, SetBookmark, nil);
BindingServices.AddMenuCommand(mcSetMark1, SetBookmark, Pointer(1));
BindingServices.AddMenuCommand(mcSetMark2, SetBookmark, Pointer(2));
BindingServices.AddMenuCommand(mcSetMark3, SetBookmark, Pointer(3));
BindingServices.AddMenuCommand(mcSetMark4, SetBookmark, Pointer(4));
BindingServices.AddMenuCommand(mcSetMark5, SetBookmark, Pointer(5));
BindingServices.AddMenuCommand(mcSetMark6, SetBookmark, Pointer(6));
BindingServices.AddMenuCommand(mcSetMark7, SetBookmark, Pointer(7));
BindingServices.AddMenuCommand(mcSetMark8, SetBookmark, Pointer(8));
BindingServices.AddMenuCommand(mcSetMark9, SetBookmark, Pointer(9));
BindingServices.AddKeyBinding([ShortCut(VK_RETURN, [ssCtrl])], OpenFileAtCursor, nil, kfImplicits, '', 'ecOpenFileAtCursor');
BindingServices.AddKeyBinding([ShortCut(VK_SPACE, [ssCtrl])], CodeCompletion, Pointer(csCodeList or csManual));
BindingServices.AddKeyBinding([ShortCut(VK_PRIOR, [ssCtrl])], MoveCursorToBOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_NEXT, [ssCtrl])], MoveCursorToEOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RIGHT, [ssCtrl])], WordRight, nil);
BindingServices.AddKeyBinding([ShortCut(VK_LEFT, [ssCtrl])], WordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_HOME, [ssCtrl])], HomeCursor, nil);
BindingServices.AddKeyBinding([ShortCut(VK_END, [ssCtrl])], EndCursor, nil);
BindingServices.AddKeyBinding([ShortCut(VK_BACK, [ssctrl])], DeleteWordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_TAB, [])], InsertTab, nil);
BindingServices.AddKeyBinding([ShortCut(VK_BACK, [])], BackSpaceDelete, nil);
BindingServices.AddKeyBinding([ShortCut(VK_HOME, [])], MoveCursorToBOL, nil);
BindingServices.AddKeyBinding([ShortCut(VK_END, [])], MoveCursorToEOL, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DELETE, [])], DeleteChar, nil);
BindingServices.AddKeyBinding([ShortCut(VK_INSERT, [])], ToggleInsertMode, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DOWN, [])], MoveCursorVertical, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(VK_UP, [])], MoveCursorVertical, Pointer(-1));
BindingServices.AddKeyBinding([ShortCut(VK_RIGHT, [])], MoveCursorHorizontal, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(VK_LEFT, [])], MoveCursorHorizontal, Pointer(-1));
BindingServices.AddKeyBinding([ShortCut(VK_PRIOR, [])], PageUp, nil);
BindingServices.AddKeyBinding([ShortCut(VK_NEXT, [])], PageDown, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RETURN, [])], InsertCharacter, Pointer($0D));
BindingServices.AddKeyBinding([ShortCut(VK_BACK, [ssShift])], BackSpaceDelete, nil);
BindingServices.AddKeyBinding([ShortCut(VK_LEFT, [ssShift])], MarkToRelativeHoriz, Pointer(-1));
BindingServices.AddKeyBinding([ShortCut(VK_RIGHT, [ssShift])], MarkToRelativeHoriz, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(VK_UP, [ssShift])], MarkToRelativeVert, Pointer(-1));
BindingServices.AddKeyBinding([ShortCut(VK_DOWN, [ssShift])], MarkToRelativeVert, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(VK_END, [ssShift])], ClassicMarkToEOL, nil);
BindingServices.AddKeyBinding([ShortCut(VK_HOME, [ssShift])], ClassicMarkToBOL, nil);
BindingServices.AddKeyBinding([ShortCut(VK_PRIOR, [ssShift])], MarkToPageUp, nil);
BindingServices.AddKeyBinding([ShortCut(VK_NEXT, [ssShift])], MarkToPageDown, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RETURN, [ssShift])], InsertCharacter, Pointer($0D));
BindingServices.AddKeyBinding([ShortCut(VK_INSERT, [ssShift])], ClipPaste, nil, kfImplicits, '', 'EditPasteItem');
BindingServices.AddKeyBinding([ShortCut(VK_INSERT, [ssCtrl])], ClipCopy, nil, kfImplicits, '', 'EditCopyItem');
BindingServices.AddKeyBinding([ShortCut(VK_DELETE, [ssShift])], ClipCut, nil, kfImplicits, '', 'EditCutItem');
BindingServices.AddKeyBinding([ShortCut(VK_DELETE, [ssCtrl])], ClipClear, nil, kfImplicits, '', 'EditDeleteItem');
BindingServices.AddMenuCommand(mcClipPaste, ClipPaste, nil);
BindingServices.AddMenuCommand(mcClipCopy, ClipCopy, nil);
BindingServices.AddMenuCommand(mcClipCut, ClipCut, nil);
BindingServices.AddMenuCommand(mcClipClear, ClipClear, nil);
BindingServices.AddKeyBinding([ShortCut(VK_LEFT, [ssShift, ssCtrl])], MarkToWordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RIGHT, [ssShift, ssCtrl])], markToWordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('C'), [ssShift, ssCtrl])], ClassComplete, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('G'), [ssShift, ssCtrl])], InsertNewGUID, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('S'), [ssShift, ssCtrl])], IncrementalSearch, nil, kfImplicits, '', 'SearchIncrementalItem');
BindingServices.AddKeyBinding([ShortCut(VK_SPACE, [ssShift, ssCtrl])], CodeCompletion, Pointer(csParamList or csManual));
BindingServices.AddKeyBinding([ShortCut(VK_END, [ssShift, ssCtrl])], ClassicMarkToViewBottom, nil);
BindingServices.AddKeyBinding([ShortCut(VK_HOME, [ssShift, ssCtrl])], ClassicMarkToViewTop, nil);
BindingServices.AddKeyBinding([ShortCut(VK_PRIOR, [ssShift, ssCtrl])], ClassicMarkToBOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_NEXT, [ssShift, ssCtrl])], ClassicMarkToEOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_UP, [ssShift, ssCtrl])], ClassNavigate, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DOWN, [ssShift, ssCtrl])], ClassNavigate, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('R'), [ssShift, ssCtrl])], ToggleMacroRecord, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('P'), [ssShift, ssCtrl, ssAlt])], LoadKeyMacro, nil);
BindingServices.AddMenuCommand(mcIncrementalSearch, IncrementalSearch, nil);
BindingServices.AddKeyBinding([TextToShortCut('.')], AutoCodeInsight, Pointer(Ord('.')));
BindingServices.AddKeyBinding([ShortCut(Ord('>'), [])], AutoCodeInsight, Pointer(Ord('>')));
BindingServices.AddKeyBinding([TextToShortCut('(')], AutoCodeInsight, Pointer(Ord('(')));
{ BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('y'), [])], DeleteToEOL, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('Q'), [ssCtrl]), ShortCut(Ord('Y'), [])], DeleteToEOL, nil);}
// Create the literal key table.. Note: needs at least one keybinding in order to be created
BindingServices.AddKeyBinding([ShortCut(0, [])], NullCmd, nil, 7, 'LiteralKeyTable');
BindingServices.SetDefaultKeyProc(LiteralKeyProc, nil, 'LiteralKeyTable');
end;
function TClassicBinding.GetBindingType: TBindingType;
begin
{$IFDEF DEBUG}
Result := btPartial;
{$ELSE}
Result := btComplete;
{$ENDIF}
end;
function TClassicBinding.GetDisplayName: string;
begin
Result := sNewIDEClassic;
end;
function TClassicBinding.GetName: string;
begin
Result := 'Borland.NewClassic'; //do not localize
end;
procedure TClassicBinding.DeleteToEOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
Pos: IOTAEditPosition;
Block: IOTAEditBlock;
begin
Pos := Context.EditBuffer.EditPosition;
Block := Context.EditBuffer.EditBlock;
Block.Visible := False;
Block.Save;
try
Block.Style := btNonInclusive;
Block.BeginBlock;
Pos.MoveEOL;
Block.EndBlock;
Block.Delete;
finally
Block.Restore;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.WordLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveCursor(mmSkipLeft or mmSkipNonWord);
Context.EditBuffer.EditPosition.MoveCursor(mmSkipLeft or mmSkipWord or mmSkipStream);
BindingResult := krHandled;
end;
procedure TClassicBinding.WordRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveCursor(mmSkipRight or mmSkipWord or mmSkipStream);
Context.EditBuffer.EditPosition.MoveCursor(mmSkipRight or mmSkipNonWord);
BindingResult := krHandled;
end;
const
BOOKMARK_ID_SYSTEM_ONE = 19;
BOOKMARK_ID_SYSTEM_TWO = 18;
BOOKMARK_ID_SYSTEM_THREE = 17;
procedure TClassicBinding.DeleteWordLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
EP := EV.Position;
if (EB.Style <> btNonInclusive) or (EB.Size <> 0) then
begin
EB.Save;
try
EP.Save;
try
EP.Move(EB.StartingRow, EB.StartingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EP.Move(EB.EndingRow,EB.EndingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
finally
EP.Restore;
end;
finally
EB.Restore;
end;
Blocked := True;
end else
Blocked := False;
EB.Style := btNonInclusive;
EB.Reset;
EB.EndBlock;
EP.MoveCursor(mmSkipLeft or mmSkipNonWord);
EP.MoveCursor(mmSkipLeft or mmSkipWord);
EB.BeginBlock;
EB.Delete;
if Blocked then
begin
EB.Style := btNonInclusive;
EP.Save;
try
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EB.BeginBlock;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EB.EndBlock;
finally
EP.Restore;
end;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.BackspaceDelete(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.BackspaceDelete(1);
BindingResult := krHandled;
end;
procedure TClassicBinding.CursorRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(0, 1);
BindingResult := krHandled;
end;
procedure TClassicBinding.LineUp(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(-1, 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.PageDown(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.PageDown;
BindingResult := krHandled;
end;
procedure TClassicBinding.CursorLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(0, -1);
BindingResult := krHandled;
end;
procedure TClassicBinding.LineDown(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(1, 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.PageUp(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.PageUp;
BindingResult := krHandled;
end;
procedure TClassicBinding.DeleteWordRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
C, SpaceAdjust: Integer;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
EP := EV.Position;
if (EB.Style <> btNonInclusive) or (EB.Size <> 0) then
begin
EB.Save;
try
EP.Save;
try
EP.Move(EB.StartingRow, EB.StartingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EP.Move(EB.EndingRow,EB.EndingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
finally
EP.Restore;
end;
finally
EB.Restore;
end;
Blocked := True;
end else
Blocked := False;
EB.Style := btNonInclusive;
EB.Reset;
EB.BeginBlock;
SpaceAdjust := 0;
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_THREE);
if EP.IsWhiteSpace then
begin
if EP.Character = #9 then
begin
C := EP.Column;
EP.Delete(1);
if C <> EP.Column then
SpaceAdjust := C - EP.Column;
end;
EP.MoveCursor(mmSkipRight or mmSkipWhite);
end
else if EP.IsWordCharacter then
begin
EP.MoveCursor(mmSkipRight or mmSkipWord);
EP.MoveCursor(mmSkipRight or mmSkipWhite);
end
else if EP.IsSpecialCharacter then
begin
EP.Delete(1);
EP.MoveCursor(mmSkipRight or mmSkipWhite);
end
else
EP.Delete(1);
EB.EndBlock;
EB.Delete;
while SpaceAdjust > 0 do
begin
EP.InsertCharacter(' ');
Dec(SpaceAdjust);
end;
if Blocked then
begin
EB.Style := btNonInclusive;
EP.Save;
try
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EB.BeginBlock;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EB.EndBlock;
finally
EP.Restore;
end;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.Scroll(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EV: IOTAEditView;
Delta: Integer;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
Delta := Integer(Context.Context);
EV.Scroll(Delta, 0);
if EP.Row >= EV.GetBottomRow then
begin
EP.Move(EP.Row - 1, EP.Column);
EV.MoveViewToCursor;
end;
if EP.Row < EV.GetTopRow then
begin
EP.Move(EP.Row + 1, EP.Column);
EV.MoveViewToCursor;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.DeleteChar(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.Delete(1);
BindingResult := krHandled;
end;
procedure TClassicBinding.InsertTab(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EO: IOTABufferOptions;
begin
EP := Context.EditBuffer.EditPosition;
EO := Context.EditBuffer.BufferOptions;
if not EO.InsertMode then
EP.Tab(1)
else if EO.SmartTab then
EP.Align(1)
else
EP.InsertCharacter(#9);
BindingResult := krHandled;
end;
procedure TClassicBinding.HomeCursor(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.Move(Context.EditBuffer.TopView.TopRow, 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.EndCursor(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.Move(Context.EditBuffer.TopView.BottomRow, 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkBlockBegin(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EP: IOTAEditPosition;
EV: IOTAEditView;
EndCol, EndRow: Integer;
TopRow, LeftCol: Integer;
begin
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
EV := Context.EditBuffer.TopView;
if (EB.Style <> btNonInclusive) or (EB.Size <> 0) then
begin
TopRow := EV.TopRow;
LeftCol := EV.LeftColumn;
EndCol := EB.EndingColumn;
EndRow := EB.EndingRow;
if EP.Row = EndRow then
if EP.Column >= EndCol then
EndCol := EP.Column;
if EP.Row > EndRow then
EndRow := EP.Row;
EP.Save;
try
EB.Reset;
EB.BeginBlock;
EB.Style := btNonInclusive;
EP.Move(EndRow, EndCol);
EB.EndBlock;
finally
EP.Restore;
end;
EV.SetTopLeft(TopRow, LeftCol);
end else
begin
EB.Reset;
EB.BeginBlock;
EB.Style := btNonInclusive;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkBlockEnd(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EP: IOTAEditPosition;
StartRow, StartCol: Integer;
begin
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
if (EB.Style <> btNonInclusive) or (EB.Size <> 0) then
begin
StartCol := EB.StartingColumn;
StartRow := EB.StartingRow;
if EP.Row = StartRow then
if EP.Column <= StartCol then
StartCol := EP.Column;
if EP.Row < StartRow then
StartRow := EP.Row;
EP.Save;
try
EP.Move(StartRow, StartCol);
EB.Reset;
EB.BeginBlock;
EB.Style := btNonInclusive;
finally
EP.Restore;
end;
end;
EB.EndBlock;
EB.Style := btNonInclusive;
BindingResult := krHandled;
end;
resourcestring
sBlockCopied = 'Block copied';
procedure TClassicBinding.CopyBlock(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
begin
EB := Context.EditBuffer.EditBlock;
if EB.Size <> 0 then
begin
EB.Copy(False);
Context.EditBuffer.EditPosition.Paste;
Context.EditBuffer.TopView.SetTempMsg(sBlockCopied);
end else
Context.EditBuffer.TopView.SetTempMsg(sNoBlockMarked);
end;
procedure TClassicBinding.AdjustWordCase(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
try
if LongBool(Context.Context) then
MarkWord(Context).LowerCase
else MarkWord(Context).UpperCase;
EB.Reset;
finally
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
end;
finally
if Blocked then
EB.Restore;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.ToggleBlock(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditBlock.Visible := not Context.EditBuffer.EditBlock.Visible;
BindingResult := krHandled;
end;
procedure TClassicBinding.IndentBlock(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
SlideBlock(Context, LongBool(Context.Context));
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkLine(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
begin
EP := Context.EditBuffer.EditPosition;
EB := Context.EditBuffer.EditBlock;
EP.Save;
try
EP.Move(0, 1);
EB.Style := btNonInclusive;
EB.BeginBlock;
EP.MoveRelative(1, 0);
EB.EndBlock;
finally
EP.Restore;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.AdjustBlockCase(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
begin
EB := Context.EditBuffer.EditBlock;
if EB.Size <> 0 then
begin
if Context.Context <> nil then
EB.LowerCase
else EB.UpperCase;
end else
Context.EditBuffer.TopView.SetTempMsg(sNoBlockMarked);
BindingResult := krHandled;
end;
procedure TClassicBinding.InsertFile(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
begin
EP := Context.EditBuffer.EditPosition;
EP.Save;
try
EP.InsertFile('');
finally
EP.Restore;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkWord(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
begin
EP := Context.EditBuffer.EditPosition;
if not EP.IsWordCharacter then
WordLeft(Context, KeyCode, BindingResult);
MarkWord(Context);
BindingResult := krHandled;
end;
resourcestring
sBlockMoved = 'Block moved';
procedure TClassicBinding.ClassicMoveBlock(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
NewRow, NewColumn: Integer;
begin
EP := Context.EditBuffer.EditPosition;
EB := Context.EditBuffer.EditBlock;
EV := Context.EditBuffer.TopView;
if EB.Size <> 0 then
begin
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EB.Save;
try
EP.Move(EB.StartingRow, EB.StartingColumn);
finally
EB.Restore;
end;
EB.Cut(False);
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
NewRow := EP.Row;
NewColumn := EP.Column;
EP.Paste;
EP.Move(NewRow, NewColumn);
EB.BeginBlock;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EB.Extend(EP.Row, EP.Column);
EB.Save;
try
EP.Move(NewRow, NewColumn);
finally
EB.Restore;
end;
EV.SetTempMsg(sBlockMoved);
end else
EV.SetTempMsg(sNoBlockMarked);
BindingResult := krHandled;
end;
resourcestring
sBlockDeleted = 'Block deleted';
procedure TClassicBinding.ClassicBlockDelete(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EV: IOTAEditView;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
if EB.Size <> 0 then
begin
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EB.Delete;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EV.SetTempMsg(sBlockDeleted);
end else
EV.SetTempMsg(sNoBlockMarked);
BindingResult := krHandled;
end;
procedure TClassicBinding.SetBookmark(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.BookmarkToggle(Integer(Context.Context));
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicToggleCase(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
Blocked: Boolean;
begin
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
if ((EP.Column <= EB.EndingColumn) and (EP.Row <= EB.EndingRow)) and
((EP.Column >= EB.StartingColumn) and (EP.Row >= EB.StartingRow)) then
EB.ToggleCase
else
begin
EB.BeginBlock;
EP.MoveRelative(0, 1);
EB.EndBlock;
EB.ToggleCase;
EB.Reset;
end;
finally
if Blocked then
EB.Restore;
end;
end;
resourcestring
sLiteralKeyInserted = 'Literal key inserted';
procedure TClassicBinding.LiteralKeyProc(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
Key: Word;
Shift: TShiftState;
begin
ShortCutToKey(KeyCode, Key, Shift);
if Shift = [ssCtrl] then
begin
if (Key >= $40) and (Key < $5F) then
begin
Dec(Key, $40);
Shift := [];
end else if (Key >= $60) and (Key < $7F) then
begin
Dec(Key, $60);
Shift := [];
end;
end;
if Shift = [] then
Context.EditBuffer.EditPosition.InsertCharacter(Char(Key));
Context.EditBuffer.TopView.SetTempMsg(sLiteralKeyInserted);
Context.KeyboardServices.PopKeyboard('LiteralKeyTable'); //do not localize
BindingResult := krHandled;
end;
procedure TClassicBinding.LoadKeyMacro(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
KS: IOTAKeyboardServices;
Stream: IStream;
begin
KS := Context.KeyboardServices;
if not KS.CurrentPlayback.IsPlaying and not KS.CurrentRecord.IsRecording then
begin
with TSaveKeyMacroDlg.Create(Application) do
try
if OpenDialog1.Execute then
try
Stream := TStreamAdapter.Create(TFileStream.Create(OpenDialog1.FileName,
fmOpenRead or fmShareDenyWrite), soOwned);
KS.CurrentPlayback.Clear;
KS.CurrentPlayback.ReadFromStream(Stream);
except
Application.HandleException(Self);
end;
finally
Free;
end;
end;
BindingResult := krHandled;
end;
resourcestring
sInsertLiteralChar = 'Inserting literal character';
procedure TClassicBinding.InsertLiteralKey(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.KeyboardServices.PushKeyboard('LiteralKeyTable'); //do not localise
Context.EditBuffer.TopView.SetTempMsg(sInsertLiteralChar);
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToBOF(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.Move(1, 1);
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToEOF(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveEOF;
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToMarkBegin(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
begin
EB := Context.EditBuffer.EditBlock;
if EB.Visible and (EB.Size <> 0) then
begin
EB.Save;
try
Context.EditBuffer.EditPosition.Move(EB.StartingRow, EB.StartingColumn);
finally
EB.Restore;
end;
end else
Context.EditBuffer.TopView.SetTempMsg(sNoBlockMarked);
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToBOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveBOL;
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToEOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveEOL;
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToMarkEnd(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
begin
EB := Context.EditBuffer.EditBlock;
if EB.Visible and (EB.Size <> 0) then
begin
EB.Save;
try
Context.EditBuffer.EditPosition.Move(EB.EndingRow, EB.EndingColumn);
finally
EB.Restore;
end;
end else
Context.EditBuffer.TopView.SetTempMsg(sNoBlockMarked);
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorToLastEdit(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EV: IOTAEditView;
begin
EP := Context.EditBuffer.EditPosition;
EV := Context.EditBuffer.TopView;
EP.Move(EV.GetLastEditRow, EV.GetLastEditColumn);
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveLineViewBottom(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
Row, TopRow, BottomRow, Height: Integer;
begin
EV := Context.EditBuffer.TopView;
Row := EV.Position.GetRow;
TopRow := EV.TopRow;
BottomRow := EV.BottomRow;
Height := BottomRow - TopRow;
if Row > Height then
EV.SetTopLeft(Row - (Height - 1), 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveLineViewTop(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
begin
EV := Context.EditBuffer.TopView;
EV.SetTopLeft(EV.Position.Row, 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.GotoBookmark(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.BookmarkGoto(Integer(Context.Context));
BindingResult := krHandled;
end;
procedure TClassicBinding.ToggleInsertMode(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EO: IOTABufferOptions;
begin
EO := Context.KeyboardServices.EditorServices.EditOptions.BufferOptions;
EO.InsertMode := not EO.InsertMode;
BindingResult := krHandled;
end;
procedure TClassicBinding.ToggleMacroRecord(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
KS: IOTAKeyboardServices;
Stream: IStream;
begin
KS := Context.KeyboardServices;
if not KS.CurrentPlayback.IsPlaying then
if KS.CurrentRecord.IsRecording then
begin
KS.ResumeRecord;
with TSaveKeyMacroDlg.Create(Application) do
try
if ShowModal = mrOK then
try
Stream := TStreamAdapter.Create(TFileStream.Create(Edit1.Text, fmCreate), soOwned);
KS.CurrentRecord.WriteToStream(Stream);
except
Application.HandleException(Self);
end;
finally
Free;
end;
end else
KS.ResumeRecord;
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicDeleteLine(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
Blocked: Boolean;
Style: TOTABlockType;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
if EB.Size <> 0 then
begin
EB.Save;
try
EP.Save;
try
EP.Move(EB.StartingRow, EB.StartingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EP.Move(EB.EndingRow, EB.EndingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
Blocked := True;
finally
EP.Restore;
end;
finally
EB.Restore;
end;
end else
Blocked := False;
try
Style := EB.Style;
try
EP.MoveBOL;
EP.Save;
try
EB.Reset;
EB.Style := btLine;
EB.BeginBlock;
EB.Delete;
finally
EP.Restore;
end;
finally
EB.Style := Style;
end;
finally
if Blocked then
begin
EP.Save;
try
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EB.BeginBlock;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EB.EndBlock;
finally
EP.Restore;
end;
end;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorHorizontal(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(0, Integer(Context.Context));
BindingResult := krHandled;
end;
procedure TClassicBinding.MoveCursorVertical(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(Integer(Context.Context), 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.InsertCharacter(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.InsertCharacter(Char(Byte(Context.Context)));
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkToViewBottom(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
if (EB.EndingRow = EP.Row) and (EB.EndingColumn = EP.Column) then
begin
// EB.Style := btNonInclusive;
EP.Move(EB.StartingRow, EB.StartingColumn);
EB.BeginBlock;
EB.Extend(EV.BottomRow - 1, EP.Column);
EB.EndBlock;
end else
begin
EB.Reset;
// EB.Style := btNonInclusive;
EB.BeginBlock;
EB.Extend(EV.BottomRow - 1, EP.Column);
EB.EndBlock;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkToViewTop(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
if (EB.StartingRow = EP.Row) and (EB.StartingColumn = EP.Column) then
begin
// EB.Style := btNonInclusive;
EP.Move(EB.EndingRow, EB.EndingColumn);
EB.EndBlock;
EB.Extend(EV.TopRow, EP.Column);
EB.BeginBlock;
end else
begin
EB.Reset;
// EB.Style := btNonInclusive;
EB.EndBlock;
EB.Extend(EV.TopRow, EP.Column);
EB.BeginBlock;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkToWordLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EP: IOTAEditPosition;
NewRow, NewColumn: Integer;
begin
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
EP.Save;
try
EB.Save;
try
WordLeft(Context, KeyCode, BindingResult);
NewRow := EP.Row;
NewColumn := EP.Column;
finally
EB.Restore;
end;
finally
EP.Restore;
end;
EB.Extend(NewRow, NewColumn);
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkToWordRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EP: IOTAEditPosition;
NewRow, NewColumn: Integer;
begin
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
EP.Save;
try
EB.Save;
try
WordRight(Context, KeyCode, BindingResult);
NewRow := EP.Row;
NewColumn := EP.Column;
finally
EB.Restore;
end;
finally
EP.Restore;
end;
EB.Extend(NewRow, NewColumn);
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkToBOF(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
if (EB.StartingRow = EP.Row) and (EB.StartingColumn = EP.Column) then
begin
// EB.Style := btNonInclusive;
EP.Move(EB.EndingRow, EB.EndingColumn);
EB.EndBlock;
EP.Move(1, 1);
EB.BeginBlock;
end else
begin
EB.Reset;
// EB.Style := btNonInclusive;
EB.EndBlock;
EP.Move(1, 1);
EB.BeginBlock;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkToEOF(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
if (EB.StartingRow = EP.Row) and (EB.StartingColumn = EP.Column) then
begin
// EB.Style := btNonInclusive;
EP.Move(EB.StartingRow, EB.StartingColumn);
EB.EndBlock;
EP.MoveEOF;
EB.BeginBlock;
end else
begin
EB.Reset;
// EB.Style := btNonInclusive;
EB.EndBlock;
EP.MoveEOF;
EB.BeginBlock;
end;
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkToRelativeHoriz(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditBlock.ExtendRelative(0, Integer(Context.Context));
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkToRelativeVert(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditBlock.ExtendRelative(Integer(Context.Context), 0);
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkToBOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EndRow, EndCol: Integer;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
EB.Save;
try
EP.Save;
try
EP.MoveBOL;
EndRow := EP.Row;
EndCol := EP.Column;
finally
EP.Restore;
end;
finally
EB.Restore;
end;
EB.Extend(EndRow, EndCol);
BindingResult := krHandled;
end;
procedure TClassicBinding.ClassicMarkToEOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EV: IOTAEditView;
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EndRow, EndCol: Integer;
begin
EV := Context.EditBuffer.TopView;
EP := EV.Position;
EB := EV.Block;
EB.Save;
try
EP.Save;
try
EP.MoveEOL;
EndRow := EP.Row;
EndCol := EP.Column;
finally
EP.Restore;
end;
finally
EB.Restore;
end;
EB.Extend(EndRow, EndCol);
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkToPageDown(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditBlock.ExtendPageDown;
BindingResult := krHandled;
end;
procedure TClassicBinding.MarkToPageUp(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditBlock.ExtendPageUp;
BindingResult := krHandled;
end;
end.
|
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
FrameLogin, FrameOfferRegisterUser,
FrameRegisterUser, FrameDialogs, DataBases, Transports;
type
{ TMainForm }
TMainForm = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
FrameLogin: TFrameLogin;
FrameOfferRegister: TFrameOfferRegisterUser;
FrameRegister: TFrameRegisterUser;
FrameDialogs: TFrameWithDialogs;
{: Показать фрэйм предложения регистрации пользователя}
procedure ShowOfferRegisterFrame;
{: Показать фрэйм регистрации пользователя}
procedure ShowRegisterFrame;
{: Показать фрэйм входа пользователя}
procedure ShowLoginFrame;
{: Показать фрэйм диалогов}
procedure ShowFrameDialogs;
{: Скрыть все фрэймы}
procedure HideAllFrames;
{: Установить заголовок основного окна}
procedure SetCaptionWithForm(Frame: TFrame);
public
{: Восстановление системы}
procedure LoadingSystem;
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
// Запуск приложения
begin
LoadingSystem;
end;
procedure TMainForm.ShowOfferRegisterFrame;
// Показать фрэйм регистрации пользователя
begin
HideAllFrames;
if not Assigned(FrameOfferRegister) then
begin
FrameOfferRegister := TFrameOfferRegisterUser.Create(MainForm);
FrameOfferRegister.Align := alClient;
end;
FrameOfferRegister.Parent := MainForm;
FrameOfferRegister.Visible := True;
SetCaptionWithForm(FrameOfferRegister);
end;
procedure TMainForm.ShowRegisterFrame;
// Показать фрэйм регистрации пользователя
begin
HideAllFrames;
if not Assigned(FrameRegister) then
begin
FrameRegister := TFrameRegisterUser.Create(MainForm);
FrameRegister.Align := alClient;
end;
FrameRegister.Parent := MainForm;
FrameRegister.Visible := True;
SetCaptionWithForm(FrameRegister);
end;
procedure TMainForm.ShowLoginFrame;
// Показать фрэйм входа в систему
begin
HideAllFrames;
if not Assigned(FrameLogin) then
begin
FrameLogin := TFrameLogin.Create(MainForm);
FrameLogin.Align := alClient;
end;
FrameLogin.Parent := MainForm;
FrameLogin.Visible := True;
SetCaptionWithForm(FrameLogin);
end;
procedure TMainForm.ShowFrameDialogs;
// Показать фрэйм диалогов
begin
HideAllFrames;
if not Assigned(FrameDialogs) then
begin
FrameDialogs := TFrameWithDialogs.Create(MainForm);
FrameDialogs.Align := alClient;
end;
FrameDialogs.Parent := MainForm;
FrameDialogs.Visible := True;
SetCaptionWithForm(FrameDialogs);
Transport.Connect;
end;
procedure TMainForm.HideAllFrames;
// Скрыть все фрэймы
begin
if Assigned(FrameOfferRegister) then
FrameOfferRegister.Visible := False;
if Assigned(FrameRegister) then
FrameRegister.Visible := False;
if Assigned(FrameLogin) then
FrameLogin.Visible := False;
if Assigned(FrameDialogs) then
FrameDialogs.Visible := False;
end;
procedure TMainForm.SetCaptionWithForm(Frame: TFrame);
// Установить заголовок основного окна
begin
Caption := 'CryptoChat: ' + Frame.Hint;
end;
procedure TMainForm.LoadingSystem;
// Восстановление всех настроек и параметров
begin
// Если надо, генерируем новый путь к базе данных
// Если бд нет на диске, то создаём
if not FileExists(DataBase.FileName) then
DataBase.CreateDataBase(DataBase.FileName)
else
DataBase.OpenDataBase(DataBase.FileName);
// Узнаём количество пользователей, если их нет
if (DataBase.GetUsersCount = INVALID_VALUE) or (DataBase.GetUsersCount = 0) then
ShowOfferRegisterFrame // показываем предложение зарегистрироваться
else
ShowLoginFrame;// показываем предложение войти
end;
end.
|
{*******************************************************************************
* *
* TkToolbar - Toolbar with form stack/transitions awareness *
* *
* https://github.com/gmurt/KernowSoftwareFMX *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksToolBar;
interface
{$I ksComponents.inc}
uses Classes, FMX.StdCtrls, FMX.Graphics, ksTypes, FMX.Objects, FMX.Types,
System.UITypes, System.UIConsts, ksSpeedButton, ksFormTransition,
FMX.Controls.Presentation, FMX.Controls, System.Types;
type
// TksToolbar = class;
{IksToolbar = interface
['{42609FB8-4DE0-472F-B49C-A6CD636A530D}//]
//procedure SetTransition(ATransition: TksTransitionType);
//end;
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64
{$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)]
TksToolbar = class(TPresentedControl)
private
FButton: TSpeedButton;
FTintColor: TAlphaColor;
FFont: TFont;
FTextColor: TAlphaColor;
FButtonColor: TAlphaColor;
FText: string;
FFormTransition: TksFormTransition;
FOnMenuButtonClick: TNotifyEvent;
FShowMenuButton: Boolean;
FOnBackButtonClick: TNotifyEvent;
FBackButtonEnabled: Boolean;
FShowBackButton: Boolean;
procedure Changed(Sender: TObject);
procedure ButtonClicked(Sender: TObject);
procedure SetShowMenuButton(const Value: Boolean);
procedure SetTintColor(const Value: TAlphaColor);
procedure SetTextColor(const Value: TAlphaColor);
procedure SetText(const Value: string);
procedure SetFont(const Value: TFont);
procedure SetShowBackButton(const Value: Boolean);
procedure SetButtonColor(const Value: TAlphaColor);
procedure UpdateButton;
protected
procedure Paint; override;
function GetDefaultSize: TSizeF; override;
procedure DoMouseLeave; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DisableBackButton;
procedure EnableBackButton;
published
property Font: TFont read FFont write SetFont;
property Text: string read FText write SetText;
property Size;
property TabOrder;
property TintColor: TAlphaColor read FTintColor write SetTintColor default claWhitesmoke;
property TextColor: TAlphaColor read FTextColor write SetTextColor default claBlack;
property ButtonColor: TAlphaColor read FButtonColor write SetButtonColor default claBlack;
property ShowMenuButton: Boolean read FShowMenuButton write SetShowMenuButton default True;
property ShowBackButton: Boolean read FShowBackButton write SetShowBackButton default True;
property OnClick;
property OnMenuButtonClick: TNotifyEvent read FOnMenuButtonClick write FOnMenuButtonClick;
property OnBackButtonClick: TNotifyEvent read FOnBackButtonClick write FOnBackButtonClick;
end;
procedure Register;
implementation
uses Math, System.TypInfo, ksCommon, SysUtils, ksPickers,
Fmx.Forms, FMX.Platform;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksToolbar]);
end;
{ TksToolbar }
procedure TksToolbar.ButtonClicked(Sender: TObject);
begin
PickerService.HidePickers;
HideKeyboard;
Application.ProcessMessages;
if FFormTransition.GetFormDepth(Root as TCommonCustomForm) = 0 then
begin
if (Assigned(FOnMenuButtonClick)) and (FShowMenuButton) then
FOnMenuButtonClick(Self);
end
else
begin
if (Assigned(FOnBackButtonClick))and (FShowBackButton) then
begin
FOnBackButtonClick(Self);
FFormTransition.Pop;
end
else
if (FShowBackButton) then
begin
FFormTransition.Pop;
end;
end;
end;
procedure TksToolbar.Changed(Sender: TObject);
begin
InvalidateRect(ClipRect);
end;
constructor TksToolbar.Create(AOwner: TComponent);
begin
inherited;
FButton := TSpeedButton.Create(Self);
FButton.Align := TAlignLayout.Left;
FButton.StyleLookup := 'detailstoolbutton';
FButton.Width := 44;
FButton.IconTintColor := claDodgerblue;
FButton.TintColor := claDodgerblue;
FButton.CanFocus := False;
FButton.Stored := False;
//FButton.Visible := False;
FButton.OnClick := ButtonClicked;
AddObject(FButton);
FFont := TFont.Create;
FFont.Size := 14;
Align := TAlignLayout.MostTop;
FFormTransition := TksFormTransition.Create(nil);
FTintColor := claWhitesmoke;
FTextColor := claBlack;
FFont.OnChanged := Changed;
FShowMenuButton := True;
FShowBackButton := True;
FBackButtonEnabled := True;
end;
destructor TksToolbar.Destroy;
begin
FreeAndNil(FFormTransition);
FreeAndNil(FFont);
inherited;
end;
procedure TksToolbar.DisableBackButton;
begin
FBackButtonEnabled := False;
end;
procedure TksToolbar.DoMouseLeave;
begin
inherited;
end;
procedure TksToolbar.EnableBackButton;
begin
FBackButtonEnabled := True;
end;
function TksToolbar.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(120, 44);
end;
procedure TksToolbar.Paint;
var
AState: TCanvasSaveState;
begin
inherited;
if Locked then
Exit;
UpdateButton;
AState := Canvas.SaveState;
try
Canvas.BeginScene;
try
Canvas.IntersectClipRect(ClipRect);
Canvas.Fill.Color := FTintColor;
Canvas.Fill.Kind := TBrushKind.Solid;
Canvas.FillRect(ClipRect, 0, 0, AllCorners, 1);
Canvas.Font.Assign(FFont);
Canvas.Fill.Color := FTextColor;
Canvas.FillText(ClipRect, FText, False, 1, [], TTextAlign.Center);
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Color := claDimgray;
Canvas.Stroke.Kind := TBrushKind.Solid;
Canvas.DrawLine(PointF(0, Height), PointF(Width, Height), 1);
finally
Canvas.EndScene;
end;
finally
Canvas.RestoreState(AState);
end;
end;
procedure TksToolbar.SetButtonColor(const Value: TAlphaColor);
begin
FButtonColor := Value;
Repaint;
end;
procedure TksToolbar.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
procedure TksToolbar.SetShowBackButton(const Value: Boolean);
begin
FShowBackButton := Value;
UpdateButton
end;
procedure TksToolbar.SetShowMenuButton(const Value: Boolean);
begin
FShowMenuButton := Value;
UpdateButton;
end;
procedure TksToolbar.SetText(const Value: string);
begin
if FText <> Value then
begin
FText := Value;
InvalidateRect(ClipRect);
end;
end;
procedure TksToolbar.SetTextColor(const Value: TAlphaColor);
begin
FTextColor := Value;
Repaint;
end;
procedure TksToolbar.SetTintColor(const Value: TAlphaColor);
begin
if FTintColor <> Value then
begin
FTintColor := Value;
Repaint;
end;
end;
procedure TksToolbar.UpdateButton;
begin
if Root is TCommonCustomForm then
begin
if (FFormTransition.GetFormDepth(Root as TCommonCustomForm) = 0) then
begin
FButton.Visible := FShowMenuButton;
if FButton.StyleLookup <> 'detailstoolbutton' then
FButton.StyleLookup := 'detailstoolbutton';
end
else
begin
FButton.Visible := FShowBackButton;
if FButton.StyleLookup <> 'arrowlefttoolbutton' then
FButton.StyleLookup := 'arrowlefttoolbutton'
end;
end;
end;
initialization
Classes.RegisterClass(TksToolbar);
end.
|
unit IM.App;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Classes, SysUtils,
JPL.Console, JPL.ConsoleApp, JPL.CmdLineParser, JPL.TStr, JPL.Conversion, JPL.FileSearcher,
IM.Types, IM.Procs;
type
TApp = class(TJPConsoleApp)
private
public
procedure Init;
procedure Run;
procedure Done;
procedure RegisterOptions;
procedure ProcessOptions;
procedure PerformMainAction;
procedure DisplayHelpAndExit(const ExCode: integer);
procedure DisplayShortUsageAndExit(const Msg: string; const ExCode: integer);
procedure DisplayBannerAndExit(const ExCode: integer);
procedure DisplayMessageAndExit(const Msg: string; const ExCode: integer);
end;
implementation
{$region ' Init '}
procedure TApp.Init;
const
SEP_LINE = '-------------------------------------------------';
begin
AppName := 'IniMod';
MajorVersion := 1;
MinorVersion := 0;
Self.Date := EncodeDate(2021, 02, 02);
FullNameFormat := '%AppName% %MajorVersion%.%MinorVersion% [%OSShort% %Bits%-bit] (%AppDate%)';
Description := 'Console application for managing INI files.';
Author := 'Jacek Pazera';
HomePage := 'https://www.pazera-software.com/products/inimod/';
HelpPage := HomePage;
AppParams.GithubUrl := 'https://github.com/jackdp/IniMod';
LicenseName := 'Freeware, Open Source';
License := 'This program is completely free. You can use it without any restrictions, also for commercial purposes.' + ENDL +
'The program''s source files are available at ' + AppParams.GithubUrl + ENDL +
'Compiled binaries can be downloaded from ' + HomePage;
AppParams.Value := '';
AppParams.Section := '';
AppParams.Key := '';
AppParams.NewKeyName := '';
AppParams.Comment := '';
AppParams.CommentPadding := 0;
SetLength(AppParams.Files, 0);
AppParams.Encoding := TEncoding.UTF8;
AppParams.Silent := False;
AppParams.RecurseDepth := 0;
AppColors.Init;
{$IFDEF MSWINDOWS}
TrimExtFromExeShortName := True;
{$ENDIF}
HintBackgroundColor := TConsole.clLightGrayBg;
HintTextColor := TConsole.clBlackText;
WarningBackgroundColor := TConsole.clDarkMagentaBg;
WarningTextColor := TConsole.clLightGrayText;
//-----------------------------------------------------------------------------
TryHelpStr := ENDL + 'Try <color=white,black>' + ExeShortName + ' --help</color> for more information.';
ShortUsageStr :=
ENDL +
'Usage: ' + ExeShortName +
' <color=' + AppColors.Command + '>COMMAND</color> FILES OPTIONS' +
ENDL +
'Options are case-insensitive. Options and values in square brackets are optional.' + ENDL +
'All parameters that do not start with the "-" or "/" sign are treated as file names/masks.' + ENDL +
'Options and input files can be placed in any order, but -- (double dash followed by space) ' +
'indicates the end of parsing options and all subsequent parameters are treated as file names/masks.';
ExtraInfoStr :=
ENDL +
'FILES - Any combination of file names/masks.' + ENDL +
' Eg.: file.ini *config*.ini "long file name.ini"' +
ENDL + SEP_LINE + ENDL +
'EXIT CODES' + ENDL +
' ' + CON_EXIT_CODE_OK.ToString + ' - OK - no errors.' + ENDL +
' ' + CON_EXIT_CODE_SYNTAX_ERROR.ToString + ' - Syntax error.' + ENDL +
' ' + CON_EXIT_CODE_ERROR.ToString + ' - Other error.';
ExamplesStr := '';
end;
{$endregion Init}
{$region ' Run & Done '}
procedure TApp.Run;
begin
inherited;
RegisterOptions;
Cmd.Parse;
ProcessOptions;
if Terminated then Exit;
PerformMainAction; // <----- the main procedure
end;
procedure TApp.Done;
begin
SetLength(AppParams.Files, 0);
if (ExitCode <> 0) and (not AppParams.Silent) then Writeln('ExitCode: ', ExitCode);
end;
{$endregion Run & Done}
{$region ' RegisterOptions '}
procedure TApp.RegisterOptions;
const
MAX_LINE_LEN = 110;
var
Category: string;
esn: string;
sc: string;
sFile: string;
begin
{$IFDEF MSWINDOWS} Cmd.CommandLineParsingMode := cpmCustom; {$ELSE} Cmd.CommandLineParsingMode := cpmDelphi; {$ENDIF}
Cmd.UsageFormat := cufWget;
Cmd.AcceptAllNonOptions := True; // All non options are treated as file names
Cmd.IgnoreCase := True;
esn := ChangeFileExt(ExeShortName, '');
sFile := 'FILES';
// ------------ Registering commands -----------------
Cmd.RegisterCommand('w', 'Write', 1, False,
'Writes a key value. ' + esn + ' w ' + sFile + ' -s Section -k Key -v Value'
);
Cmd.RegisterCommand('r', 'Read', 1, False,
'Reads and displays the value of a key. ' + esn + ' r ' + sFile + ' -s Section -k Key'
);
Cmd.RegisterCommand('rnk', 'RenameKey', 1, False,
'Renames the key. ' + esn + ' rnk ' + sFile + ' -s Section -k OldKeyName -kn NewKeyName'
);
Cmd.RegisterCommand('rmk', 'RemoveKey', 1, False,
'Removes the key. ' + esn + ' rmk ' + sFile + ' -s Section -k Key'
);
Cmd.RegisterCommand('rms', 'RemoveSection', 1, False,
'Removes the given section. ' + esn + ' rms ' + sFile + ' -s Section'
);
Cmd.RegisterCommand('ras', 'RemoveAllSections', 1, False,
'Removes all sections. ' + esn + ' ras ' + sFile
);
Cmd.RegisterCommand('rs', 'ReadSection', 1, False,
'Displays section keys and values. ' + esn + ' rs ' + sFile + ' -s Section'
);
Cmd.RegisterCommand('rk', 'ReadKeys', 1, False,
'Displays section keys. ' + esn + ' rk ' + sFile + ' -s Section'
);
Cmd.RegisterCommand('ls', 'ListSections', 1, False,
'Displays the names of all sections. ' + esn + ' ls ' + sFile
);
Cmd.RegisterCommand('wsc', 'WriteSectionComment', 1, False,
'' + esn + ' wsc ' + sFile + ' -s Section -c Comment [-x NUM]'
);
Cmd.RegisterCommand('rsc', 'RemoveSectionComment', 1, False,
'' + esn + ' rsc ' + sFile + ' -s Section'
);
Cmd.RegisterCommand('wfc', 'WriteFileComment', 1, False,
'Adds one line to the file comment. ' + esn + ' wfc ' + sFile + ' -c Comment [-x NUM]'
);
Cmd.RegisterCommand('rfc', 'RemoveFileComment', 1, False,
'Clears file comment. ' + esn + ' rfc ' + sFile + ''
);
// ------------ Registering options -----------------
Category := 'main';
Cmd.RegisterOption('s', 'section', cvtRequired, False, False, 'Section name.', 'NAME', Category);
Cmd.RegisterOption('k', 'key', cvtRequired, False, False, 'Key name.', 'NAME', Category);
Cmd.RegisterOption('kn', 'new-key-name', cvtRequired, False, False, 'Key name.', 'NAME', Category);
Cmd.RegisterOption('v', 'value', cvtRequired, False, False, 'Key value.', 'STR', Category);
Cmd.RegisterOption('c', 'comment', cvtRequired, False, False, 'Section or file comment.', 'STR', Category);
Cmd.RegisterShortOption('x', cvtRequired, False, False, 'Padding spaces (for comments). NUM - a positive integer.', 'NUM', Category);
Cmd.RegisterOption(
'rd', 'recurse-depth', cvtRequired, False, False, 'Recursion depth when searching for files. NUM - a positive integer.', 'NUM', Category
);
Cmd.RegisterLongOption('silent', cvtNone, False, False, 'Do not display some messages.', '', Category);
Category := 'info';
Cmd.RegisterOption('h', 'help', cvtNone, False, False, 'Show this help.', '', Category);
Cmd.RegisterShortOption('?', cvtNone, False, True, '', '', '');
Cmd.RegisterLongOption('version', cvtNone, False, False, 'Show application version.', '', Category);
Cmd.RegisterLongOption('license', cvtNone, False, False, 'Display program license.', '', Category);
{$IFDEF MSWINDOWS}
Cmd.RegisterLongOption('home', cvtNone, False, False, 'Opens program home page in the default browser.', '', Category);
Cmd.RegisterLongOption('github', cvtNone, False, False, 'Opens the GitHub page with the program''s source files.', '', Category);
{$ENDIF}
// ----------------- Colors --------------------
sc := Cmd.CommandsUsageStr(' ', 140, ' ', 10);
sc := TStr.ReplaceFirst(sc, 'w, Write', '<color=' + AppColors.Command + '>w</color>, <color=' + AppColors.Command + '>Write</color>', True);
sc := TStr.ReplaceFirst(
sc, 'wsc, WriteSectionComment', '<color=' + AppColors.Command + '>wsc</color>, <color=' + AppColors.Command + '>WriteSectionComment</color>', True
);
sc := TStr.ReplaceFirst(
sc, 'rsc, RemoveSectionComment', '<color=' + AppColors.Command + '>rsc</color>, <color=' + AppColors.Command + '>RemoveSectionComment</color>', True
);
sc := TStr.ReplaceFirst(
sc, 'rmk, RemoveKey', '<color=' + AppColors.Command + '>rmk</color>, <color=' + AppColors.Command + '>RemoveKey</color>', True
);
sc := TStr.ReplaceFirst(
sc, 'rms, RemoveSection', '<color=' + AppColors.Command + '>rms</color>, <color=' + AppColors.Command + '>RemoveSection</color>', True
);
sc := TStr.ReplaceFirst(
sc, 'ras, RemoveAllSections', '<color=' + AppColors.Command + '>ras</color>, <color=' + AppColors.Command + '>RemoveAllSections</color>', True
);
sc := TStr.ReplaceFirst(sc, 'r, Read', '<color=' + AppColors.Command + '>r</color>, <color=' + AppColors.Command + '>Read</color>', True);
sc := TStr.ReplaceFirst(sc, 'rnk, RenameKey', '<color=' + AppColors.Command + '>rnk</color>, <color=' + AppColors.Command + '>RenameKey</color>', True);
sc := TStr.ReplaceFirst(sc, 'rs, ReadSection', '<color=' + AppColors.Command + '>rs</color>, <color=' + AppColors.Command + '>ReadSection</color>', True);
sc := TStr.ReplaceFirst(sc, 'rk, ReadKeys', '<color=' + AppColors.Command + '>rk</color>, <color=' + AppColors.Command + '>ReadKeys</color>', True);
sc := TStr.ReplaceFirst(
sc, 'ls, ListSections', '<color=' + AppColors.Command + '>ls</color>, <color=' + AppColors.Command + '>ListSections</color>', True
);
sc := TStr.ReplaceFirst(
sc, 'wfc, WriteFileComment', '<color=' + AppColors.Command + '>wfc</color>, <color=' + AppColors.Command + '>WriteFileComment</color>', True
);
sc := TStr.ReplaceFirst(
sc, 'rfc, RemoveFileComment', '<color=' + AppColors.Command + '>rfc</color>, <color=' + AppColors.Command + '>RemoveFileComment</color>', True
);
sc := TStr.ReplaceAll(sc, 's Section', '<color=' + AppColors.Section + '>s Section</color>', False);
sc := TStr.ReplaceAll(sc, 'k Key', '<color=' + AppColors.Key + '>k Key</color>', True);
sc := TStr.ReplaceAll(sc, 'k OldKeyName', '<color=' + AppColors.Key + '>k OldKeyName</color>', True);
sc := TStr.ReplaceAll(sc, 'kn NewKeyName', '<color=' + AppColors.Key + '>kn NewKeyName</color>', True);
sc := TStr.ReplaceAll(sc, 'v Value', '<color=' + AppColors.Value + '>v Value</color>', True);
sc := TStr.ReplaceAll(sc, 'c Comment', '<color=' + AppColors.Comment + '>c Comment</color>', True);
sc := TStr.ReplaceFirst(sc, ' w ' + sFile, ' <color=' + AppColors.Command + '>w</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' wsc ' + sFile, ' <color=' + AppColors.Command + '>wsc</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rsc ' + sFile, ' <color=' + AppColors.Command + '>rsc</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rmk ' + sFile, ' <color=' + AppColors.Command + '>rmk</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rms ' + sFile, ' <color=' + AppColors.Command + '>rms</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' ras ' + sFile, ' <color=' + AppColors.Command + '>ras</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' r ' + sFile, ' <color=' + AppColors.Command + '>r</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rnk ' + sFile, ' <color=' + AppColors.Command + '>rnk</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rs ' + sFile, ' <color=' + AppColors.Command + '>rs</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rk ' + sFile, ' <color=' + AppColors.Command + '>rk</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' ls ' + sFile, ' <color=' + AppColors.Command + '>ls</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' wfc ' + sFile, ' <color=' + AppColors.Command + '>wfc</color> ' + sFile, True);
sc := TStr.ReplaceFirst(sc, ' rfc ' + sFile, ' <color=' + AppColors.Command + '>rfc</color> ' + sFile, True);
sc := TStr.ReplaceAll(sc, esn, '<color=white>' + esn + '</color>', True);
UsageStr :=
ENDL +
'COMMANDS' + ENDL + sc + ENDL + ENDL +
'MAIN OPTIONS' + ENDL + Cmd.OptionsUsageStr(' ', 'main', MAX_LINE_LEN, ' ', 30) + ENDL + ENDL +
'INFO' + ENDL + Cmd.OptionsUsageStr(' ', 'info', MAX_LINE_LEN, ' ', 30);
end;
{$endregion RegisterOptions}
{$region ' ProcessOptions '}
procedure TApp.ProcessOptions;
var
x, i: integer;
s: string;
begin
//------------------------------------ Help ---------------------------------------
if (ParamCount = 0) or ParamExists('--help') or ParamExists('-h') or (Cmd.IsLongOptionExists('help')) or (Cmd.IsOptionExists('?')) then
begin
DisplayHelpAndExit(TConsole.ExitCodeOK);
Exit;
end;
//---------------------------------- Home -----------------------------------------
{$IFDEF MSWINDOWS}
if Cmd.IsLongOptionExists('home') or ParamExists('--home') then
begin
GoToHomePage;
Terminate;
Exit;
end;
if Cmd.IsOptionExists('github') or ParamExists('--github') then
begin
GoToUrl(AppParams.GithubUrl);
Terminate;
Exit;
end;
{$ENDIF}
//------------------------------- Version ------------------------------------------
if Cmd.IsOptionExists('version') or ParamExists('--version') then
begin
DisplayMessageAndExit(AppFullName, TConsole.ExitCodeOK);
Exit;
end;
//------------------------------- Version ------------------------------------------
if Cmd.IsLongOptionExists('license') or ParamExists('--license') then
begin
TConsole.WriteTaggedTextLine('<color=white,black>' + LicenseName + '</color>');
DisplayLicense;
Terminate;
Exit;
end;
// ---------------------------- Invalid options -----------------------------------
if Cmd.ErrorCount > 0 then
begin
DisplayShortUsageAndExit(Cmd.ErrorsStr, TConsole.ExitCodeSyntaxError);
Exit;
end;
AppParams.Silent := Cmd.IsLongOptionExists('silent');
if Cmd.IsOptionExists('s') then AppParams.Section := Trim(Cmd.GetOptionValue('s')); // Section
if Cmd.IsOptionExists('k') then AppParams.Key := Trim(Cmd.GetOptionValue('k')); // Key
if Cmd.IsOptionExists('kn') then AppParams.NewKeyName := Trim(Cmd.GetOptionValue('kn')); // New key name (for RenameKey)
if Cmd.IsOptionExists('v') then AppParams.Value := Cmd.GetOptionValue('v'); // Key value
if Cmd.IsOptionExists('c') then AppParams.Comment := Cmd.GetOptionValue('c'); // File or section comment
// Comment padding
if Cmd.IsOptionExists('x') then
begin
s := Trim(Cmd.GetOptionValue('x'));
x := 0;
if (not TryStrToInt(s, x)) or (x < 0) then
begin
DisplayError('Invalid value for option "x": ' + s);
DisplayHint('Expected positive integer');
ExitCode := TConsole.ExitCodeSyntaxError;
Terminate;
Exit;
end;
AppParams.CommentPadding := x;
end;
// Recursion depth
if Cmd.IsOptionExists('rd') then
begin
s := Trim(Cmd.GetOptionValue('rd'));
x := 0;
if (not TryStrToInt(s, x)) or (x < 0) then
begin
DisplayError('Invalid value for option "rd": ' + s);
DisplayHint('Expected positive integer');
ExitCode := TConsole.ExitCodeSyntaxError;
Terminate;
Exit;
end;
AppParams.RecurseDepth := x;
end;
//---------------------------- Unknown Params (file names/masks) --------------------------
for i := 0 to Cmd.UnknownParamCount - 1 do
begin
s := StripQuotes(Cmd.UnknownParams[i].ParamStr);
if s = '' then Continue;
s := ExpandFileName(s);
SetLength(AppParams.Files, Length(AppParams.Files) + 1);
AppParams.Files[High(AppParams.Files)] := s;
end;
end;
{$endregion ProcessOptions}
{$region ' PerformMainAction '}
procedure TApp.PerformMainAction;
var
i, xFileCount: integer;
fName, sFileCount, clFile, uCommand: string;
slFiles: TStringList;
fs: TJPFileSearcher;
function CheckCommand(const CommandShortName, CommandLongName: string): Boolean;
begin
Result := (UpperCase(CommandLongName) = uCommand) or (UpperCase(CommandShortName) = uCommand);
end;
procedure CheckSection;
begin
if AppParams.Section = '' then
begin
DisplayError('The SECTION name was not specified!');
ExitCode := TConsole.ExitCodeSyntaxError;
Terminate;
end;
end;
procedure CheckKey;
begin
if AppParams.Key = '' then
begin
DisplayError('The KEY name was not specified!');
ExitCode := TConsole.ExitCodeSyntaxError;
Terminate;
end;
end;
procedure CheckNewKeyName;
begin
if AppParams.NewKeyName = '' then
begin
DisplayError('The NewKeyName was not specified!');
ExitCode := TConsole.ExitCodeSyntaxError;
Terminate;
end;
end;
procedure CheckComment;
begin
// Zakładam, że użytkownik może podać pusty komentarz: -c ""
if not Cmd.IsOptionExists('c') then
begin
DisplayError('The COMMENT was not specified!');
ExitCode := TConsole.ExitCodeSyntaxError;
Terminate;
end;
end;
begin
if Terminated then Exit;
slFiles := TStringList.Create;
try
slFiles.Sorted := True;
slFiles.Duplicates := dupIgnore;
fs := TJPFileSearcher.Create;
try
for i := 0 to High(AppParams.Files) do
begin
fName := AppParams.Files[i];
//if (not IsFileMask(fName)) and (not FileExists(fName)) then
//begin
// if not AppParams.Silent then DisplayWarning('Warning: Input file "' + fName + '" does not exists!');
//end
//else
fs.AddInput(fName, AppParams.RecurseDepth);
end;
fs.Search;
fs.GetFileList(slFiles);
finally
fs.Free;
end;
xFileCount := slFiles.Count;
if xFileCount = 0 then
begin
if not AppParams.Silent then DisplayHint('No INI files found.');
Exit;
end;
uCommand := UpperCase(Cmd.CommandValue);
clFile := 'white';
sFileCount := itos(xFileCount);
for i := 0 to slFiles.Count - 1 do
begin
fName := slFiles[i];
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Processing file ' + itos(i + 1) + '/' + sFileCount + ' : <color=' + clFile + '>' + fName + '</color>');
// ---------------- Write key value --------------------
if CheckCommand('w', 'Write') then
begin
CheckSection;
CheckKey;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine(
'Writing: [<color=' + AppColors.Section + '>' + AppParams.Section + '</color>] ' +
'<color=' + AppColors.Key + '>' + AppParams.Key + '</color>' +
'<color=' + AppColors.Symbol + '>=</color>' +
'<color=' + AppColors.Value + '>' + AppParams.Value + '</color>'
);
WriteIniValue(fName, AppParams.Section, AppParams.Key, AppParams.Value, AppParams.Encoding);
end
// ------------------ Read key value -----------------
else if CheckCommand('r', 'Read') then
begin
CheckSection;
CheckKey;
if Terminated then Exit;
DisplayIniValue(fName, AppParams.Section, AppParams.Key, AppParams.Encoding);
end
// --------------- Rename key ------------
else if CheckCommand('rnk', 'RenameKey') then
begin
CheckSection;
CheckKey;
CheckNewKeyName;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine(
'Renaming key: <color=' + AppColors.Key + '>' + AppParams.Key + '</color>' +
'<color=' + AppColors.Symbol + '> -> </color><color=' + AppColors.Key + '>' + AppParams.NewKeyName + '</color>'
);
RenameIniKey(fName, AppParams.Section, AppParams.Key, AppParams.NewKeyName, AppParams.Encoding);
end
// --------------- Remove key ------------
else if CheckCommand('rmk', 'RemoveKey') then
begin
CheckSection;
CheckKey;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Removing key: <color=' + AppColors.Key + '>' + AppParams.Key + '</color>');
RemoveIniKey(fName, AppParams.Section, AppParams.Key, AppParams.Encoding);
end
// --------------- Remove section ------------
else if CheckCommand('rms', 'RemoveSection') then
begin
CheckSection;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Removing section: <color=' + AppColors.Section + '>' + AppParams.Section + '</color>');
RemoveIniSection(fName, AppParams.Section, AppParams.Encoding);
end
// --------------- Remove all sections ------------
else if CheckCommand('ras', 'RemoveAllSections') then
begin
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Removing all sections.');
RemoveIniAllSections(fName, AppParams.Encoding);
end
// --------------- Read section keys and values ------------
else if CheckCommand('rs', 'ReadSection') then
begin
CheckSection;
if Terminated then Exit;
DisplayIniSection(fName, AppParams.Section, AppParams.Encoding);
end
// -------------- Read section keys -------------------
else if CheckCommand('rk', 'ReadKeys') then
begin
CheckSection;
if Terminated then Exit;
DisplayIniSectionKeys(fName, AppParams.Section, AppParams.Encoding);
end
// ------------------ Write file comment -------------------
else if CheckCommand('wfc', 'WriteFileComment') then
begin
CheckComment;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Writing file comment: <color=' + AppColors.Comment + '>' + AppParams.Comment + '</color>');
WriteIniFileComment(fName, AppParams.Comment, AppParams.Encoding, AppParams.CommentPadding);
end
// ------------------ Remove file comment -------------------
else if CheckCommand('rfc', 'RemoveFileComment') then
begin
if not AppParams.Silent then TConsole.WriteTaggedTextLine('Removing file comment.');
RemoveIniFileComment(fName, AppParams.Encoding);
end
// ------------------ Write section comment -------------------
else if CheckCommand('wsc', 'WriteSectionComment') then
begin
CheckSection;
CheckComment;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Writing section comment: <color=' + AppColors.Comment + '>' + AppParams.Comment + '</color>');
WriteIniSectionComment(fName, AppParams.Section, AppParams.Comment, AppParams.Encoding, AppParams.CommentPadding);
end
// ------------------ Remove section comment -------------------
else if CheckCommand('rsc', 'RemoveSectionComment') then
begin
CheckSection;
if Terminated then Exit;
if not AppParams.Silent then
TConsole.WriteTaggedTextLine('Removing section comment: [<color=' + AppColors.Section + '>' + AppParams.Section + '</color>]');
RemoveIniSectionComment(fName, AppParams.Section, AppParams.Encoding);
end
else if CheckCommand('ls', 'ListSections') then
begin
ListIniSections(fName, AppParams.Encoding);
end;
if not AppParams.Silent then Writeln;
end; // for i
finally
slFiles.Free;
end;
end;
{$endregion PerformMainAction}
{$region ' Display... procs '}
procedure TApp.DisplayHelpAndExit(const ExCode: integer);
begin
DisplayBanner;
DisplayShortUsage;
DisplayUsage;
DisplayExtraInfo;
ExitCode := ExCode;
Terminate;
end;
procedure TApp.DisplayShortUsageAndExit(const Msg: string; const ExCode: integer);
begin
if Msg <> '' then Writeln(Msg);
DisplayShortUsage;
DisplayTryHelp;
ExitCode := ExCode;
Terminate;
end;
procedure TApp.DisplayBannerAndExit(const ExCode: integer);
begin
DisplayBanner;
ExitCode := ExCode;
Terminate;
end;
procedure TApp.DisplayMessageAndExit(const Msg: string; const ExCode: integer);
begin
Writeln(Msg);
ExitCode := ExCode;
Terminate;
end;
{$endregion Display... procs}
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.Utility;
interface
uses
System.Classes;
function ParseURLPath(const AURL: string): TStrings;
implementation
uses
System.SysUtils;
function ParseURLPath(const AURL: string): TStrings;
const
REQUEST_DELIMITER = '/';
var
LIndex, LSlashPos: Integer;
LMoreSegments: Boolean;
LSegment: string;
begin
LIndex := 0;
Result := TStringList.Create;
LSlashPos := AURL.IndexOf(REQUEST_DELIMITER);
LMoreSegments := LSlashPos >= 0;
if not LMoreSegments and (AURL <> '') then
Result.Add(AURL);
while LMoreSegments do
begin
LSegment := AURL.SubString(LIndex, LSlashPos-LIndex+1);
Result.Add(LSegment);
LIndex := LSlashPos+1;
LMoreSegments := LIndex < AURL.Length;
if LMoreSegments then
begin
LSlashPos := AURL.IndexOf(REQUEST_DELIMITER, LIndex);
if LSlashPos < 0 then
LSlashPos := AURL.Length - 1;
end;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FVectorEditor<p>
Editor for a vector.<p>
<b>Historique : </b><font size=-1><ul>
<li>05/10/08 - DanB - Removed Kylix support
<li>29/03/07 - DaStr - Renamed LINUX to KYLIX (BugTrackerID=1681585)
<li>03/07/04 - LR - Make change for Linux
<li>?/?/? - - Creation
</ul></font>
}
unit FVectorEditor;
interface
{$i GLScene.inc}
uses
System.Classes, System.SysUtils,
VCL.Forms, VCL.ComCtrls, VCL.StdCtrls, VCL.ToolWin,
VCL.ExtCtrls, VCL.Buttons, VCL.Graphics, VCL.Controls,
GLVectorGeometry, GLUtils, GLVectorTypes;
type
TVectorEditorForm = class(TForm)
EDx: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
EDy: TEdit;
EDz: TEdit;
BBok: TBitBtn;
BBcancel: TBitBtn;
IMx: TImage;
IMy: TImage;
IMz: TImage;
SpeedButton1: TSpeedButton;
SBmX: TSpeedButton;
SpeedButton3: TSpeedButton;
SBmY: TSpeedButton;
SpeedButton5: TSpeedButton;
SBmZ: TSpeedButton;
SpeedButton7: TSpeedButton;
SBUnit: TSpeedButton;
SpeedButton9: TSpeedButton;
Bevel1: TBevel;
SBInvert: TSpeedButton;
procedure TBxClick(Sender: TObject);
procedure TByClick(Sender: TObject);
procedure TBzClick(Sender: TObject);
procedure TBnullClick(Sender: TObject);
procedure EDxChange(Sender: TObject);
procedure EDyChange(Sender: TObject);
procedure EDzChange(Sender: TObject);
procedure SBmXClick(Sender: TObject);
procedure SBmYClick(Sender: TObject);
procedure SBmZClick(Sender: TObject);
procedure SBUnitClick(Sender: TObject);
procedure SpeedButton9Click(Sender: TObject);
procedure SBInvertClick(Sender: TObject);
private
{ Déclarations privées }
vx, vy, vz : Single;
procedure TestInput(edit : TEdit; imError : TImage; var dest : Single);
public
{ Déclarations publiques }
function Execute(var x, y, z : Single) : Boolean;
end;
function VectorEditorForm : TVectorEditorForm;
procedure ReleaseVectorEditorForm;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
{$R *.dfm}
var
vVectorEditorForm : TVectorEditorForm;
function VectorEditorForm : TVectorEditorForm;
begin
if not Assigned(vVectorEditorForm) then
vVectorEditorForm:=TVectorEditorForm.Create(nil);
Result:=vVectorEditorForm;
end;
procedure ReleaseVectorEditorForm;
begin
if Assigned(vVectorEditorForm) then begin
vVectorEditorForm.Free; vVectorEditorForm:=nil;
end;
end;
// Execute
//
function TVectorEditorForm.Execute(var x, y, z : Single) : Boolean;
begin
// setup dialog fields
vx:=x;
vy:=y;
vz:=z;
EDx.Text:=FloatToStr(vx);
EDy.Text:=FloatToStr(vy);
EDz.Text:=FloatToStr(vz);
// show the dialog
Result:=(ShowModal=mrOk);
if Result then begin
x:=vx;
y:=vy;
z:=vz;
end;
end;
procedure TVectorEditorForm.TestInput(edit : TEdit; imError : TImage; var dest : Single);
begin
if Visible then begin
try
dest:=StrToFloat(edit.Text);
imError.Visible:=False;
except
imError.Visible:=True;
end;
BBOk.Enabled:=not (IMx.Visible or IMy.Visible or IMz.Visible);
end;
end;
procedure TVectorEditorForm.TBxClick(Sender: TObject);
begin
EDx.Text:='1'; EDy.Text:='0'; EDz.Text:='0';
end;
procedure TVectorEditorForm.TByClick(Sender: TObject);
begin
EDx.Text:='0'; EDy.Text:='1'; EDz.Text:='0';
end;
procedure TVectorEditorForm.TBzClick(Sender: TObject);
begin
EDx.Text:='0'; EDy.Text:='0'; EDz.Text:='1';
end;
procedure TVectorEditorForm.TBnullClick(Sender: TObject);
begin
EDx.Text:='0'; EDy.Text:='0'; EDz.Text:='0';
end;
procedure TVectorEditorForm.EDxChange(Sender: TObject);
begin
TestInput(EDx, IMx, vx);
end;
procedure TVectorEditorForm.EDyChange(Sender: TObject);
begin
TestInput(EDy, IMy, vy);
end;
procedure TVectorEditorForm.EDzChange(Sender: TObject);
begin
TestInput(EDz, IMz, vz);
end;
procedure TVectorEditorForm.SBmXClick(Sender: TObject);
begin
EDx.Text:='-1'; EDy.Text:='0'; EDz.Text:='0';
end;
procedure TVectorEditorForm.SBmYClick(Sender: TObject);
begin
EDx.Text:='0'; EDy.Text:='-1'; EDz.Text:='0';
end;
procedure TVectorEditorForm.SBmZClick(Sender: TObject);
begin
EDx.Text:='0'; EDy.Text:='0'; EDz.Text:='-1';
end;
procedure TVectorEditorForm.SBUnitClick(Sender: TObject);
begin
EDx.Text:='1'; EDy.Text:='1'; EDz.Text:='1';
end;
procedure TVectorEditorForm.SpeedButton9Click(Sender: TObject);
var
v : TAffineVector;
begin
SetVector(v, GLUtils.StrToFloatDef(EDx.Text, 0), GLUtils.StrToFloatDef(EDy.Text, 0), GLUtils.StrToFloatDef(EDz.Text, 0));
if VectorLength(v)=0 then
v:=NullVector
else NormalizeVector(v);
EDx.Text:=FloatToStr(v.V[0]);
EDy.Text:=FloatToStr(v.V[1]);
EDz.Text:=FloatToStr(v.V[2]);
end;
procedure TVectorEditorForm.SBInvertClick(Sender: TObject);
var
v : TAffineVector;
begin
SetVector(v, GLUtils.StrToFloatDef(EDx.Text, 0), GLUtils.StrToFloatDef(EDy.Text, 0), GLUtils.StrToFloatDef(EDz.Text, 0));
NegateVector(v);
EDx.Text:=FloatToStr(v.V[0]);
EDy.Text:=FloatToStr(v.V[1]);
EDz.Text:=FloatToStr(v.V[2]);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
finalization
ReleaseVectorEditorForm;
end.
|
unit uWNJVioThread;
interface
uses
System.Classes, SysUtils, ActiveX, uGlobal;
type
TWNJVioThread = class(TThread)
private
function GetSecondPic(hphm, hpzl, picUrl: String; wfsj: TDateTime): String;
function Getpic(sql, picUrl: String): String;
function SaveVio(cjjg, hphm, hpzl, wfsj, wfdd, tp1, tp2: String): Boolean;
protected
procedure Execute; override;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TWNJVioThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ TWNJVioThread }
procedure TWNJVioThread.Execute;
var
s, cjjg, hphm, hpzl, wfdd, tp1, tp2: String;
wfsj: TDateTime;
vioList: TStrings;
begin
ActiveX.CoInitialize(nil);
vioList:= TStringList.Create;
gLogger.Info('WNJVioThread Start');
s := ' select c.CJJG, a.HPHM, a.HPZL, a.GCSJ, a.KDBH, a.VIOURL '
+' from T_KK_ALARMRESULT a '
+' inner join S_DEVICE c '
+' on a.KDBH = c.SBBH and c.WNJVio = 1 '
+' left join T_VIO_TEMP b '
+' on a.HPHM=b.HPHM and a.HPZL=b.HPZL and a.GCSJ=b.WFSJ '
+' where a.bkzl=''×Ô¶¯²¼¿Ø'' and a.BKLX=''06'' and a.GCSJ>''' +
FormatDateTime('yyyy-mm-dd hh:nn:ss', now - 3 / 24) +
''' and b.wfxw = ''1340'' and b.HPHM is null ';
with gSQLHelper.Query(s) do
begin
while not Eof do
begin
cjjg:= FieldByName('CJJG').AsString;
hphm:= FieldByName('hphm').AsString;
hpzl:= FieldByName('hpzl').AsString;
wfdd:= FieldByName('kdbh').AsString;
wfsj:= FieldByName('GCSJ').AsDateTime;
tp1:= FieldByName('VIOURL').AsString;
if vioList.IndexOf(hphm+hpzl) >= 0 then
continue;
tp2:= GetSecondPic(hphm, hpzl, tp1, wfsj);
if tp2 <> '' then
begin
if SaveVio(cjjg, hphm, hpzl, FormatDateTime('yyyy-mm-dd hh:nn:ss', wfsj), wfdd, tp1, tp2) then
vioList.Add(hphm+hpzl);
end;
Next;
end;
Free;
end;
gLogger.Info('WNJVioThread Start');
ActiveX.CoUninitialize;
end;
function TWNJVioThread.Getpic(sql, picUrl: String): String;
var
fwqdz, tp1, tp2: String;
begin
Result:= '';
fwqdz:= '';
tp1:= '';
tp2:= '';
with gSQLHelper.Query(sql) do
begin
while not Eof do
begin
fwqdz:= Trim(Fields[0].AsString);
tp1:= Trim(Fields[1].AsString);
tp2:= Trim(Fields[2].AsString);
if (fwqdz = '') or (tp1 = '') then
continue;
tp1:= fwqdz + tp1;
if tp1 <> picUrl then
begin
Result:= tp1;
break;
end;
if tp2 <> '' then
begin
tp2:= fwqdz + tp2;
if tp2 <> picUrl then
begin
Result:= tp2;
break;
end;
end;
Next;
end;
Free;
end;
end;
function TWNJVioThread.GetSecondPic(hphm, hpzl, picUrl: String; wfsj: TDateTime): String;
var
tbName, s: String;
begin
Result:= '';
tbName:= gConfig.DBNamePass + '.dbo.T_KK_VEH_PASSREC_' + FormatDatetime('yyyymmdd', wfsj);
s:= 'select FWQDZ, TP1, TP2 from ' + tbName + ' where hphm=' +
hphm.QuotedString + ' and hpzl=' + hpzl.QuotedString + ' and gcsj = ' +
FormatDatetime('yyyy-mm-dd hh:nn:ss', wfsj).QuotedString;
Result:= Getpic(s, picUrl);
if Result = '' then
begin
s:= ' select FWQDZ, TP1, TP2 from ' + tbName + ' where hphm=' +
hphm.QuotedString + ' and hpzl=' + hpzl.QuotedString + ' and gcsj <> ' +
FormatDatetime('yyyy-mm-dd hh:nn:ss', wfsj).QuotedString+' order by gcsj desc';
Result:= Getpic(s, picUrl);
end;
end;
function TWNJVioThread.SaveVio(cjjg, hphm, hpzl, wfsj, wfdd, tp1, tp2: String): Boolean;
var
s: String;
begin
s:= 'insert into T_VIO_TEMP(cjjg, hphm, hpzl, wfsj, wfdd, PHOTOFILE1, PHOTOFILE2, wfxw) values '
+'('+cjjg.QuotedString +','+hphm.QuotedString+','+hpzl.QuotedString+','
+wfsj.QuotedString+','+wfdd.QuotedString+','+tp1.QuotedString+','+tp2.QuotedString+',''1340'')';
Result:= gSQLHelper.ExecuteSql(s);
if Result then
gLogger.Info('[WNJVioThread] Save Vio Succ: ' + hphm + ',' + hpzl)
else
gLogger.Error('[WNJVioThread] Save Vio error: ' + s);
end;
end.
|
unit AEstagioProducao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Localizacao, StdCtrls, Mask,
DBCtrls, Tabela, DBKeyViolation, Db, DBTables, CBancoDados, Buttons,
BotaoCadastro, Grids, DBGrids, DBClient;
type
TFEstagioProducao = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor2: TPanelColor;
BotaoCadastrar1: TBotaoCadastrar;
BotaoAlterar1: TBotaoAlterar;
BotaoExcluir1: TBotaoExcluir;
BFechar: TBitBtn;
Grade: TGridIndice;
PanelColor1: TPanelColor;
BotaoConsultar1: TBotaoConsultar;
EDescricao: TEditColor;
Label2: TLabel;
EstagioProducao: TRBSQL;
EstagioProducaoCODEST: TFMTBCDField;
EstagioProducaoNOMEST: TWideStringField;
EstagioProducaoCODTIP: TFMTBCDField;
EstagioProducaoINDFIN: TWideStringField;
EstagioProducaoCODPLA: TWideStringField;
EstagioProducaoCODEMP: TFMTBCDField;
EstagioProducaoINDOBS: TWideStringField;
EstagioProducaoMAXDIA: TFMTBCDField;
EstagioProducaoTIPEST: TWideStringField;
EstagioProducaoDATALT: TSQLTimeStampField;
DataEstagioProducao: TDataSource;
EstagioProducaoVALHOR: TFMTBCDField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GradeOrdem(Ordem: String);
procedure BFecharClick(Sender: TObject);
procedure BotaoCadastrar1AntesAtividade(Sender: TObject);
procedure BotaoCadastrar1DepoisAtividade(Sender: TObject);
procedure BotaoAlterar1Atividade(Sender: TObject);
procedure BotaoExcluir1DepoisAtividade(Sender: TObject);
procedure BotaoExcluir1DestroiFormulario(Sender: TObject);
procedure EDescricaoExit(Sender: TObject);
procedure EDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
VprOrdem : string;
procedure AtualizaConsulta;
procedure AdicionaFiltros(VpaFiltros : TStrings);
public
{ Public declarations }
end;
var
FEstagioProducao: TFEstagioProducao;
implementation
uses APrincipal, ATipoEstagioProducao, FunObjeto, UnSistema, funSql, ANovoEstagio;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFEstagioProducao.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprOrdem := 'order by CODEST';
AtualizaConsulta;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFEstagioProducao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
EstagioProducao.Close;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFEstagioProducao.GradeOrdem(Ordem: String);
begin
VprOrdem := Ordem;
end;
{******************************************************************************}
procedure TFEstagioProducao.AdicionaFiltros(VpaFiltros: TStrings);
begin
if EDescricao.Text <> '' then
AdicionaSQLTabela(EstagioProducao,'and NOMEST LIKE '''+EDescricao.Text + '%''');
end;
{******************************************************************************}
procedure TFEstagioProducao.AtualizaConsulta;
begin
LimpaSQLTabela(EstagioProducao);
AdicionaSQLTabela(EstagioProducao,'Select * from ESTAGIOPRODUCAO '+
' Where 1 = 1');
AdicionaFiltros(EstagioProducao.SQL);
AdicionaSQLTabela(EstagioProducao,VprOrdem);
EstagioProducao.Open;
end;
{******************************************************************************}
procedure TFEstagioProducao.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFEstagioProducao.BotaoAlterar1Atividade(Sender: TObject);
begin
AdicionaSQLAbreTabela(FNovoEstagio.EstagioProducao,'Select * from ESTAGIOPRODUCAO ' +
' Where CODEST = '+IntToStr(EstagioProducaoCODEST.AsInteger));
end;
{******************************************************************************}
procedure TFEstagioProducao.BotaoCadastrar1AntesAtividade(Sender: TObject);
begin
FNovoEstagio := TFNovoEstagio.criarSDI(Application,'',FPrincipal.VerificaPermisao('FNovoEstagio'));
end;
{******************************************************************************}
procedure TFEstagioProducao.BotaoCadastrar1DepoisAtividade(Sender: TObject);
begin
FNovoEstagio.ShowModal;
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFEstagioProducao.BotaoExcluir1DepoisAtividade(Sender: TObject);
begin
FNovoEstagio.Show;
end;
{******************************************************************************}
procedure TFEstagioProducao.BotaoExcluir1DestroiFormulario(Sender: TObject);
begin
FNovoEstagio.Free;
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFEstagioProducao.EDescricaoExit(Sender: TObject);
begin
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFEstagioProducao.EDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if key = 13 then
AtualizaConsulta;
end;
{******************************************************************************}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFEstagioProducao]);
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://localhost:8080/wsdl/ISetExamState
// >Import : http://localhost:8080/wsdl/ISetExamState>0
// Version : 1.0
// (05/06/2015 03:07:30 - - $Rev: 69934 $)
// ************************************************************************ //
unit ISetExamState_Test;
interface
uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Embarcadero types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:dateTime - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:int - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:string - "http://www.w3.org/2001/XMLSchema"[Gbl]
SetExamStateRequest = class; { "urn:SetExamStateIntf"[GblCplx] }
SetExamStateResponse = class; { "urn:SetExamStateIntf"[GblCplx] }
// ************************************************************************ //
// XML : SetExamStateRequest, global, <complexType>
// Namespace : urn:SetExamStateIntf
// ************************************************************************ //
SetExamStateRequest = class(TRemotable)
private
Fusn: string;
Fpwd: string;
Fappointment_id: string;
Fexam_type_id: Integer;
Fexam_id: Integer;
Fexam_status: Integer;
Fexam_datetime: TXSDateTime;
public
destructor Destroy; override;
published
property usn: string read Fusn write Fusn;
property pwd: string read Fpwd write Fpwd;
property appointment_id: string read Fappointment_id write Fappointment_id;
property exam_id: Integer read Fexam_id write Fexam_id;
property exam_type_id: Integer read Fexam_type_id write Fexam_type_id;
property exam_status: Integer read Fexam_status write Fexam_status;
property exam_datetime: TXSDateTime read Fexam_datetime write Fexam_datetime;
end;
// ************************************************************************ //
// XML : SetExamStateResponse, global, <complexType>
// Namespace : urn:SetExamStateIntf
// ************************************************************************ //
SetExamStateResponse = class(TRemotable)
private
Fres_code: Integer;
Fres_msg: string;
published
property res_code: Integer read Fres_code write Fres_code;
property res_msg: string read Fres_msg write Fres_msg;
end;
// ************************************************************************ //
// Namespace : urn:SetExamStateIntf-ISetExamState
// soapAction: urn:SetExamStateIntf-ISetExamState#SetExamState
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// use : encoded
// binding : ISetExamStatebinding
// service : ISetExamStateservice
// port : ISetExamStatePort
// URL : http://localhost:8080/soap/ISetExamState
// ************************************************************************ //
ISetExamState = interface(IInvokable)
['{D4C8E1C3-BCC0-CFB7-6932-FF17EB64A83B}']
function SetExamState(const pSetExamStateRequest: SetExamStateRequest): SetExamStateResponse; stdcall;
end;
function GetISetExamState(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ISetExamState;
implementation
uses System.SysUtils;
function GetISetExamState(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ISetExamState;
const
defWSDL = 'http://localhost:8080/wsdl/ISetExamState';
defURL = 'http://localhost:8080/soap/ISetExamState';
defSvc = 'ISetExamStateservice';
defPrt = 'ISetExamStatePort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as ISetExamState);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor SetExamStateRequest.Destroy;
begin
System.SysUtils.FreeAndNil(Fexam_datetime);
inherited Destroy;
end;
initialization
{ ISetExamState }
InvRegistry.RegisterInterface(TypeInfo(ISetExamState), 'urn:SetExamStateIntf-ISetExamState', '');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ISetExamState), 'urn:SetExamStateIntf-ISetExamState#SetExamState');
RemClassRegistry.RegisterXSClass(SetExamStateRequest, 'urn:SetExamStateIntf', 'SetExamStateRequest');
RemClassRegistry.RegisterXSClass(SetExamStateResponse, 'urn:SetExamStateIntf', 'SetExamStateResponse');
end. |
unit frmUserGroupList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList,
Vcl.XPStyleActnCtrls, Vcl.ActnMan, Vcl.Menus, Vcl.ComCtrls,uUserInfo;
type
TfUserGroupList = class(TForm)
lv1: TListView;
pm1: TPopupMenu;
NewGroup1: TMenuItem;
DeleteGroup2: TMenuItem;
EditGroup1: TMenuItem;
DeleteGroup3: TMenuItem;
N3: TMenuItem;
Refresh2: TMenuItem;
actmgr1: TActionManager;
actNewGroup: TAction;
actRefresh: TAction;
actDelGroup: TAction;
actEditGroup: TAction;
procedure FormShow(Sender: TObject);
procedure actNewGroupExecute(Sender: TObject);
procedure actEditGroupExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure actDelGroupExecute(Sender: TObject);
private
{ Private declarations }
procedure AddGroupList(AGroup : TUserGroup);
procedure LoadGroupData;
public
{ Public declarations }
end;
var
fUserGroupList: TfUserGroupList;
implementation
uses
uUserControl, frmUserGroupInfo;
{$R *.dfm}
{ TfUserGroupOption }
procedure TfUserGroupList.actDelGroupExecute(Sender: TObject);
var
AUserGroup : TUserGroup;
begin
if lv1.Selected <> nil then
begin
if MessageBox(0, '确认要删除选择的记录吗?', '提示',
MB_YESNO + MB_ICONQUESTION) = IDYES then
begin
AUserGroup := TUserGroup(lv1.Selected.Data);
if Assigned(UserControl) then
begin
UserControl.DelUserGroup(AUserGroup);
lv1.DeleteSelected;
ShowMessage('删除组成功!');
end
else
ShowMessage('删除组失败');
end;
end;
end;
procedure TfUserGroupList.actEditGroupExecute(Sender: TObject);
var
AUserGroup : TUserGroup;
lvSel : TListItem;
begin
if lv1.ItemIndex <> -1 then
begin
lvSel := lv1.Selected;
AUserGroup := TUserGroup(lvSel.Data);
with TfUserGroupInfo.Create(nil) do
begin
ShowInfo(AUserGroup);
if ShowModal = mrOk then
begin
SaveInfo;
if Assigned(UserControl) then
begin
UserControl.SaveUserGroup(AUserGroup);
with lvSel do
begin
Caption := AUserGroup.GroupName;
SubItems[0] := AUserGroup.Description;
Data := AUserGroup;
end;
MessageBox(0, '编辑成功!', '提示', MB_OK);
end;
end;
Free;
end;
end
else
begin
MessageBox(0, '请选择需要编辑的组!', '提示', MB_OK);
end;
end;
procedure TfUserGroupList.actNewGroupExecute(Sender: TObject);
var
AUserGroup : TUserGroup;
begin
with TfUserGroupInfo.Create(nil) do
begin
AUserGroup := TUserGroup.Create;
ShowInfo(AUserGroup);
if ShowModal = mrOk then
begin
SaveInfo;
if Assigned(UserControl) then
begin
UserControl.SaveUserGroup(AUserGroup);
AddGroupList(AUserGroup);
MessageBox(0, '保存成功!', '提示', MB_OK);
end;
end;
Free;
end;
end;
procedure TfUserGroupList.actRefreshExecute(Sender: TObject);
begin
LoadGroupData;
end;
procedure TfUserGroupList.AddGroupList(AGroup: TUserGroup);
begin
if Assigned(AGroup) then
begin
with lv1.Items.Add, TUserGroup( AGroup ) do
begin
Caption := GroupName;
SubItems.Add( Description );
Data := AGroup;
end;
end;
end;
procedure TfUserGroupList.FormShow(Sender: TObject);
begin
LoadGroupData;
end;
procedure TfUserGroupList.LoadGroupData;
var
i : integer;
begin
lv1.Items.Clear;
if Assigned(UserControl) then
begin
with UserControl.UserGroupList do
begin
for i := 0 to Count - 1 do
AddGroupList(TUserGroup(Objects[i]));
end;
end;
if lv1.Items.Count > 0 then
lv1.ItemIndex := 0;
end;
end.
|
{$R-}
{$Q-}
unit ncEncRc6;
// To disable as much of RTTI as possible (Delphi 2009/2010),
// Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$ENDIF}
interface
uses
System.Classes, System.Sysutils, ncEnccrypt2, ncEncblockciphers;
const
NUMROUNDS = 20; { number of rounds must be between 16-24 }
type
TncEnc_rc6 = class(TncEnc_blockcipher128)
protected
KeyData: array [0 .. ((NUMROUNDS * 2) + 3)] of DWord;
procedure InitKey(const Key; Size: longword); override;
public
class function GetAlgorithm: string; override;
class function GetMaxKeySize: integer; override;
class function SelfTest: boolean; override;
procedure Burn; override;
procedure EncryptECB(const InData; var OutData); override;
procedure DecryptECB(const InData; var OutData); override;
end;
{ ****************************************************************************** }
{ ****************************************************************************** }
implementation
uses ncEncryption;
const
sBox: array [0 .. 51] of DWord = ($B7E15163, $5618CB1C, $F45044D5, $9287BE8E, $30BF3847, $CEF6B200, $6D2E2BB9, $0B65A572, $A99D1F2B, $47D498E4, $E60C129D,
$84438C56, $227B060F, $C0B27FC8, $5EE9F981, $FD21733A, $9B58ECF3, $399066AC, $D7C7E065, $75FF5A1E, $1436D3D7, $B26E4D90, $50A5C749, $EEDD4102, $8D14BABB,
$2B4C3474, $C983AE2D, $67BB27E6, $05F2A19F, $A42A1B58, $42619511, $E0990ECA, $7ED08883, $1D08023C, $BB3F7BF5, $5976F5AE, $F7AE6F67, $95E5E920, $341D62D9,
$D254DC92, $708C564B, $0EC3D004, $ACFB49BD, $4B32C376, $E96A3D2F, $87A1B6E8, $25D930A1, $C410AA5A, $62482413, $007F9DCC, $9EB71785, $3CEE913E);
function LRot32(X: DWord; c: longword): DWord;
begin
LRot32 := (X shl c) or (X shr (32 - c));
end;
function RRot32(X: DWord; c: longword): DWord;
begin
RRot32 := (X shr c) or (X shl (32 - c));
end;
class function TncEnc_rc6.GetAlgorithm: string;
begin
Result := 'RC6';
end;
class function TncEnc_rc6.GetMaxKeySize: integer;
begin
Result := 2048;
end;
class function TncEnc_rc6.SelfTest: boolean;
const
Key1: array [0 .. 15] of byte = ($01, $23, $45, $67, $89, $AB, $CD, $EF, $01, $12, $23, $34, $45, $56, $67, $78);
Plain1: array [0 .. 15] of byte = ($02, $13, $24, $35, $46, $57, $68, $79, $8A, $9B, $AC, $BD, $CE, $DF, $E0, $F1);
Cipher1: array [0 .. 15] of byte = ($52, $4E, $19, $2F, $47, $15, $C6, $23, $1F, $51, $F6, $36, $7E, $A4, $3F, $18);
Key2: array [0 .. 31] of byte = ($01, $23, $45, $67, $89, $AB, $CD, $EF, $01, $12, $23, $34, $45, $56, $67, $78, $89, $9A, $AB, $BC, $CD, $DE, $EF, $F0, $10,
$32, $54, $76, $98, $BA, $DC, $FE);
Plain2: array [0 .. 15] of byte = ($02, $13, $24, $35, $46, $57, $68, $79, $8A, $9B, $AC, $BD, $CE, $DF, $E0, $F1);
Cipher2: array [0 .. 15] of byte = ($C8, $24, $18, $16, $F0, $D7, $E4, $89, $20, $AD, $16, $A1, $67, $4E, $5D, $48);
var
Cipher: TncEnc_rc6;
Data: array [0 .. 15] of byte;
begin
Cipher := TncEnc_rc6.Create(nil);
Cipher.Init(Key1, Sizeof(Key1) * 8, nil);
Cipher.EncryptECB(Plain1, Data);
Result := boolean(CompareMem(@Data, @Cipher1, Sizeof(Data)));
Cipher.DecryptECB(Data, Data);
Result := Result and boolean(CompareMem(@Data, @Plain1, Sizeof(Data)));
Cipher.Burn;
Cipher.Init(Key2, Sizeof(Key2) * 8, nil);
Cipher.EncryptECB(Plain2, Data);
Result := Result and boolean(CompareMem(@Data, @Cipher2, Sizeof(Data)));
Cipher.DecryptECB(Data, Data);
Result := Result and boolean(CompareMem(@Data, @Plain2, Sizeof(Data)));
Cipher.Burn;
Cipher.Free;
end;
procedure TncEnc_rc6.InitKey(const Key; Size: longword);
var
xKeyD: array [0 .. 63] of DWord;
i, j, k, xKeyLen: longword;
A, B: DWord;
begin
Size := Size div 8;
FillChar(xKeyD, Sizeof(xKeyD), 0);
Move(Key, xKeyD, Size);
xKeyLen := Size div 4;
if (Size mod 4) <> 0 then
Inc(xKeyLen);
Move(sBox, KeyData, ((NUMROUNDS * 2) + 4) * 4);
i := 0;
j := 0;
A := 0;
B := 0;
if xKeyLen > ((NUMROUNDS * 2) + 4) then
k := xKeyLen * 3
else
k := ((NUMROUNDS * 2) + 4) * 3;
for k := 1 to k do
begin
A := LRot32(KeyData[i] + A + B, 3);
KeyData[i] := A;
B := LRot32(xKeyD[j] + A + B, A + B);
xKeyD[j] := B;
i := (i + 1) mod ((NUMROUNDS * 2) + 4);
j := (j + 1) mod xKeyLen;
end;
FillChar(xKeyD, Sizeof(xKeyD), 0);
end;
procedure TncEnc_rc6.Burn;
begin
FillChar(KeyData, Sizeof(KeyData), $FF);
inherited Burn;
end;
procedure TncEnc_rc6.EncryptECB(const InData; var OutData);
var
x0, x1, x2, x3: DWord;
u, t: DWord;
i: longword;
begin
if not fInitialized then
raise EncEnc_blockcipher.Create('Cipher not initialized');
x0 := PDword(@InData)^;
x1 := PDword(longword(@InData) + 4)^;
x2 := PDword(longword(@InData) + 8)^;
x3 := PDword(longword(@InData) + 12)^;
x1 := x1 + KeyData[0];
x3 := x3 + KeyData[1];
for i := 1 to NUMROUNDS do
begin
t := LRot32(x1 * (2 * x1 + 1), 5);
u := LRot32(x3 * (2 * x3 + 1), 5);
x0 := LRot32(x0 xor t, u) + KeyData[2 * i];
x2 := LRot32(x2 xor u, t) + KeyData[2 * i + 1];
t := x0;
x0 := x1;
x1 := x2;
x2 := x3;
x3 := t;
end;
x0 := x0 + KeyData[(2 * NUMROUNDS) + 2];
x2 := x2 + KeyData[(2 * NUMROUNDS) + 3];
PDword(@OutData)^ := x0;
PDword(longword(@OutData) + 4)^ := x1;
PDword(longword(@OutData) + 8)^ := x2;
PDword(longword(@OutData) + 12)^ := x3;
end;
procedure TncEnc_rc6.DecryptECB(const InData; var OutData);
var
x0, x1, x2, x3: DWord;
u, t: DWord;
i: longword;
begin
if not fInitialized then
raise EncEnc_blockcipher.Create('Cipher not initialized');
x0 := PDword(@InData)^;
x1 := PDword(longword(@InData) + 4)^;
x2 := PDword(longword(@InData) + 8)^;
x3 := PDword(longword(@InData) + 12)^;
x2 := x2 - KeyData[(2 * NUMROUNDS) + 3];
x0 := x0 - KeyData[(2 * NUMROUNDS) + 2];
for i := NUMROUNDS downto 1 do
begin
t := x0;
x0 := x3;
x3 := x2;
x2 := x1;
x1 := t;
u := LRot32(x3 * (2 * x3 + 1), 5);
t := LRot32(x1 * (2 * x1 + 1), 5);
x2 := RRot32(x2 - KeyData[2 * i + 1], t) xor u;
x0 := RRot32(x0 - KeyData[2 * i], u) xor t;
end;
x3 := x3 - KeyData[1];
x1 := x1 - KeyData[0];
PDword(@OutData)^ := x0;
PDword(longword(@OutData) + 4)^ := x1;
PDword(longword(@OutData) + 8)^ := x2;
PDword(longword(@OutData) + 12)^ := x3;
end;
end.
|
unit binsearch_range_1;
interface
implementation
type
TIntArray = array of Integer;
function SearchInRange(const Values: TIntArray; const Value: Integer; out FoundIndex: Integer): Boolean;
var
L, H: Integer;
mid, cmp: Integer;
LastState: (ssNone, sLess, sGreater);
begin
Result := False;
L := 0;
H := Length(Values) - 1;
LastState := ssNone;
while L <= H do
begin
mid := L + (H - L) shr 1;
cmp := Values[mid] - Value;
if cmp < 0 then
begin
if L = H then
begin
FoundIndex := L;
Exit;
end;
L := mid + 1;
LastState := sGreater;
end else
if cmp = 0 then
begin
FoundIndex := mid;
Result := True;
Exit;
end else
begin
if (L = H) and (LastState = sGreater) then
begin
FoundIndex := L - 1;
Exit;
end;
H := mid - 1;
LastState := sLess;
end;
end;
FoundIndex := H;
end;
var
A: TIntArray;
I: Integer;
B: Boolean;
procedure Test1;
begin
A := [];
B := SearchInRange(A, 5, I);
Assert(I = -1);
end;
procedure Test2;
begin
A := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
B := SearchInRange(A, 5, I);
Assert(I = 5);
end;
procedure Test3;
begin
A := [0, 2, 4, 6, 8, 10];
B := SearchInRange(A, 3, I);
Assert(I = 1);
end;
procedure Test4;
begin
A := [0, 2, 4, 6, 8, 10];
B := SearchInRange(A, 5, I);
Assert(I = 2);
end;
procedure Test5;
begin
A := [0, 2, 4, 6, 8, 10];
B := SearchInRange(A, 9, I);
Assert(I = 4);
end;
procedure Test6;
begin
A := [0, 2, 4, 6, 8, 10];
B := SearchInRange(A, 10, I);
Assert(I = 5);
end;
procedure Test7;
begin
A := [0, 2, 4, 6, 8, 10];
B := SearchInRange(A, 11, I);
Assert(I = 5);
end;
initialization
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
finalization
end. |
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXStreamer;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXStream;
type
TDBXJSonReader = class(TDBXReader)
public
constructor Create(const DbxContext: TDBXContext; const ADbxRow: TDBXRow; const ARowHandle: Integer; const ACommandHandle: Integer; const ADbxValues: TDBXWritableValueArray; const ADbxReader: TDBXJSonStreamReader; const ADbxWriter: TDBXJSonStreamWriter; const ADbxRowBuffer: TDBXRowBuffer; const Updateable: Boolean);
destructor Destroy; override;
function ReadFirstData: Boolean;
procedure DerivedClose; override;
function DerivedNext: Boolean; override;
protected
function GetRowHandle: Integer; override;
function GetByteReader: TDBXByteReader; override;
function IsUpdateable: Boolean; override;
private
function ReadData: Boolean;
private
FPosition: Int64;
FCommandHandle: Integer;
FRowHandle: Integer;
FDbxReader: TDBXJSonStreamReader;
FDbxWriter: TDBXJSonStreamWriter;
FDbxRowBuffer: TDBXRowBuffer;
FUpdateable: Boolean;
FReadLastBuffer: Boolean;
FByteReader: TDBXByteReader;
FInitialized: Boolean;
end;
implementation
uses
Data.DBXClient,
Data.DBXPlatform,
System.SysUtils;
constructor TDBXJSonReader.Create(const DbxContext: TDBXContext; const ADbxRow: TDBXRow; const ARowHandle: Integer; const ACommandHandle: Integer; const ADbxValues: TDBXWritableValueArray; const ADbxReader: TDBXJSonStreamReader; const ADbxWriter: TDBXJSonStreamWriter; const ADbxRowBuffer: TDBXRowBuffer; const Updateable: Boolean);
begin
inherited Create(DbxContext, ADbxRow, nil);
FRowHandle := ARowHandle;
FCommandHandle := ACommandHandle;
FDbxReader := ADbxReader;
FDbxWriter := ADbxWriter;
FDbxRowBuffer := ADbxRowBuffer;
SetValues(ADbxValues);
FPosition := -1;
FDbxRowBuffer.ColumnCount := ColumnCount;
end;
destructor TDBXJSonReader.Destroy;
begin
FreeAndNil(FDbxRowBuffer);
FreeAndNil(FByteReader);
inherited Destroy;
end;
function TDBXJSonReader.ReadFirstData: Boolean;
begin
if not FInitialized then
begin
FInitialized := True;
Exit(ReadData);
end;
Result := False;
end;
function TDBXJSonReader.GetRowHandle: Integer;
begin
Result := FRowHandle;
end;
function TDBXJSonReader.GetByteReader: TDBXByteReader;
begin
if FByteReader = nil then
FByteReader := TDBXJSonByteReader.Create(DBXContext, RowHandle, self, FDbxReader, FDbxWriter, FDbxRowBuffer);
Result := FByteReader;
end;
procedure TDBXJSonReader.DerivedClose;
begin
if (FDbxWriter <> nil) and (FRowHandle >= 0) then
FDbxWriter.WriteReaderCloseObject(FRowHandle, FCommandHandle);
FreeAndNil(FByteReader);
end;
function TDBXJSonReader.DerivedNext: Boolean;
begin
if FPosition < 0 then
begin
FPosition := 0;
Result := (FDbxRowBuffer.ReadSize > 0);
end
else if FDbxRowBuffer.NextRow then
begin
FPosition := FPosition + 1;
Result := True;
end
else
begin
if FReadLastBuffer then
Result := False
else
begin
if FDbxRowBuffer.Client then
FDbxWriter.WriteClientNextObject(FRowHandle, FPosition + 1, FCommandHandle)
else
FDbxWriter.WriteServerNextObject(FRowHandle, FPosition + 1, FCommandHandle);
FDbxWriter.Flush;
if ReadData then
begin
FPosition := FPosition + 1;
Exit(True);
end;
Result := False;
end;
end;
end;
function TDBXJSonReader.IsUpdateable: Boolean;
begin
Result := FUpdateable;
end;
function TDBXJSonReader.ReadData: Boolean;
var
DataSize: Integer;
ResultCode: Integer;
HasData: Boolean;
Buffer: TBytes;
begin
HasData := False;
FDbxReader.Next(TDBXTokens.ObjectStartToken);
FDbxReader.Next(TDBXTokens.StringStartToken);
ResultCode := FDbxReader.ReadStringCode;
if ResultCode = TDBXStringCodes.Data then
begin
FDbxReader.Next(TDBXTokens.NameSeparatorToken);
FDbxReader.Next(TDBXTokens.ArrayStartToken);
DataSize := FDbxReader.ReadInt;
if DataSize > 0 then
FReadLastBuffer := False
else
begin
FReadLastBuffer := True;
DataSize := -DataSize;
end;
if DataSize <> 0 then
begin
Buffer := FDbxRowBuffer.Buffer;
if Length(Buffer) < DataSize then
begin
FDbxRowBuffer.Growbuf(DataSize - Length(Buffer));
Buffer := FDbxRowBuffer.Buffer;
end;
FDbxReader.Next(TDBXTokens.ValueSeparatorToken);
FDbxReader.ReadDataBytes(FDbxRowBuffer.Buffer, 0, DataSize);
HasData := True;
end;
FDbxRowBuffer.ReadSize := DataSize;
end
else if ResultCode = TDBXStringCodes.Error then
FDbxReader.ReadErrorBody;
FDbxReader.SkipToEndOfObject;
Result := HasData;
end;
end.
|
unit caMarkup;
{$INCLUDE ca.inc}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
caClasses,
caUtils,
// caUtils,
caGraphics;
type
//---------------------------------------------------------------------------
// IcaHTMLElement
//---------------------------------------------------------------------------
IcaHTMLElement = interface
['{EA991982-EC63-4D17-9DF8-FD373629DB4D}']
// Property methods
function GetAscent: Integer;
function GetBeginText: String;
function GetBounds: TRect;
function GetBreakLine: Boolean;
function GetEndText: String;
function GetFontColor: TColor;
function GetFontName: String;
function GetFontSize: Integer;
function GetFontStyle: TFontStyles;
function GetHeight: Integer;
function GetText: String;
function GetWidth: Integer;
procedure SetAscent(const Value: Integer);
procedure SetBeginText(const Value: String);
procedure SetBounds(const Value: TRect);
procedure SetBreakLine(const Value: Boolean);
procedure SetEndText(const Value: String);
procedure SetFontColor(const Value: TColor);
procedure SetFontName(const Value: String);
procedure SetFontSize(const Value: Integer);
procedure SetFontStyle(const Value: TFontStyles);
procedure SetHeight(const Value: Integer);
procedure SetText(const Value: String);
procedure SetWidth(const Value: Integer);
// Public methods
procedure Break(ACanvas: TCanvas; AvailableWidth: Integer);
// Properties
property Ascent: Integer read GetAscent write SetAscent;
property BeginText: String read GetBeginText write SetBeginText;
property Bounds: TRect read GetBounds write SetBounds;
property BreakLine: Boolean read GetBreakLine write SetBreakLine;
property EndText: String read GetEndText write SetEndText;
property FontColor: TColor read GetFontColor write SetFontColor;
property FontName: String read GetFontName write SetFontName;
property FontSize: Integer read GetFontSize write SetFontSize;
property FontStyle: TFontStyles read GetFontStyle write SetFontStyle;
property Height: Integer read GetHeight write SetHeight;
property Text: String read GetText write SetText;
property Width: Integer read GetWidth write SetWidth;
end;
//---------------------------------------------------------------------------
// TcaHTMLElement
//---------------------------------------------------------------------------
TcaHTMLElement = class(TInterfacedObject, IcaHTMLElement)
private
FAscent: Integer;
FBeginText: String;
FBounds: TRect;
FBreakLine: Boolean;
FEndText: String;
FFontColor: TColor;
FFontName: String;
FFontSize: Integer;
FFontStyle: TFontStyles;
FHeight: Integer;
FText: String;
FWidth: Integer;
function GetAscent: Integer;
function GetBeginText: String;
function GetBounds: TRect;
function GetBreakLine: Boolean;
function GetEndText: String;
function GetFontColor: TColor;
function GetFontName: String;
function GetFontSize: Integer;
function GetFontStyle: TFontStyles;
function GetHeight: Integer;
function GetText: String;
function GetWidth: Integer;
procedure SetAscent(const Value: Integer);
procedure SetBeginText(const Value: String);
procedure SetBounds(const Value: TRect);
procedure SetBreakLine(const Value: Boolean);
procedure SetEndText(const Value: String);
procedure SetFontColor(const Value: TColor);
procedure SetFontName(const Value: String);
procedure SetFontSize(const Value: Integer);
procedure SetFontStyle(const Value: TFontStyles);
procedure SetHeight(const Value: Integer);
procedure SetText(const Value: String);
procedure SetWidth(const Value: Integer);
public
procedure Break(ACanvas: TCanvas; AvailableWidth: Integer);
property Ascent: Integer read GetAscent write SetAscent;
property BeginText: String read GetBeginText write SetBeginText;
property Bounds: TRect read GetBounds write SetBounds;
property BreakLine: Boolean read GetBreakLine write SetBreakLine;
property EndText: String read GetEndText write SetEndText;
property FontColor: TColor read GetFontColor write SetFontColor;
property FontName: String read GetFontName write SetFontName;
property FontSize: Integer read GetFontSize write SetFontSize;
property FontStyle: TFontStyles read GetFontStyle write SetFontStyle;
property Height: Integer read GetHeight write SetHeight;
property Text: String read GetText write SetText;
property Width: Integer read GetWidth write SetWidth;
end;
//---------------------------------------------------------------------------
// IcaHTMLElementList
//---------------------------------------------------------------------------
IcaHTMLElementList = interface
['{BA19C11B-22A6-46A8-A945-648AD4AD2ED0}']
// Property methods
function GetItem(Index: Integer): TcaHTMLElement;
procedure SetItem(Index: Integer; const Item: TcaHTMLElement);
// Public methods
function Add(Item: TcaHTMLElement): Integer;
function Extract(Item: TcaHTMLElement): TcaHTMLElement;
function First: TcaHTMLElement;
function IndexOf(Item: TcaHTMLElement): Integer;
function Last: TcaHTMLElement;
function Remove(Item: TcaHTMLElement): Integer;
procedure Insert(Index: Integer; Item: TcaHTMLElement);
// Properties
property Items[Index: Integer]: TcaHTMLElement read GetItem write SetItem;
end;
//---------------------------------------------------------------------------
// IcaHTMLElementStack
//---------------------------------------------------------------------------
IcaHTMLElementStack = interface
['{22A74502-8838-4A61-A267-27CDFD9CF6CE}']
procedure Push(Item: TcaHTMLElement);
function Pop: TcaHTMLElement;
function Peek: TcaHTMLElement;
end;
//---------------------------------------------------------------------------
// TcaHTMLElementList
//---------------------------------------------------------------------------
TcaHTMLElementList = class(TInterfacedObject, IcaList, IcaHTMLElementList, IcaHTMLElementStack)
private
FListBase: IcaList;
function GetItem(Index: Integer): TcaHTMLElement;
procedure SetItem(Index: Integer; const Value: TcaHTMLElement);
public
constructor Create;
function Add(Item: TcaHTMLElement): Integer;
function Extract(Item: TcaHTMLElement): TcaHTMLElement;
function First: TcaHTMLElement;
function IndexOf(Item: TcaHTMLElement): Integer;
function Last: TcaHTMLElement;
function Peek: TcaHTMLElement;
function Pop: TcaHTMLElement;
function Remove(Item: TcaHTMLElement): Integer;
procedure Push(Item: TcaHTMLElement);
procedure Insert(Index: Integer; Item: TcaHTMLElement);
property Items[Index: Integer]: TcaHTMLElement read GetItem write SetItem;
property ListBase: IcaList read FListBase implements IcaList;
end;
//---------------------------------------------------------------------------
// IcaMarkupViewer
//---------------------------------------------------------------------------
IcaMarkupViewer = interface
['{4DAB603A-C02D-4C0C-BABD-8EC67DCDDC20}']
// Property methods
function GetColor: TColor;
function GetLines: TStrings;
function GetMarginLeft: Integer;
function GetMarginRight: Integer;
function GetMarginTop: Integer;
function GetMouseOverElement: TcaHTMLElement;
procedure SetColor(const Value: TColor);
procedure SetLines(const Value: TStrings);
procedure SetMarginLeft(const Value: Integer);
procedure SetMarginRight(const Value: Integer);
procedure SetMarginTop(const Value: Integer);
procedure SetMouseOverElement(const Value: TcaHTMLElement);
// Properties
property Color: TColor read GetColor write SetColor;
property Lines: TStrings read GetLines write SetLines;
property MarginLeft: Integer read GetMarginLeft write SetMarginLeft;
property MarginRight: Integer read GetMarginRight write SetMarginRight;
property MarginTop: Integer read GetMarginTop write SetMarginTop;
property MouseOverElement: TcaHTMLElement read GetMouseOverElement write SetMouseOverElement;
end;
//---------------------------------------------------------------------------
// TcaCustomMarkupViewer
//---------------------------------------------------------------------------
TcaCustomMarkupViewer = class(TCustomControl, IcaMarkupViewer)
private
FBitmap: TBitmap;
FColor: TColor;
FElementStack: IcaHTMLElementStack;
FFrameBottom: Integer;
FFrameTop: Integer;
FLines: TStrings;
FMarginLeft: Integer;
FMarginRight: Integer;
FMarginTop: Integer;
FMouseOverElement: TcaHTMLElement;
FPageBottom: Integer;
FScrollBar: TScrollbar;
FTagStack: IcaHTMLElementStack;
// Property methods
function GetColor: TColor;
function GetLines: TStrings;
function GetMarginLeft: Integer;
function GetMarginRight: Integer;
function GetMarginTop: Integer;
function GetMouseOverElement: TcaHTMLElement;
procedure SetColor(const Value: TColor);
procedure SetLines(const Value: TStrings);
procedure SetMarginLeft(const Value: Integer);
procedure SetMarginRight(const Value: Integer);
procedure SetMarginTop(const Value: Integer);
procedure SetMouseOverElement(const Value: TcaHTMLElement);
// Private methods
function GetElement(Index: Integer): TcaHTMLElement;
function GetElementCount: Integer;
procedure ClearBreakText;
procedure LinesChanged;
procedure LinesChangedEvent(Sender: TObject);
procedure ParseHTML;
procedure RenderHTML;
procedure ScrollViewerEvent(Sender: TObject);
procedure UpdateConstraints;
procedure UpdateElementDimensions;
procedure UpdateMouseOverElement(X, Y: Integer);
// Message handlers
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
procedure CreateWnd; override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
property Color: TColor read GetColor write SetColor;
property Lines: TStrings read GetLines write SetLines;
property MarginLeft: Integer read GetMarginLeft write SetMarginLeft;
property MarginRight: Integer read GetMarginRight write SetMarginRight;
property MarginTop: Integer read GetMarginTop write SetMarginTop;
property MouseOverElement: TcaHTMLElement read GetMouseOverElement write SetMouseOverElement;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
end;
//---------------------------------------------------------------------------
// TcaMarkupViewer
//---------------------------------------------------------------------------
TcaMarkupViewer = class(TcaCustomMarkupViewer)
public
property MouseOverElement;
published
property Align;
property Anchors;
property Color;
property Constraints;
property Lines;
property MarginLeft;
property MarginRight;
property MarginTop;
property OnMouseMove;
end;
implementation
//---------------------------------------------------------------------------
// TcaHTMLElement
//---------------------------------------------------------------------------
procedure TcaHTMLElement.Break(ACanvas: TCanvas; AvailableWidth: Integer);
var
S: String;
Index: Integer;
Wth: Integer;
begin
ACanvas.Font.Name := FFontName;
ACanvas.Font.Size := FFontSize;
ACanvas.Font.Style := FFontStyle;
ACanvas.Font.Color := FFontColor;
if FBeginText = '' then
S := FText
else
S := FEndText;
if ACanvas.TextWidth(S) <= AvailableWidth then
begin
FBeginText := S;
FEndText := '';
end
else
begin
for Index := Length(S) downto 1 do
begin
if S[Index] = #32 then
begin
Wth := ACanvas.TextWidth(Copy(S, 1, Index));
if Wth <= AvailableWidth then
begin
FBeginText := Copy(S, 1, Index);
FEndText := Copy(S, Index + 1, Length(S));
System.Break;
end;
end;
end;
end;
end;
function TcaHTMLElement.GetAscent: Integer;
begin
Result := FAscent;
end;
function TcaHTMLElement.GetBeginText: String;
begin
Result := FBeginText;
end;
function TcaHTMLElement.GetBounds: TRect;
begin
Result := FBounds;
end;
function TcaHTMLElement.GetBreakLine: Boolean;
begin
Result := FBreakLine;
end;
function TcaHTMLElement.GetEndText: String;
begin
Result := FEndText;
end;
function TcaHTMLElement.GetFontColor: TColor;
begin
Result := FFontColor;
end;
function TcaHTMLElement.GetFontName: String;
begin
Result := FFontName;
end;
function TcaHTMLElement.GetFontSize: Integer;
begin
Result := FFontSize;
end;
function TcaHTMLElement.GetFontStyle: TFontStyles;
begin
Result := FFontStyle;
end;
function TcaHTMLElement.GetHeight: Integer;
begin
Result := FHeight;
end;
function TcaHTMLElement.GetText: String;
begin
Result := FText;
end;
function TcaHTMLElement.GetWidth: Integer;
begin
Result := FWidth;
end;
procedure TcaHTMLElement.SetAscent(const Value: Integer);
begin
FAscent := Value;
end;
procedure TcaHTMLElement.SetBeginText(const Value: String);
begin
FBeginText := Value;
end;
procedure TcaHTMLElement.SetBounds(const Value: TRect);
begin
FBounds := Value;
end;
procedure TcaHTMLElement.SetBreakLine(const Value: Boolean);
begin
FBreakLine := Value;
end;
procedure TcaHTMLElement.SetEndText(const Value: String);
begin
FEndText := Value;
end;
procedure TcaHTMLElement.SetFontColor(const Value: TColor);
begin
FFontColor := Value;
end;
procedure TcaHTMLElement.SetFontName(const Value: String);
begin
FFontName := Value;
end;
procedure TcaHTMLElement.SetFontSize(const Value: Integer);
begin
FFontSize := Value;
end;
procedure TcaHTMLElement.SetFontStyle(const Value: TFontStyles);
begin
FFontStyle := Value;
end;
procedure TcaHTMLElement.SetHeight(const Value: Integer);
begin
FHeight := Value;
end;
procedure TcaHTMLElement.SetText(const Value: String);
begin
FText := Value;
end;
procedure TcaHTMLElement.SetWidth(const Value: Integer);
begin
FWidth := Value;
end;
//---------------------------------------------------------------------------
// TcaHTMLElementList
//---------------------------------------------------------------------------
constructor TcaHTMLElementList.Create;
begin
inherited;
FListBase := TcaList.Create;
end;
function TcaHTMLElementList.Add(Item: TcaHTMLElement): Integer;
begin
Result := FListBase.List.Add(Pointer(Item));
end;
function TcaHTMLElementList.Extract(Item: TcaHTMLElement): TcaHTMLElement;
begin
Result := TcaHTMLElement(FListBase.List.Extract(Pointer(Item)));
end;
function TcaHTMLElementList.First: TcaHTMLElement;
begin
Result := TcaHTMLElement(FListBase.List.First);
end;
function TcaHTMLElementList.GetItem(Index: Integer): TcaHTMLElement;
begin
Result := TcaHTMLElement(FListBase.List.Items[Index]);
end;
function TcaHTMLElementList.IndexOf(Item: TcaHTMLElement): Integer;
begin
Result := FListBase.List.IndexOf(Pointer(Item));
end;
procedure TcaHTMLElementList.Insert(Index: Integer;
Item: TcaHTMLElement);
begin
FListBase.List.Insert(Index, Pointer(Item));
end;
function TcaHTMLElementList.Last: TcaHTMLElement;
begin
Result := TcaHTMLElement(FListBase.List.Last);
end;
function TcaHTMLElementList.Peek: TcaHTMLElement;
begin
if FListBase.Count = 0 then
Result := nil
else
Result := Last;
end;
function TcaHTMLElementList.Pop: TcaHTMLElement;
begin
Result := Peek;
if Result <> nil then
FListBase.Delete(FListBase.Count - 1);
end;
procedure TcaHTMLElementList.Push(Item: TcaHTMLElement);
begin
Add(Item);
end;
function TcaHTMLElementList.Remove(Item: TcaHTMLElement): Integer;
begin
Result := FListBase.List.Remove(Pointer(Item));
end;
procedure TcaHTMLElementList.SetItem(Index: Integer;
const Value: TcaHTMLElement);
begin
FListBase.List.Items[Index] := Pointer(Value);
end;
//---------------------------------------------------------------------------
// TcaCustomMarkupViewer
//---------------------------------------------------------------------------
constructor TcaCustomMarkupViewer.Create(AOwner: TComponent);
begin
inherited;
FElementStack := TcaHTMLElementList.Create;
FTagStack := TcaHTMLElementList.Create;
Width := 300;
Height := 275;
FMarginLeft := 5;
FMarginRight := 5;
FMargintop := 5;
FColor := clWindow;
FLines := TStringList.Create;
TStringList(FLines).OnChange := LinesChangedEvent;
end;
procedure TcaCustomMarkupViewer.CreateWnd;
begin
inherited;
FScrollBar := TScrollBar.create(Self);
FScrollBar.Kind := sbVertical;
FScrollBar.Parent := Self;
FScrollBar.Align := alRight;
FScrollBar.Min := 0;
FScrollBar.Max := 0;
FScrollBar.OnChange := ScrollViewerEvent;
FFrameTop := 0;
FFrameBottom := ClientHeight;
FBitmap := TBitmap.Create;
FBitmap.Width := ClientWidth - FScrollBar.Width;
FBitmap.Height := ClientHeight;
end;
destructor TcaCustomMarkupViewer.Destroy;
begin
FBitmap.Free;
FLines.Free;
inherited;
end;
procedure TcaCustomMarkupViewer.CMMouseEnter(var Message: TMessage);
begin
inherited;
end;
procedure TcaCustomMarkupViewer.CMMouseLeave(var Message: TMessage);
begin
inherited;
FMouseOverElement := nil;
end;
function TcaCustomMarkupViewer.GetColor: TColor;
begin
Result := FColor;
end;
function TcaCustomMarkupViewer.GetLines: TStrings;
begin
Result := FLines;
end;
function TcaCustomMarkupViewer.GetMarginLeft: Integer;
begin
Result := FMarginLeft;
end;
function TcaCustomMarkupViewer.GetMarginRight: Integer;
begin
Result := FMarginRight;
end;
function TcaCustomMarkupViewer.GetMarginTop: Integer;
begin
Result := FMarginTop;
end;
procedure TcaCustomMarkupViewer.ScrollViewerEvent(Sender: TObject);
begin
FFrameTop := FScrollBar.Position;
FFrameBottom := FFrameTop + ClientHeight - 1;
if GetElementCount > 0 then RenderHTML;
UpdateConstraints;
Canvas.Draw(0, 0, FBitmap);
end;
procedure TcaCustomMarkupViewer.UpdateElementDimensions;
var
Index: Integer;
Element: TcaHTMLElement;
ElementStr: String;
TextMetrics: TTextMetric;
begin
for Index := 0 to GetElementCount - 1 do
begin
Element := GetElement(Index);
ElementStr := Element.Text;
Canvas.Font.Name := Element.FontName;
Canvas.Font.Size := Element.FontSize;
Canvas.Font.Style := Element.FontStyle;
Canvas.Font.Color := Element.FontColor;
GetTextMetrics(Canvas.Handle, TextMetrics);
Element.Height := TextMetrics.tmHeight;
Element.Ascent := TextMetrics.tmAscent;
Element.Width := Canvas.TextWidth(ElementStr);
end;
end;
procedure TcaCustomMarkupViewer.ClearBreakText;
var
Index: Integer;
Element: TcaHTMLElement;
begin
for Index := 0 to GetElementCount - 1 do
begin
Element := GetElement(Index);
Element.BeginText := '';
Element.EndText := '';
end;
end;
function TcaCustomMarkupViewer.GetElementCount: Integer;
begin
Result := (FElementStack as IcaList).Count;
end;
function TcaCustomMarkupViewer.GetElement(Index: Integer): TcaHTMLElement;
begin
Result := (FElementStack as IcaHTMLElementList).Items[Index];
end;
function TcaCustomMarkupViewer.GetMouseOverElement: TcaHTMLElement;
begin
Result := FMouseOverElement;
end;
procedure TcaCustomMarkupViewer.Paint;
var
OffPageHeight: Integer;
MathUtils: IcaMathUtils;
begin
MathUtils := Utils as IcaMathUtils;
FBitmap.Width := ClientWidth - FScrollBar.Width;
FBitmap.Height := ClientHeight;
if GetElementCount > 0 then RenderHTML;
UpdateConstraints;
Canvas.Draw(0, 0, FBitmap);
FScrollBar.Min := 0;
OffPageHeight := FPageBottom - ClientHeight;
if OffPageHeight > 0 then
FScrollBar.Max := OffPageHeight
else
FScrollBar.Max := 0;
FScrollBar.Position := 0;
FScrollBar.LargeChange := MathUtils.Trunc(0.8 * ClientHeight);
end;
procedure TcaCustomMarkupViewer.RenderHTML;
var
BaseLine: Integer;
BreakPos: Integer;
Element: TcaHTMLElement;
Index: Integer;
EmtCount: Integer;
IsEndOfLine: Boolean;
LineEnd: Integer;
LineStart: Integer;
MaxAscent: Integer;
MaxHeight: Integer;
PendingBreak: boolean;
R: TRect;
XPos: Integer;
YPos: Integer;
procedure SetFont(AElement: TcaHTMLElement);
begin
FBitmap.Canvas.Font.Name := AElement.FontName;
FBitmap.Canvas.Font.Size := AElement.FontSize;
FBitmap.Canvas.Font.Style := AElement.FontStyle;
FBitmap.Canvas.Font.Color := AElement.FontColor;
end;
procedure RenderString(AElement: TcaHTMLElement);
var
S: String;
Wth: Integer;
Hgt: Integer;
R: TRect;
TextYPos: Integer;
begin
SetFont(AElement);
if AElement.BeginText <> '' then
begin
S := AElement.BeginText;
Wth := FBitmap.Canvas.TextWidth(S);
Hgt := FBitmap.Canvas.TextHeight(S);
TextYPos := YPos + BaseLine - AElement.Ascent - FFrameTop;
FBitmap.Canvas.TextOut(XPos, TextYPos, S);
R := Rect(XPos, TextYPos, XPos + Wth, TextYPos + Hgt);
AElement.Bounds := R;
Inc(XPos, Wth);
end;
end;
begin
LineEnd := 0;
R := Rect(0, 0, FBitmap.Width, FBitmap.Height);
FBitmap.Canvas.Brush.Color := Color;
FBitmap.Canvas.FillRect(R);
ClearBreakText;
FBitmap.Canvas.Brush.Style := bsClear;
YPos := FMarginTop;
LineStart := 0;
PendingBreak := False;
EmtCount := GetElementCount;
repeat
Index := LineStart;
BreakPos := FBitmap.Width - FMarginRight;
MaxHeight := 0;
MaxAscent := 0;
IsEndOfLine := False;
repeat
Element := GetElement(Index);
if Element.BreakLine then
begin
if not PendingBreak then
begin
PendingBreak := True;
IsEndOfLine := True;
LineEnd := Index - 1;
end
else
PendingBreak := False;
end;
if not PendingBreak then
begin
if Element.Height > MaxHeight then MaxHeight := Element.Height;
if Element.Ascent > MaxAscent then MaxAscent := Element.Ascent;
Element.Break(FBitmap.Canvas, BreakPos);
if Element.BeginText <> '' then
begin
BreakPos := BreakPos - FBitmap.Canvas.TextWidth(Element.BeginText);
if Element.EndText = '' then
begin
if Index >= EmtCount - 1 then
begin
IsEndOfLine := True;
LineEnd := Index;
end
else
begin
Inc(Index);
end
end
else
begin
IsEndOfLine := True;
LineEnd := Index;
end;
end
else
begin
IsEndOfLine := True;
LineEnd := Index;
end;
end;
until IsEndOfLine;
XPos := FMarginLeft;
BaseLine := MaxAscent;
if (YPos + MaxHeight >= FFrameTop) and (YPos <= FFrameBottom) then
for Index := LineStart to LineEnd do
begin
Element := GetElement(Index);
RenderString(Element);
end;
YPos := YPos + MaxHeight;
if not Pendingbreak then
LineStart := LineEnd
else
LineStart := LineEnd + 1;
until (LineEnd >= EmtCount - 1) and (Element.EndText = '');
FPageBottom := YPos;
end;
procedure TcaCustomMarkupViewer.ParseHTML;
var
AText: String;
BreakLine: boolean;
Element: TcaHTMLElement;
ElementColor: TColor;
ElementText: String;
FontColor: TColor;
FontName: String;
FontSize: Integer;
FontStyle: TFontStyles;
TagPos: Integer;
procedure PushTag;
begin
Element := TcaHTMLElement.Create;
Element.FontName := FontName;
Element.FontSize := FontSize;
Element.FontStyle := FontStyle;
Element.FontColor := FontColor;
FTagStack.Push(Element);
end;
procedure PopTag;
begin
Element := FTagStack.Pop;
if Element <> nil then
begin
FontName := Element.FontName;
FontSize := Element.FontSize;
FontStyle := Element.FontStyle;
FontColor := Element.FontColor;
Element.Free;
end;
end;
procedure PushElement;
begin
Element := TcaHTMLElement.Create;
Element.Text := ElementText;
Element.FontName := FontName;
Element.FontSize := FontSize;
Element.FontStyle := FontStyle;
Element.FontColor := FontColor;
Element.BreakLine := BreakLine;
BreakLine := False;
FElementStack.Push(Element);
end;
procedure ParseTag(ParseText: String);
var
HasParams: Boolean;
OldFontSize: Integer;
P: Integer;
Param: String;
S: String;
TagStr: String;
TagValue: String;
begin
S := Trim(ParseText);
HasParams := False;
P := Pos(' ', S);
if P = 0 then
TagStr := S // tag only
else
begin // tag + attributes
TagStr := Copy(S, 1, P - 1);
S := Trim(Copy(S, P + 1, length(S)));
HasParams := True;
end;
// handle TagStr
TagStr := Lowercase(TagStr);
if TagStr = 'br' then
BreakLine := True
else if TagStr = 'b' then
begin // bold
PushTag;
FontStyle := FontStyle + [fsbold];
end
else if TagStr = '/b' then
begin // cancel bold
FontStyle := FontStyle - [fsbold];
PopTag;
end
else if TagStr = 'i' then
begin // italic
PushTag;
FontStyle := FontStyle + [fsitalic];
end
else if TagStr = '/i' then
begin // cancel italic
FontStyle := FontStyle - [fsitalic];
PopTag;
end
else if TagStr = 'u' then
begin // underline
PushTag;
FontStyle := FontStyle + [fsunderline];
end
else if TagStr = '/u' then
begin // cancel underline
FontStyle := FontStyle - [fsunderline];
PopTag;
end
else if TagStr = 'font' then
begin
PushTag;
end
else if TagStr = '/font' then
begin
PopTag
end;
if HasParams then
begin
repeat
P := Pos('="', S);
if P > 0 then
begin
Param := lowercase(Trim(Copy(S, 1, P - 1)));
delete(S, 1, P + 1);
P := Pos('"', S);
if P > 0 then
begin
TagValue := Copy(S, 1, P - 1);
Delete(S, 1, P);
if Param = 'face' then
begin
FontName := TagValue;
end
else if Param = 'size' then
begin
OldFontSize := FontSize;
FontSize := StrToIntDef(TagValue, -1);
if FontSize = -1 then FontSize := OldFontSize;
end
else if Param = 'color' then
begin
ElementColor := Utils.HTMLColorToColor(TagValue);
if ElementColor <> clNone then
FontColor := ElementColor;
end;
end;
end;
until P = 0;
end;
end;
begin
AText := TrimRight(StringReplace(FLines.Text, #13#10, ' ', [rfReplaceAll]));
(FElementStack as IcaList).Clear;
(FTagStack as IcaList).Clear;
FontStyle := [];
FontName := 'Arial';
FontSize := 12;
FontColor := clWindowText;
BreakLine := False;
repeat
TagPos := Pos('<', AText);
if TagPos = 0 then
begin
ElementText := AText;
PushElement;
end
else
begin
if TagPos > 1 then
begin
ElementText := Copy(AText, 1, TagPos - 1);
PushElement;
Delete(AText, 1, TagPos - 1);
end;
TagPos := Pos('>', AText);
if TagPos > 0 then
begin
ParseTag(Copy(AText, 2, TagPos - 2));
Delete(AText, 1, TagPos);
end;
end;
until TagPos = 0;
end;
procedure TcaCustomMarkupViewer.SetColor(const Value: TColor);
begin
if Value <> FColor then
begin
FColor := Value;
Invalidate;
end;
end;
procedure TcaCustomMarkupViewer.LinesChangedEvent(Sender: TObject);
begin
LinesChanged;
end;
procedure TcaCustomMarkupViewer.SetLines(const Value: TStrings);
begin
FLines.Assign(Value);
end;
procedure TcaCustomMarkupViewer.LinesChanged;
begin
ParseHTML;
UpdateElementDimensions;
Invalidate;
end;
procedure TcaCustomMarkupViewer.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
UpdateMouseOverElement(X, Y);
inherited;
end;
procedure TcaCustomMarkupViewer.SetMarginLeft(const Value: Integer);
begin
if Value <> FMarginLeft then
begin
FMarginLeft := Value;
Invalidate;
end;
end;
procedure TcaCustomMarkupViewer.SetMarginRight(const Value: Integer);
begin
if Value <> FMarginRight then
begin
FMarginRight := Value;
Invalidate;
end;
end;
procedure TcaCustomMarkupViewer.SetMarginTop(const Value: Integer);
begin
if Value <> FMarginTop then
begin
FMarginTop := Value;
Invalidate;
end;
end;
procedure TcaCustomMarkupViewer.SetMouseOverElement(const Value: TcaHTMLElement);
begin
FMouseOverElement := Value;
end;
procedure TcaCustomMarkupViewer.UpdateConstraints;
var
Index: Integer;
Element: TcaHTMLElement;
MaxWidth: Integer;
begin
MaxWidth := 0;
for Index := 0 to GetElementCount - 1 do
begin
Element := GetElement(Index);
if Element.Width > MaxWidth then MaxWidth := Element.Width;
end;
Constraints.MinWidth := MaxWidth;
end;
procedure TcaCustomMarkupViewer.UpdateMouseOverElement(X, Y: Integer);
var
Index: Integer;
Element: TcaHTMLElement;
begin
FMouseOverElement := nil;
for Index := 0 to GetElementCount - 1 do
begin
Element := GetElement(Index);
if Utils.InRect(X, Y, Element.Bounds) then
begin
FMouseOverElement := Element;
Break;
end;
end;
end;
end.
|
unit ncJob;
{
ResourceString: Dario 13/03/13
}
interface
uses
SysUtils,
DB,
MD5,
Dialogs,
Classes,
Windows,
ClasseCS,
ncClassesBase;
type
TncJob = class ( TncClasse )
private
FPrinterIndex : Integer; // index of printer in Printer.Printers
FPrinterName : String ; // printers devicename
FPrinterPort : String ; // printers port name
FPrinterServer: String; // server name in case of network printer
FPrinterShare : String; // share name in case of a network printer
FComputer : String; // computer that originated the job
FUser : String; // user that originated the job
FDocument : String; // jobs document name
FPages : Integer; // pages printed so far
FClientPages : Integer; // paginas detectadas via NexGuard
FTotalPages : Integer; // total pages in job
FJobID : Cardinal; // the ID of the job
FStatus : Byte; // the jobs status
FCopies : Cardinal; // number of copies requested for job
FPrtHandle : THandle;
FMaquina : Word;
FDeleted : Boolean;
FLiberacao : Byte; // 0=Pendente, 1=Imprimir, 2=Cancelar
FPausou : Boolean;
FSpooling : Boolean;
FImpID : Cardinal;
FJobCliID : Cardinal;
FStatusPaused : Boolean;
FImpDia : Cardinal;
FImpMes : Cardinal;
FMaxImpDia : Cardinal;
FMaxImpMes : Cardinal;
FCotasProc : Boolean;
FCotasLoaded : Boolean;
FDataHora : TDateTime;
// FBytesPrinted : Integer;
procedure SetComputer(Value: String);
function GetSpooling: Boolean;
procedure SetSpooling(const Value: Boolean);
protected
function GetChave: Variant; override;
public
function Clone: TncJob;
constructor Create;
function TipoClasse: Integer; override;
function PaginasReg: Integer;
function ControlarCotas: Boolean;
function Registrar: Boolean;
function Doc_NexCafe: Boolean;
function PassouCota: Integer;
function AguardaConf: Boolean;
property StatusPaused: Boolean
read FStatusPaused write FStatusPaused;
published
property PrinterIndex: Integer
read FPrinterIndex write FPrinterIndex;
property PrinterName: String
read FPrinterName write FPrinterName;
property PrinterPort: String
read FPrinterPort write FPrinterPort;
property PrinterServer: String
read FPrinterServer write FPrinterServer;
property PrinterShare: String
read FPrinterShare write FPrinterShare;
property Computer: String
read FComputer write SetComputer;
property Deleted: Boolean
read FDeleted write FDeleted;
property User: String
read FUser write FUser;
property Document: String
read FDocument write FDocument;
{ property BytesPrinted: Integer
read FBytesPrinted write FBytesPrinted; }
property Pages: Integer
read FPages write FPages;
property TotalPages: Integer
read FTotalPages write FTotalPages;
property ClientPages: Integer
read FClientPages write FClientPages;
property JobID: Cardinal
read FJobID write FJobId;
property JobCliID: Cardinal
read FJobCliID write FJobCliID;
property Status: Byte
read FStatus write FStatus;
property Copies: Cardinal
read FCopies write FCopies;
property PrtHandle: Cardinal
read FPrtHandle write FPrtHandle;
property Maquina: Word
read FMaquina write FMaquina;
property Liberacao: Byte
read FLiberacao write FLiberacao;
property ImpID: Cardinal
read FImpID write FImpID;
property Pausou: Boolean
read FPausou write FPausou;
property Spooling: Boolean
read GetSpooling write SetSpooling;
property ImpDia: Cardinal
read FImpDia write FImpDia;
property ImpMes: Cardinal
read FImpMes write FImpMes;
property MaxImpDia: Cardinal
read FMaxImpDia write FMaxImpDia;
property MaxImpMes: Cardinal
read FMaxImpMes write FMaxImpMes;
property CotasProc: Boolean
read FCotasProc Write FCotasProc;
property CotasLoaded: Boolean
read FCotasLoaded write FCotasLoaded;
property DataHora: TDateTime
read FDataHora write FDataHora;
end;
TncJobs = class ( TListaClasseCS )
private
function GetJob(I: Integer): TncJob;
function GetPorJobID(aPrinterIndex: Integer; aJobID: Cardinal): TncJob;
function GetPorMaquina(aMaq: Word; aLiberacao: Integer): TncJob;
public
function JobPendMaq(aMaq: Word; aSoDentroCota: Boolean): TncJob;
function PrinterIndexByComputer(aComputer: String): Integer;
function JobMaqCliID(aMaq: Word; aJobCliID: Cardinal): TncJob;
function TemJobPend(aMaq: Word): Boolean;
property Itens[I: Integer]: TncJob
read GetJob; default;
property PorJobID[aPrinterIndex: Integer; aJobID: Cardinal]: TncJob
read GetPorJobID;
property PorMaquina[aMaq: Word; aLiberacao: Integer]: TncJob
read GetPorMaquina;
end;
const
jsNone = 0;
jsNew = 1;
jsProcessing = 2;
jsPaused = 3;
jsResumed = 4;
jsAborted = 5;
jsCompleted = 6;
jsError = 7;
jsPrinting = 8;
jsDeleted = 9;
jlNaoPausou = 0;
jlPendente = 1;
jlImprimir = 2;
jlCancelar = 3;
var
PreferTotalPages : Boolean = False;
CorrigeImp : Integer = 1;
UsaSpooling : Boolean = False;
implementation
{ TncJob }
function TncJob.AguardaConf: Boolean;
begin
Result := (not FSpooling) and (FLiberacao=jlPendente);
end;
function TncJob.Clone: TncJob;
begin
Result := TncJob.Create;
Result.FPrinterIndex := FPrinterIndex;
Result.FPrinterName := FPrinterName;
Result.FPrinterPort := FPrinterPort;
Result.FPrinterServer:= FPrinterServer;
Result.FPrinterShare := FPrinterShare;
Result.FComputer := FComputer;
Result.FUser := FUser;
Result.FDocument := FDocument;
Result.FPages := FPages;
Result.FTotalPages := FTotalPages;
Result.FClientPages := FClientPages;
Result.FJobID := FJobID;
Result.FJobCliID := FJobCliID;
Result.FStatus := FStatus;
Result.FDeleted := FDeleted;
Result.FCopies := FCopies;
Result.FPrtHandle := FPrtHandle;
Result.FMaquina := FMaquina;
Result.FLiberacao := FLiberacao;
Result.FImpID := FImpID;
Result.FPausou := FPausou;
Result.FSpooling := FSpooling;
Result.FStatusPaused := FStatusPaused;
Result.FMaxImpDia := FMaxImpDia;
Result.FmaxImpMes := FMaxImpMes;
Result.FImpDia := FImpDia;
Result.FImpMes := FImpMes;
Result.FCotasProc := FCotasProc;
Result.FCotasLoaded := FCotasLoaded;
Result.FDataHora := FDataHora;
// Result.FBytesPrinted := FBytesPrinted;
end;
function TncJob.ControlarCotas: Boolean;
begin
Result := gConfig.PMPausaAutomatica and gConfig.PMCotas and (FMaquina>0) and FCotasLoaded and
((FMaxImpDia>0) or (FMaxImpMes>0));
end;
constructor TncJob.Create;
begin
inherited;
FDataHora := Now;
FPrinterIndex := -1;
FPrinterName := '';
FPrinterPort := '';
FPrinterServer:= '';
FSpooling := UsaSpooling;
FPrinterShare := '';
FComputer := '';
FUser := '';
FDeleted := False;
FDocument := '';
FClientPages := 0;
FTotalPages := 0;
FJobID := 0;
FJobCliID := 0;
FStatus := jsNone;
FStatusPaused := False;
FCopies := 0;
FPrtHandle := 0;
FMaquina := 0;
FLiberacao := 0;
FImpID := 0;
FMaxImpDia := 0;
FMaxImpMes := 0;
FImpDia := 0;
FImpMes := 0;
// FBytesPrinted := 0;
FPausou := False;
FCotasProc := False;
FCotasLoaded := False;
end;
function TncJob.Doc_NexCafe: Boolean;
begin
Result := SameText('NEXCAFE_RECIBO', FDOCUMENT) or // do not localize
SameText('NEXCAFE_CAIXA', FDOCUMENT) or // do not localize
IsPDFFromNexCafe(FDocument);
end;
function TncJob.GetChave: Variant;
begin
Result := IntToStr(FPrinterIndex)+'#'+IntToStr(FJobID);
end;
function TncJob.GetSpooling: Boolean;
begin
Result := FSpooling;
end;
function TncJob.PaginasReg: Integer;
begin
if FClientPages>0 then
Result := FClientPages
else
if (CorrigeImp>1) and (FPages>=CorrigeImp) then
Result := FPages div CorrigeImp
else
if PreferTotalPages then begin
if FTotalPages>0 then begin
if FCopies>0 then
Result := FCopies * FTotalPages else
Result := FTotalPages;
end else begin
if FCopies>0 then
Result := FCopies * FPages else
Result := FPages;
end;
end else begin
if FPages>0 then begin
if FCopies>0 then
Result := FCopies * FPages else
Result := FPages;
end else begin
if FCopies>0 then
Result := FCopies * FTotalPages else
Result := FTotalPages;
end;
end;
end;
function TncJob.PassouCota: Integer;
var r2: integer;
begin
Result := 0;
if FMaxImpDia>0 then
Result := (FImpDia+PaginasReg)-FMaxImpDia;
r2 := 0;
if FMaxImpMes>0 then
r2 := (FImpMes+PaginasReg)-FMaxImpMes;
if r2>result then
Result := r2;
end;
function TncJob.Registrar: Boolean;
begin
if Maquina>0 then
Result := (gConfig.ControlaImp>0) else
Result := gConfig.DetectarImpServ ;
Result := Result and (not Doc_NexCafe) and (PaginasReg>0);
end;
procedure TncJob.SetComputer(Value: String);
const
Invalid_Chars : String = '[]';
var I : Integer;
begin
FComputer := '';
for I := 1 to Length(Value) do
if (Pos(Value[I], Invalid_Chars)<1) then
FComputer := FComputer + Value[I];
end;
procedure TncJob.SetSpooling(const Value: Boolean);
begin
if (not LadoServidor) or UsaSpooling then
FSpooling := Value else
FSpooling := False;
end;
function TncJob.TipoClasse: Integer;
begin
Result := tcJob;
end;
{ TncJobs }
function TncJobs.GetJob(I: Integer): TncJob;
begin
Result := TncJob(GetItem(I));
end;
function TncJobs.GetPorJobID(aPrinterIndex: Integer; aJobID: Cardinal): TncJob;
var I : Integer;
begin
for I := 0 to Count - 1 do with Itens[i] do
if (PrinterIndex=aPrinterIndex) and (JobID=aJobID) then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncJobs.GetPorMaquina(aMaq: Word; aLiberacao: Integer): TncJob;
var I : Integer;
begin
for I := 0 to Count - 1 do with Itens[i] do
if (Maquina=aMaq) and ((aLiberacao=-1) or (Liberacao=aLiberacao)) then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncJobs.JobMaqCliID(aMaq: Word; aJobCliID: Cardinal): TncJob;
var I : Integer;
begin
for I := 0 to Count-1 do with Itens[I] do
if (FMaquina=aMaq) and (JobCliID=aJobCliID) and (FLiberacao=jlPendente) then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncJobs.JobPendMaq(aMaq: Word; aSoDentroCota: Boolean): TncJob;
var I : Integer;
begin
for I := 0 to Count-1 do with Itens[I] do
if (FMaquina=aMaq) and (FImpID=0) and (FLiberacao=jlPendente) and (not Spooling) and ((not aSoDentroCota) or (PassouCota<1)) then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncJobs.PrinterIndexByComputer(aComputer: String): Integer;
var I: integer;
begin
Result := -1;
for I := 0 to Count-1 do with Itens[I] do
if MesmoComputerName(aComputer, FComputer) then begin
Result := PrinterIndex;
Exit;
end;
end;
function TncJobs.TemJobPend(aMaq: Word): Boolean;
var I: Integer;
begin
Result := True;
for I := 0 to Count-1 do with Itens[I] do
if (FMaquina=aMaq) and (FLiberacao=jlPendente) then Exit;
Result := False;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ BDE Provider }
{ }
{ Copyright (c) 1997, 1998 Inprise Corporation }
{ }
{*******************************************************}
unit BdeProv;
interface
uses
Classes, Provider, DB, DBTables, SysUtils, DBClient;
type
TProvider = class(TDataSetProvider)
private
FResolveToDataSet: Boolean;
FQuery: TQuery;
FDatabase: TDatabase;
FRangeActive: Boolean;
procedure SetResolveToDataSet(Value: Boolean);
protected
function FetchParams: OleVariant; override;
function GetDataSet: TDBDataSet;
procedure SetDataSet(ADataSet: TDBDataSet);
function GetKeyFields(const Tablename: string; ADelta: TClientDataSet): string; override;
procedure SetParamByName(const ParamName: string; const Value: OleVariant); override;
procedure SetParamByIndex(ParamIndex: Integer; const Value: OleVariant); override;
function GetParamCount: Integer; override;
function CreateResolver: TCustomResolver; override;
procedure ExecSQL(Sender: TObject; SQL: TStringList; Params: TParams);
procedure GetValues(Sender: TObject; SQL: TStringList; Params: TParams;
DataSet: TDataSet);
function GetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError; override;
public
constructor Create(AOwner: TComponent); override;
function ApplyUpdates(var Delta: OleVariant; MaxErrors: Integer;
out ErrorCount: Integer): OleVariant; override;
function FetchData(const Packet: OleVariant): OleVariant; override;
procedure Reset(MetaData: WordBool); override;
procedure SetParams(Values: OleVariant); override;
published
property DataSet: TDBDataSet read GetDataSet write SetDataSet;
property ResolveToDataSet: Boolean read FResolveToDataSet write SetResolveToDataSet default False;
end;
procedure UseBdeProv;
implementation
uses StdVcl, BDE, MidConst;
function CreateProvider(Source: TDBDataSet): IProvider;
begin
with TProvider.Create(Source) do
begin
Result := Provider;
DataSet := Source;
end;
end;
{ TCachedQuery }
type
PStmtInfo = ^TStmtInfo;
TStmtInfo = record
HashCode: Integer;
StmtHandle: HDBIStmt;
SQLText: string;
end;
TCachedQuery = class(TQuery)
private
FStmtList: TList;
function GetStmtInfo(SQL: PChar): PStmtInfo;
protected
procedure GetStatementHandle(SQLText: PChar); override;
procedure FreeStatement; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ClearStatements;
end;
constructor TCachedQuery.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStmtList := TList.Create;
end;
destructor TCachedQuery.Destroy;
begin
ClearStatements;
FStmtList.Free;
inherited Destroy;
end;
procedure TCachedQuery.GetStatementHandle(SQLText: PChar);
var
Info: PStmtInfo;
begin
Info := GetStmtInfo(SQLText);
if not Assigned(Info.StmtHandle) then
begin
inherited GetStatementHandle(SQLText);
Info.SQLText := SQLText;
Info.StmtHandle := StmtHandle;
end else
StmtHandle := Info.StmtHandle;
end;
procedure TCachedQuery.FreeStatement;
begin
{Do not free cached statment handles.}
end;
procedure TCachedQuery.ClearStatements;
var
i: Integer;
begin
for i := 0 to FStmtList.Count - 1 do
begin
StmtHandle := PStmtInfo(FStmtList[i]).StmtHandle;
inherited FreeStatement;
Dispose(PStmtInfo(FStmtList[i]));
end;
FStmtList.Clear;
end;
function TCachedQuery.GetStmtInfo(SQL: PChar): PStmtInfo;
function GetHashCode(Str: PChar): Integer;
var
Off, Len, Skip, I: Integer;
begin
Result := 0;
Off := 1;
Len := StrLen(Str);
if Len < 16 then
for I := (Len - 1) downto 0 do
begin
Result := (Result * 37) + Ord(Str[Off]);
Inc(Off);
end
else
begin
{ Only sample some characters }
Skip := Len div 8;
I := Len - 1;
while I >= 0 do
begin
Result := (Result * 39) + Ord(Str[Off]);
Dec(I, Skip);
Inc(Off, Skip);
end;
end;
end;
var
HashCode, i: Integer;
Info: PStmtInfo;
begin
Result := nil;
HashCode := GetHashCode(SQL);
for i := 0 to FStmtList.Count - 1 do
begin
Info := PStmtInfo(FStmtList[i]);
if (Info.HashCode = HashCode) and
(AnsiStrIComp(PChar(Info.SQLText), SQL) = 0) then
begin
Result := Info;
break;
end;
end;
if not Assigned(Result) then
begin
New(Result);
FStmtList.Add(Result);
FillChar(Result^, SizeOf(Result^), 0);
Result.HashCode := HashCode;
end;
end;
{ TProvider }
constructor TProvider.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FResolveToDataSet := False;
FQuery := TCachedQuery.Create(Self);
FQuery.ParamCheck := False;
FRangeActive := False;
end;
function TProvider.GetDataSet: TDBDataSet;
begin
Result := TDBDataSet(inherited GetDataSet);
end;
procedure TProvider.SetDataSet(ADataSet: TDBDataSet);
begin
inherited SetDataSet(ADataSet);
end;
function TProvider.ApplyUpdates(var Delta: OleVariant; MaxErrors: Integer;
out ErrorCount: Integer): OleVariant;
var
TransactionStarted: Boolean;
begin
FDatabase := DataSet.DBSession.OpenDatabase(DataSet.DatabaseName);
try
FQuery.SessionName := FDatabase.SessionName;
FQuery.DatabaseName := FDatabase.DatabaseName;
TransactionStarted := not FDatabase.InTransaction;
if TransactionStarted then
begin
if not FDatabase.IsSQLBased then
FDatabase.TransIsolation := tiDirtyRead;
FDatabase.StartTransaction;
end;
try
Result := inherited ApplyUpdates(Delta, MaxErrors, ErrorCount);
finally
if TransactionStarted then
begin
if (ErrorCount <= MaxErrors) or (MaxErrors = -1) then
FDatabase.Commit else
FDatabase.Rollback;
end;
end;
finally
TCachedQuery(FQuery).ClearStatements;
DataSet.DBSession.CloseDatabase(FDatabase);
end;
end;
function TProvider.GetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError;
var
PrevErr: Integer;
begin
if Prev <> nil then
PrevErr := Prev.ErrorCode else
PrevErr := 0;
if E is EDBEngineError then
with EDBEngineError(E).Errors[0] do
Result := EUpdateError.Create(E.Message, '', ErrorCode, PrevErr, E) else
Result := inherited GetUpdateException(E, Prev);
end;
function TProvider.GetKeyFields(const Tablename: string; ADelta: TClientDataSet): string;
var
Table: TTable;
i, Pos: Integer;
IndexFound: Boolean;
begin
Result := '';
Table := TTable.Create(nil);
try
Table.TableName := Tablename;
with Table do
begin
ObjectView := True;
SessionName := FDatabase.SessionName;
DatabaseName := FDatabase.DatabaseName;
IndexDefs.Update;
{ Search for a unique index that contains fields which are also
present in the delta dataset }
for i := 0 to IndexDefs.Count - 1 do
if ixUnique in IndexDefs[I].Options then
begin
Pos := 1;
Result := IndexDefs[I].Fields;
IndexFound := False;
while Pos <= Length(Result) do
begin
IndexFound := ADelta.FindField(ExtractFieldName(Result, Pos)) <> nil;
if not IndexFound then Break;
end;
if IndexFound then Break;
end;
end;
finally
Table.Free;
end;
end;
procedure TProvider.ExecSQL(Sender: TObject; SQL: TStringList; Params: TParams);
begin
FQuery.SQL.Assign(SQL);
FQuery.Params.Assign(Params);
FQuery.ExecSQL;
if FQuery.RowsAffected > 1 then
DatabaseError(STooManyRecordsModified);
if FQuery.RowsAffected < 1 then
DatabaseError(SRecordChanged);
end;
procedure TProvider.GetValues(Sender: TObject; SQL: TStringList; Params: TParams;
DataSet: TDataSet);
begin
FQuery.SQL.Assign(SQL);
FQuery.Params.Assign(Params);
FQuery.RequestLive := False;
FQuery.Open;
try
if FQuery.RecordCount = 1 then
(DataSet as TPacketDataSet).AssignCurValues(FQuery);
finally
FQuery.Close;
end;
end;
procedure TProvider.SetResolveToDataSet(Value: Boolean);
begin
if (Value <> FResolveToDataSet) and Assigned(Resolver) then
FreeResolver;
FResolveToDataSet := Value;
end;
procedure TProvider.Reset(MetaData: WordBool);
begin
inherited Reset(MetaData);
if (DataSet <> nil) and (DataSet.Active) then
DbiForceReread(DataSet.Handle);
end;
function TProvider.CreateResolver: TCustomResolver;
var
Info: TSQLGenInfo;
begin
if ResolveToDataSet then
Result := TDataSetResolver.Create(Self) else
begin
Info.ExecSQLProc := ExecSQL;
Info.GetValuesProc := GetValues;
Result := TSQLResolver.Create(Self, Info);
end;
end;
function TProvider.GetParamCount: Integer;
begin
Result := 0;
if not Assigned(DataSet) then Exit;
if DataSet is TTable then
Result := TTable(DataSet).IndexFieldCount else
if DataSet is TQuery then
Result := TQuery(DataSet).Params.Count else
if DataSet is TStoredProc then
Result := TStoredProc(DataSet).Params.Count;
end;
procedure TProvider.SetParamByName(const ParamName: string; const Value: OleVariant);
var
Params: TParams;
begin
if DataSet is TQuery then
Params := TQuery(DataSet).Params else
Params := TStoredProc(DataSet).Params;
Params.ParamByName(ParamName).Value := Value;
end;
procedure TProvider.SetParamByIndex(ParamIndex: Integer; const Value: OleVariant);
var
Params: TParams;
begin
if DataSet is TQuery then
Params := TQuery(DataSet).Params else
Params := TStoredProc(DataSet).Params;
Params[ParamIndex].Value := Value;
end;
function TProvider.FetchParams: OleVariant;
var
Params: TParams;
i: Integer;
begin
if DataSet is TQuery then
Params := TQuery(DataSet).Params
else if DataSet is TStoredProc then
Params := TStoredProc(DataSet).Params
else
Params := nil;
if (Params = nil) or (Params.Count = 0) then
Result := NULL else
begin
Result := VarArrayCreate([0, Params.Count - 1], varVariant);
for i := 0 to Params.Count - 1 do
with Params[i] do
Result[i] := VarArrayOf([Name, Ord(DataType), Ord(ParamType), Value]);
end;
end;
function TProvider.FetchData(const Packet: OleVariant): OleVariant;
begin
FDatabase := DataSet.DBSession.OpenDatabase(DataSet.DatabaseName);
try
Result := inherited FetchData(Packet);
finally
TCachedQuery(FQuery).ClearStatements;
DataSet.DBSession.CloseDatabase(FDatabase);
end;
end;
procedure TProvider.SetParams(Values: OleVariant);
procedure AssignFields(Table: TTable);
var
I, MaxIndex: Integer;
begin
with Table do
begin
MaxIndex := VarArrayHighBound(Values, 1);
if MaxIndex >= IndexFieldCount then MaxIndex := IndexFieldCount - 1;
for I := 0 to MaxIndex do
if VarIsArray(Values[I]) then
FieldByName(Values[I][0]).Value := Values[I][1] else
IndexFields[I].Value := Values[I];
end;
end;
begin
if DataSet is TTable then
begin
if not VarIsNull(Values) and not VarIsArray(Values) then
Values := VarArrayOf([Values]);
with TTable(DataSet) do
begin
if VarIsNull(Values) then
begin
CancelRange;
FRangeActive := False;
end else
begin
Open;
SetRangeStart;
AssignFields(TTable(DataSet));
SetRangeEnd;
AssignFields(TTable(DataSet));
ApplyRange;
FRangeActive := True;
end;
end;
Reset(False);
end
else
begin
inherited SetParams(Values);
DataSet.Close;
end;
end;
procedure UseBdeProv;
begin
// CBuilder's remote data module calls
// this procedure to create a reference to bdeprov.
end;
begin
if not Assigned(CreateProviderProc) then
CreateProviderProc := CreateProvider;
end.
|
unit PlotControls;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Grids,
Plots;
type
TGraphGrid = class(TCustomGrid)
private
FGraph: TGraph;
FAlternateRows: Boolean;
procedure SetGraph(Value: TGraph);
procedure AdjustColSizes;
protected
procedure Resize; override;
procedure DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); override;
public
constructor Create(AOwner: TWinControl);
property Graph: TGraph read FGraph write SetGraph;
end;
implementation
uses
StdCtrls, Graphics, Math,
OriGraphics,
SpectrumTypes;
const
SourceDPI = 96;
{%region TGraphGrid}
constructor TGraphGrid.Create(AOwner: TWinControl);
begin
inherited Create(AOwner);
Align := alClient;
Parent := AOwner;
BorderSpacing.Around := ScaleX(3, SourceDPI);
ColCount := 3;
RowCount := 2;
ScrollBars := ssAutoVertical;
Options := Options - [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine,
goEditing, goRowSizing, goColSizing] + [goRangeSelect, goTabs, goThumbTracking];
FAlternateRows := True;
end;
procedure TGraphGrid.SetGraph(Value: TGraph);
begin
if FGraph <> Value then
begin
FGraph := Value;
if Assigned(FGraph)
then RowCount := Max(FGraph.ValueCount+1, 2)
else RowCount := 2;
AdjustColSizes;
Invalidate;
end;
end;
procedure TGraphGrid.AdjustColSizes;
var
S: String;
begin
if Assigned(FGraph)
then S := IntToStr(FGraph.ValueCount)
else S := '9999';
Canvas.Font := Self.Font;
ColWidths[0] := Canvas.TextWidth(S) + 6;
ColWidths[1] := (ClientWidth - ColWidths[0]) div 2;
ColWidths[2] := ClientWidth - ColWidths[0] - ColWidths[1];
end;
procedure TGraphGrid.Resize;
begin
if Assigned(Parent) then AdjustColSizes;
end;
procedure TGraphGrid.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState);
var
TxtRect: TRect;
Str: String;
TS: TTextStyle;
Values: TValueArray;
begin
TxtRect := ARect;
Inc(TxtRect.Left, 2);
Dec(TxtRect.Right, 2);
TS := Canvas.TextStyle;
TS.Layout := tlCenter;
TS.Alignment := taLeftJustify;
TS.Opaque := False;
TS.Clipping := True;
TS.SystemFont := Canvas.Font.IsDefault;
with Canvas do
begin
Brush.Style := bsSolid;
if gdFixed in AState then
begin
Brush.Color := clBtnFace;
FillRect(ARect);
Pen.Color := clBtnShadow;
MoveTo(ARect.Left, ARect.Bottom-1);
LineTo(ARect.Right-1, ARect.Bottom-1);
if ACol < 2 then
LineTo(ARect.Right-1, ARect.Top-1);
case ACol of
1: begin TS.Alignment := taCenter; Str := 'X'; end;
2: begin TS.Alignment := taCenter; Str := 'Y'; end;
else if ARow > 0 then Str := IntToStr(ARow) else Str := '';
end;
end
else
begin
if gdSelected in AState then
begin
if FAlternateRows and (ARow mod 2 = 0)
then Brush.Color := Blend(clHighlight, clWindow, 40)
else Brush.Color := Blend(clHighlight, clWindow, 30);
if gdFocused in AState
then Pen.Color := clHighlight
else Pen.Color := Brush.Color;
Rectangle(ARect);
end
else begin
if FAlternateRows and (ARow mod 2 = 0)
then Brush.Color := Lighten(clWindow, -10)
else Brush.Color := clWindow;
FillRect(ARect);
end;
if Assigned(FGraph) then
begin
if ACol = 1
then Values := FGraph.ValuesX
else Values := FGraph.ValuesY;
Str := FloatToStr(Values[ARow-1]);
end
else Str := '';
end;
Font := Self.Font;
TextRect(TxtRect, TxtRect.Left, TxtRect.Top, Str, TS);
end;
end;
{%endregion}
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.HTTPUtil;
interface
uses System.Types, System.Classes;
type
{ Java-style StringTokenizer }
IStringTokenizer = interface
['{8C216E9D-984E-4E38-893F-0A222AC547DA}']
function getTokenCounts: Integer;
function hasMoreTokens: Boolean;
function nextToken: string;
property countTokens: Integer read getTokenCounts;
end;
IStreamLoader = interface
['{395CDFB2-1D10-4A37-AC16-393D569676F0}']
procedure Load(const WSDLFileName: string; Stream: TMemoryStream);
function GetProxy: string;
procedure SetProxy(const Proxy: string);
function GetUserName: string;
procedure SetUserName(const UserName: string);
function GetPassword: string;
procedure SetPassword(const Password: string);
function GetTimeout: Integer;
procedure SetTimeout(ATimeOut: Integer);
property Proxy: string read GetProxy write SetProxy;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property Timeout: Integer read GetTimeOut write SetTimeOut;
end;
function StartsWith(const str: string; const sub: string): Boolean;
function FirstDelimiter(const delimiters: string; const Str: String): Integer; overload;
{$IFNDEF NEXTGEN}
function FirstDelimiter(const delimiters: WideString; const Str: WideString): Integer; overload;
{$ENDIF !NEXTGEN}
function StringTokenizer(const str: string; const delim: string): IStringTokenizer;
function StringToStringArray(const str: string; const delim: string): TStringDynArray;
function HTMLEscape(const Str: string): string;
function GetDefaultStreamLoader: IStreamLoader;
implementation
uses
System.SysUtils, Soap.SOAPHTTPTrans;
type
TStreamLoader = class(TInterfacedObject, IStreamLoader)
private
FHTTPReqResp: IHTTPReqResp;
FProxy: string;
FUserName: string;
FPassword: string;
FTimeOut: Integer;
public
procedure Load(const WSDLFileName: string; Stream: TMemoryStream);
constructor Create;
destructor Destroy; override;
function GetProxy: string;
procedure SetProxy(const Proxy: string);
function GetUserName: string;
procedure SetUserName(const UserName: string);
function GetPassword: string;
procedure SetPassword(const Password: string);
function GetTimeout: Integer;
procedure SetTimeout(ATimeOut: Integer);
end;
constructor TStreamLoader.Create;
begin
inherited Create;
FHTTPReqResp := THTTPReqResp.Create(nil);
end;
destructor TStreamLoader.Destroy;
begin
inherited Destroy;
end;
procedure TStreamLoader.Load(const WSDLFileName: string; Stream: TMemoryStream);
procedure LoadFromURL(URL: string; Stream: TStream);
begin
{ Load HTTPReqResp with parameters of request }
FHTTPReqResp.GetHTTPReqResp.URL := URL;
FHTTPReqResp.GetHTTPReqResp.UserName := FUserName;
FHTTPReqResp.GetHTTPReqResp.Password := FPassword;
FHTTPReqResp.GetHTTPReqResp.Proxy := FProxy;
{ Timeouts }
if FTimeOut <> 0 then
begin
FHTTPReqResp.GetHTTPReqResp.ConnectTimeout := FTimeOut;
FHTTPReqResp.GetHTTPReqResp.ReceiveTimeout := FTimeOut;
end;
FHTTPReqResp.GetHTTPReqResp.Get(Stream);
end;
function isHTTP(const Name: string): boolean;
const
sHTTPPrefix = 'http://';
sHTTPsPrefix= 'https://';
begin
Result := SameText(Copy(Name, 1, Length(sHTTPPrefix)), sHTTPPrefix) or
SameText(Copy(Name, 1, Length(sHTTPsPrefix)),sHTTPsPrefix);
end;
var
FileName: string;
begin
FileName := Trim(WSDLFileName);
if isHTTP(FileName) then
LoadFromURL(FileName, Stream)
else
Stream.LoadFromFile(FileName);
end;
function TStreamLoader.GetProxy: string;
begin
Result := FProxy;
end;
procedure TStreamLoader.SetProxy(const Proxy: string);
begin
FProxy := Proxy;
end;
function TStreamLoader.GetUserName: string;
begin
Result := FUserName;
end;
procedure TStreamLoader.SetUserName(const UserName: string);
begin
FUserName := UserName;
end;
function TStreamLoader.GetPassword: string;
begin
Result := FPassword;
end;
procedure TStreamLoader.SetPassword(const Password: string);
begin
FPassword := Password;
end;
function GetDefaultStreamLoader: IStreamLoader;
begin
Result := TStreamLoader.Create;
end;
function StartsWith(const str: string; const sub: string): Boolean;
begin
// Result := (Length(str) >= Length(sub)) and (Copy(str, 1, Length(sub)) = sub);
Result := str.StartsWith(sub);
end;
type
TStringTokenizer = class(TInterfacedObject, IStringTokenizer)
FString: string;
FDelim: string;
FCurPos: Integer;
public
constructor Create(const str: string; delim: string);
function getTokenCounts: Integer;
function hasMoreTokens: boolean;
function nextToken: string;
property countTokens: Integer read getTokenCounts;
end;
{$IFDEF NEXTGEN}
function _IndexOf(const ch: Char; const Str: String): Integer; overload;
begin
Result := 1+ Str.IndexOf(ch);
end;
{$ELSE !NEXTGEN}
function _IndexOf(const ch: Char; const Str: String): Integer; overload;
var
I: Integer;
begin
Result := 0;
I := 1;
while I <= Length(Str) do
begin
if Str[I] = ch then
begin
Result := I;
Exit;
end;
Inc(I);
end;
end;
function _IndexOf(const ch: WideChar; const Str: WideString): Integer; overload;
var
I: Integer;
begin
Result := 0;
I := 1;
while I <= Length(Str) do
begin
if Str[I] = ch then
begin
Result := I;
Exit;
end;
Inc(I);
end;
end;
{$ENDIF NEXTGEN}
{$IFDEF NEXTGEN}
function FirstDelimiter(const delimiters: string; const Str: String): Integer;
begin
Result := 1 + Str.IndexOfAny(delimiters.ToCharArray);
end;
{$ELSE !NEXTGEN}
function FirstDelimiter(const delimiters: string; const Str: String): Integer;
var
I: Integer;
begin
Result := 0;
I := 1;
while I <= Length(Str) do
begin
if CharInSet(Str[I], LeadBytes) then
Inc(I)
else if _IndexOf(Str[I], delimiters) > 0 then
begin
Result := I;
Exit;
end;
Inc(I);
end;
end;
function FirstDelimiter(const delimiters: WideString; const Str: WideString): Integer;
var
I: Integer;
begin
Result := 0;
I := 1;
while I <= Length(Str) do
begin
if _IndexOf(Str[I], delimiters) > 0 then
begin
Result := I;
Exit;
end;
Inc(I);
end;
end;
{$ENDIF NEXTGEN}
function StringTokenizer(const str: string; const delim: string): IStringTokenizer;
begin
Result := TStringTokenizer.Create(str, delim);
end;
constructor TStringTokenizer.Create(const str: string; delim: string);
begin
FString := str;
FDelim := delim;
FCurPos := Low(string);
{ Point FCurPos to beginning of next Token }
while (FCurPos <= High(FString)) and (_IndexOf(FString[FCurPos], FDelim) > 0) do
Inc(FCurPos);
end;
function TStringTokenizer.getTokenCounts: Integer;
var
I: Integer;
Cnt: Integer;
Limit: Integer;
begin
Cnt := 0;
I := Low(String);
Limit := High(FString);
while I <= Limit do
begin
while (I <= Limit) and (_IndexOf(FString[I], FDelim) > 0) do
Inc(I);
if I <= Limit then
Inc(Cnt);
while (I <= Limit) and (_IndexOf(FString[I], FDelim) = 0) do
Inc(I);
end;
Result := Cnt;
end;
function TStringTokenizer.hasMoreTokens: boolean;
begin
Result := FCurPos <= High(FString);
end;
function TStringTokenizer.nextToken: string;
var
endPos: Integer;
begin
if FCurPos > High(FString) then
begin
Result := '';
Exit;
end;
endPos := FCurPos;
while (endPos <= High(FString)) and (_IndexOf(FString[endPos], FDelim) = 0) do
Inc(endPos);
// Result := Copy(FString, FCurPos, endPos-FCurPos);
Result := FString.Substring(FCurPos-Low(string), endPos-FCurPos);
{ Point FCurPos to beginning of next Token }
FCurPos := endPos;
while (FCurPos <= High(FString)) and (_IndexOf(FString[FCurPos], FDelim) > 0) do
Inc(FCurPos);
end;
function StringToStringArray(const str: string; const delim: string): TStringDynArray;
var
StrTok: IStringTokenizer;
Count, I: Integer;
begin
if str = '' then
begin
Result := nil;
Exit;
end;
StrTok := StringTokenizer(str, delim);
Count := StrTok.countTokens;
SetLength(Result, Count);
I := 0;
while StrTok.hasMoreTokens do
begin
Result[I] := StrTok.nextToken;
Inc(I);
end;
end;
function HTMLEscape(const Str: string): string;
var
i: Integer;
begin
Result := '';
for i := Low(Str) to High(Str) do
begin
case Str[i] of
'<' : Result := Result + '<'; { Do not localize }
'>' : Result := Result + '>'; { Do not localize }
'&' : Result := Result + '&'; { Do not localize }
'"' : Result := Result + '"'; { Do not localize }
{$IFNDEF UNICODE}
#92, Char(160) .. #255 : Result := Result + '&#' + IntToStr(Ord(Str[ i ])) +';'; { Do not localize }
{$ELSE}
// NOTE: Not very efficient
#$0080..#$FFFF : Result := Result + '&#' + IntToStr(Ord(Str[ i ])) +';'; { Do not localize }
{$ENDIF}
else
Result := Result + Str[i];
end;
end;
end;
function TStreamLoader.GetTimeout: Integer;
begin
Result := FTimeOut;
end;
procedure TStreamLoader.SetTimeout(ATimeOut: Integer);
begin
FTimeOut := ATimeOut;
end;
end.
|
unit BCEditor.Editor.InternalImage;
interface
uses
Graphics;
type
TBCEditorInternalImage = class(TObject)
strict private
FCount: Integer;
FHeight: Integer;
FImages: Graphics.TBitmap;
FWidth: Integer;
function CreateBitmapFromInternalList(AModule: THandle; const Name: string): Graphics.TBitmap;
procedure FreeBitmapFromInternalList;
public
constructor Create(AModule: THandle; const Name: string; const Count: Integer);
destructor Destroy; override;
procedure Draw(ACanvas: TCanvas; const Number: Integer; const X: Integer; const Y: Integer; const LineHeight: Integer);
procedure DrawTransparent(ACanvas: TCanvas; const Number: Integer; const X: Integer; const Y: Integer;
const LineHeight: Integer; const TransparentColor: TColor);
end;
implementation
uses
Windows, Classes, Types, SysUtils;
type
TInternalResource = class(TObject)
public
UsageCount: Integer;
Name: string;
Bitmap: Graphics.TBitmap;
end;
var
InternalResources: TList;
{ TBCEditorInternalImage }
constructor TBCEditorInternalImage.Create(AModule: THandle; const Name: string; const Count: Integer);
begin
inherited Create;
FImages := CreateBitmapFromInternalList(AModule, name);
FWidth := (FImages.Width + Count shr 1) div Count;
FHeight := FImages.Height;
FCount := Count;
end;
destructor TBCEditorInternalImage.Destroy;
begin
FreeBitmapFromInternalList;
inherited Destroy;
end;
function TBCEditorInternalImage.CreateBitmapFromInternalList(AModule: THandle; const Name: string): Graphics.TBitmap;
var
i: Integer;
InternalResource: TInternalResource;
begin
for i := 0 to InternalResources.Count - 1 do
if TInternalResource(InternalResources[i]).Name = UpperCase(Name) then
with TInternalResource(InternalResources[i]) do
begin
UsageCount := UsageCount + 1;
Result := Bitmap;
Exit;
end;
Result := Graphics.TBitmap.Create;
Result.Handle := LoadBitmap(AModule, PChar(name));
InternalResource := TInternalResource.Create;
with InternalResource do
begin
UsageCount := 1;
Name := UpperCase(Name);
Bitmap := Result;
end;
InternalResources.Add(InternalResource);
end;
procedure TBCEditorInternalImage.FreeBitmapFromInternalList;
var
i: Integer;
InternalResource: TInternalResource;
function FindImageIndex: Integer;
begin
for Result := 0 to InternalResources.Count - 1 do
if TInternalResource(InternalResources[Result]).Bitmap = FImages then
Exit;
Result := -1;
end;
begin
i := FindImageIndex;
if i = -1 then
Exit;
InternalResource := TInternalResource(InternalResources[i]);
with InternalResource do
begin
UsageCount := UsageCount - 1;
if UsageCount = 0 then
begin
Bitmap.Free;
Bitmap := nil;
InternalResources.Delete(i);
InternalResource.Free;
end;
end;
end;
procedure TBCEditorInternalImage.Draw(ACanvas: TCanvas; const Number: Integer; const X: Integer; const Y: Integer;
const LineHeight: Integer);
var
SourceRect, DestinationRect: TRect;
LY: Integer;
begin
if (Number >= 0) and (Number < FCount) then
begin
LY := Y;
if LineHeight >= FHeight then
begin
SourceRect := Rect(Number * FWidth, 0, (Number + 1) * FWidth, FHeight);
Inc(LY, (LineHeight - FHeight) div 2);
DestinationRect := Rect(X, LY, X + FWidth, LY + FHeight);
end
else
begin
DestinationRect := Rect(X, LY, X + FWidth, LY + LineHeight);
LY := (FHeight - LineHeight) div 2;
SourceRect := Rect(Number * FWidth, LY, (Number + 1) * FWidth, LY + LineHeight);
end;
ACanvas.CopyRect(DestinationRect, FImages.Canvas, SourceRect);
end;
end;
procedure TBCEditorInternalImage.DrawTransparent(ACanvas: TCanvas; const Number: Integer; const X: Integer;
const Y: Integer; const LineHeight: Integer; const TransparentColor: TColor);
var
SourceRect, DestinationRect: TRect;
LY: Integer;
begin
LY := Y;
if (Number >= 0) and (Number < FCount) then
begin
if LineHeight >= FHeight then
begin
SourceRect := Rect(Number * FWidth, 0, (Number + 1) * FWidth, FHeight);
Inc(LY, (LineHeight - FHeight) div 2);
DestinationRect := Rect(X, LY, X + FWidth, LY + FHeight);
end
else
begin
DestinationRect := Rect(X, LY, X + FWidth, LY + LineHeight);
LY := (FHeight - LineHeight) div 2;
SourceRect := Rect(Number * FWidth, LY, (Number + 1) * FWidth, LY + LineHeight);
end;
ACanvas.BrushCopy(DestinationRect, FImages, SourceRect, TransparentColor);
end;
end;
initialization
InternalResources := TList.Create;
finalization
InternalResources.Free;
InternalResources := nil;
end.
|
//
// uUIShowings.pas
// TestAnim
// 子控件切换显示时渐变的动态效果
//
// Created by SunSeed on 14-11-1.
// Copyright (c) 2014年 SunSeed. All rights reserved.
//
unit uUIShowings;
interface
uses
Classes, Messages, Controls, Types, windows, Graphics, Forms, SysUtils;
procedure PrepareForAnimation(AHideView: TWinControl);
procedure PrepareAnimScreen(AView:TWinControl);
procedure AnimShowControl(AView: TWinControl; ATime: word = 500);
implementation
type
TacWinControl = class(TWinControl);
TMaskWindow = class(TCustomControl)
private
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
procedure WMNCPaint(var Message: TWmEraseBkgnd); message WM_NCPAINT;
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent); override;
property Canvas;
end;
// 用于扫描bmp像素
TRGBA = packed record
B: Byte;
G: Byte;
R: Byte;
A: Byte;
end;
PRGBAArray = ^TRGBAArray;
TRGBAArray = array [0 .. MAXWORD] of TRGBA;
const
TimerInterval = 12;
var
AnimBmp: TBitmap = nil;
MaskWindow: TMaskWindow = nil;
function acLayered: boolean;
begin
Result := False;
end;
function max(v1, v2: integer):integer;
begin
Result := v1;
if v2 > v1 then
Result := v2;
end;
procedure SetChildOrderAfter(Child: TWinControl; Control: TControl);
var
I: Integer;
begin
for I := 0 to Child.Parent.ControlCount do
if Child.Parent.Controls[I] = Control then
begin
TacWinControl(Child.Parent).SetChildOrder(Child, I + 1);
break;
end;
end;
function CreateBmp32(const AWidth, AHeight: integer): TBitmap;
begin
Result := TBitmap.Create;
Result.PixelFormat := pf32bit;
Result.HandleType := bmDIB;
Result.Width := AWidth;
Result.Height := AHeight;
end;
procedure SumBitmapsByMask(var Outbmp, Src1, Src2: TBitmap; MaskBmp: TBitmap; Percent: word = 0);
var
S1, S2, M: PRGBAArray;
R: PRGBAArray;
X, Y, w, h: integer;
begin
if (Src1.Width <> Src2.Width) or (Src1.Height <> Src2.Height) then
Exit;
w := Src1.Width - 1;
h := Src1.Height - 1;
if MaskBmp = nil then
for Y := 0 to h do
begin
S1 := Src1.ScanLine[Y];
S2 := Src2.ScanLine[Y];
R := Outbmp.ScanLine[Y];
for X := 0 to w do
begin
R[X].R := (((S1[X].R - S2[X].R) * Percent + S2[X].R shl 8) shr 8) and MaxByte;
R[X].G := (((S1[X].G - S2[X].G) * Percent + S2[X].G shl 8) shr 8) and MaxByte;
R[X].B := (((S1[X].B - S2[X].B) * Percent + S2[X].B shl 8) shr 8) and MaxByte;
end
end
else
for Y := 0 to h do
begin
S1 := Src1.ScanLine[Y];
S2 := Src2.ScanLine[Y];
R := Outbmp.ScanLine[Y];
M := MaskBmp.ScanLine[Y];
for X := 0 to w do
begin
R[X].R := (((S1[X].R - S2[X].R) * M[X].R + S2[X].R shl 8) shr 8) and MaxByte;
R[X].G := (((S1[X].G - S2[X].G) * M[X].G + S2[X].G shl 8) shr 8) and MaxByte;
R[X].B := (((S1[X].B - S2[X].B) * M[X].B + S2[X].B shl 8) shr 8) and MaxByte;
end
end
end;
procedure PrepareForAnimation(AHideView: TWinControl);
var
cParent: TWinControl;
Flags: Cardinal;
R: TRect;
hScrDC: hdc;
begin
GetWindowRect(AHideView.Handle, R);
if AnimBmp = nil then
AnimBmp := CreateBmp32(AHideView.Width, AHideView.Height);
hScrDC := GetDC(0);
BitBlt(AnimBmp.Canvas.Handle, 0, 0, AHideView.Width, AHideView.Height, hScrDC, R.Left, R.Top, SRCCOPY);
ReleaseDC(0, hScrDC);
if MaskWindow = nil then
MaskWindow := TMaskWindow.Create(AHideView);
cParent := AHideView.Parent;
if cParent <> nil then
begin
MaskWindow.Parent := cParent;
MaskWindow.BoundsRect := AHideView.BoundsRect;
MaskWindow.SetZOrder(True);
end
else
MaskWindow.BoundsRect := R;
BitBlt(MaskWindow.Canvas.Handle, 0, 0, AHideView.Width, AHideView.Height, AnimBmp.Canvas.Handle, 0, 0, SRCCOPY);
if MaskWindow.Parent = nil then
begin
Flags := SWP_NOZORDER or SWP_SHOWWINDOW or SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE;
SetWindowPos(MaskWindow.Handle, GetWindow(TWinControl(AHideView).Handle, GW_HWNDPREV), 0, 0, 0, 0, Flags);
end
else
ShowWindow(MaskWindow.Handle, SW_SHOWNA);
end;
procedure AnimShowControl(AView: TWinControl; ATime: word);
var
cMixbmp: TBitmap;
cDestbmp: TBitmap;
SavedDC, hPaintDC: hdc;
I, iStepCount, prc: integer;
iPercent: integer;
begin
if MaskWindow = nil then PrepareForAnimation(AView);
if MaskWindow = nil then Exit;
// 获取目标显示界面
cDestbmp := CreateBmp32(AView.Width, AView.Height);
cDestbmp.Canvas.Lock;
SavedDC := SaveDC(cDestbmp.Canvas.Handle);
SendMessage(AView.Handle, WM_ERASEBKGND, WPARAM(cDestbmp.Canvas.Handle), 0);
SendMessage(AView.Handle, WM_PAINT, WPARAM(cDestbmp.Canvas.Handle), 0);
RestoreDC(cDestbmp.Canvas.Handle, SavedDC);
cDestbmp.Canvas.UnLock;
//
cMixbmp := CreateBmp32(AView.Width, AView.Height);
iStepCount := ATime div TimerInterval;
hPaintDC := GetWindowDC(MaskWindow.Handle);
if iStepCount > 0 then
begin
prc := MaxByte div iStepCount;
iPercent := MaxByte;
I := 0;
while I <= iStepCount do
begin
SumBitmapsByMask(cMixbmp, AnimBmp, cDestbmp, nil, max(0, iPercent));
BitBlt(hPaintDC, 0, 0, AView.Width, AView.Height, cMixbmp.Canvas.Handle, 0, 0, SRCCOPY);
inc(I);
dec(iPercent, prc);
if (I > iStepCount) then
break;
if iStepCount > 0 then
Sleep(TimerInterval);
end;
end;
BitBlt(hPaintDC, 0, 0, AView.Width, AView.Height, cDestbmp.Canvas.Handle, 0, 0, SRCCOPY);
if AView.Visible then
begin
SendMessage(AView.Handle, WM_SETREDRAW, 1, 0); // Vista
if Win32MajorVersion >= 6 then
RedrawWindow(AView.Handle, nil, 0, RDW_ERASE or RDW_FRAME or RDW_ALLCHILDREN or RDW_INVALIDATE or RDW_UPDATENOW);
if not(AView is TCustomForm) or (dword(GetWindowLong(AView.Handle, GWL_EXSTYLE)) and WS_EX_LAYERED <> WS_EX_LAYERED) then
SetWindowPos(MaskWindow.Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or SWP_HIDEWINDOW or SWP_NOREDRAW or { SWP_NOCOPYBITS or } SWP_NOACTIVATE);
end;
ReleaseDC(MaskWindow.Handle, hPaintDC);
FreeAndnil(MaskWindow);
FreeAndnil(cMixbmp);
FreeAndnil(AnimBmp);
FreeAndnil(cDestbmp);
end;
procedure PrepareAnimScreen(AView:TWinControl);
begin
if (MaskWindow <> nil) then
TacWinControl(MaskWindow).SetZOrder(True);
end;
{ TMaskWindow }
constructor TMaskWindow.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Visible := False;
Color := clBlack;
end;
procedure TMaskWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
if (Parent = nil) and (ParentWindow = 0) then
begin
Params.Style := WS_POPUP;
if (Owner is TWinControl) and
((dword(GetWindowLong(TWinControl(Owner).Handle, GWL_EXSTYLE)) and WS_EX_TOPMOST) <> 0) then
Params.ExStyle := ExStyle or WS_EX_TOPMOST;
WndParent := Application.Handle;
end;
end;
end;
procedure TMaskWindow.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TMaskWindow.WMNCPaint(var Message: TWmEraseBkgnd);
begin
Message.Result := 0;
end;
end.
|
unit DW.SMSReceiver.Android;
interface
uses
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Provider, Androidapi.JNI.Telephony,
DW.MultiReceiver.Android, DW.SMSMessage.Types;
type
TSMSReceiver = class(TMultiReceiver)
private
FOnMessagesReceived: TSMSMessagesEvent;
procedure DoMessagesReceived(const AMessages: TSMSMessages);
protected
procedure Receive(context: JContext; intent: JIntent); override;
procedure ConfigureActions; override;
public
property OnMessagesReceived: TSMSMessagesEvent read FOnMessagesReceived write FOnMessagesReceived;
end;
implementation
uses
Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, Androidapi.Helpers;
{ TSMSReceiver }
procedure TSMSReceiver.ConfigureActions;
begin
IntentFilter.addAction(TJSms_Intents.JavaClass.SMS_RECEIVED_ACTION);
end;
procedure TSMSReceiver.DoMessagesReceived(const AMessages: TSMSMessages);
begin
if Assigned(FOnMessagesReceived) and (Length(AMessages) > 0) then
FOnMessagesReceived(Self, AMessages);
end;
procedure TSMSReceiver.Receive(context: JContext; intent: JIntent);
var
LJSmsMessages: TJavaObjectArray<JSmsMessage>;
LSMSMessages: TSMSMessages;
I: Integer;
begin
LJSmsMessages := TJSms_Intents.JavaClass.getMessagesFromIntent(intent);
SetLength(LSMSMessages, LJSmsMessages.Length);
for I := 0 to LJSmsMessages.Length - 1 do
begin
LSMSMessages[I].OriginatingAddress := JStringToString(LJSmsMessages[I].getOriginatingAddress);
LSMSMessages[I].MessageBody := JStringToString(LJSmsMessages[I].getMessageBody);
end;
DoMessagesReceived(LSMSMessages);
end;
end.
|
unit uxPLRFXMessages;
interface
Uses uxPLRFXConst, u_xPL_Message, Classes;
type
TxPLRFXMessages = class // contains a list of xPL Messages
private
FItems : TList;
function GetxPLMessage(Index : Integer) : TxPLMessage;
public
property Items[Index : Integer] : TxPLMessage read GetxPLMessage; default;
function Add(RawxPL : String) : Integer;
constructor Create;
destructor Destroy;
function Count : Integer;
procedure Clear;
end;
implementation
Uses SysUtils;
/////////////////////////
// TxPLRFXMessages
constructor TxPLRFXMessages.Create;
begin
FItems := TList.Create;
end;
destructor TxPLRFXMessages.Destroy;
begin
end;
function TxPLRFXMessages.GetxPLMessage(Index: Integer) : TxPLMessage;
begin
Result := TxPLMessage(FItems[Index]);
end;
function TxPLRFXMessages.Add(RawxPL: string) : Integer;
begin
Result := FItems.Add(TxPLMessage.Create(nil,RawxPL));
end;
function TxPLRFXMessages.Count : Integer;
begin
Result := FItems.Count;
end;
procedure TxPLRFXMessages.Clear;
var
i : Integer;
begin
for i := 0 to FItems.Count-1 do
TxPLMessage(FItems[i]).Free; // Free all xPL Messages
FItems.Clear; // Empty the list
end;
end.
|
program Sample;
uses crt;
var ch : char;
begin
WriteLn('Waiting for key press');
while not KeyPressed() do
begin
Delay(1);
end;
ch := ReadKey;
WriteLn('Got character: ', ch);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ODBC MS Access driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.MSAcc;
interface
uses
System.Classes,
FireDAC.Stan.Error,
FireDAC.Phys, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCBase;
type
EMSAccessNativeException = class;
TFDPhysMSAccessDriverLink = class;
TFDMSAccessService = class;
EMSAccessNativeException = class(EODBCNativeException)
public
function AppendError(AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage,
AResultMessage, ACommandText, AObject: String; AKind: TFDCommandExceptionKind;
ACmdOffset, ARowIndex: Integer): TFDDBError; override;
end;
[ComponentPlatformsAttribute(pfidWindows)]
TFDPhysMSAccessDriverLink = class(TFDPhysODBCBaseDriverLink)
protected
function GetBaseDriverID: String; override;
end;
TFDMSAccessDBVersion = (avDefault, avAccess2, avAccess95, avAccess97,
avAccess2000, avAccess2003, avAccess2007);
[ComponentPlatformsAttribute(pfidWindows)]
TFDMSAccessService = class (TFDPhysODBCBaseService)
private type
TAction = (aaCompactDB, aaRepairDB, aaCreateDB, aaDropDB);
private
FAction: TAction;
FDatabase: String;
FDestDatabase: String;
FDBVersion: TFDMSAccessDBVersion;
FSortOrder: String;
FEncrypted: Boolean;
FPassword: String;
FResetPassword: Boolean;
function GetDriverLink: TFDPhysMSAccessDriverLink;
procedure SetDriverLink(const AValue: TFDPhysMSAccessDriverLink);
protected
procedure InternalExecute; override;
public
procedure CreateDB;
procedure Drop;
procedure Repair;
procedure Compact;
published
property DriverLink: TFDPhysMSAccessDriverLink read GetDriverLink write SetDriverLink;
property Database: String read FDatabase write FDatabase;
property DestDatabase: String read FDestDatabase write FDestDatabase;
property SortOrder: String read FSortOrder write FSortOrder;
property DBVersion: TFDMSAccessDBVersion read FDBVersion write FDBVersion default avDefault;
property Encrypted: Boolean read FEncrypted write FEncrypted default False;
property Password: String read FPassword write FPassword;
property ResetPassword: Boolean read FResetPassword write FResetPassword default False;
end;
{-------------------------------------------------------------------------------}
implementation
uses
{$IFDEF MSWINDOWS}
// Preventing from "Inline has not been expanded"
Winapi.Windows, System.Win.ComObj,
{$ENDIF}
{$IFDEF POSIX}
// Preventing from "Inline has not been expanded"
Posix.UniStd,
{$ENDIF}
System.SysUtils, System.Variants,
FireDAC.Stan.Consts, FireDAC.Stan.ResStrs, FireDAC.Stan.Intf, FireDAC.Stan.Util,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.MSAccMeta,
FireDAC.Phys.MSAccDef;
type
TFDPhysMSAccessDriver = class;
TFDPhysMSAccessConnection = class;
TFDPhysMSAccessDriver = class(TFDPhysODBCDriverBase)
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
end;
TFDPhysMSAccessConnection = class(TFDPhysODBCConnectionBase)
private
FStringFormat: TFDDataType;
protected
function InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
procedure InternalConnect; override;
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); override;
function GetStrsType: TFDDataType; override;
function GetExceptionClass: EODBCNativeExceptionClass; override;
end;
{-------------------------------------------------------------------------------}
{ EMSAccessNativeException }
{-------------------------------------------------------------------------------}
function EMSAccessNativeException.AppendError(AHandle: TODBCHandle;
ARecNum: SQLSmallint; const ASQLState: String; ANativeError: SQLInteger;
const ADiagMessage, AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError;
var
sObj: String;
procedure ExtractObjName;
var
i1, i2: Integer;
begin
i1 := Pos('''', ADiagMessage);
if i1 <> 0 then begin
i2 := Pos('''', ADiagMessage, i1 + 1);
if i2 <> 0 then
sObj := Copy(ADiagMessage, i1 + 1, i2 - i1 - 1);
end;
end;
begin
// following is not supported by MSAccess:
// ekNoDataFound
// ekUserPwdExpired
// ekUserPwdWillExpire
sObj := AObject;
case ANativeError of
-1102:
AKind := ekRecordLocked;
-1605:
AKind := ekUKViolated;
-1613:
AKind := ekFKViolated;
-1305:
begin
AKind := ekObjNotExists;
// first 'xxxx' - object name
ExtractObjName;
end;
-1905:
AKind := ekUserPwdInvalid;
end;
Result := inherited AppendError(AHandle, ARecNum, ASQLState, ANativeError,
ADiagMessage, AResultMessage, ACommandText, sObj, AKind, ACmdOffset, ARowIndex);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSAccessDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_MSAccId;
end;
{-------------------------------------------------------------------------------}
{ TFDMSAccessService }
{-------------------------------------------------------------------------------}
function TFDMSAccessService.GetDriverLink: TFDPhysMSAccessDriverLink;
begin
Result := inherited DriverLink as TFDPhysMSAccessDriverLink;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSAccessService.SetDriverLink(const AValue: TFDPhysMSAccessDriverLink);
begin
inherited DriverLink := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSAccessService.CreateDB;
begin
FAction := aaCreateDB;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSAccessService.Drop;
begin
FAction := aaDropDB;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSAccessService.Compact;
begin
FAction := aaCompactDB;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSAccessService.Repair;
begin
FAction := aaRepairDB;
Execute;
end;
{-------------------------------------------------------------------------------}
procedure TFDMSAccessService.InternalExecute;
var
sStr, sDrv, sDb: String;
lSort, lLastDrv: Boolean;
function NormFileName(AName: String): String;
begin
Result := FDExpandStr(AName);
if (Pos(' ', Result) > 0) and (Result[1] <> '"') then
Result := '"' + Result + '"';
end;
procedure DeleteDatabase(const AName: String);
var
sFile: String;
begin
sFile := FDExpandStr(AName);
System.SysUtils.DeleteFile(sFile);
System.SysUtils.DeleteFile(ChangeFileExt(sFile, '.ldb'));
System.SysUtils.DeleteFile(ChangeFileExt(sFile, '.laccdb'));
end;
{$IFDEF MSWINDOWS}
function RenameDatabase(const AOldName, ANewName: String): Boolean;
var
sOldFile, sNewFile, sLdbFile: String;
begin
sOldFile := FDExpandStr(AOldName);
sNewFile := FDExpandStr(ANewName);
Result := RenameFile(sOldFile, sNewFile);
if Result then begin
sLdbFile := ChangeFileExt(sOldFile, '.ldb');
if FileExists(sLdbFile) then
RenameFile(sLdbFile, ChangeFileExt(sNewFile, '.ldb'));
sLdbFile := ChangeFileExt(sOldFile, '.laccdb');
if FileExists(sLdbFile) then
RenameFile(sLdbFile, ChangeFileExt(sNewFile, '.laccdb'));
end;
end;
function GenTempFileName(const AName: String): String;
var
sPath: String;
begin
sPath := ExtractFilePath(FDExpandStr(AName));
SetLength(Result, MAX_PATH);
GetTempFileName(PChar(sPath), 'FD', 0, PChar(Result));
Result := PChar(Result);
end;
procedure ProcessOLEException(AExc: EOleSysError);
var
sMsg: String;
iCode: Integer;
oExc: EFDDBEngineException;
oErr: TFDDBError;
begin
sMsg := AExc.Message;
iCode := er_FD_AccUnknownOleError;
if AExc is EOLEException then begin
if Pos('Class not registered', sMsg) > 0 then
iCode := er_FD_AccClassNotRegistered
else if Pos('Unrecognized database format', sMsg) > 0 then
iCode := er_FD_AccUnrecognizedDbFormat
else if Pos('Not a valid password', sMsg) > 0 then
iCode := er_FD_AccNotValidPassword;
end
else
if Pos('Class not registered', sMsg) > 0 then
iCode := er_FD_AccSysClassNotRegistered;
oExc := FDDBEngineExceptionCreate(EMSAccessNativeException, iCode, [sMsg]);
oErr := TFDDBError.Create;
oErr.Message := sMsg;
oExc.Append(oErr);
FDException(Self, oExc{$IFDEF FireDAC_Monitor}, False{$ENDIF});
end;
procedure CompactRepairJRO(const ADestDB: String);
var
sSource, sDest, sProvider: String;
iEngine: Integer;
vJro: Variant;
begin
sSource := 'Provider=%s;Data Source=%s;Jet OLEDB:Engine Type=%d';
sDest := sSource;
if Password <> '' then begin
sSource := sSource + ';Jet OLEDB:Database Password=' + Password;
if not ResetPassword then
sDest := sSource;
end;
if lSort then
sDest := sDest + ';LocaleIdentifier=' + SortOrder;
if Encrypted then
sDest := sDest + ';Jet OLEDB:Encrypt Database=True';
iEngine := 5;
case DBVersion of
avDefault:
begin
if sDrv = 'Microsoft Access Driver (*.mdb, *.accdb)' then
sProvider := 'Microsoft.ACE.OLEDB.12.0'
else
sProvider := 'Microsoft.Jet.OLEDB.4.0';
end;
avAccess2:
begin
sProvider := 'Microsoft.Jet.OLEDB.4.0';
iEngine := 3;
end;
avAccess95,
avAccess97:
begin
sProvider := 'Microsoft.Jet.OLEDB.4.0';
iEngine := 4;
end;
avAccess2000,
avAccess2003:
begin
sProvider := 'Microsoft.Jet.OLEDB.4.0';
iEngine := 5;
end;
end;
vJro := CreateOLEObject('JRO.JetEngine');
try
vJro.CompactDatabase(Format(sSource, [sProvider, FDExpandStr(Database),
iEngine]), Format(sDest, [sProvider, FDExpandStr(ADestDB), iEngine]));
finally
vJro := Unassigned;
end;
end;
procedure CompactRepairDAO(const ADestDB: String);
var
vDao, vDstLocale, vOptions, vPassword: Variant;
begin
if lSort then
vDstLocale := SortOrder
else
vDstLocale := '';
vOptions := 128;
if ResetPassword then begin
vDstLocale := vDstLocale + ';pwd=';
vPassword := ';pwd=' + Password;
end
else if Encrypted then
vDstLocale := vDstLocale + ';pwd=' + Password
else if Password <> '' then begin
vDstLocale := vDstLocale + ';pwd=' + Password;
vPassword := ';pwd=' + Password;
end;
// Requires to install "Microsoft Access Database Engine 2010 Redistributable"
// https://www.microsoft.com/en-us/download/details.aspx?id=13255
vDao := CreateOLEObject('DAO.DBEngine.120');
try
vDao.CompactDatabase(FDExpandStr(Database), FDExpandStr(ADestDB),
vDstLocale, vOptions, vPassword);
finally
vDao := Unassigned;
end;
end;
procedure CompactRepairWin;
var
sDestDatabase: String;
lRename: Boolean;
begin
if not FileExists(Database) then
FDException(Self, FDDBEngineExceptionCreate(EMSAccessNativeException,
er_FD_AccDbNotExists, [Database]) {$IFDEF FireDAC_Monitor}, False{$ENDIF});
try
lRename := (DestDatabase = '') or (DestDatabase = Database);
if lRename then
sDestDatabase := GenTempFileName(Database)
else
sDestDatabase := DestDatabase;
DeleteDatabase(sDestDatabase);
if DBVersion = avAccess2007 then
CompactRepairDAO(sDestDatabase)
else
CompactRepairJRO(sDestDatabase);
if lRename then begin
DeleteDatabase(Database);
if RenameDatabase(sDestDatabase, Database) then
DeleteDatabase(sDestDatabase);
end;
except
on E: EOleSysError do
ProcessOLEException(EOleSysError(E))
end;
end;
{$ENDIF}
begin
sDrv := (DriverLink.DriverIntf as IFDPhysODBCDriver).ODBCDriver;
case FAction of
aaCompactDB:
{$IFDEF MSWINDOWS}
CompactRepairWin;
{$ELSE}
begin
sDb := NormFileName(Database);
sStr := 'COMPACT_DB=' + sDb + ' ';
if DestDatabase = '' then
sStr := sStr + sDb
else
sStr := sStr + NormFileName(DestDatabase);
if SortOrder <> '' then
sStr := sStr + ' ' + SortOrder;
ExecuteBase(ODBC_ADD_DSN, sDrv, sStr);
end;
{$ENDIF}
aaRepairDB:
{$IFDEF MSWINDOWS}
CompactRepairWin;
{$ELSE}
begin
sStr := 'REPAIR_DB=' + NormFileName(Database);
ExecuteBase(ODBC_ADD_DSN, sDrv, sStr);
end;
{$ENDIF}
aaCreateDB:
begin
sStr := 'CREATE_DB';
lLastDrv := sDrv = 'Microsoft Access Driver (*.mdb, *.accdb)';
case DBVersion of
avDefault: ;
avAccess2: sStr := sStr + 'V2';
avAccess95,
avAccess97: sStr := sStr + 'V3';
avAccess2000: sStr := sStr + 'V4';
avAccess2003,
avAccess2007:
begin
sDrv := 'Microsoft Access Driver (*.mdb, *.accdb)';
lLastDrv := True;
end;
end;
sStr := sStr + '=' + NormFileName(Database);
lSort := SortOrder <> '';
if lSort and (Pos('0x', SortOrder) = 0) then begin
sStr := sStr + ' ' + SortOrder;
{$IFDEF MSWINDOWS}
lSort := False;
{$ENDIF}
end;
if Encrypted and not lLastDrv then
sStr := sStr + ' ENCRYPT';
ExecuteBase(ODBC_ADD_DSN, sDrv, sStr);
{$IFDEF MSWINDOWS}
if (Password <> '') or lSort or (Encrypted and lLastDrv) then begin
sDb := DestDatabase;
DestDatabase := '';
try
CompactRepairWin;
finally
DestDatabase := sDb;
end;
end;
{$ENDIF}
end;
aaDropDB:
DeleteDatabase(Database);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSAccessDriver }
{-------------------------------------------------------------------------------}
class function TFDPhysMSAccessDriver.GetBaseDriverID: String;
begin
Result := S_FD_MSAccId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSAccessDriver.GetBaseDriverDesc: String;
begin
Result := 'Microsoft Access Database';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSAccessDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MSAccess;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMSAccessDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysMSAccConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSAccessDriver.InternalLoad;
begin
ODBCAdvanced := 'ExtendedAnsiSQL=1';
inherited InternalLoad;
if ODBCDriver = '' then
ODBCDriver := FindBestDriver([
'Microsoft Access Driver (*.mdb, *.accdb)',
'Microsoft Access Driver (*.mdb)',
'Driver do Microsoft Access (*.mdb)',
'Microsoft Access-Treiber (*.mdb)']);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysMSAccessConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSAccessDriver.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
inherited GetODBCConnectStringKeywords(AKeywords);
AKeywords.Add(S_FD_ConnParam_Common_Database + '=DBQ*');
AKeywords.Add(S_FD_ConnParam_MSAcc_SystemDB);
AKeywords.Add(S_FD_ConnParam_MSAcc_ReadOnly);
AKeywords.Add('=ExtendedAnsiSQL');
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('Type', '@F:Microsoft Access Database|*.mdb;*.accdb');
oView.Rows[0].SetValues('LoginIndex', 2);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSAcc_SystemDB, '@S', '', S_FD_ConnParam_MSAcc_SystemDB, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSAcc_ReadOnly, '@L', '', S_FD_ConnParam_MSAcc_ReadOnly, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_MSAcc_StringFormat, S_FD_Choose + ';' + S_FD_Unicode + ';' + S_FD_ANSI, S_FD_Choose, S_FD_ConnParam_MSAcc_StringFormat, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSAccessConnection }
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysMSAccCommandGenerator.Create(ACommand)
else
Result := TFDPhysMSAccCommandGenerator.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessConnection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
begin
GetVersions(iSrvVer, iClntVer);
Result := TFDPhysMSAccMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSAccessConnection.InternalConnect;
var
oParams: TFDPhysMSAccConnectionDefParams;
begin
inherited InternalConnect;
oParams := ConnectionDef.Params as TFDPhysMSAccConnectionDefParams;
case oParams.StringFormat of
sfChoose: FStringFormat := dtUnknown;
sfUnicode: FStringFormat := dtWideString;
sfANSI: FStringFormat := dtAnsiString;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMSAccessConnection.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize, AByteSize: Integer);
begin
case AStrDataType of
SQL_C_CHAR, SQL_C_WCHAR:
ACharSize := 255;
SQL_C_BINARY:
ACharSize := 510;
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_MSAccId]);
end;
AByteSize := ACharSize;
if AStrDataType = SQL_C_WCHAR then
AByteSize := AByteSize * SizeOf(SQLWChar);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessConnection.GetStrsType: TFDDataType;
begin
Result := FStringFormat;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSAccessConnection.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := EMSAccessNativeException;
end;
{-------------------------------------------------------------------------------}
function MSAccessNativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := EMSAccessNativeException.Create;
EMSAccessNativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysMSAccessDriver);
FDStorageManager().RegisterClass(EMSAccessNativeException, 'MSAccessNativeException',
@MSAccessNativeExceptionLoad, @FDExceptionSave);
finalization
FDUnregisterDriverClass(TFDPhysMSAccessDriver);
end.
|
{ This unit is a drop in replacement to build-in unit crt }
Unit MyCrt;
Interface
Uses Windows, Math;
Const
Black: Integer = 0;
Blue: Integer = 1;
Green: Integer = 2;
Red: Integer = 4;
Gray: Integer = 8;
Aqua: Integer = 3;
Purple: Integer = 5;
Yellow: Integer = 6;
LightGray: Integer = 7;
LightBlue: Integer = 9;
LightGreen: Integer = 10;
LightRed: Integer = 12;
LightAqua: Integer = 11;
LightPurple: Integer = 13;
LightYellow: Integer = 14;
White: Integer = 15;
v : Char = #186;
h : Char = #205;
cul : Char = #201;
cur : Char = #187;
cll : Char = #200;
clr : Char = #188;
Function StrDup(Const str: String; Const cnt: Integer): String;
Procedure InitConsole();
Procedure SetConsoleSize(Const Width: Integer; Const Height: Integer);
Procedure SetConsoleBuffer(Const Width: Integer; Const Height: Integer);
Procedure PollConsoleInput(Var irInBuf: Array Of INPUT_RECORD; Const bufSize: DWord; Var cNumRead: DWord);
Procedure ClrScr();
Procedure SetConsoleColor(Const color: Word);
Procedure TextBackground(Const color: Integer);
Procedure TextColor(Const color: Integer);
Procedure GoToXY(Const X: Integer; Const Y: Integer);
Procedure WriteDup(Const X: Integer; Const Y: Integer; Const c: PChar; Const n: Integer);
Procedure WriteDupAttr(Const X: Integer; Const Y: Integer; Const n: Integer);
Procedure CursorOff();
Procedure CursorOn();
Procedure FlushInput();
Procedure RestoreConsole();
Implementation
Var
hStdin: Handle;
hStdout: Handle;
fdwSaveOldMode: DWord;
Function StrDup(Const str: String; Const cnt: Integer): String;
Var
result: String;
i: Integer;
Begin
result := '';
For i := 1 To cnt Do
result := result + str;
StrDup := result;
End;
Procedure InitConsole();
Var
fdwMode: DWord;
FontInfo: CONSOLE_FONT_INFOEX;
Begin
GetConsoleMode(hStdin, @fdwSaveOldMode);
fdwMode := ENABLE_WINDOW_INPUT Or ENABLE_MOUSE_INPUT Or ENABLE_EXTENDED_FLAGS Or ENABLE_ECHO_INPUT Or ENABLE_LINE_INPUT Or ENABLE_INSERT_MODE;
SetConsoleMode(hStdin, fdwMode);
CursorOff();
FontInfo.cbSize := sizeof(CONSOLE_FONT_INFOEX);
GetCurrentConsoleFontEx(hStdout, False, @FontInfo);
FontInfo.FaceName := 'Lucida Console';
FontInfo.dwFontSize.X := 8;
FontInfo.dwFontSize.Y := 16;
SetCurrentConsoleFontEx(hStdout, False, @FontInfo);
TextBackground(Black);
TextColor(White);
ClrScr();
End;
Procedure SetConsoleSize(Const Width: Integer; Const Height: Integer);
Var
ConsoleSize: SMALL_RECT;
CurrentInfo: CONSOLE_SCREEN_BUFFER_INFO;
Begin
GetConsoleScreenBufferInfo(hStdout, @CurrentInfo);
{ Set a buffer size bigger than the console size, this nearly guarantees the success of setting console size }
SetConsoleBuffer(Max(CurrentInfo.dwSize.X, Width), Max(CurrentInfo.dwSize.Y, Height));
{ Then safely set the console size, will fail if the screen is too small }
ConsoleSize.Top := 0;
ConsoleSize.Left := 0;
ConsoleSize.Right := Width - 1;
ConsoleSize.Bottom := Height - 1;
SetConsoleWindowInfo(hStdout, True, ConsoleSize);
{ Set the buffer size to be equal to the console size }
SetConsoleBuffer(Width, Height);
End;
Procedure SetConsoleBuffer(Const Width: Integer; Const Height: Integer);
Var
BufferSize: Coord;
Begin
{ Set the buffer size directly, this fails if the buffer size is too small }
BufferSize.X := Width;
BufferSize.Y := Height;
SetConsoleScreenBufferSize(hStdout, BufferSize);
End;
Procedure PollConsoleInput(Var irInBuf: Array Of INPUT_RECORD; Const bufSize: DWord; Var cNumRead: DWord);
Begin
ReadConsoleInput(hStdin, irInBuf, bufSize, @cNumRead);
End;
Procedure ClrScr();
Var
screen: Coord;
cCharsWritten: DWord;
CurrentInfo: CONSOLE_SCREEN_BUFFER_INFO;
Begin
GetConsoleScreenBufferInfo(hStdout, @CurrentInfo);
screen.X := 0;
screen.Y := 0;
FillConsoleOutputCharacter(hStdout, ' ', CurrentInfo.dwSize.X * CurrentInfo.dwSize.Y, screen, @cCharsWritten);
FillConsoleOutputAttribute(hStdout, CurrentInfo.wAttributes, CurrentInfo.dwSize.X * CurrentInfo.dwSize.Y, screen, @cCharsWritten);
GoToXY(0, 0);
End;
Procedure SetConsoleColor(Const color: Word);
Begin
SetConsoleTextAttribute(hStdout, color);
End;
Procedure TextBackground(Const color: Integer);
Var
CurrentInfo: CONSOLE_SCREEN_BUFFER_INFO;
Begin
GetConsoleScreenBufferInfo(hStdout, @CurrentInfo);
SetConsoleColor(CurrentInfo.wAttributes And 15 + color * 16);
End;
Procedure TextColor(Const color: Integer);
Var
CurrentInfo: CONSOLE_SCREEN_BUFFER_INFO;
Begin
GetConsoleScreenBufferInfo(hStdout, @CurrentInfo);
SetConsoleColor(CurrentInfo.wAttributes And 240 + color);
End;
Procedure GoToXY(Const X: Integer; Const Y: Integer);
Var
Loc: Coord;
Begin
Loc.X := X;
Loc.Y := Y;
SetConsoleCursorPosition(hStdout, Loc);
End;
Procedure WriteDup(Const X: Integer; Const Y: Integer; Const c: PChar; Const n: Integer);
Var
Loc: Coord;
written: DWord;
Begin
Loc.X := X;
Loc.Y := Y;
WriteConsoleOutputCharacter(hStdout, c, n, Loc, written);
WriteDupAttr(X, Y, n);
End;
Procedure WriteDupAttr(Const X: Integer; Const Y: Integer; Const n: Integer);
Var
Loc: Coord;
written: DWord;
CurrentInfo: CONSOLE_SCREEN_BUFFER_INFO;
Attributes: Array Of Word;
i: Integer;
Begin
Loc.X := X;
Loc.Y := Y;
GetConsoleScreenBufferInfo(hStdout, @CurrentInfo);
SetLength(Attributes, n);
For i := 0 To n - 1 Do
Attributes[i] := CurrentInfo.wAttributes;
WriteConsoleOutputAttribute(hStdout, @Attributes[0], n, Loc, written);
End;
Procedure CursorOff();
Var
cursorInfo: CONSOLE_CURSOR_INFO;
Begin
cursorInfo.bVisible := False;
cursorInfo.dwSize := 100;
SetConsoleCursorInfo(hStdout, cursorInfo);
End;
Procedure CursorOn();
Var
cursorInfo: CONSOLE_CURSOR_INFO;
Begin
cursorInfo.bVisible := True;
cursorInfo.dwSize := 100;
SetConsoleCursorInfo(hStdout, cursorInfo);
End;
Procedure FlushInput();
Begin
FlushConsoleInputBuffer(hStdin);
End;
Procedure RestoreConsole();
Begin
SetConsoleMode(hStdin, fdwSaveOldMode);
End;
Initialization
SetConsoleOutputCP(437);
hStdin := GetStdHandle(STD_INPUT_HANDLE);
hStdout := GetStdHandle(STD_OUTPUT_HANDLE);
InitConsole();
Finalization
RestoreConsole();
End. |
unit vclutils;
interface
uses vcl.stdctrls, vcl.controls, vcl.ComCtrls, vcl.graphics, system.Types;
type
TControlProc = reference to procedure(const AControl: TControl);
procedure SetButtonMultiline(b: TButton);
procedure ModifyControl(const AControl: TControl; const ARef: TControlProc);
procedure PageControl_DrawVerticalTab1(Control: TCustomTabControl;
TabIndex: integer; const Rect: system.Types.TRect; Active: boolean);
procedure PageControl_DrawVerticalTab2(Control: TCustomTabControl;
TabIndex: integer; const Rect: system.Types.TRect; Active: boolean);
procedure ConvertImagesToHighColor(ImageList: TImageList);
function GetVCLControlAtPos(c: TWinControl; mousePos: TPoint): TWinControl;
function GetVCLControlParentN(c: TWinControl; N: integer): TWinControl;
procedure RichEdit_PopupMenu(re: TRichEdit);
implementation
uses vcl.forms, Clipbrd, Winapi.Messages, Winapi.commctrl,
Winapi.Windows, SysUtils;
function GetVCLControlParentN(c: TWinControl; N: integer): TWinControl;
begin
Result := c;
while N > 0 do
begin
if not Assigned(Result.Parent) then
exit;
Result := Result.Parent;
Dec(N);
end;
end;
function GetVCLControlAtPos(c: TWinControl; mousePos: TPoint): TWinControl;
var
p: TPoint;
begin
p := c.ScreenToClient(mousePos);
c := TWinControl(c.ControlAtPos(p, false, true));
while Assigned(c) do
begin
Result := c;
p := c.ScreenToClient(mousePos);
c := TWinControl(c.ControlAtPos(p, false, true));
end;
end;
procedure ConvertImagesToHighColor(ImageList: TImageList);
// To show smooth images we have to convert the image list from 16 colors to high color.
var
IL: TImageList;
begin
// Have to create a temporary copy of the given list, because the list is cleared on handle creation.
IL := TImageList.Create(nil);
IL.Assign(ImageList);
with ImageList do
Handle := ImageList_Create(Width, Height, ILC_COLOR16 or ILC_MASK,
Count, AllocBy);
ImageList.Assign(IL);
IL.Free;
end;
procedure ModifyControl(const AControl: TControl; const ARef: TControlProc);
var
i: integer;
begin
if AControl = nil then
exit;
if AControl is TWinControl then
begin
for i := 0 to TWinControl(AControl).ControlCount - 1 do
ModifyControl(TWinControl(AControl).controls[i], ARef);
end;
ARef(AControl);
end;
procedure SetButtonMultiline(b: TButton);
begin
SetWindowLong(b.Handle, GWL_STYLE, GetWindowLong(b.Handle, GWL_STYLE) or
BS_MULTILINE);
end;
procedure PageControl_DrawVerticalTab1(Control: TCustomTabControl;
TabIndex: integer; const Rect: system.Types.TRect; Active: boolean);
var
i: integer;
PageControl: TPageControl;
x, y: integer;
txt_height: double;
word: string;
begin
PageControl := Control as TPageControl;
Active := PageControl.ActivePageIndex = TabIndex;
if PageControl.ActivePageIndex = TabIndex then
begin
PageControl.Canvas.Brush.Color := clGradientInactiveCaption;
PageControl.Canvas.Font.Color := clNavy;
end
else
begin
PageControl.Canvas.Brush.Color := clWindow;
PageControl.Canvas.Font.Color := clBlack;
end;
word := PageControl.Pages[TabIndex].Caption;
x := Rect.Left + 7;
txt_height := PageControl.Canvas.TextHeight(word);
y := Rect.Top + round((Rect.Height - txt_height) / 2.0);
PageControl.Canvas.TextRect(Rect, x, y, word);
end;
procedure PageControl_DrawVerticalTab2(Control: TCustomTabControl;
TabIndex: integer; const Rect: system.Types.TRect; Active: boolean);
var
i: integer;
PageControl: TPageControl;
word, word2: string;
words: TArray<string>;
x, y: integer;
txt_height: double;
begin
PageControl := Control as TPageControl;
Active := PageControl.ActivePageIndex = TabIndex;
if PageControl.ActivePageIndex = TabIndex then
begin
PageControl.Canvas.Brush.Color := clGradientInactiveCaption;
PageControl.Canvas.Font.Color := clNavy;
end
else
begin
PageControl.Canvas.Brush.Color := clWindow;
PageControl.Canvas.Font.Color := clBlack;
end;
word := PageControl.Pages[TabIndex].Caption;
words := word.Split([' '], TStringSplitOptions.ExcludeEmpty);
x := Rect.Left + 7;
txt_height := PageControl.Canvas.TextHeight(word);
if Length(words) = 1 then
begin
y := Rect.Top + round((Rect.Height - txt_height) / 2.0);
PageControl.Canvas.TextRect(Rect, x, y, word);
end
else
begin
y := Rect.Top + 5;
PageControl.Canvas.FillRect(Rect);
PageControl.Canvas.TextOut(x, y, words[0]);
y := y + round(txt_height) + 3;
PageControl.Canvas.TextOut(x, y, words[1]);
end;
end;
procedure RichEdit_PopupMenu(re: TRichEdit);
const
IDM_UNDO = WM_UNDO;
IDM_CUT = WM_CUT;
IDM_COPY = WM_COPY;
IDM_PASTE = WM_PASTE;
IDM_DELETE = WM_CLEAR;
IDM_SELALL = EM_SETSEL;
IDM_RTL = $8000; // WM_APP ?
Enables: array [boolean] of DWORD = (MF_DISABLED or MF_GRAYED, MF_ENABLED);
Checks: array [boolean] of DWORD = (MF_UNCHECKED, MF_CHECKED);
var
hUser32: HMODULE;
hmnu, hmenuTrackPopup: HMENU;
Cmd: DWORD;
Flags: Cardinal;
HasSelText: boolean;
FormHandle: HWND;
// IsRTL: Boolean;
begin
hUser32 := LoadLibraryEx(user32, 0, LOAD_LIBRARY_AS_DATAFILE);
if (hUser32 <> 0) then
try
hmnu := LoadMenu(hUser32, MAKEINTRESOURCE(1));
if (hmnu <> 0) then
try
hmenuTrackPopup := GetSubMenu(hmnu, 0);
HasSelText := Length(re.SelText) <> 0;
EnableMenuItem(hmnu, IDM_UNDO, Enables[re.CanUndo]);
EnableMenuItem(hmnu, IDM_CUT, Enables[HasSelText]);
EnableMenuItem(hmnu, IDM_COPY, Enables[HasSelText]);
EnableMenuItem(hmnu, IDM_PASTE,
Enables[Clipboard.HasFormat(CF_TEXT)]);
EnableMenuItem(hmnu, IDM_DELETE, Enables[HasSelText]);
EnableMenuItem(hmnu, IDM_SELALL,
Enables[Length(re.text) <> 0]);
// IsRTL := GetWindowLong(re.Handle, GWL_EXSTYLE) and WS_EX_RTLREADING <> 0;
// EnableMenuItem(hmnu, IDM_RTL, Enables[True]);
// CheckMenuItem(hmnu, IDM_RTL, Checks[IsRTL]);
FormHandle := GetParentForm(re).Handle;
Flags := TPM_LEFTALIGN or TPM_RIGHTBUTTON or TPM_NONOTIFY or
TPM_RETURNCMD;
Cmd := DWORD(TrackPopupMenu(hmenuTrackPopup, Flags,
Mouse.CursorPos.x, Mouse.CursorPos.y, 0,
FormHandle, nil));
if Cmd <> 0 then
begin
case Cmd of
IDM_UNDO:
re.Undo;
IDM_CUT:
re.CutToClipboard;
IDM_COPY:
re.CopyToClipboard;
IDM_PASTE:
re.PasteFromClipboard;
IDM_DELETE:
re.ClearSelection;
IDM_SELALL:
re.SelectAll;
IDM_RTL:
; // ?
end;
end;
finally
DestroyMenu(hmnu);
end;
finally
FreeLibrary(hUser32);
end;
end;
end.
|
unit PlayerSubtitleExtractors;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Process, PlayerThreads, PlayerSessionStorage;
type
{ TPlayerExtractorService }
TPlayerExtractorService = class
private
FProcess: TProcess;
public
procedure StopProcess;
property Process: TProcess read FProcess;
end;
{ TPlayerSubtitleExtractor }
TPlayerSubtitleExtractor = class(TPlayerExtractorService) // mp4 -> raw subtitle file
private
FFileName, FTempFileName: String;
public
constructor Create(const AFileName, ATempFileName: String); virtual;
procedure Extract; virtual; abstract;
property FileName: String read FFileName;
end;
{ TPlayerSubtitleFfmpegExtractor }
TPlayerSubtitleFfmpegExtractor = class(TPlayerSubtitleExtractor)
public
procedure Extract; override;
end;
{ TPlayerTrackParser }
TPlayerTrackParser = class;
TPlayerTrackParserSaveEvent = procedure (Sender: TPlayerTrackParser;
Points: TPlayerPointArray) of object;
TPlayerTrackParser = class(TPlayerExtractorService) // raw subtitle -> nmea -> track
private
FFileName: String;
FOnSave: TPlayerTrackParserSaveEvent;
FThread: TPlayerThread;
FSaveTrackLimit: Integer;
protected
procedure DoSave(Points: TPlayerPointArray); virtual;
public
constructor Create(const AFileName:
String; AThread: TPlayerThread); virtual;
procedure Parse; virtual; abstract;
property FileName: String read FFileName;
property SaveTrackLimit: Integer read FSaveTrackLimit write FSaveTrackLimit;
property OnSave: TPlayerTrackParserSaveEvent read FOnSave write FOnSave;
end;
{ TPlayerNmeaTrackParser }
TPlayerNmeaTrackParser = class(TPlayerTrackParser)
private
FTempFileName: String;
procedure LoadNmea;
public
procedure Parse; override;
end;
implementation
uses
dateutils, Math;
{ TPlayerExtractorService }
procedure TPlayerExtractorService.StopProcess;
begin
if (FProcess <> nil) and FProcess.Running then
FProcess.Terminate(0);
end;
{ TPlayerNmeaTrackParser }
procedure TPlayerNmeaTrackParser.LoadNmea;
var
CSV: TextFile;
Line: String;
Values: TStringArray;
PrevPoint, Point: TPlayerPoint;
deg, min: String;
Points: TPlayerPointArray;
Counter, Rn: Integer;
begin
AssignFile(CSV, FTempFileName);
Reset(CSV);
try
SetLength(Points, 0);
Counter:=0;
Rn:=0;
while not Eof(CSV) and not FThread.Terminated do
begin
ReadLn(CSV, Line);
Values:=Line.Split(',');
if Length(Values) <> 13 then
raise Exception.CreateFmt('incorrent nmea line %s', [Line]);
Point.time:=ScanDateTime('DDMMYY HHMMSS', Values[9] + ' ' + Values[1]);
Point.ptype:=Values[2];
if Point.ptype = 'A' then
begin
Point.speed:=RoundTo(Values[7].ToDouble * 1.852, -2);
Point.course:=Values[8].ToDouble;
deg:=Copy(Values[3], 1, 2);
min:=Copy(Values[3], 3, Length(Values[3]));
Point.lat:=RoundTo(deg.ToDouble + (min.ToDouble / 60), -6);
if Values[4] = 'S' then Point.lat:=-Point.lat;
deg:=Copy(Values[5], 1, 3);
min:=Copy(Values[5], 4, Length(Values[5]));
Point.lon:=RoundTo(deg.ToDouble + (min.ToDouble / 60), -6);
if Values[6] = 'S' then Point.lon:=-Point.lon;
end else
begin
Point.speed:=0;
Point.course:=0;
Point.lat:=0;
Point.lon:=0;
end;
if Point <> PrevPoint then
begin
Inc(Rn);
Point.rn:=Rn;
Inc(Counter);
SetLength(Points, Counter);
Points[High(Points)]:=Point;
if Counter = SaveTrackLimit then
begin
DoSave(Points);
Counter:=0;
SetLength(Points, 0);
end;
end;
PrevPoint:=Point;
end;
DoSave(Points);
finally
CloseFile(CSV);
end;
end;
procedure TPlayerNmeaTrackParser.Parse;
const
BUF_SIZE = 16384;
var
OutputStream: TFileStream;
Buffer: array[0..BUF_SIZE - 1] of Byte;
BytesRead: LongInt;
begin
FTempFileName:=FFileName + '.nmea';
FProcess:=TProcess.Create(nil);
try
with Process do
begin
// grep -aoE $'\$G[A-Z]+RMC[A-Z\.,*0-9]+\n' samples/trendvision.data
Executable:='/bin/grep';
Parameters.Add('-aoE');
Parameters.Add('\$G[A-Z]+RMC[A-Z\.,*0-9]+');
Parameters.Add(FileName);
Options:=[poUsePipes];
end;
Process.Execute;
OutputStream:=TFileStream.Create(FTempFileName, fmCreate);
try
repeat
Buffer[0]:=0;
BytesRead:=Process.Output.Read(Buffer, BUF_SIZE);
OutputStream.Write(Buffer, BytesRead);
until BytesRead = 0;
finally
OutputStream.Free;
end;
LoadNmea;
if Process.Running then
Process.Terminate(0);
finally
Process.Free;
FProcess:=nil;
end;
end;
{ TPlayerTrackParser }
procedure TPlayerTrackParser.DoSave(Points: TPlayerPointArray);
begin
if @FOnSave <> nil then
FOnSave(Self, Points);
end;
constructor TPlayerTrackParser.Create(const AFileName: String;
AThread: TPlayerThread);
begin
FThread:=AThread;
inherited Create;
FFileName:=AFileName;
FSaveTrackLimit:=100;
end;
{ TPlayerSubtitleFfmpegExtractor }
procedure TPlayerSubtitleFfmpegExtractor.Extract;
begin
FProcess:=TProcess.Create(nil);
try
with Process do
begin
// ffmpeg -f concat -i mylist.txt -map 0:s:0 -c copy -f data out.data
Executable:='/usr/bin/ffmpeg';
Parameters.Add('-i');
Parameters.Add(FileName);
Parameters.Add('-map');
Parameters.Add('0:s:0');
Parameters.Add('-c');
Parameters.Add('copy');
Parameters.Add('-f');
Parameters.Add('data');
Parameters.Add('-v');
Parameters.Add('quiet');
Parameters.Add(FTempFileName);
Options:=[poWaitOnExit, poUsePipes];
end;
Process.Execute;
finally
Process.Free;
FProcess:=nil;
end;
end;
{ TPlayerSubtitleExtractor }
constructor TPlayerSubtitleExtractor.Create(const AFileName,
ATempFileName: String);
begin
inherited Create;
FFileName:=AFileName;
FTempFileName:=ATempFileName;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.WebNode;
interface
uses
System.Classes, Soap.IntfInfo, Soap.SOAPAttachIntf;
type
WebNodeOption = (wnoSOAP12);
WebNodeOptions = set of WebNodeOption;
{ IWebNode defines the basic interface to be implemented by any
SOAP Transport. IOW, if you want to implement SOAP on SMTP,
plain Socket, etc - you'll have to create a RIO that implements
IWebNode.
See THTTPRIO and TLinkedRIO for examples }
IWebNode = interface
['{77DB2644-0C12-4C0A-920E-89579DB9CC16}']
{ Obsolete - use version that takes a Stream as first parameter }
procedure Execute(const DataMsg: String; Response: TStream); overload; deprecated;
procedure BeforeExecute(const IntfMD: TIntfMetaData;
const MethMD: TIntfMethEntry;
MethodIndex: Integer;
AttachHandler: IMimeAttachmentHandler);
procedure Execute(const Request: TStream; Response: TStream); overload;
function Execute(const Request: TStream): TStream; overload;
{ Transport Attributes exposed in a generic fashion so that Converter
can break apart a multipart/related packet }
function GetMimeBoundary: string;
procedure SetMimeBoundary(const Value: string);
function GetWebNodeOptions: WebNodeOptions;
procedure SetWebNodeOptions(Value: WebNodeOptions);
property MimeBoundary: string read GetMimeBoundary write SetMimeBoundary;
property Options: WebNodeOptions read GetWebNodeOptions write SetWebNodeOptions;
end;
implementation
end.
|
unit Phistfrm;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, Types, DB, DBTables, Grids, ComCtrls,
ExtCtrls;
type
THistorySummaryForm = class(TForm)
AssessmentNotesTable: TTable;
Panel1: TPanel;
HistoryPageControl: TPageControl;
SummaryTabSheet: TTabSheet;
HistoryStringGrid: TStringGrid;
AssessmentTabSheet: TTabSheet;
AssessmentStringGrid: TStringGrid;
Panel2: TPanel;
SchoolCodeLabel: TLabel;
ParcelCreateLabel: TLabel;
SplitMergeInfoLabel1: TLabel;
SplitMergeInfoLabel2: TLabel;
CloseButton: TBitBtn;
procedure CloseButtonClick(Sender: TObject);
procedure HistoryStringGridDrawCell(Sender: TObject; Col, Row: Longint;
Rect: TRect; State: TGridDrawState);
procedure AssessmentStringGridDrawCell(Sender: TObject; Col,
Row: Integer; Rect: TRect; State: TGridDrawState);
private
{ Private declarations }
public
ParcelTable, AssessmentTable,
ParcelExemptionTable, ExemptionCodeTable : TTable;
{ Public declarations }
Procedure InitializeForm(SwisSBLKey : String);
Procedure FillInYearInfo( SwisSBLKey : String;
ProcessingType : Integer;
TaxRollYr,
TaxRollYrToDisplay : String;
UsePriorFields : Boolean;
var SplitMergeNo,
SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String;
var RowIndex : Integer);
Procedure FillInSummaryGrid( SwisSBLKey : String;
var SplitMergeNo : String;
var SplitMergeYear : String;
var SplitMergeRelationship : String;
var SplitMergeRelatedParcelID : String);
Procedure FillInSplitMergeInformation(SplitMergeNo : String;
SplitMergeYear : String;
SplitMergeRelationship : String;
SplitMergeRelatedParcelID : String);
Procedure FillInAssessmentInformationForOneYear(SwisSBLKey : String;
AssessmentYear : String;
ProcessingType : Integer;
CurrentRow : Integer);
Procedure FillInAssessmentGrid(SwisSBLKey : String);
end;
var
HistorySummaryForm: THistorySummaryForm;
implementation
{$R *.DFM}
uses GlblVars, PASTypes, WinUtils, PASUTILS, UTILEXSD, Utilitys,
DataModule, Math,
GlblCnst;
const
smYearColumn = 0;
smOwnerColumn = 1;
smHomesteadColumn = 2;
smAVColumn = 3;
smTAVColumn = 4;
smRSColumn = 5;
smPropertyClassColumn = 6;
smBasicSTARColumn = 7;
smEnhancedSTARColumn = 8;
smSeniorColumn = 9;
smAlternateVetColumn = 10;
smOtherExemptionColumn = 11;
avYearColumn = 0;
avLandAssessmentColumn = 1;
avTotalAssessmentColumn = 2;
avUniformPercentOrRARColumn = 3;
avFullMarketColumn = 4;
avDifferenceColumn = 5;
avAssessmentNotesColumn = 6;
avPhysicalIncreaseColumn = 6;
avEqualizationIncreaseColumn = 7;
avPhysicalDecreaseColumn = 8;
avEqualizationDecreaseColumn = 9;
{=================================================================}
Procedure THistorySummaryForm.FillInYearInfo( SwisSBLKey : String;
ProcessingType : Integer;
TaxRollYr,
TaxRollYrToDisplay : String;
UsePriorFields : Boolean;
var SplitMergeNo,
SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String;
var RowIndex : Integer);
var
BasicSTARAmount, EnhancedSTARAmount,
AssessedVal, TaxableVal,
SeniorAmount, AlternateVetAmount, OtherExemptionAmount : Comp;
ExemptionTotaled, ParcelFound : Boolean;
ExemptArray : ExemptionTotalsArrayType;
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts : TStringList;
PropertyClass : String;
BankCode : String;
_Name : String;
OwnershipCode, RollSection, HomesteadCode : String;
SchoolCode : String;
AssessedValStr, TaxableValStr : String;
SBLRec : SBLRecord;
I : Integer;
begin
{CHG11231999-1: Add columns for senior, alt vet, other ex.}
PropertyClass := '';
BankCode := '';
_Name := '';
OwnershipCode := '';
RollSection := '';
HomesteadCode := '';
SchoolCode := '';
AssessedValStr := '';
TaxableValStr := '';
BasicSTARAmount := 0;
EnhancedSTARAmount := 0;
SeniorAmount := 0;
AlternateVetAmount := 0;
OtherExemptionAmount := 0;
ExemptionCodes := TStringList.Create;
ExemptionHomesteadCodes := TStringList.Create;
ResidentialTypes := TStringList.Create;
CountyExemptionAmounts := TStringList.Create;
TownExemptionAmounts := TStringList.Create;
SchoolExemptionAmounts := TStringList.Create;
VillageExemptionAmounts := TStringList.Create;
ParcelTable := FindTableInDataModuleForProcessingType(DataModuleParcelTableName,
ProcessingType);
AssessmentTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentTableName,
ProcessingType);
ParcelExemptionTable := FindTableInDataModuleForProcessingType(DataModuleExemptionTableName,
ProcessingType);
ExemptionCodeTable := FindTableInDataModuleForProcessingType(DataModuleExemptionCodeTableName,
ProcessingType);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
ParcelFound := FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot',
'Suffix'],
[TaxRollYr, SwisCode, Section, Subsection,
Block, Lot, Sublot, Suffix]);
FindKeyOld(AssessmentTable, ['TaxRollYr', 'SwisSBLKey'],
[TaxRollYr, SwisSBLKey]);
with HistoryStringGrid do
begin
ColWidths[smYearColumn] := 20;
ColWidths[smOwnerColumn] := 78;
ColWidths[smAVColumn] := 70;
ColWidths[smHomesteadColumn] := 20;
ColWidths[smTAVColumn] := 70;
ColWidths[smRSColumn] := 20;
ColWidths[smPropertyClassColumn] := 33;
ColWidths[smBasicSTARColumn] := 60;
ColWidths[smEnhancedSTARColumn] := 60;
ColWidths[smSeniorColumn] := 48;
ColWidths[smAlternateVetColumn] := 48;
ColWidths[smOtherExemptionColumn] := 64;
end; {with HistoryStringGrid do}
with ParcelTable do
If ParcelFound
then
If UsePriorFields
then
begin
AssessedVal := AssessmentTable.FieldByName('PriorTotalValue').AsFloat;
AssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, AssessedVal);
TaxableValStr := 'Not on file';
PropertyClass := FieldByName('PriorPropertyClass').Text;
OwnershipCode := FieldByName('PriorOwnershipCode').Text;
SchoolCode := FieldByName('PriorSchoolDistrict').Text;
_Name := 'Not on file';
RollSection := FieldByName('PriorRollSection').Text;
HomesteadCode := FieldByName('PriorHomesteadCode').Text;
end
else
begin
AssessedVal := AssessmentTable.FieldByName('TotalAssessedVal').AsFloat;
ExemptArray := TotalExemptionsForParcel(TaxRollYr, SwisSBLKey,
ParcelExemptionTable,
ExemptionCodeTable,
ParcelTable.FieldByName('HomesteadCode').Text,
'A',
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts,
BasicSTARAmount,
EnhancedSTARAmount);
For I := 0 to (ExemptionCodes.Count - 1) do
begin
ExemptionTotaled := False;
If ((Take(4, ExemptionCodes[I]) = '4112') or
(Take(4, ExemptionCodes[I]) = '4113') or
(Take(4, ExemptionCodes[I]) = '4114'))
then
begin
AlternateVetAmount := AlternateVetAmount + StrToFloat(TownExemptionAmounts[I]);
ExemptionTotaled := True;
end;
If (Take(4, ExemptionCodes[I]) = '4180')
then
begin
SeniorAmount := SeniorAmount + StrToFloat(TownExemptionAmounts[I]);
ExemptionTotaled := True;
end;
If not ExemptionTotaled
then OtherExemptionAmount := OtherExemptionAmount + StrToFloat(TownExemptionAmounts[I]);
end; {For I := 0 to (ExemptionCodes.Count - 1) do}
TaxableVal := Max((AssessedVal - ExemptArray[EXTown]), 0);
AssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, AssessedVal);
TaxableValStr := FormatFloat(CurrencyDisplayNoDollarSign, TaxableVal);
PropertyClass := FieldByName('PropertyClassCode').Text;
OwnershipCode := FieldByName('OwnershipCode').Text;
SchoolCode := FieldByName('SchoolCode').Text;
_Name := FieldByName('Name1').Text;
RollSection := FieldByName('RollSection').Text;
HomesteadCode := FieldByName('HomesteadCode').Text;
end; {else of If UsePriorFields}
If ParcelFound
then
begin
with HistoryStringGrid do
begin
Cells[smYearColumn, RowIndex] := Copy(TaxRollYrToDisplay, 3, 2);
Cells[smOwnerColumn, RowIndex] := Take(11, _Name);
Cells[smAVColumn, RowIndex] := AssessedValStr;
Cells[smHomesteadColumn, RowIndex] := HomesteadCode;
{FXX05012000-8: If the parcel is inactive, then say so.}
If ParcelIsActive(ParcelTable)
then
begin
Cells[smTAVColumn, RowIndex] := TaxableValStr;
Cells[smRSColumn, RowIndex] := RollSection;
Cells[smPropertyClassColumn, RowIndex] := PropertyClass + OwnershipCode;
Cells[smBasicSTARColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, BasicSTARAmount);
Cells[smEnhancedSTARColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, EnhancedSTARAmount);
Cells[smSeniorColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, SeniorAmount);
Cells[smAlternateVetColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, AlternateVetAmount);
Cells[smOtherExemptionColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, OtherExemptionAmount);
end
else Cells[smTAVColumn, RowIndex] := InactiveLabelText;
RowIndex := RowIndex + 1;
end; {with HistoryStringGrid do}
ParcelCreateLabel.Caption := 'Parcel Created: ' +
ParcelTable.FieldByName('ParcelCreatedDate').Text;
SchoolCodeLabel.Caption := 'School Code: ' +
ParcelTable.FieldByName('SchoolCode').Text;
{CHG03302000-3: Show split\merge information - display most recent.}
{If there is split merge info, fill it in. Note that we do not
fill it in if there is already info - we want to show the most
recent and we are working backwards through the years.}
If ((Deblank(SplitMergeNo) = '') and
(Deblank(ParcelTable.FieldByName('SplitMergeNo').Text) <> ''))
then
begin
SplitMergeNo := ParcelTable.FieldByName('SplitMergeNo').Text;
SplitMergeYear := TaxRollYr;
SplitMergeRelatedParcelID := ParcelTable.FieldByName('RelatedSBL').Text;
If (Deblank(SplitMergeRelatedParcelID) = '')
then
begin
SplitMergeRelatedParcelID := 'unknown';
SplitMergeRelationship := 'unknown';
end
else
begin
SplitMergeRelationship := ParcelTable.FieldByName('SBLRelationship').Text;
SplitMergeRelationship := Take(1, SplitMergeRelationship);
case SplitMergeRelationship[1] of
'C' : SplitMergeRelationship := 'Parent';
'P' : SplitMergeRelationship := 'Child';
end;
end; {else of If (Deblank(SplitMergeRelatedParcelID) = '')}
end; {If ((Deblank(SplitMergeNo) = '') and ...}
end; {If ParcelFound}
ExemptionCodes.Free;
ExemptionHomesteadCodes.Free;
ResidentialTypes.Free;
CountyExemptionAmounts.Free;
TownExemptionAmounts.Free;
SchoolExemptionAmounts.Free;
VillageExemptionAmounts.Free;
end; {FillInYearInfo}
{=================================================================}
Procedure THistorySummaryForm.FillInSummaryGrid( SwisSBLKey : String;
var SplitMergeNo : String;
var SplitMergeYear : String;
var SplitMergeRelationship : String;
var SplitMergeRelatedParcelID : String);
var
Index, TempTaxYear : Integer;
TaxRollYear, PriorTaxYear : String;
TaxYearFound : Boolean;
TempStr : String;
begin
Index := 1;
If ((not GlblUserIsSearcher) or
SearcherCanSeeNYValues)
then FillInYearInfo(SwisSBLKey, NextYear, GlblNextYear, GlblNextYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
FillInYearInfo(SwisSBLKey, ThisYear, GlblThisYear, GlblThisYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
TempTaxYear := StrToInt(GlblThisYear);
PriorTaxYear := IntToStr(TempTaxYear - 1);
ParcelTable := FindTableInDataModuleForProcessingType(DataModuleParcelTableName,
History);
If HistoryExists
then
begin
repeat
FillInYearInfo(SwisSBLKey, History, PriorTaxYear, PriorTaxYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
{Now try back one more year.}
TempTaxYear := StrToInt(PriorTaxYear);
PriorTaxYear := IntToStr(TempTaxYear - 1);
FindNearestOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot',
'Suffix'],
[PriorTaxYear, ' ', ' ', ' ', ' ',
' ', ' ', ' ']);
TaxYearFound := (ParcelTable.FieldByName('TaxRollYr').Text = PriorTaxYear);
TempStr := ParcelTable.FieldByName('TaxRollYr').Text;
{Now do the prior in history.}
If not TaxYearFound
then
begin
TaxRollYear := IntToStr(TempTaxYear);
FillInYearInfo(SwisSBLKey, History, TaxRollYear,
PriorTaxYear, True,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
end; {If not TaxYearFound}
until (not TaxYearFound);
end
else FillInYearInfo(SwisSBLKey, ThisYear, GlblThisYear, PriorTaxYear, True,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
with HistoryStringGrid do
begin
Cells[smYearColumn, 0] := 'Yr';
Cells[smOwnerColumn, 0] := 'Owner';
Cells[smAVColumn, 0] := 'Assessed';
Cells[smHomesteadColumn, 0] := 'HC';
Cells[smTAVColumn, 0] := 'Taxable';
Cells[smRSColumn, 0] := 'RS';
Cells[smPropertyClassColumn, 0] := 'Class';
Cells[smBasicSTARColumn, 0] := 'Res STAR';
Cells[smEnhancedSTARColumn, 0] := 'Enh STAR';
Cells[smSeniorColumn, 0] := 'Senior';
Cells[smAlternateVetColumn, 0] := 'Alt Vet';
Cells[smOtherExemptionColumn, 0] := 'Other EX';
end; {with HistoryStringGrid do}
end; {FillInSummaryGrid}
{=================================================================}
Procedure THistorySummaryForm.FillInSplitMergeInformation(SplitMergeNo : String;
SplitMergeYear : String;
SplitMergeRelationship : String;
SplitMergeRelatedParcelID : String);
begin
SplitMergeInfoLabel1.Visible := True;
SplitMergeInfoLabel2.Visible := True;
SplitMergeInfoLabel1.Caption := 'S\M #: ' + SplitMergeNo + ' (' +
SplitMergeYear + ')';
SplitMergeInfoLabel2.Caption := 'Related Parcel: ' + SplitMergeRelatedParcelID +
' (' + SplitMergeRelationship + ')';
end; {FillInSplitMergeInformation}
{=================================================================}
Procedure THistorySummaryForm.FillInAssessmentInformationForOneYear(SwisSBLKey : String;
AssessmentYear : String;
ProcessingType : Integer;
CurrentRow : Integer);
var
ParcelTable, AssessmentTable, SwisCodeTable : TTable;
FoundAssessment, IsUniformPercent, Quit : Boolean;
SBLRec : SBLRecord;
TempPercent, FullMarketValue : Double;
begin
AssessmentTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentTableName,
ProcessingType);
SwisCodeTable := FindTableInDataModuleForProcessingType(DataModuleSwisCodeTableName,
ProcessingType);
ParcelTable := FindTableInDataModuleForProcessingType(DataModuleParcelTableName,
ProcessingType);
OpenTableForProcessingType(AssessmentNotesTable, AssessmentNotesTableName,
ProcessingType, Quit);
If (ProcessingType = History)
then
begin
SwisCodeTable.Filter := 'TaxRollYr=' + AssessmentYear;
SwisCodeTable.Filtered := True;
end
else SwisCodeTable.Filtered := False;
FoundAssessment := FindKeyOld(AssessmentTable, ['TaxRollYr', 'SwisSBLKey'],
[AssessmentYear, SwisSBLKey]);
If FoundAssessment
then
begin
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'],
[AssessmentYear, SwisCode, Section, Subsection,
Block, Lot, Sublot, Suffix]);
FindKeyOld(SwisCodeTable, ['SwisCode'], [Copy(SwisSBLKey, 1, 6)]);
with AssessmentStringGrid, AssessmentTable do
begin
FullMarketValue := ComputeFullValue(FieldByName('TotalAssessedVal').AsFloat,
SwisCodeTable,
ParcelTable.FieldByName('PropertyClassCode').Text,
ParcelTable.FieldByname('OwnershipCode').Text,
False);
{CHG10162004-1(2.8.0.14): If this is a parcel that uses the RAR, show it.}
with ParcelTable do
TempPercent := GetUniformPercentOrRAR(SwisCodeTable,
FieldByName('PropertyClassCode').Text,
FieldByName('OwnershipCode').Text,
False, IsUniformPercent);
Cells[avYearColumn, CurrentRow] := Copy(AssessmentYear, 3, 2);
Cells[avLandAssessmentColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('LandAssessedVal').AsFloat);
Cells[avTotalAssessmentColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('TotalAssessedVal').AsInteger);
{CHG10162004-1(2.8.0.14): If this is a parcel that uses the RAR, show it.}
Cells[avUniformPercentOrRARColumn, CurrentRow] := FormatFloat(DecimalEditDisplay, TempPercent);
Cells[avFullMarketColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FullMarketValue);
{CHG10162004-3(2.8.0.14): Option to show the AV notes on the history screen.}
If GlblShowAssessmentNotesOnAVHistoryScreen
then
begin
If FindKeyOld(AssessmentNotesTable, ['TaxRollYr', 'SwisSBLKey'],
[AssessmentYear, SwisSBLKey])
then Cells[avAssessmentNotesColumn, CurrentRow] := AssessmentNotesTable.FieldByName('Note').AsString
else Cells[avAssessmentNotesColumn, CurrentRow] := '';
end
else
begin
Cells[avPhysicalIncreaseColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('PhysicalQtyIncrease').AsFloat);
Cells[avEqualizationIncreaseColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('IncreaseForEqual').AsFloat);
Cells[avPhysicalDecreaseColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('PhysicalQtyDecrease').AsFloat);
Cells[avEqualizationDecreaseColumn, CurrentRow] := FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('DecreaseForEqual').AsFloat);
end; {else of If GlblShowAssessmentNotesOnAVHistoryScreen}
end; {with AssessmentStringGrid do}
end; {If FoundAssessment}
SwisCodeTable.Filtered := False;
end; {FillInAssessmentInformationForOneYear}
{=================================================================}
Procedure THistorySummaryForm.FillInAssessmentGrid(SwisSBLKey : String);
var
Done, FirstTimeThrough, FirstYearFound : Boolean;
AssessmentYearControlTable : TTable;
I, CurrentRow : Integer;
PriorAssessedValue, CurrentAssessedValue : LongInt;
begin
{First fill in the column headers.}
with AssessmentStringGrid do
begin
Cells[avYearColumn, 0] := 'Yr';
Cells[avLandAssessmentColumn, 0] := 'Land AV';
Cells[avTotalAssessmentColumn, 0] := 'Total AV';
{CHG10162004-1(2.8.0.14): If this is a parcel that uses the RAR, show it.}
If GlblUseRAR
then Cells[avUniformPercentOrRARColumn, 0] := 'Unf%\RAR'
else Cells[avUniformPercentOrRARColumn, 0] := 'Unif %';
Cells[avFullMarketColumn, 0] := 'Full Mkt Val';
Cells[avDifferenceColumn, 0] := 'AV Diff';
{CHG10162004-3(2.8.0.14): Option to show the AV notes on the history screen.}
If GlblShowAssessmentNotesOnAVHistoryScreen
then
begin
ColWidths[6] := ColWidths[avPhysicalIncreaseColumn] +
ColWidths[avEqualizationIncreaseColumn] +
ColWidths[avPhysicalDecreaseColumn] +
ColWidths[avEqualizationDecreaseColumn] + 3;
ColCount := 7;
Cells[avAssessmentNotesColumn, 0] := 'Assessment Notes';
end
else
begin
Cells[avPhysicalIncreaseColumn, 0] := 'Phys Inc';
Cells[avEqualizationIncreaseColumn, 0] := 'Eq Inc';
Cells[avPhysicalDecreaseColumn, 0] := 'Phys Dec';
Cells[avEqualizationDecreaseColumn, 0] := 'Eq Dec';
end; {If GlblShowAssessmentNotesOnAVHistoryScreen}
end; {with AssessmentStringGrid do}
FillInAssessmentInformationForOneYear(SwisSBLKey, GlblNextYear, NextYear, 1);
FillInAssessmentInformationForOneYear(SwisSBLKey, GlblThisYear, ThisYear, 2);
AssessmentYearControlTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentYearControlTableName,
History);
AssessmentYearControlTable.IndexName := 'BYTAXROLLYR';
AssessmentYearControlTable.Last;
Done := False;
FirstTimeThrough := True;
CurrentRow := 3;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else AssessmentYearControlTable.Prior;
If AssessmentYearControlTable.BOF
then Done := True;
If not Done
then
begin
FillInAssessmentInformationForOneYear(SwisSBLKey,
AssessmentYearControlTable.FieldByName('TaxRollYr').Text,
History, CurrentRow);
CurrentRow := CurrentRow + 1;
end; {If not Done}
until Done;
{CHG10162004-2(2.8.0.14): Instead of equalization rate, show the difference in AV between years.}
PriorAssessedValue := 0;
CurrentAssessedValue := 0;
FirstYearFound := True;
with AssessmentStringGrid do
For I := (RowCount - 1) downto 1 do
If (Trim(Cells[avYearColumn, I]) <> '')
then
begin
If FirstYearFound
then
begin
Cells[avDifferenceColumn, I] := 'Unknown';
FirstYearFound := False;
end
else
begin
try
CurrentAssessedValue := StrToInt(StringReplace(Cells[avTotalAssessmentColumn, I], ',', '', [rfReplaceAll]))
except
end;
Cells[avDifferenceColumn, I] := FormatFloat(CurrencyDisplayNoDollarSign,
(CurrentAssessedValue - PriorAssessedValue));
end; {else of If (I = 0)}
try
PriorAssessedValue := StrToInt(StringReplace(Cells[avTotalAssessmentColumn, I], ',', '', [rfReplaceAll]));
except
end;
end; {I (Trim(Cells[avYearColumn]) <> '')}
end; {FillInAssessmentGrid}
{=================================================================}
Procedure THistorySummaryForm.InitializeForm(SwisSBLKey : String);
var
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String;
begin
{CHG09142004-1(2.8.0.11): Include the parcel ID in the caption.}
Caption := 'Parcel History for ' + ConvertSBLOnlyToDashDot(Copy(SwisSBLKey, 7, 20));
GlblDialogBoxShowing := True;
HistoryPageControl.ActivePage := SummaryTabSheet;
SplitMergeNo := '';
SplitMergeYear := '';
SplitMergeRelationship := '';
SplitMergeRelatedParcelID := '';
SplitMergeInfoLabel1.Caption := '';
SplitMergeInfoLabel2.Caption := '';
{FXX03302000-4: Clear the string grid 1st.}
ClearStringGrid(HistoryStringGrid);
ClearStringGrid(AssessmentStringGrid);
FillInSummaryGrid(SwisSBLKey, SplitMergeNo, SplitMergeYear,
SplitMergeRelationship, SplitMergeRelatedParcelID);
{CHG03212004-2(2.08): Add assessment page with full market value and assessment history.}
{CHG11012004-2(2.8.0.16)[1963]: Make the assessment tab visible to the searcher if they
show assessment notes on the AV history screen.}
If (GlblUserIsSearcher and
(not GlblShowAssessmentNotesOnAVHistoryScreen))
then AssessmentTabSheet.TabVisible := False
else FillInAssessmentGrid(SwisSBLKey);
{CHG03302000-3: Show split\merge information - display most recent.}
If (Deblank(SplitMergeNo) <> '')
then FillInSplitMergeInformation(SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID);
end; {InitializeForm}
{===============================================================}
Procedure THistorySummaryForm.HistoryStringGridDrawCell(Sender: TObject;
Col, Row: Longint;
Rect: TRect;
State: TGridDrawState);
var
ACol, ARow : LongInt;
TempColor : TColor;
begin
ACol := Col;
ARow := Row;
TempColor := clBlue;
with HistoryStringGrid do
begin
Canvas.Font.Size := 9;
Canvas.Font.Name := 'Arial';
Canvas.Font.Style := [fsBold];
end;
with HistoryStringGrid do
If (ARow > 0)
then
begin
case ACol of
smYearColumn : TempColor := clBlack;
smRSColumn,
smHomesteadColumn,
smPropertyClassColumn : TempColor := clNavy;
smOwnerColumn : TempColor := clGreen;
smAVColumn,
smTAVColumn,
smBasicSTARColumn,
smEnhancedSTARColumn,
smSeniorColumn,
smAlternateVetColumn,
smOtherExemptionColumn : TempColor := clPurple;
end; {case ARow of}
HistoryStringGrid.Canvas.Font.Color := TempColor;
end; {If (ARow > 0)}
{Header row.}
If (ARow = 0)
then HistoryStringGrid.Canvas.Font.Color := clBlue;
with HistoryStringGrid do
If (ARow = 0)
then CenterText(CellRect(ACol, ARow), Canvas, Cells[ACol, ARow], True,
True, clBtnFace)
else
case ACol of
smYearColumn,
smRSColumn,
smHomesteadColumn,
smPropertyClassColumn,
smOwnerColumn : LeftJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True,
False, clWhite, 2);
smAVColumn,
smTAVColumn,
smBasicSTARColumn,
smEnhancedSTARColumn,
smSeniorColumn,
smAlternateVetColumn,
smOtherExemptionColumn : RightJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True,
False, clWhite, 2);
end; {case ACol of}
end; {HistoryStringGridDrawCell}
{===============================================================}
Procedure THistorySummaryForm.AssessmentStringGridDrawCell(Sender: TObject;
Col, Row: Integer;
Rect: TRect;
State: TGridDrawState);
var
ACol, ARow : LongInt;
TempColor : TColor;
begin
ACol := Col;
ARow := Row;
TempColor := clBlue;
with AssessmentStringGrid do
begin
Canvas.Font.Size := 9;
Canvas.Font.Name := 'Arial';
Canvas.Font.Style := [fsBold];
end;
with AssessmentStringGrid do
If (ARow > 0)
then
begin
case ACol of
avYearColumn : TempColor := clBlack;
avUniformPercentOrRARColumn : TempColor := clNavy;
avDifferenceColumn,
avLandAssessmentColumn,
avTotalAssessmentColumn : TempColor := clGreen;
avPhysicalIncreaseColumn,
avEqualizationIncreaseColumn,
avPhysicalDecreaseColumn,
avEqualizationDecreaseColumn : TempColor := clPurple;
avFullMarketColumn : TempColor := clRed;
end; {case ARow of}
AssessmentStringGrid.Canvas.Font.Color := TempColor;
end; {If (ARow > 0)}
{Header row.}
If (ARow = 0)
then AssessmentStringGrid.Canvas.Font.Color := clBlue;
with AssessmentStringGrid do
If (ARow = 0)
then
begin
If ((ACol = avUniformPercentOrRARColumn) and
GlblUseRAR)
then TwoLineText(CellRect(ACol, ARow), Canvas, 'Unif %', 'or RAR', True,
True, clBtnFace)
else CenterText(CellRect(ACol, ARow), Canvas, Cells[ACol, ARow], True,
True, clBtnFace);
end
else
case ACol of
avYearColumn : LeftJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True,
False, clWhite, 2);
avAssessmentNotesColumn :
If GlblShowAssessmentNotesOnAVHistoryScreen
then LeftJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True, False, clWhite, 2)
else RightJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True, False, clWhite, 2);
avUniformPercentOrRARColumn,
avDifferenceColumn,
avLandAssessmentColumn,
avTotalAssessmentColumn,
avFullMarketColumn,
avEqualizationIncreaseColumn,
avPhysicalDecreaseColumn,
avEqualizationDecreaseColumn : RightJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True,
False, clWhite, 2);
end; {case ACol of}
end; {AssessmentStringGridDrawCell}
{===============================================================}
Procedure THistorySummaryForm.CloseButtonClick(Sender: TObject);
begin
Close;
GlblDialogBoxShowing := False;
end;
end. |
unit Thread.Trim;
interface
uses
Classes, SysUtils,
TrimList, Thread.Trim.Helper.List;
type
TTrimStage = (Initial, InProgress, Finished, Error);
TTrimThread = class(TThread)
private
class var InnerTrimStage: TTrimStage;
ListTrimmer: TListTrimmer;
public
class property TrimStage: TTrimStage read InnerTrimStage;
constructor Create
(CreateSuspended: Boolean; IsUIInteractionNeeded: Boolean);
destructor Destroy; override;
function SetPartitionList(PartitionsToTrim: TTrimList): Boolean;
protected
procedure Execute; override;
end;
implementation
constructor TTrimThread.Create(CreateSuspended, IsUIInteractionNeeded: Boolean);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := true;
ListTrimmer := TListTrimmer.Create(IsUIInteractionNeeded);
InnerTrimStage := TTrimStage.Initial;
end;
destructor TTrimThread.Destroy;
begin
FreeAndNil(ListTrimmer);
inherited Destroy;
end;
function TTrimThread.SetPartitionList(PartitionsToTrim: TTrimList): Boolean;
begin
result := ListTrimmer.SetPartitionList(PartitionsToTrim);
end;
procedure TTrimThread.Execute;
begin
InnerTrimStage := TTrimStage.InProgress;
if ListTrimmer.IsUIInteractionNeeded then
ListTrimmer.TrimAppliedPartitionsWithUI(Self)
else
ListTrimmer.TrimAppliedPartitionsWithoutUI;
InnerTrimStage := TTrimStage.Finished;
end;
end.
|
unit adot.VCL.MVC;
interface
uses
Vcl.Forms,
System.Classes;
type
{
Example:
*******************************************************************************
Sets.Model.pas / Sets.Model.dfm
TSetsDM = class(TDataModule, IModel)
...
end;
var
SetsDM: TSetsDM;
*******************************************************************************
Sets.View.pas / Sets.View.dfm
TFormSets = class(TForm, IView)
...
end;
*******************************************************************************
Sets.Controller.Pas
TController = class(TCustomController)
private
FModelObj: TSetsDM;
FViewObj: TFormSets;
FModel: IModel;
FView: IView;
end;
constructor TController.Create;
begin
MVC.CreateModelAndView<TSetsDM, TFormSets>(
SetsDM, // automatic global var in data module
FModelObj, // field of type TSetsDM
FViewObj // field of type TFormSets
);
FModel := FModelObj; // field of type IModel
FView := FViewObj; // field of type IView
FModel.SetController(Self);
FView.SetController(Self);
end;
destructor TController.Destroy;
begin
FView := nil; // release interface first
FModel := nil; // release interface first
Sys.FreeAndNil(FViewObj); // then we can release view (in Delphi a form is using data module)
Sys.FreeAndNil(FModelObj); // then we can release model (it is not in use anymore)
inherited;
end;
*******************************************************************************
}
MVC = class
public
{
Creates form & private instance of data module. Usefull for MVC pattern.
Delphi by default creates one shared global instance of data unit when app is initializing.
}
class procedure CreateModelAndView<TModel: TDataModule; TView: TForm>(
var ADMGlobalVar : TModel; { when form is creating, it is important to assign correct instance of DM to global var }
out ADataModule : TModel; { new instance of a data module }
out AForm : TView; { new instance of a form }
ADMOwner : TComponent;
AFormOwner : TComponent
); overload; static;
{
Same, but with no owner.
}
class procedure CreateModelAndView<TModel: TDataModule; TView: TForm>(
var ADMGlobalVar : TModel; { when form is creating, it is important to assign correct instance of DM to global var }
out ADataModule : TModel; { new instance of a data module }
out AForm : TView { new instance of a form }
); overload; static;
end;
implementation
class procedure MVC.CreateModelAndView<TModel, TView>(
var ADMGlobalVar : TModel;
out ADataModule : TModel;
out AForm : TView;
ADMOwner : TComponent;
AFormOwner : TComponent);
var
PrevDMInst: TModel;
begin
PrevDMInst := ADMGlobalVar;
try
ADataModule := TModel.Create(ADMOwner);
ADMGlobalVar := ADataModule; { should be assigned when form is creating }
AForm := TView.Create(AFormOwner);
finally
ADMGlobalVar := PrevDMInst;
end;
end;
class procedure MVC.CreateModelAndView<TModel, TView>(var ADMGlobalVar: TModel; out ADataModule: TModel; out AForm: TView);
begin
CreateModelAndView<TModel, TView>(ADMGlobalVar, ADataModule, AForm, nil, nil);
end;
end.
|
unit SHA512;
{512 bit Secure Hash Function}
interface
(*************************************************************************
DESCRIPTION : SHA512 - 512 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
* http://disastry.dhs.org/pgp/pgp263iamulti06.zip
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 19.11.02 W.Ehrhardt Reference implementation (TP7, D1-D6, FPC, VP)
0.11 19.11.02 we TP5/5.5/6
0.12 19.11.02 we BASM: Add64
0.13 19.11.02 we S[x] := S[x-1] with .L and .H
0.14 19.11.02 we Maj/Ch inline
0.15 19.11.02 we BASM: RR2
0.16 20.11.02 we BIT32: RR2 inline
0.17 20.11.02 we BASM16: Sum0/1, Sig0/1
0.18 20.11.02 we BASM16: Add64 inline()
0.19 20.11.02 we BIT16: $F-
0.20 20.11.02 we 128 bit UpdateLen, K array of TW64
0.21 20.11.02 we Ref: Add64 opt, removd RR2 in Sum0/1, Sig0/1
0.22 21.11.02 we Ref: Add64/RB more opt, interface SHA512UpdateXL
0.23 24.11.02 we Opt. UpdateLen, BASM16: RA inline()
3.00 01.12.03 we Common version 3.0
3.01 22.12.03 we TP5/5.5: shl/shr inline
3.02 22.12.03 we Changed Add64 def, TP5/5.5: Add64 inline
3.03 24.12.03 we Changed Ch() and Maj()
3.04 14.01.04 we Int64 support (default for D4+)
3.05 15.01.04 we Bit32: inline Sum/Sig0/1
3.06 22.01.04 we Inc64
3.07 05.03.04 we Update fips180-2 URL, no Add64 for Int64
3.08 04.01.05 we Bugfix SHA512Final
3.09 04.01.05 we Bugfix Int64 version of SHA512Compress
3.10 26.02.05 we With {$ifdef StrictLong}
3.11 05.05.05 we $R- for StrictLong, D9: errors if $R+ even if warnings off
3.12 17.12.05 we Force $I- in SHA512File
3.13 15.01.06 we uses Hash unit and THashDesc
3.14 15.01.06 we BugFix for UseInt64
3.15 18.01.06 we Descriptor fields HAlgNum, HSig
3.16 22.01.06 we Removed HSelfTest from descriptor
3.17 11.02.06 we Descriptor as typed const
3.18 07.08.06 we $ifdef BIT32: (const fname: shortstring...)
3.19 22.02.07 we values for OID vector
3.20 30.06.07 we Use conditional define FPC_ProcVar
3.21 29.09.07 we Bugfix for message bit lengths >= 2^32
3.22 04.10.07 we FPC: {$asmmode intel}
3.23 03.05.08 we Bit-API: SHA512FinalBits/Ex
3.24 05.05.08 we THashDesc constant with HFinalBit field
3.25 12.11.08 we Uses BTypes, Ptr2Inc and/or Str255/Str127
3.26 11.03.12 we Updated references
3.27 26.12.12 we D17 and PurePascal
3.28 16.08.15 we Removed $ifdef DLL / stdcall
3.29 15.05.17 we adjust OID to new MaxOIDLen
3.30 29.11.17 we SHA512File - 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.
----------------------------------------------------------------------------*)
{ [*] Janis Jagars, known to the PGP community as "Disastry",
perished on October 31, 2002 while on vacation in Nepal. }
{ NOTE: FIPS Ch and May functions can be optimized. Wei Dai (Crypto++ V 3.1)
credits Rich Schroeppel (rcs@cs.arizona.edu), V 5.1 does not!?}
{$i STD.INC}
{$ifdef BIT64}
{$ifndef PurePascal}
{$define PurePascal}
{$endif}
{$endif}
{$ifdef PurePascal}
{$define UseInt64}
{$else}
{$ifdef D4Plus}
{$define UseInt64}
{$endif}
{$ifdef FPC}
{$define UseInt64}
{$endif}
{$endif}
uses
BTypes,Hash;
procedure SHA512Init(var Context: THashContext);
{-initialize context}
procedure SHA512Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
procedure SHA512UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
procedure SHA512Final(var Context: THashContext; var Digest: TSHA512Digest);
{-finalize SHA512 calculation, clear context}
procedure SHA512FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize SHA512 calculation, clear context}
procedure SHA512FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize SHA512 calculation with bitlen bits from BData (big-endian), clear context}
procedure SHA512FinalBits(var Context: THashContext; var Digest: TSHA512Digest; BData: byte; bitlen: integer);
{-finalize SHA512 calculation with bitlen bits from BData (big-endian), clear context}
function SHA512SelfTest: boolean;
{-self test for string from SHA512 document}
procedure SHA512Full(var Digest: TSHA512Digest; Msg: pointer; Len: word);
{-SHA512 of Msg with init/update/final}
procedure SHA512FullXL(var Digest: TSHA512Digest; Msg: pointer; Len: longint);
{-SHA512 of Msg with init/update/final}
procedure SHA512File({$ifdef CONST} const {$endif} fname: string;
var Digest: TSHA512Digest; var buf; bsize: word; var Err: word);
{-SHA512 of file, buf: buffer with at least bsize bytes}
implementation
{$ifdef BIT16}
{$F-}
{$endif}
const
SHA512_BlockLen = 128;
{Internal types for type casting}
type
TW64 = packed record
L,H: longint;
end;
{2.16.840.1.101.3.4.2.3}
{joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) hashAlgs(2) sha512(3)}
const
SHA512_OID : TOID_Vec = (2,16,840,1,101,3,4,2,3,-1,-1); {Len=9}
{$ifndef VER5X}
const
SHA512_Desc: THashDesc = (
HSig : C_HashSig;
HDSize : sizeof(THashDesc);
HDVersion : C_HashVers;
HBlockLen : SHA512_BlockLen;
HDigestlen: sizeof(TSHA512Digest);
{$ifdef FPC_ProcVar}
HInit : @SHA512Init;
HFinal : @SHA512FinalEx;
HUpdateXL : @SHA512UpdateXL;
{$else}
HInit : SHA512Init;
HFinal : SHA512FinalEx;
HUpdateXL : SHA512UpdateXL;
{$endif}
HAlgNum : longint(_SHA512);
HName : 'SHA512';
HPtrOID : @SHA512_OID;
HLenOID : 9;
HFill : 0;
{$ifdef FPC_ProcVar}
HFinalBit : @SHA512FinalBitsEx;
{$else}
HFinalBit : SHA512FinalBitsEx;
{$endif}
HReserved : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
);
{$else}
var
SHA512_Desc: THashDesc;
{$endif}
{$ifndef BIT16}
{$ifdef PurePascal}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{$else}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; assembler;
{-reverse byte order in longint}
asm
{$ifdef LoadArgs}
mov eax,[A]
{$endif}
xchg al,ah
rol eax,16
xchg al,ah
end;
{---------------------------------------------------------------------------}
procedure Inc64(var Z: TW64; const X: TW64); assembler;
{-Inc a 64 bit integer}
asm
{$ifdef LoadArgs}
mov eax,[Z]
mov edx,[X]
{$endif}
mov ecx, [edx]
add [eax], ecx
mov ecx, [edx+4]
adc [eax+4],ecx
end;
{$endif}
{$ifndef UseInt64}
{---------------------------------------------------------------------------}
procedure Add64(var Z: TW64; const X,Y: TW64);
{-Add two 64 bit integers}
begin
asm
mov ecx, [X]
mov eax, [ecx]
mov edx, [ecx+4]
mov ecx, [Y]
add eax, [ecx]
adc edx, [ecx+4]
mov ecx, [Z]
mov [ecx], eax
mov [ecx+4], edx
end;
end;
{$endif}
{$else}
{*** 16 bit ***}
(**** TP5-7/Delphi1 for 386+ *****)
{$ifndef BASM16}
(*** TP 5/5.5 ***)
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al}
$86/$E2); {xchg dl,ah}
{---------------------------------------------------------------------------}
function ISHR(x: longint; c: integer): longint;
{-Shift x right}
inline(
$59/ { pop cx }
$58/ { pop ax }
$5A/ { pop dx }
$D1/$EA/ {L:shr dx,1 }
$D1/$D8/ { rcr ax,1 }
$49/ { dec cx }
$75/$F9); { jne L }
{---------------------------------------------------------------------------}
function ISHR0(x: longint; c: integer): longint;
{-Shift x right, c+16}
inline(
$59/ { pop cx }
$58/ { pop ax }
$58/ { pop ax }
$33/$D2/ { xor dx,dx}
$D1/$EA/ {L:shr dx,1 }
$D1/$D8/ { rcr ax,1 }
$49/ { dec cx }
$75/$F9); { jne L }
{---------------------------------------------------------------------------}
function ISHL(x: longint; c: integer): longint;
{-Shift x left}
inline(
$59/ { pop cx }
$58/ { pop ax }
$5A/ { pop dx }
$D1/$E0/ {L:shl ax,1 }
$D1/$D2/ { rcl dx,1 }
$49/ { dec cx }
$75/$F9); { jne L }
{---------------------------------------------------------------------------}
function ISHL0(x: longint; c: integer): longint;
{-Shift x left, c+16}
inline(
$59/ { pop cx }
$5A/ { pop dx }
$58/ { pop ax }
$33/$C0/ { xor ax,ax}
$D1/$E0/ {L:shl ax,1 }
$D1/$D2/ { rcl dx,1 }
$49/ { dec cx }
$75/$F9); { jne L }
{---------------------------------------------------------------------------}
procedure Add64(var Z: TW64; var X,Y: TW64);
{-Add two 64 bit integers: Z:=X+Y}
inline(
$8C/$DF/ {mov di,ds }
$5E/ {pop si }
$1F/ {pop ds }
$8B/$04/ {mov ax,[si] }
$8B/$5C/$02/ {mov bx,[si+02]}
$8B/$4C/$04/ {mov cx,[si+04]}
$8B/$54/$06/ {mov dx,[si+06]}
$5E/ {pop si }
$1F/ {pop ds }
$03/$04/ {add ax,[si] }
$13/$5C/$02/ {adc bx,[si+02]}
$13/$4C/$04/ {adc cx,[si+04]}
$13/$54/$06/ {adc dx,[si+06]}
$5E/ {pop si }
$1F/ {pop ds }
$89/$04/ {mov [si],ax }
$89/$5C/$02/ {mov [si+02],bx}
$89/$4C/$04/ {mov [si+04],cx}
$89/$54/$06/ {mov [si+06],dx}
$8E/$DF); {mov ds,di }
{---------------------------------------------------------------------------}
procedure Inc64(var Z: TW64; var X: TW64);
{-Inc a 64 bit integer}
inline(
$8C/$DF/ {mov di,ds }
$5E/ {pop si }
$1F/ {pop ds }
$8B/$04/ {mov ax,[si] }
$8B/$5C/$02/ {mov bx,[si+02]}
$8B/$4C/$04/ {mov cx,[si+04]}
$8B/$54/$06/ {mov dx,[si+06]}
$5E/ {pop si }
$1F/ {pop ds }
$01/$04/ {add [si],ax }
$11/$5C/$02/ {adc [si+02],bx}
$11/$4C/$04/ {adc [si+04],cx}
$11/$54/$06/ {adc [si+06],dx}
$8E/$DF); {mov ds,di }
{---------------------------------------------------------------------------}
procedure Sum0(var X: TW64; var R: TW64);
{-Big-Sigma-0 function, 'preproccessed' for shift counts > 16}
begin
R.L := (ISHR0(X.L,12) or ISHL(X.H,4)) xor (ISHR(X.H,2) or ISHL0(X.L,14)) xor (ISHR(X.H,7) or ISHL0(X.L,9));
R.H := (ISHR0(X.H,12) or ISHL(X.L,4)) xor (ISHR(X.L,2) or ISHL0(X.H,14)) xor (ISHR(X.L,7) or ISHL0(X.H,9));
end;
{---------------------------------------------------------------------------}
procedure Sum1(var X: TW64; var R: TW64);
{-Big-Sigma-1 function, 'preproccessed' for shift counts > 16}
begin
R.L := (ISHR(X.L,14) or ISHL0(X.H,2)) xor (ISHR0(X.L,2) or ISHL(X.H,14)) xor (ISHR(X.H,9) or ISHL0(X.L,7));
R.H := (ISHR(X.H,14) or ISHL0(X.L,2)) xor (ISHR0(X.H,2) or ISHL(X.L,14)) xor (ISHR(X.L,9) or ISHL0(X.H,7));
end;
{---------------------------------------------------------------------------}
procedure Sig0(var X: TW64; var R: TW64);
{-Small-Sigma-0 function, 'preproccessed' for shift counts > 16}
begin
R.L := (ISHR(X.L,1) or ISHL0(X.H,15)) xor (ISHR(X.L,8) or ISHL0(X.H,8)) xor (ISHR(X.L,7) or ISHL0(X.H,9));
R.H := (ISHR(X.H,1) or ISHL0(X.L,15)) xor (ISHR(X.H,8) or ISHL0(X.L,8)) xor ISHR(X.H,7);
end;
{---------------------------------------------------------------------------}
procedure Sig1(var X: TW64; var R: TW64);
{-Small-Sigma-1 function, 'preproccessed' for shift counts > 31}
begin
R.L := (ISHR0(X.L,3) or ISHL(X.H,13)) xor (ISHR0(X.H,13) or ISHL(X.L,3)) xor (ISHR(X.L,6) or ISHL0(X.H,10));
R.H := (ISHR0(X.H,3) or ISHL(X.L,13)) xor (ISHR0(X.L,13) or ISHL(X.H,3)) xor ISHR(X.H,6);
end;
{$else}
(**** TP 6/7/Delphi1 for 386+ *****)
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al}
$86/$E2); {xchg dl,ah}
{---------------------------------------------------------------------------}
procedure Add64(var Z: TW64; {$ifdef CONST} const {$else} var {$endif} X,Y: TW64);
{-Add two 64 bit integers}
inline(
$8C/$D9/ {mov cx,ds }
$5B/ {pop bx }
$1F/ {pop ds }
$66/$8B/$07/ {mov eax,[bx] }
$66/$8B/$57/$04/ {mov edx,[bx+04]}
$5B/ {pop bx }
$1F/ {pop ds }
$66/$03/$07/ {add eax,[bx] }
$66/$13/$57/$04/ {adc edx,[bx+04]}
$5B/ {pop bx }
$1F/ {pop ds }
$66/$89/$07/ {mov [bx],eax }
$66/$89/$57/$04/ {mov [bx+04],edx}
$8E/$D9); {mov ds,cx }
{---------------------------------------------------------------------------}
procedure Inc64(var Z: TW64; {$ifdef CONST} const {$else} var {$endif} X: TW64);
{-Inc a 64 bit integer}
inline(
(*
{slower on Pentium 4}
$8C/$D9/ {mov cx,ds }
$5B/ {pop bx }
$1F/ {pop ds }
$66/$8B/$07/ {mov eax,[bx] }
$66/$8B/$57/$04/ {mov edx,[bx+04]}
$5B/ {pop bx }
$1F/ {pop ds }
$66/$01/$07/ {add [bx],eax }
$66/$11/$57/$04/ {adc [bx+04],edx}
$8E/$D9); {mov ds,cx }
*)
$8C/$D9/ {mov cx,ds }
$5B/ {pop bx }
$1F/ {pop ds }
$66/$8B/$07/ {mov eax,[bx] }
$66/$8B/$57/$04/ {mov edx,[bx+04]}
$5B/ {pop bx }
$1F/ {pop ds }
$66/$03/$07/ {add eax,[bx] }
$66/$13/$57/$04/ {adc edx,[bx+04]}
$66/$89/$07/ {mov [bx],eax }
$66/$89/$57/$04/ {mov [bx+04],edx}
$8E/$D9); {mov ds,cx }
{--------------------------------------------------------------------------}
procedure Sum0({$ifdef CONST} const {$else} var {$endif} X: TW64; var R: TW64); assembler;
{-Big-Sigma-0 function, 'preproccessed' for shift counts > 31}
asm
{ R.L := ((X.L shr 28) or (X.H shl 4)) xor ((X.H shr 2) or (X.L shl 30)) xor ((X.H shr 7) or (X.L shl 25));
R.H := ((X.H shr 28) or (X.L shl 4)) xor ((X.L shr 2) or (X.H shl 30)) xor ((X.L shr 7) or (X.H shl 25));}
les bx,[X]
db $66; mov si,es:[bx] {X.L}
db $66; mov di,es:[bx+4] {X.H}
db $66; mov ax,si {(X.L shr 28) or (X.H shl 4)}
db $66; mov dx,di
db $66; shr ax,28
db $66; shl dx,4
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,di {(X.H shr 2) or (X.L shl 30)}
db $66; mov dx,si
db $66; shr ax,2
db $66; shl dx,30
db $66; or ax,dx
db $66; xor cx,ax
db $66; mov ax,di {(X.H shr 7) or (X.L shl 25)}
db $66; mov dx,si
db $66; shr ax,7
db $66; shl dx,25
db $66; or ax,dx
db $66; xor ax,cx
les bx,[R]
db $66; mov es:[bx],ax
db $66; mov ax,di {(X.H shr 28) or (X.L shl 4)}
db $66; mov dx,si
db $66; shr ax,28
db $66; shl dx,4
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,si {(X.L shr 2) or (X.H shl 30)}
db $66; mov dx,di
db $66; shr ax,2
db $66; shl dx,30
db $66; or ax,dx
db $66; xor cx,ax
db $66; mov ax,si {(X.L shr 7) or (X.H shl 25)}
db $66; mov dx,di
db $66; shr ax,7
db $66; shl dx,25
db $66; or ax,dx
db $66; xor ax,cx
db $66; mov es:[bx+4],ax
end;
{---------------------------------------------------------------------------}
procedure Sum1({$ifdef CONST} const {$else} var {$endif} X: TW64; var R: TW64); assembler;
{-Big-Sigma-1 function, 'preproccessed' for shift counts > 31}
asm
{ R.L := ((X.L shr 14) or (X.H shl 18)) xor ((X.L shr 18) or (X.H shl 14)) xor ((X.H shr 9) or (X.L shl 23));
R.H := ((X.H shr 14) or (X.L shl 18)) xor ((X.H shr 18) or (X.L shl 14)) xor ((X.L shr 9) or (X.H shl 23));}
les bx,[X]
db $66; mov si,es:[bx] {X.L}
db $66; mov di,es:[bx+4] {X.H}
db $66; mov ax,si {(X.L shr 14) or (X.H shl 18)}
db $66; mov dx,di
db $66; shr ax,14
db $66; shl dx,18
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,si {(X.L shr 18) or (X.H shl 14)}
db $66; mov dx,di
db $66; shr ax,18
db $66; shl dx,14
db $66; or ax,dx
db $66; xor cx,ax
db $66; mov ax,di {(X.H shr 9) or (X.L shl 23)}
db $66; mov dx,si
db $66; shr ax,9
db $66; shl dx,23
db $66; or ax,dx
db $66; xor ax,cx
les bx,[R]
db $66; mov es:[bx],ax
db $66; mov ax,di {(X.H shr 14) or (X.L shl 18)}
db $66; mov dx,si
db $66; shr ax,14
db $66; shl dx,18
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,di {(X.H shr 18) or (X.L shl 14)}
db $66; mov dx,si
db $66; shr ax,18
db $66; shl dx,14
db $66; or ax,dx
db $66; xor cx,ax
db $66; mov ax,si {(X.L shr 9) or (X.H shl 23)}
db $66; mov dx,di
db $66; shr ax,9
db $66; shl dx,23
db $66; or ax,dx
db $66; xor ax,cx
db $66; mov es:[bx+4],ax
end;
{---------------------------------------------------------------------------}
procedure Sig0({$ifdef CONST} const {$else} var {$endif} X: TW64; var R: TW64); assembler;
{-Small-Sigma-0 function, 'preproccessed' for shift counts > 31}
asm
{ R.L := ((X.L shr 1) or (X.H shl 31)) xor ((X.L shr 8) or (X.H shl 24)) xor ((X.L shr 7) or (X.H shl 25));
R.H := ((X.H shr 1) or (X.L shl 31)) xor ((X.H shr 8) or (X.L shl 24)) xor (X.H shr 7);}
les bx,[X]
db $66; mov si,es:[bx] {X.L}
db $66; mov di,es:[bx+4] {X.H}
db $66; mov ax,si {(X.L shr 1) or (X.H shl 31)}
db $66; mov dx,di
db $66; shr ax,1
db $66; shl dx,31
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,si {(X.L shr 8) or (X.H shl 24)}
db $66; mov dx,di
db $66; shr ax,8
db $66; shl dx,24
db $66; or ax,dx
db $66; xor cx,ax
db $66; mov ax,si {(X.L shr 7) or (X.H shl 25)}
db $66; mov dx,di
db $66; shr ax,7
db $66; shl dx,25
db $66; or ax,dx
db $66; xor ax,cx
les bx,[R]
db $66; mov es:[bx],ax
db $66; mov ax,di {(X.H shr 1) or (X.L shl 31)}
db $66; mov dx,si
db $66; shr ax,1
db $66; shl dx,31
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,di {(X.H shr 8) or (X.L shl 24)}
db $66; mov dx,si
db $66; shr ax,8
db $66; shl dx,24
db $66; or ax,dx
db $66; xor ax,cx
db $66; shr di,7 {(X.H shr 7)}
db $66; xor ax,di
db $66; mov es:[bx+4],ax
end;
{---------------------------------------------------------------------------}
procedure Sig1({$ifdef CONST} const {$else} var {$endif} X: TW64; var R: TW64); assembler;
{-Small-Sigma-1 function, 'preproccessed' for shift counts > 31}
asm
{ R.L := ((X.L shr 19) or (X.H shl 13)) xor ((X.H shr 29) or (X.L shl 3)) xor ((X.L shr 6) or (X.H shl 26));
R.H := ((X.H shr 19) or (X.L shl 13)) xor ((X.L shr 29) or (X.H shl 3)) xor (X.H shr 6);}
les bx,[X]
db $66; mov si,es:[bx] {X.L}
db $66; mov di,es:[bx+4] {X.H}
db $66; mov ax,si {(X.L shr 19) or (X.H shl 13)}
db $66; mov dx,di
db $66; shr ax,19
db $66; shl dx,13
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,di {(X.H shr 29) or (X.L shl 3)}
db $66; mov dx,si
db $66; shr ax,29
db $66; shl dx,3
db $66; or ax,dx
db $66; xor cx,ax
db $66; mov ax,si {(X.L shr 6) or (X.H shl 26)}
db $66; mov dx,di
db $66; shr ax,6
db $66; shl dx,26
db $66; or ax,dx
db $66; xor ax,cx
les bx,[R]
db $66; mov es:[bx],ax
db $66; mov ax,di {(X.H shr 19) or (X.L shl 13)}
db $66; mov dx,si
db $66; shr ax,19
db $66; shl dx,13
db $66; or ax,dx
db $66; mov cx,ax
db $66; mov ax,si {(X.L shr 29) or (X.H shl 3)}
db $66; mov dx,di
db $66; shr ax,29
db $66; shl dx,3
db $66; or ax,dx
db $66; xor ax,cx
db $66; shr di,6 {(X.H shr 6)}
db $66; xor ax,di
db $66; mov es:[bx+4],ax
end;
{$endif BASM16}
{$endif BIT16}
{$ifdef UseInt64}
{---------------------------------------------------------------------------}
procedure SHA512Compress(var Data: THashContext);
{-Actual hashing function}
type
THash64 = array[0..7] of int64;
TBuf64 = array[0..79] of int64;
THLA64 = array[0..79] of TW64;
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9 errors!}
{$endif}
{Use the round constant construct from non-int64 because}
{Delphi 2 does not compile even though code is not used }
{and FPC does not know int64 constants }
const
KT: array[0..79] of TW64 = (
(L:$d728ae22; H:$428a2f98), (L:$23ef65cd; H:$71374491),
(L:$ec4d3b2f; H:$b5c0fbcf), (L:$8189dbbc; H:$e9b5dba5),
(L:$f348b538; H:$3956c25b), (L:$b605d019; H:$59f111f1),
(L:$af194f9b; H:$923f82a4), (L:$da6d8118; H:$ab1c5ed5),
(L:$a3030242; H:$d807aa98), (L:$45706fbe; H:$12835b01),
(L:$4ee4b28c; H:$243185be), (L:$d5ffb4e2; H:$550c7dc3),
(L:$f27b896f; H:$72be5d74), (L:$3b1696b1; H:$80deb1fe),
(L:$25c71235; H:$9bdc06a7), (L:$cf692694; H:$c19bf174),
(L:$9ef14ad2; H:$e49b69c1), (L:$384f25e3; H:$efbe4786),
(L:$8b8cd5b5; H:$0fc19dc6), (L:$77ac9c65; H:$240ca1cc),
(L:$592b0275; H:$2de92c6f), (L:$6ea6e483; H:$4a7484aa),
(L:$bd41fbd4; H:$5cb0a9dc), (L:$831153b5; H:$76f988da),
(L:$ee66dfab; H:$983e5152), (L:$2db43210; H:$a831c66d),
(L:$98fb213f; H:$b00327c8), (L:$beef0ee4; H:$bf597fc7),
(L:$3da88fc2; H:$c6e00bf3), (L:$930aa725; H:$d5a79147),
(L:$e003826f; H:$06ca6351), (L:$0a0e6e70; H:$14292967),
(L:$46d22ffc; H:$27b70a85), (L:$5c26c926; H:$2e1b2138),
(L:$5ac42aed; H:$4d2c6dfc), (L:$9d95b3df; H:$53380d13),
(L:$8baf63de; H:$650a7354), (L:$3c77b2a8; H:$766a0abb),
(L:$47edaee6; H:$81c2c92e), (L:$1482353b; H:$92722c85),
(L:$4cf10364; H:$a2bfe8a1), (L:$bc423001; H:$a81a664b),
(L:$d0f89791; H:$c24b8b70), (L:$0654be30; H:$c76c51a3),
(L:$d6ef5218; H:$d192e819), (L:$5565a910; H:$d6990624),
(L:$5771202a; H:$f40e3585), (L:$32bbd1b8; H:$106aa070),
(L:$b8d2d0c8; H:$19a4c116), (L:$5141ab53; H:$1e376c08),
(L:$df8eeb99; H:$2748774c), (L:$e19b48a8; H:$34b0bcb5),
(L:$c5c95a63; H:$391c0cb3), (L:$e3418acb; H:$4ed8aa4a),
(L:$7763e373; H:$5b9cca4f), (L:$d6b2b8a3; H:$682e6ff3),
(L:$5defb2fc; H:$748f82ee), (L:$43172f60; H:$78a5636f),
(L:$a1f0ab72; H:$84c87814), (L:$1a6439ec; H:$8cc70208),
(L:$23631e28; H:$90befffa), (L:$de82bde9; H:$a4506ceb),
(L:$b2c67915; H:$bef9a3f7), (L:$e372532b; H:$c67178f2),
(L:$ea26619c; H:$ca273ece), (L:$21c0c207; H:$d186b8c7),
(L:$cde0eb1e; H:$eada7dd6), (L:$ee6ed178; H:$f57d4f7f),
(L:$72176fba; H:$06f067aa), (L:$a2c898a6; H:$0a637dc5),
(L:$bef90dae; H:$113f9804), (L:$131c471b; H:$1b710b35),
(L:$23047d84; H:$28db77f5), (L:$40c72493; H:$32caab7b),
(L:$15c9bebc; H:$3c9ebe0a), (L:$9c100d4c; H:$431d67c4),
(L:$cb3e42b6; H:$4cc5d4be), (L:$fc657e2a; H:$597f299c),
(L:$3ad6faec; H:$5fcb6fab), (L:$4a475817; H:$6c44198c)
);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
var
i,j: integer;
t0,t1: int64;
A,B,C,D,E,F,G,H: int64;
W: TBuf64;
K: TBuf64 absolute KT;
begin
{Assign old working hash to variables a..h}
A := THash64(Data.Hash)[0];
B := THash64(Data.Hash)[1];
C := THash64(Data.Hash)[2];
D := THash64(Data.Hash)[3];
E := THash64(Data.Hash)[4];
F := THash64(Data.Hash)[5];
G := THash64(Data.Hash)[6];
H := THash64(Data.Hash)[7];
{Message schedule}
{Part 1: Transfer buffer with little -> big endian conversion}
j := 0;
for i:=0 to 15 do begin
{Old shl 32 version was buggy, use helper record}
THLA64(W)[i].H := RB(THashBuf32(Data.Buffer)[j]);
THLA64(W)[i].L := RB(THashBuf32(Data.Buffer)[j+1]);
inc(j,2);
end;
{Part 2: Calculate remaining "expanded message blocks"}
for i:=16 to 79 do begin
W[i] := (((W[i-2] shr 19) or (W[i-2] shl 45)) xor ((W[i-2] shr 61) or (W[i-2] shl 3)) xor (W[i-2] shr 6))
+ W[i-7]
+ (((W[i-15] shr 1) or (W[i-15] shl 63)) xor ((W[i-15] shr 8) or (W[i-15] shl 56)) xor (W[i-15] shr 7))
+ W[i-16];
end;
{SHA512 compression function, partial unroll}
{line length must be < 128 for 16bit compilers even if code is not used}
i := 0;
while i<79 do begin
t0:=H+((E shr 14 or E shl 50)xor(E shr 18 or E shl 46)xor(E shr 41 or E shl 23))+((E and (F xor G)) xor G)+K[i ]+W[i ];
t1:=((A shr 28 or A shl 36)xor(A shr 34 or A shl 30)xor(A shr 39 or A shl 25))+((A or B) and C or A and B);
D :=D+t0;
H :=t0+t1;
t0:=G+((D shr 14 or D shl 50)xor(D shr 18 or D shl 46)xor(D shr 41 or D shl 23))+((D and (E xor F)) xor F)+K[i+1]+W[i+1];
t1:=((H shr 28 or H shl 36)xor(H shr 34 or H shl 30)xor(H shr 39 or H shl 25))+((H or A) and B or H and A);
C :=C+t0;
G :=t0+t1;
t0:=F+((C shr 14 or C shl 50)xor(C shr 18 or C shl 46)xor(C shr 41 or C shl 23))+((C and (D xor E)) xor E)+K[i+2]+W[i+2];
t1:=((G shr 28 or G shl 36)xor(G shr 34 or G shl 30)xor(G shr 39 or G shl 25))+((G or H) and A or G and H);
B :=B+t0;
F :=t0+t1;
t0:=E+((B shr 14 or B shl 50)xor(B shr 18 or B shl 46)xor(B shr 41 or B shl 23))+((B and (C xor D)) xor D)+K[i+3]+W[i+3];
t1:=((F shr 28 or F shl 36)xor(F shr 34 or F shl 30)xor(F shr 39 or F shl 25))+((F or G) and H or F and G);
A :=A+t0;
E :=t0+t1;
t0:=D+((A shr 14 or A shl 50)xor(A shr 18 or A shl 46)xor(A shr 41 or A shl 23))+((A and (B xor C)) xor C)+K[i+4]+W[i+4];
t1:=((E shr 28 or E shl 36)xor(E shr 34 or E shl 30)xor(E shr 39 or E shl 25))+((E or F) and G or E and F);
H :=H+t0;
D :=t0+t1;
t0:=C+((H shr 14 or H shl 50)xor(H shr 18 or H shl 46)xor(H shr 41 or H shl 23))+((H and (A xor B)) xor B)+K[i+5]+W[i+5];
t1:=((D shr 28 or D shl 36)xor(D shr 34 or D shl 30)xor(D shr 39 or D shl 25))+((D or E) and F or D and E);
G :=G+t0;
C :=t0+t1;
t0:=B+((G shr 14 or G shl 50)xor(G shr 18 or G shl 46)xor(G shr 41 or G shl 23))+((G and (H xor A)) xor A)+K[i+6]+W[i+6];
t1:=((C shr 28 or C shl 36)xor(C shr 34 or C shl 30)xor(C shr 39 or C shl 25))+((C or D) and E or C and D);
F :=F+t0;
B :=t0+t1;
t0:=A+((F shr 14 or F shl 50)xor(F shr 18 or F shl 46)xor(F shr 41 or F shl 23))+((F and (G xor H)) xor H)+K[i+7]+W[i+7];
t1:=((B shr 28 or B shl 36)xor(B shr 34 or B shl 30)xor(B shr 39 or B shl 25))+((B or C) and D or B and C);
E :=E+t0;
A :=t0+t1;
inc(i,8);
end;
{Calculate new working hash}
inc(THash64(Data.Hash)[0], A);
inc(THash64(Data.Hash)[1], B);
inc(THash64(Data.Hash)[2], C);
inc(THash64(Data.Hash)[3], D);
inc(THash64(Data.Hash)[4], E);
inc(THash64(Data.Hash)[5], F);
inc(THash64(Data.Hash)[6], G);
inc(THash64(Data.Hash)[7], H);
end;
{---------------------------------------------------------------------------}
procedure UpdateLen(var Context: THashContext; Len: longint; IsByteLen: boolean);
{-Update 128 bit message bit length, Len = byte length if IsByteLen}
var
t0,t1: TW64;
i: integer;
begin
if IsByteLen then int64(t0) := 8*int64(Len)
else int64(t0) := int64(Len);
t1.L := Context.MLen[0];
t1.H := 0;
Inc(int64(t0),int64(t1));
Context.MLen[0] := t0.L;
for i:=1 to 3 do begin
if t0.H=0 then exit;
t1.L := Context.MLen[i];
t0.L := t0.H;
t0.H := 0;
Inc(int64(t0),int64(t1));
Context.MLen[i] := t0.L;
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure SHA512Compress(var Data: THashContext);
{-Actual hashing function}
type
THash64 = array[0..7] of TW64;
TBuf64 = array[0..79] of TW64;
var
i,j: integer;
t,t0,t1: TW64;
S: THash64;
W: TBuf64;
const
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9 errors!}
{$endif}
K: array[0..79] of TW64 = (
(L:$d728ae22; H:$428a2f98), (L:$23ef65cd; H:$71374491),
(L:$ec4d3b2f; H:$b5c0fbcf), (L:$8189dbbc; H:$e9b5dba5),
(L:$f348b538; H:$3956c25b), (L:$b605d019; H:$59f111f1),
(L:$af194f9b; H:$923f82a4), (L:$da6d8118; H:$ab1c5ed5),
(L:$a3030242; H:$d807aa98), (L:$45706fbe; H:$12835b01),
(L:$4ee4b28c; H:$243185be), (L:$d5ffb4e2; H:$550c7dc3),
(L:$f27b896f; H:$72be5d74), (L:$3b1696b1; H:$80deb1fe),
(L:$25c71235; H:$9bdc06a7), (L:$cf692694; H:$c19bf174),
(L:$9ef14ad2; H:$e49b69c1), (L:$384f25e3; H:$efbe4786),
(L:$8b8cd5b5; H:$0fc19dc6), (L:$77ac9c65; H:$240ca1cc),
(L:$592b0275; H:$2de92c6f), (L:$6ea6e483; H:$4a7484aa),
(L:$bd41fbd4; H:$5cb0a9dc), (L:$831153b5; H:$76f988da),
(L:$ee66dfab; H:$983e5152), (L:$2db43210; H:$a831c66d),
(L:$98fb213f; H:$b00327c8), (L:$beef0ee4; H:$bf597fc7),
(L:$3da88fc2; H:$c6e00bf3), (L:$930aa725; H:$d5a79147),
(L:$e003826f; H:$06ca6351), (L:$0a0e6e70; H:$14292967),
(L:$46d22ffc; H:$27b70a85), (L:$5c26c926; H:$2e1b2138),
(L:$5ac42aed; H:$4d2c6dfc), (L:$9d95b3df; H:$53380d13),
(L:$8baf63de; H:$650a7354), (L:$3c77b2a8; H:$766a0abb),
(L:$47edaee6; H:$81c2c92e), (L:$1482353b; H:$92722c85),
(L:$4cf10364; H:$a2bfe8a1), (L:$bc423001; H:$a81a664b),
(L:$d0f89791; H:$c24b8b70), (L:$0654be30; H:$c76c51a3),
(L:$d6ef5218; H:$d192e819), (L:$5565a910; H:$d6990624),
(L:$5771202a; H:$f40e3585), (L:$32bbd1b8; H:$106aa070),
(L:$b8d2d0c8; H:$19a4c116), (L:$5141ab53; H:$1e376c08),
(L:$df8eeb99; H:$2748774c), (L:$e19b48a8; H:$34b0bcb5),
(L:$c5c95a63; H:$391c0cb3), (L:$e3418acb; H:$4ed8aa4a),
(L:$7763e373; H:$5b9cca4f), (L:$d6b2b8a3; H:$682e6ff3),
(L:$5defb2fc; H:$748f82ee), (L:$43172f60; H:$78a5636f),
(L:$a1f0ab72; H:$84c87814), (L:$1a6439ec; H:$8cc70208),
(L:$23631e28; H:$90befffa), (L:$de82bde9; H:$a4506ceb),
(L:$b2c67915; H:$bef9a3f7), (L:$e372532b; H:$c67178f2),
(L:$ea26619c; H:$ca273ece), (L:$21c0c207; H:$d186b8c7),
(L:$cde0eb1e; H:$eada7dd6), (L:$ee6ed178; H:$f57d4f7f),
(L:$72176fba; H:$06f067aa), (L:$a2c898a6; H:$0a637dc5),
(L:$bef90dae; H:$113f9804), (L:$131c471b; H:$1b710b35),
(L:$23047d84; H:$28db77f5), (L:$40c72493; H:$32caab7b),
(L:$15c9bebc; H:$3c9ebe0a), (L:$9c100d4c; H:$431d67c4),
(L:$cb3e42b6; H:$4cc5d4be), (L:$fc657e2a; H:$597f299c),
(L:$3ad6faec; H:$5fcb6fab), (L:$4a475817; H:$6c44198c)
);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
begin
{Assign old working hash to variables a..h=S[0]..S[7]}
S := THash64(Data.Hash);
{Message schedule}
{Part 1: Transfer buffer with little -> big endian conversion}
j := 0;
for i:=0 to 15 do begin
W[i].H:= RB(THashBuf32(Data.Buffer)[j]);
W[i].L:= RB(THashBuf32(Data.Buffer)[j+1]);
inc(j,2);
end;
{Part 2: Calculate remaining "expanded message blocks"}
for i:=16 to 79 do begin
{W[i]:= Sig1(W[i-2]) + W[i-7] + Sig0(W[i-15]) + W[i-16];}
{$ifndef BIT16}
t.L := W[i-2].L;
t.H := W[i-2].H;
t0.L := ((t.L shr 19) or (t.H shl 13)) xor ((t.H shr 29) or (t.L shl 3)) xor ((t.L shr 6) or (t.H shl 26));
t0.H := ((t.H shr 19) or (t.L shl 13)) xor ((t.L shr 29) or (t.H shl 3)) xor (t.H shr 6);
Inc64(t0,W[i-7]);
t.L := W[i-15].L;
t.H := W[i-15].H;
t1.L := ((t.L shr 1) or (t.H shl 31)) xor ((t.L shr 8) or (t.H shl 24)) xor ((t.L shr 7) or (t.H shl 25));
t1.H := ((t.H shr 1) or (t.L shl 31)) xor ((t.H shr 8) or (t.L shl 24)) xor (t.H shr 7);
Inc64(t0,t1);
Add64(W[i], W[i-16], t0);
{$else}
Sig1(W[i-2], t0);
Inc64(t0,W[i-7]);
Sig0(W[i-15], t);
Inc64(t0,t);
Add64(W[i], W[i-16], t0);
{$endif}
end;
{SHA512 compression function}
for i:=0 to 79 do begin
{t0:= S[7] + Sum1(S[4]) + Ch(S[4],S[5],S[6]) + K[i] + W[i];}
{$ifndef BIT16}
t0.L := (S[4].L shr 14 or S[4].H shl 18) xor (S[4].L shr 18 or S[4].H shl 14) xor (S[4].H shr 9 or S[4].L shl 23);
t0.H := (S[4].H shr 14 or S[4].L shl 18) xor (S[4].H shr 18 or S[4].L shl 14) xor (S[4].L shr 9 or S[4].H shl 23);
{$else}
Sum1(S[4],t0);
{$endif}
Inc64(t0, S[7]);
t.L := ((S[5].L xor S[6].L) and S[4].L) xor S[6].L;
t.H := ((S[5].H xor S[6].H) and S[4].H) xor S[6].H;
Inc64(t0, t);
Inc64(t0, K[i]);
Inc64(t0, W[i]);
{t1:= Sum0(S[0]) + Maj(S[0],S[1],S[2]));}
{$ifndef BIT16}
t1.L := (S[0].L shr 28 or S[0].H shl 4) xor (S[0].H shr 2 or S[0].L shl 30) xor (S[0].H shr 7 or S[0].L shl 25);
t1.H := (S[0].H shr 28 or S[0].L shl 4) xor (S[0].L shr 2 or S[0].H shl 30) xor (S[0].L shr 7 or S[0].H shl 25);
{$else}
Sum0(S[0],t1);
{$endif}
t.L := ((S[0].L or S[1].L) and S[2].L) or (S[0].L and S[1].L);
t.h := ((S[0].H or S[1].H) and S[2].H) or (S[0].H and S[1].H);
Inc64(t1, t);
S[7].L := S[6].L;
S[7].H := S[6].H;
S[6].L := S[5].L;
S[6].H := S[5].H;
S[5].H := S[4].H;
S[5].L := S[4].L;
Add64(S[4],t0, S[3]);
S[3].L := S[2].L;
S[3].H := S[2].H;
S[2].L := S[1].L;
S[2].H := S[1].H;
S[1].L := S[0].L;
S[1].H := S[0].H;
Add64(S[0],t0,t1);
end;
{Calculate new working hash}
for i:=0 to 7 do Inc64(THash64(Data.Hash)[i], S[i]);
end;
{---------------------------------------------------------------------------}
procedure UpdateLen(var Context: THashContext; Len: longint; IsByteLen: boolean);
{-Update 128 bit message bit length, Len = byte length if IsByteLen}
var
t0,t1: TW64;
i: integer;
begin
if IsByteLen then begin
{Calculate bit length increment = 8*Len}
if Len<=$0FFFFFFF then begin
{safe to multiply without overflow}
t0.L := 8*Len;
t0.H := 0;
end
else begin
t0.L := Len;
t0.H := 0;
Inc64(t0,t0);
Inc64(t0,t0);
Inc64(t0,t0);
end;
end
else begin
t0.L := Len;
t0.H := 0;
end;
{Update 128 bit length}
t1.L := Context.MLen[0];
t1.H := 0;
Inc64(t0,t1);
Context.MLen[0] := t0.L;
for i:=1 to 3 do begin
{propagate carry into higher bits}
if t0.H=0 then exit;
t1.L := Context.MLen[i];
t0.L := t0.H;
t0.H := 0;
Inc64(t0,t1);
Context.MLen[i] := t0.L;
end;
end;
{$endif}
{---------------------------------------------------------------------------}
procedure SHA512Init(var Context: THashContext);
{-initialize context}
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9 errors!}
{$endif}
const
SIV: THashState = ($f3bcc908, $6a09e667, $84caa73b, $bb67ae85,
$fe94f82b, $3c6ef372, $5f1d36f1, $a54ff53a,
$ade682d1, $510e527f, $2b3e6c1f, $9b05688c,
$fb41bd6b, $1f83d9ab, $137e2179, $5be0cd19);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
begin
{Clear context, buffer=0!!}
fillchar(Context,sizeof(Context),0);
Context.Hash := SIV;
end;
{---------------------------------------------------------------------------}
procedure SHA512UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
begin
{Update message bit length}
UpdateLen(Context, Len, true);
while Len > 0 do begin
{fill block with msg data}
Context.Buffer[Context.Index]:= pByte(Msg)^;
inc(Ptr2Inc(Msg));
inc(Context.Index);
dec(Len);
if Context.Index=SHA512_BlockLen then begin
{If 512 bit transferred, compress a block}
Context.Index:= 0;
SHA512Compress(Context);
while Len>=SHA512_BlockLen do begin
move(Msg^,Context.Buffer,SHA512_BlockLen);
SHA512Compress(Context);
inc(Ptr2Inc(Msg),SHA512_BlockLen);
dec(Len,SHA512_BlockLen);
end;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure SHA512Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
begin
SHA512UpdateXL(Context, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA512FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize SHA512 calculation with bitlen bits from BData (big-endian), clear context}
var
i: integer;
begin
{Message padding}
{append bits from BData and a single '1' bit}
if (bitlen>0) and (bitlen<=7) then begin
Context.Buffer[Context.Index]:= (BData and BitAPI_Mask[bitlen]) or BitAPI_PBit[bitlen];
UpdateLen(Context, bitlen, false);
end
else Context.Buffer[Context.Index]:= $80;
for i:=Context.Index+1 to 127 do Context.Buffer[i] := 0;
{2. Compress if more than 448 bits, (no room for 64 bit length}
if Context.Index>= 112 then begin
SHA512Compress(Context);
fillchar(Context.Buffer,sizeof(Context.Buffer),0);
end;
{Write 128 bit msg length into the last bits of the last block}
{(in big endian format) and do a final compress}
THashBuf32(Context.Buffer)[28]:= RB(Context.MLen[3]);
THashBuf32(Context.Buffer)[29]:= RB(Context.MLen[2]);
THashBuf32(Context.Buffer)[30]:= RB(Context.MLen[1]);
THashBuf32(Context.Buffer)[31]:= RB(Context.MLen[0]);
SHA512Compress(Context);
{Hash -> Digest to little endian format}
for i:=0 to 15 do THashDig32(Digest)[i]:= RB(Context.Hash[i xor 1]);
{Clear context}
fillchar(Context,sizeof(Context),0);
end;
{---------------------------------------------------------------------------}
procedure SHA512FinalBits(var Context: THashContext; var Digest: TSHA512Digest; BData: byte; bitlen: integer);
{-finalize SHA512 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 SHA512FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize SHA512 calculation, clear context}
begin
SHA512FinalBitsEx(Context,Digest,0,0);
end;
{---------------------------------------------------------------------------}
procedure SHA512Final(var Context: THashContext; var Digest: TSHA512Digest);
{-finalize SHA512 calculation, clear context}
var
tmp: THashDigest;
begin
SHA512FinalBitsEx(Context, tmp, 0, 0);
move(tmp,Digest,sizeof(Digest));
end;
{---------------------------------------------------------------------------}
function SHA512SelfTest: boolean;
{-self test for string from SHA512 document}
const
s1: string[3] = 'abc';
s2: string[112] = 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn'
+'hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu';
D1: TSHA512Digest = ($dd, $af, $35, $a1, $93, $61, $7a, $ba,
$cc, $41, $73, $49, $ae, $20, $41, $31,
$12, $e6, $fa, $4e, $89, $a9, $7e, $a2,
$0a, $9e, $ee, $e6, $4b, $55, $d3, $9a,
$21, $92, $99, $2a, $27, $4f, $c1, $a8,
$36, $ba, $3c, $23, $a3, $fe, $eb, $bd,
$45, $4d, $44, $23, $64, $3c, $e8, $0e,
$2a, $9a, $c9, $4f, $a5, $4c, $a4, $9f );
D2: TSHA512Digest = ($8e, $95, $9b, $75, $da, $e3, $13, $da,
$8c, $f4, $f7, $28, $14, $fc, $14, $3f,
$8f, $77, $79, $c6, $eb, $9f, $7f, $a1,
$72, $99, $ae, $ad, $b6, $88, $90, $18,
$50, $1d, $28, $9e, $49, $00, $f7, $e4,
$33, $1b, $99, $de, $c4, $b5, $43, $3a,
$c7, $d3, $29, $ee, $b6, $dd, $26, $54,
$5e, $96, $e5, $5b, $87, $4b, $e9, $09 );
D3: TSHA512Digest = ($b4, $59, $4e, $b1, $29, $59, $fc, $2e,
$69, $79, $b6, $78, $35, $54, $29, $9c,
$c0, $36, $9f, $44, $08, $3a, $8b, $09,
$55, $ba, $ef, $d8, $83, $0c, $da, $22,
$89, $4b, $0b, $46, $c0, $ed, $49, $49,
$0e, $39, $1a, $d9, $9a, $f8, $56, $cc,
$1b, $d9, $6f, $23, $8c, $7f, $2a, $17,
$cf, $37, $ae, $b7, $e7, $93, $39, $5a);
D4: TSHA512Digest = ($46, $4a, $e5, $27, $7a, $3d, $9e, $35,
$14, $46, $90, $ac, $ef, $57, $18, $f2,
$17, $e3, $28, $56, $27, $26, $20, $8f,
$b1, $53, $bd, $31, $64, $1a, $fa, $9e,
$ab, $d6, $44, $90, $8d, $18, $b1, $86,
$68, $20, $ed, $a6, $14, $2e, $98, $37,
$2e, $ca, $db, $bd, $15, $53, $51, $c9,
$af, $c1, $8b, $17, $8f, $58, $4b, $82);
var
Context: THashContext;
Digest : TSHA512Digest;
function SingleTest(s: Str127; TDig: TSHA512Digest): 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}
SHA512Full(Digest, @s[1],length(s));
{Compare with known value}
if not HashSameDigest(@SHA512_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
{2. one update call for all chars}
SHA512Init(Context);
for i:=1 to length(s) do SHA512Update(Context,@s[i],1);
SHA512Final(Context,Digest);
{Compare with known value}
if not HashSameDigest(@SHA512_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
SingleTest := true;
end;
begin
SHA512SelfTest := false;
{1 Zero bit from NESSIE test vectors}
SHA512Init(Context);
SHA512FinalBits(Context,Digest,0,1);
if not HashSameDigest(@SHA512_Desc, PHashDigest(@Digest), PHashDigest(@D3)) then exit;
{4 hightest bits of $50, D4 calculated with program shatest from RFC 4634}
SHA512Init(Context);
SHA512FinalBits(Context,Digest,$50,4);
if not HashSameDigest(@SHA512_Desc, PHashDigest(@Digest), PHashDigest(@D4)) then exit;
{strings from SHA512 document}
SHA512SelfTest := SingleTest(s1, D1) and SingleTest(s2, D2)
end;
{---------------------------------------------------------------------------}
procedure SHA512FullXL(var Digest: TSHA512Digest; Msg: pointer; Len: longint);
{-SHA512 of Msg with init/update/final}
var
Context: THashContext;
begin
SHA512Init(Context);
SHA512UpdateXL(Context, Msg, Len);
SHA512Final(Context, Digest);
end;
{---------------------------------------------------------------------------}
procedure SHA512Full(var Digest: TSHA512Digest; Msg: pointer; Len: word);
{-SHA512 of Msg with init/update/final}
begin
SHA512FullXL(Digest, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA512File({$ifdef CONST} const {$endif} fname: string;
var Digest: TSHA512Digest; var buf; bsize: word; var Err: word);
{-SHA512 of file, buf: buffer with at least bsize bytes}
var
tmp: THashDigest;
begin
HashFile(fname, @SHA512_Desc, tmp, buf, bsize, Err);
move(tmp,Digest,sizeof(Digest));
end;
begin
{$ifdef VER5X}
fillchar(SHA512_Desc, sizeof(SHA512_Desc), 0);
with SHA512_Desc do begin
HSig := C_HashSig;
HDSize := sizeof(THashDesc);
HDVersion := C_HashVers;
HBlockLen := SHA512_BlockLen;
HDigestlen:= sizeof(TSHA512Digest);
HInit := SHA512Init;
HFinal := SHA512FinalEx;
HUpdateXL := SHA512UpdateXL;
HAlgNum := longint(_SHA512);
HName := 'SHA512';
HPtrOID := @SHA512_OID;
HLenOID := 9;
HFinalBit := SHA512FinalBitsEx;
end;
{$endif}
RegisterHash(_SHA512, @SHA512_Desc);
end.
|
unit IdThreadMgrPool;
interface
uses
Classes,
IdThread, IdThreadMgr;
type
TIdThreadMgrPool = class(TIdThreadMgr)
protected
FPoolSize: Integer;
FThreadPool: TList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetThread: TIdThread; override;
procedure ReleaseThread(AThread: TIdThread); override;
published
property PoolSize: Integer read FPoolSize write FPoolSize default 0;
end;
implementation
uses
IdGlobal, SysUtils;
constructor TIdThreadMgrPool.Create(AOwner: TComponent);
begin
inherited;
FThreadPool := TList.Create;
end;
destructor TIdThreadMgrPool.Destroy;
var
i: integer;
begin
PoolSize := 0;
Lock.Enter;
try
for i := 0 to FThreadPool.Count - 1 do
begin
TIdThread(FThreadPool[i]).Free;
end;
finally
Lock.Leave;
end;
FreeAndNil(FThreadPool);
inherited;
end;
function TIdThreadMgrPool.GetThread: TIdThread;
var
i: integer;
begin
Lock.Enter;
try
i := FThreadPool.Count - 1;
while (i > 0) and not (TIdThread(FThreadPool[i]).Suspended and
TIdThread(FThreadPool[i]).Stopped) do
begin
if TIdThread(FThreadPool[i]).Terminated then
begin
TIdThread(FThreadPool[i]).Free;
FThreadPool.Delete(i);
end;
Dec(i);
end;
if i >= 0 then
begin
Result := FThreadPool[i];
FThreadPool.Delete(i);
end
else
begin
Result := CreateNewThread;
Result.StopMode := smSuspend;
end;
ActiveThreads.Add(Result);
finally
Lock.Leave;
end;
end;
procedure TIdThreadMgrPool.ReleaseThread(AThread: TIdThread);
begin
Lock.Enter;
try
ActiveThreads.Remove(AThread);
if (FThreadPool.Count >= PoolSize) or AThread.Terminated then
begin
if IsCurrentThread(AThread) then
begin
AThread.FreeOnTerminate := True;
AThread.Terminate;
end
else
begin
AThread.TerminateAndWaitFor;
AThread.Free;
end;
end
else
begin
AThread.Stop;
FThreadPool.Add(AThread);
end;
finally Lock.Leave;
end;
end;
end.
|
(* Autor: Atanas Kerezov
Date: 5.11.2012
Description:
Program prints set of question and
expect aswer after each and save it
into file.
Version:
1.0 only two question: 'How do you do?, 'What are you doing?'
2.0 add writing answers in file and get time of answers
*)
program Homebot;
uses sysutils;
type
question_enum=(howdoyoudo,whatareyoudoing);
question = array [question_enum] of string;
answer = array [question_enum] of string;
const
db_filename = 'answers.db';
var
index: question_enum;
db: text;
questions:question = ('How do you do?', 'What are you doing?');
answers:question;
answers_times:array[question_enum] of AnsiString;
begin (* main *)
for index := howdoyoudo to whatareyoudoing do
begin
writeln (questions[index]);
readln (answers[index]);
answers_times[index] := DateTimeToStr(Now);
end;
writeln ('Your answers are: ');
for index := howdoyoudo to whatareyoudoing do
write(answers[index], ', ');
assign (db, db_filename);
append (db);
for index := howdoyoudo to whatareyoudoing do
writeln (db, answers_times[index], '\t', answers[index]);
close (db);
end. (* end main *)
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ 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/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclSysInfo.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ This unit contains routines and classes to retrieve various pieces of system information. }
{ Examples are the location of standard folders, settings of environment variables, processor }
{ details and the Windows version. }
{ }
{ Unit owner: Eric S. Fisher }
{ Last modified: March 11, 2002 }
{ }
{**************************************************************************************************}
unit JclSysInfo;
{$I jcl.inc}
interface
uses
Windows, ActiveX, Classes, ShlObj,
JclResources;
//--------------------------------------------------------------------------------------------------
// Environment Variables
//--------------------------------------------------------------------------------------------------
type
TEnvironmentOption = (eoLocalMachine, eoCurrentUser, eoAdditional);
TEnvironmentOptions = set of TEnvironmentOption;
function DelEnvironmentVar(const Name: string): Boolean;
function ExpandEnvironmentVar(var Value: string): Boolean;
function GetEnvironmentVar(const Name: string; var Value: string; Expand: Boolean): Boolean;
function GetEnvironmentVars(const Vars: TStrings; Expand: Boolean): Boolean;
function SetEnvironmentVar(const Name, Value: string): Boolean;
function CreateEnvironmentBlock(const Options: TEnvironmentOptions; const AdditionalVars: TStrings): PChar;
//--------------------------------------------------------------------------------------------------
// Common Folder Locations
//--------------------------------------------------------------------------------------------------
function GetCommonFilesFolder: string;
function GetCurrentFolder: string;
function GetProgramFilesFolder: string;
function GetWindowsFolder: string;
function GetWindowsSystemFolder: string;
function GetWindowsTempFolder: string;
function GetDesktopFolder: string;
function GetProgramsFolder: string;
function GetPersonalFolder: string;
function GetFavoritesFolder: string;
function GetStartupFolder: string;
function GetRecentFolder: string;
function GetSendToFolder: string;
function GetStartmenuFolder: string;
function GetDesktopDirectoryFolder: string;
function GetNethoodFolder: string;
function GetFontsFolder: string;
function GetCommonStartmenuFolder: string;
function GetCommonProgramsFolder: string;
function GetCommonStartupFolder: string;
function GetCommonDesktopdirectoryFolder: string;
function GetCommonAppdataFolder: string;
function GetAppdataFolder: string;
function GetPrinthoodFolder: string;
function GetCommonFavoritesFolder: string;
function GetTemplatesFolder: string;
function GetInternetCacheFolder: string;
function GetCookiesFolder: string;
function GetHistoryFolder: string;
//--------------------------------------------------------------------------------------------------
// Advanced Power Management (APM)
//--------------------------------------------------------------------------------------------------
type
TAPMLineStatus = (alsOffline, alsOnline, alsUnknown);
TAPMBatteryFlag = (abfHigh, abfLow, abfCritical, abfCharging, abfNoBattery, abfUnknown);
function GetAPMLineStatus: TAPMLineStatus;
function GetAPMBatteryFlag: TAPMBatteryFlag;
function GetAPMBatteryLifePercent: Integer;
function GetAPMBatteryLifeTime: DWORD;
function GetAPMBatteryFullLifeTime: DWORD;
//--------------------------------------------------------------------------------------------------
// Identification
//--------------------------------------------------------------------------------------------------
function GetVolumeName(const Drive: string): string;
function GetVolumeSerialNumber(const Drive: string): string;
function GetVolumeFileSystem(const Drive: string): string;
function GetIPAddress(const HostName: string): string;
function GetLocalComputerName: string;
function GetLocalUserName: string;
function GetUserDomainName(const CurUser: string): string;
function GetDomainName: string;
function GetRegisteredCompany: string;
function GetRegisteredOwner: string;
function GetBIOSName: string;
function GetBIOSCopyright: string;
function GetBIOSExtendedInfo: string;
function GetBIOSDate: TDateTime;
//--------------------------------------------------------------------------------------------------
// Processes, Tasks and Modules
//--------------------------------------------------------------------------------------------------
type
TJclTerminateAppResult = (taError, taClean, taKill);
function RunningProcessesList(const List: TStrings; FullPath: Boolean = True): Boolean;
function LoadedModulesList(const List: TStrings; ProcessID: DWORD; HandlesOnly: Boolean = False): Boolean;
function GetTasksList(const List: TStrings): Boolean;
function ModuleFromAddr(const Addr: Pointer): HMODULE;
function IsSystemModule(const Module: HMODULE): Boolean;
function IsMainAppWindow(Wnd: HWND): Boolean;
function IsWindowResponding(Wnd: HWND; Timeout: Integer): Boolean;
function GetWindowIcon(Wnd: HWND; LargeIcon: Boolean): HICON;
function GetWindowCaption(Wnd: HWND): string;
function TerminateTask(Wnd: HWND; Timeout: Integer): TJclTerminateAppResult;
function TerminateApp(ProcessID: DWORD; Timeout: Integer): TJclTerminateAppResult;
function GetPidFromProcessName(const ProcessName: string): DWORD;
function GetProcessNameFromWnd(Wnd: HWND): string;
function GetProcessNameFromPid(PID: DWORD): string;
function GetMainAppWndFromPid(PID: DWORD): HWND;
function GetShellProcessName: string;
function GetShellProcessHandle: THandle;
//--------------------------------------------------------------------------------------------------
// Version Information
//--------------------------------------------------------------------------------------------------
// TODOC Added wvWinNT351, wvWinNT35, IsWinNT351 and changed wvWinNT3 to wvWinNT31
type
TWindowsVersion = (wvUnknown, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE,
wvWinME, wvWinNT31, wvWinNT35, wvWinNT351, wvWinNT4, wvWin2000, wvWinXP);
TNtProductType = (ptUnknown, ptWorkStation, ptServer, ptAdvancedServer,
ptPersonal, ptProfessional, ptDatacenterServer);
{ TODOC
Added to TNtProductType (by Jean-Fabien Connault):
ptPersonal Windows XP Personal
ptProfessional Windows 2000/XP Proffesional
ptDatacenterServer Windows 2000 DataCenter server
}
var
{ in case of additions, don't forget to update initialization section! }
IsWin95: Boolean = False;
IsWin95OSR2: Boolean = False;
IsWin98: Boolean = False;
IsWin98SE: Boolean = False;
IsWinME: Boolean = False;
IsWinNT: Boolean = False;
IsWinNT3: Boolean = False;
IsWinNT31: Boolean = False;
IsWinNT35: Boolean = False;
IsWinNT351: Boolean = False;
IsWinNT4: Boolean = False;
IsWin2K: Boolean = False;
IsWinXP: Boolean = False;
function GetWindowsVersion: TWindowsVersion;
function NtProductType: TNtProductType;
// TODOC
function GetWindowsVersionString: string;
{
ShortDescr: Returns the windows version as a string.
Descr: GetWindowsVersion returns the operating system as a string. For example, 'Windows 2000'.
Result: The windows version as a string or an empty string if the OS is not recognized.
Author: Jean-Fabien Connault
}
function NtProductTypeString: string;
{
ShortDescr: Returns the Windows NT product type as a string.
Descr: NtProductTypeString returns the NT product type as a string. For example 'Workstation'.
Result: The NT product type as a string or an empty string if the product type is not recognized.
Author: Jean-Fabien Connault
}
function GetWindowsServicePackVersion: Integer;
{
ShortDescr: Returns the installed service pack
Descr: Returns the major version number of the latest installed Windows Service Pack.
Result: The major version number of the latest installed Service Pack. In case of failure, or it
no Service Pack is installed, the function returns 0.
Author: Jean-Fabien Connault
}
function GetWindowsServicePackVersionString: string;
{
ShortDescr: Returns the installed service pack as a string
Descr: Returns the major version number of the latest installed Windows Service Pack.
Result: The major version number of the latest installed Service Pack. In case of failure, or if
no Service Pack is installed, the function returns an empty string.
Author: Jean-Fabien Connault
}
//--------------------------------------------------------------------------------------------------
// Hardware
//--------------------------------------------------------------------------------------------------
function GetMacAddresses(const Machine: string; const Addresses: TStrings): Integer;
function ReadTimeStampCounter: Int64;
type
TIntelSpecific = record
L2Cache: Cardinal;
CacheDescriptors: array [0..15] of Byte;
BrandID : Byte;
end;
TCyrixSpecific = record
L1CacheInfo: array [0..3] of Byte;
TLBInfo: array [0..3] of Byte;
end;
TAMDSpecific = record
DataTLB: array [0..1] of Byte;
InstructionTLB: array [0..1] of Byte;
L1DataCache: array [0..3] of Byte;
L1ICache: array [0..3] of Byte;
end;
TCacheInfo = record
D: Byte;
I: string;
end;
TFreqInfo = record
RawFreq: Cardinal;
NormFreq: Cardinal;
InCycles: Cardinal;
ExTicks: Cardinal;
end;
TCpuInfo = record
HasInstruction: Boolean;
MMX: Boolean;
IsFDIVOK: Boolean;
HasCacheInfo: Boolean;
HasExtendedInfo: Boolean;
CpuType: Byte;
PType: Byte;
Family: Byte;
Model: Byte;
Stepping: Byte;
Features: Cardinal;
FrequencyInfo: TFreqInfo;
VendorIDString: array [0..11] of Char;
Manufacturer: array [0..9] of Char;
CpuName: array [0..47] of Char;
IntelSpecific: TIntelSpecific;
CyrixSpecific: TCyrixSpecific;
AMDSpecific: TAMDSpecific;
end;
const
CPU_TYPE_INTEL = 1;
CPU_TYPE_CYRIX = 2;
CPU_TYPE_AMD = 3;
CPU_TYPE_CRUSOE = 4;
// Constants to be used with Feature Flag set of a CPU
// eg. IF (Features and FPU_FLAG = FPU_FLAG) THEN CPU has Floating-Point unit on
// chip. However, Intel claims that in future models, a zero in the feature
// flags will mean that the chip has that feature, however, the following flags
// will work for any production 80x86 chip or clone.
// eg. IF (Features and FPU_FLAG = 0) then CPU has Floating-Point unit on chip.
const
{ Standard (Intel) Feature Flags }
FPU_FLAG = $00000001; // Floating-Point unit on chip
VME_FLAG = $00000002; // Virtual Mode Extention
DE_FLAG = $00000004; // Debugging Extention
PSE_FLAG = $00000008; // Page Size Extention
TSC_FLAG = $00000010; // Time Stamp Counter
MSR_FLAG = $00000020; // Model Specific Registers
PAE_FLAG = $00000040; // Physical Address Extention
MCE_FLAG = $00000080; // Machine Check Exception
CX8_FLAG = $00000100; // CMPXCHG8 Instruction
APIC_FLAG = $00000200; // Software-accessible local APIC on Chip
BIT_10 = $00000400; // Reserved, do not count on value
SEP_FLAG = $00000800; // Fast System Call
MTRR_FLAG = $00001000; // Memory Type Range Registers
PGE_FLAG = $00002000; // Page Global Enable
MCA_FLAG = $00004000; // Machine Check Architecture
CMOV_FLAG = $00008000; // Conditional Move Instruction
PAT_FLAG = $00010000; // Page Attribute Table
PSE36_FLAG = $00020000; // 36-bit Page Size Extention
BIT_18 = $00040000; // Reserved, do not count on value
BIT_19 = $00080000; // Reserved, do not count on value
BIT_20 = $00100000; // Reserved, do not count on value
BIT_21 = $00200000; // Reserved, do not count on value
BIT_22 = $00400000; // Reserved, do not count on value
MMX_FLAG = $00800000; // MMX technology
FXSR_FLAG = $01000000; // Fast Floating Point Save and Restore
BIT_25 = $02000000; // Reserved, do not count on value
BIT_26 = $04000000; // Reserved, do not count on value
BIT_27 = $08000000; // Reserved, do not count on value
BIT_28 = $10000000; // Reserved, do not count on value
BIT_29 = $20000000; // Reserved, do not count on value
BIT_30 = $40000000; // Reserved, do not count on value
BIT_31 = DWORD($80000000); // Reserved, do not count on value
{ AMD Standard Feature Flags }
AMD_FPU_FLAG = $00000001; // Floating-Point unit on chip
AMD_VME_FLAG = $00000002; // Virtual Mode Extention
AMD_DE_FLAG = $00000004; // Debugging Extention
AMD_PSE_FLAG = $00000008; // Page Size Extention
AMD_TSC_FLAG = $00000010; // Time Stamp Counter
AMD_MSR_FLAG = $00000020; // Model Specific Registers
AMD_BIT_6 = $00000040; // Reserved, do not count on value
AMD_MCE_FLAG = $00000080; // Machine Check Exception
AMD_CX8_FLAG = $00000100; // CMPXCHG8 Instruction
AMD_APIC_FLAG = $00000200; // Software-accessible local APIC on Chip
AMD_BIT_10 = $00000400; // Reserved, do not count on value
AMD_BIT_11 = $00000800; // Reserved, do not count on value
AMD_MTRR_FLAG = $00001000; // Memory Type Range Registers
AMD_PGE_FLAG = $00002000; // Page Global Enable
AMD_BIT_14 = $00004000; // Reserved, do not count on value
AMD_CMOV_FLAG = $00008000; // Conditional Move Instruction
AMD_BIT_16 = $00010000; // Reserved, do not count on value
AMD_BIT_17 = $00020000; // Reserved, do not count on value
AMD_BIT_18 = $00040000; // Reserved, do not count on value
AMD_BIT_19 = $00080000; // Reserved, do not count on value
AMD_BIT_20 = $00100000; // Reserved, do not count on value
AMD_BIT_21 = $00200000; // Reserved, do not count on value
AMD_BIT_22 = $00400000; // Reserved, do not count on value
AMD_MMX_FLAG = $00800000; // MMX technology
AMD_BIT_24 = $01000000; // Reserved, do not count on value
AMD_BIT_25 = $02000000; // Reserved, do not count on value
AMD_BIT_26 = $04000000; // Reserved, do not count on value
AMD_BIT_27 = $08000000; // Reserved, do not count on value
AMD_BIT_28 = $10000000; // Reserved, do not count on value
AMD_BIT_29 = $20000000; // Reserved, do not count on value
AMD_BIT_30 = $40000000; // Reserved, do not count on value
AMD_BIT_31 = DWORD($80000000); // Reserved, do not count on value
{ AMD Enhanced Feature Flags }
EAMD_FPU_FLAG = $00000001; // Floating-Point unit on chip
EAMD_VME_FLAG = $00000002; // Virtual Mode Extention
EAMD_DE_FLAG = $00000004; // Debugging Extention
EAMD_PSE_FLAG = $00000008; // Page Size Extention
EAMD_TSC_FLAG = $00000010; // Time Stamp Counter
EAMD_MSR_FLAG = $00000020; // Model Specific Registers
EAMD_BIT_6 = $00000040; // Reserved, do not count on value
EAMD_MCE_FLAG = $00000080; // Machine Check Exception
EAMD_CX8_FLAG = $00000100; // CMPXCHG8 Instruction
EAMD_BIT_9 = $00000200; // Reserved, do not count on value
EAMD_BIT_10 = $00000400; // Reserved, do not count on value
EAMD_SEP_FLAG = $00000800; // Fast System Call
EAMD_BIT_12 = $00001000; // Reserved, do not count on value
EAMD_PGE_FLAG = $00002000; // Page Global Enable
EAMD_BIT_14 = $00004000; // Reserved, do not count on value
EAMD_ICMOV_FLAG = $00008000; // Integer Conditional Move Instruction
EAMD_FCMOV_FLAG = $00010000; // Floating Point Conditional Move Instruction
EAMD_BIT_17 = $00020000; // Reserved, do not count on value
EAMD_BIT_18 = $00040000; // Reserved, do not count on value
EAMD_BIT_19 = $00080000; // Reserved, do not count on value
EAMD_BIT_20 = $00100000; // Reserved, do not count on value
EAMD_BIT_21 = $00200000; // Reserved, do not count on value
EAMD_BIT_22 = $00400000; // Reserved, do not count on value
EAMD_MMX_FLAG = $00800000; // MMX technology
EAMD_BIT_24 = $01000000; // Reserved, do not count on value
EAMD_BIT_25 = $02000000; // Reserved, do not count on value
EAMD_BIT_26 = $04000000; // Reserved, do not count on value
EAMD_BIT_27 = $08000000; // Reserved, do not count on value
EAMD_BIT_28 = $10000000; // Reserved, do not count on value
EAMD_BIT_29 = $20000000; // Reserved, do not count on value
EAMD_BIT_30 = $40000000; // Reserved, do not count on value
EAMD_3DNOW_FLAG = DWORD($80000000); // AMD 3DNOW! Technology
{ Cyrix Standard Feature Flags }
CYRIX_FPU_FLAG = $00000001; // Floating-Point unit on chip
CYRIX_VME_FLAG = $00000002; // Virtual Mode Extention
CYRIX_DE_FLAG = $00000004; // Debugging Extention
CYRIX_PSE_FLAG = $00000008; // Page Size Extention
CYRIX_TSC_FLAG = $00000010; // Time Stamp Counter
CYRIX_MSR_FLAG = $00000020; // Model Specific Registers
CYRIX_PAE_FLAG = $00000040; // Physical Address Extention
CYRIX_MCE_FLAG = $00000080; // Machine Check Exception
CYRIX_CX8_FLAG = $00000100; // CMPXCHG8 Instruction
CYRIX_APIC_FLAG = $00000200; // Software-accessible local APIC on Chip
CYRIX_BIT_10 = $00000400; // Reserved, do not count on value
CYRIX_BIT_11 = $00000800; // Reserved, do not count on value
CYRIX_MTRR_FLAG = $00001000; // Memory Type Range Registers
CYRIX_PGE_FLAG = $00002000; // Page Global Enable
CYRIX_MCA_FLAG = $00004000; // Machine Check Architecture
CYRIX_CMOV_FLAG = $00008000; // Conditional Move Instruction
CYRIX_BIT_16 = $00010000; // Reserved, do not count on value
CYRIX_BIT_17 = $00020000; // Reserved, do not count on value
CYRIX_BIT_18 = $00040000; // Reserved, do not count on value
CYRIX_BIT_19 = $00080000; // Reserved, do not count on value
CYRIX_BIT_20 = $00100000; // Reserved, do not count on value
CYRIX_BIT_21 = $00200000; // Reserved, do not count on value
CYRIX_BIT_22 = $00400000; // Reserved, do not count on value
CYRIX_MMX_FLAG = $00800000; // MMX technology
CYRIX_BIT_24 = $01000000; // Reserved, do not count on value
CYRIX_BIT_25 = $02000000; // Reserved, do not count on value
CYRIX_BIT_26 = $04000000; // Reserved, do not count on value
CYRIX_BIT_27 = $08000000; // Reserved, do not count on value
CYRIX_BIT_28 = $10000000; // Reserved, do not count on value
CYRIX_BIT_29 = $20000000; // Reserved, do not count on value
CYRIX_BIT_30 = $40000000; // Reserved, do not count on value
CYRIX_BIT_31 = DWORD($80000000); // Reserved, do not count on value
{ Cyrix Enhanced Feature Flags }
ECYRIX_FPU_FLAG = $00000001; // Floating-Point unit on chip
ECYRIX_VME_FLAG = $00000002; // Virtual Mode Extention
ECYRIX_DE_FLAG = $00000004; // Debugging Extention
ECYRIX_PSE_FLAG = $00000008; // Page Size Extention
ECYRIX_TSC_FLAG = $00000010; // Time Stamp Counter
ECYRIX_MSR_FLAG = $00000020; // Model Specific Registers
ECYRIX_PAE_FLAG = $00000040; // Physical Address Extention
ECYRIX_MCE_FLAG = $00000080; // Machine Check Exception
ECYRIX_CX8_FLAG = $00000100; // CMPXCHG8 Instruction
ECYRIX_APIC_FLAG = $00000200; // Software-accessible local APIC on Chip
ECYRIX_SEP_FLAG = $00000400; // Fast System Call
ECYRIX_BIT_11 = $00000800; // Reserved, do not count on value
ECYRIX_MTRR_FLAG = $00001000; // Memory Type Range Registers
ECYRIX_PGE_FLAG = $00002000; // Page Global Enable
ECYRIX_MCA_FLAG = $00004000; // Machine Check Architecture
ECYRIX_ICMOV_FLAG = $00008000; // Integer Conditional Move Instruction
ECYRIX_FCMOV_FLAG = $00010000; // Floating Point Conditional Move Instruction
ECYRIX_BIT_17 = $00020000; // Reserved, do not count on value
ECYRIX_BIT_18 = $00040000; // Reserved, do not count on value
ECYRIX_BIT_19 = $00080000; // Reserved, do not count on value
ECYRIX_BIT_20 = $00100000; // Reserved, do not count on value
ECYRIX_BIT_21 = $00200000; // Reserved, do not count on value
ECYRIX_BIT_22 = $00400000; // Reserved, do not count on value
ECYRIX_MMX_FLAG = $00800000; // MMX technology
ECYRIX_EMMX_FLAG = $01000000; // Extended MMX Technology
ECYRIX_BIT_25 = $02000000; // Reserved, do not count on value
ECYRIX_BIT_26 = $04000000; // Reserved, do not count on value
ECYRIX_BIT_27 = $08000000; // Reserved, do not count on value
ECYRIX_BIT_28 = $10000000; // Reserved, do not count on value
ECYRIX_BIT_29 = $20000000; // Reserved, do not count on value
ECYRIX_BIT_30 = $40000000; // Reserved, do not count on value
ECYRIX_BIT_31 = DWORD($80000000); // Reserved, do not count on value
const
IntelCacheDescription: array [0..13] of TCacheInfo = (
(D: $01; I: RsIntelCacheDescr01),
(D: $02; I: RsIntelCacheDescr02),
(D: $03; I: RsIntelCacheDescr03),
(D: $04; I: RsIntelCacheDescr04),
(D: $06; I: RsIntelCacheDescr06),
(D: $08; I: RsIntelCacheDescr08),
(D: $0A; I: RsIntelCacheDescr0A),
(D: $0C; I: RsIntelCacheDescr0C),
(D: $40; I: RsIntelCacheDescr40),
(D: $41; I: RsIntelCacheDescr41),
(D: $42; I: RsIntelCacheDescr42),
(D: $43; I: RsIntelCacheDescr43),
(D: $44; I: RsIntelCacheDescr44),
(D: $45; I: RsIntelCacheDescr45));
procedure GetCpuInfo(var CpuInfo: TCpuInfo);
function GetIntelCacheDescription(const D: Byte): string;
function RoundFrequency(const Frequency: Integer): Integer;
function GetCPUSpeed(var CpuSpeed: TFreqInfo): Boolean;
function CPUID: TCpuInfo;
function TestFDIVInstruction: Boolean;
//--------------------------------------------------------------------------------------------------
// Memory Information
//--------------------------------------------------------------------------------------------------
function GetMaxAppAddress: Integer;
function GetMinAppAddress: Integer;
function GetMemoryLoad: Byte;
function GetSwapFileSize: Integer;
function GetSwapFileUsage: Integer;
function GetTotalPhysicalMemory: Integer;
function GetFreePhysicalMemory: Integer;
function GetTotalPageFileMemory: Integer;
function GetFreePageFileMemory: Integer;
function GetTotalVirtualMemory: Integer;
function GetFreeVirtualMemory: Integer;
//--------------------------------------------------------------------------------------------------
// Alloc granularity
//--------------------------------------------------------------------------------------------------
procedure RoundToAllocGranularity64(var Value: Int64; Up: Boolean);
procedure RoundToAllocGranularityPtr(var Value: Pointer; Up: Boolean);
//--------------------------------------------------------------------------------------------------
// Keyboard Information
//--------------------------------------------------------------------------------------------------
function GetKeyState(const VirtualKey: Cardinal): Boolean;
function GetNumLockKeyState: Boolean;
function GetScrollLockKeyState: Boolean;
function GetCapsLockKeyState: Boolean;
//--------------------------------------------------------------------------------------------------
// Windows 95/98/Me system resources information
//--------------------------------------------------------------------------------------------------
type
TFreeSysResKind = (rtSystem, rtGdi, rtUser);
TFreeSystemResources = record
SystemRes, GdiRes, UserRes: Integer;
end;
function IsSystemResourcesMeterPresent: Boolean;
function GetFreeSystemResources(const ResourceType: TFreeSysResKind): Integer; overload;
function GetFreeSystemResources: TFreeSystemResources; overload;
//--------------------------------------------------------------------------------------------------
// Public global variables
//--------------------------------------------------------------------------------------------------
var
ProcessorCount: Cardinal = 0;
AllocGranularity: Cardinal = 0;
PageSize: Cardinal = 0;
implementation
uses
Messages, SysUtils, TLHelp32, PsApi, Winsock,
{$IFNDEF DELPHI5_UP}
JclSysUtils,
{$ENDIF DELPHI5_UP}
JclBase, JclFileUtils, JclRegistry, JclShell, JclStrings, JclWin32;
//==================================================================================================
// Environment
//==================================================================================================
function DelEnvironmentVar(const Name: string): Boolean;
begin
Result := SetEnvironmentVariable(PChar(Name), nil);
end;
//--------------------------------------------------------------------------------------------------
function ExpandEnvironmentVar(var Value: string): Boolean;
var
R: Integer;
Expanded: string;
begin
R := ExpandEnvironmentStrings(PChar(Value), nil, 0);
SetLength(Expanded, R);
Result := ExpandEnvironmentStrings(PChar(Value), PChar(Expanded), R) <> 0;
if Result then
begin
StrResetLength(Expanded);
Value := Expanded;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetEnvironmentVar(const Name: string; var Value: string; Expand: Boolean): Boolean;
var
R: DWORD;
begin
R := GetEnvironmentVariable(PChar(Name), nil, 0);
SetLength(Value, R);
R := GetEnvironmentVariable(PChar(Name), PChar(Value), R);
Result := R <> 0;
if not Result then
Value := ''
else
begin
SetLength(Value, R);
if Expand then
ExpandEnvironmentVar(Value);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetEnvironmentVars(const Vars: TStrings; Expand: Boolean): Boolean;
var
Raw: PChar;
Expanded: string;
I: Integer;
begin
Vars.Clear;
Raw := GetEnvironmentStrings;
try
MultiSzToStrings(Vars, Raw);
Result := True;
finally
FreeEnvironmentStrings(Raw);
end;
if Expand then
begin
for I := 0 to Vars.Count - 1 do
begin
Expanded := Vars[I];
if ExpandEnvironmentVar(Expanded) then
Vars[I] := Expanded;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function SetEnvironmentVar(const Name, Value: string): Boolean;
begin
Result := SetEnvironmentVariable(PChar(Name), PChar(Value));
end;
//--------------------------------------------------------------------------------------------------
function CreateEnvironmentBlock(const Options: TEnvironmentOptions; const AdditionalVars: TStrings): PChar;
const
RegLocalEnvironment = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment';
RegUserEnvironment = '\Environment\';
var
KeyNames, TempList: TStrings;
Temp, Name, Value: string;
I: Integer;
begin
TempList := TStringList.Create;
try
// add additional environment variables
if eoAdditional in Options then
for I := 0 to AdditionalVars.Count - 1 do
begin
Temp := AdditionalVars[I];
ExpandEnvironmentVar(Temp);
TempList.Add(Temp);
end;
// get environment strings from local machine
if eoLocalMachine in Options then
begin
KeyNames := TStringList.Create;
try
if RegGetValueNames(HKEY_LOCAL_MACHINE, RegLocalEnvironment, KeyNames) then
begin
for I := 0 to KeyNames.Count - 1 do
begin
Name := KeyNames[I];
Value := RegReadString(HKEY_LOCAL_MACHINE, RegLocalEnvironment, Name);
ExpandEnvironmentVar(Value);
TempList.Add(Name + '=' + Value);
end;
end;
finally
FreeAndNil(KeyNames);
end;
end;
// get environment strings from current user
if eoCurrentUser in Options then
begin
KeyNames := TStringLIst.Create;
try
if RegGetValueNames(HKEY_CURRENT_USER, RegUserEnvironment, KeyNames) then
begin
for I := 0 to KeyNames.Count - 1 do
begin
Name := KeyNames[I];
Value := RegReadString(HKEY_CURRENT_USER, RegUserEnvironment, Name);
ExpandEnvironmentVar(Value);
TempList.Add(Name + '=' + Value);
end;
end;
finally
KeyNames.Free;
end;
end;
// transform stringlist into multi-PChar
StringsToMultiSz(Result, TempList);
finally
FreeAndNil(TempList);
end;
end;
//==================================================================================================
// Common Folders
//==================================================================================================
// Utility function which returns the Windows independent CurrentVersion key
// inside HKEY_LOCAL_MACHINE
const
HKLM_CURRENT_VERSION_WINDOWS = 'Software\Microsoft\Windows\CurrentVersion';
HKLM_CURRENT_VERSION_NT = 'Software\Microsoft\Windows NT\CurrentVersion';
function REG_CURRENT_VERSION: string;
begin
if IsWinNT then
Result := HKLM_CURRENT_VERSION_NT
else
Result := HKLM_CURRENT_VERSION_WINDOWS;
end;
//--------------------------------------------------------------------------------------------------
function GetCommonFilesFolder: string;
begin
Result := RegReadStringDef(HKEY_LOCAL_MACHINE, HKLM_CURRENT_VERSION_WINDOWS,
'CommonFilesDir', '');
end;
//--------------------------------------------------------------------------------------------------
function GetCurrentFolder: string;
var
Required: Cardinal;
begin
Result := '';
Required := GetCurrentDirectory(0, nil);
if Required <> 0 then
begin
SetLength(Result, Required);
GetCurrentDirectory(Required, PChar(Result));
StrResetLength(Result);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetProgramFilesFolder: string;
begin
Result := RegReadStringDef(HKEY_LOCAL_MACHINE, HKLM_CURRENT_VERSION_WINDOWS, 'ProgramFilesDir', '');
end;
//--------------------------------------------------------------------------------------------------
function GetWindowsFolder: string;
var
Required: Cardinal;
begin
Result := '';
Required := GetWindowsDirectory(nil, 0);
if Required <> 0 then
begin
SetLength(Result, Required);
GetWindowsDirectory(PChar(Result), Required);
StrResetLength(Result);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetWindowsSystemFolder: string;
var
Required: Cardinal;
begin
Result := '';
Required := GetSystemDirectory(nil, 0);
if Required <> 0 then
begin
SetLength(Result, Required);
GetSystemDirectory(PChar(Result), Required);
StrResetLength(Result);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetWindowsTempFolder: string;
var
Required: Cardinal;
begin
Result := '';
Required := GetTempPath(0, nil);
if Required <> 0 then
begin
SetLength(Result, Required);
GetTempPath(Required, PChar(Result));
StrResetLength(Result);
Result := PathRemoveSeparator(Result);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetDesktopFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_DESKTOP);
end;
//--------------------------------------------------------------------------------------------------
function GetProgramsFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_PROGRAMS);
end;
//--------------------------------------------------------------------------------------------------
function GetPersonalFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_PERSONAL);
end;
//--------------------------------------------------------------------------------------------------
function GetFavoritesFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_FAVORITES);
end;
//--------------------------------------------------------------------------------------------------
function GetStartupFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_STARTUP);
end;
//--------------------------------------------------------------------------------------------------
function GetRecentFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_RECENT);
end;
//--------------------------------------------------------------------------------------------------
function GetSendToFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_SENDTO);
end;
//--------------------------------------------------------------------------------------------------
function GetStartmenuFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_STARTMENU);
end;
//--------------------------------------------------------------------------------------------------
function GetDesktopDirectoryFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_DESKTOPDIRECTORY);
end;
//--------------------------------------------------------------------------------------------------
function GetNethoodFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_NETHOOD);
end;
//--------------------------------------------------------------------------------------------------
function GetFontsFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_FONTS);
end;
//--------------------------------------------------------------------------------------------------
function GetCommonStartmenuFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COMMON_STARTMENU);
end;
//--------------------------------------------------------------------------------------------------
function GetCommonProgramsFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COMMON_PROGRAMS);
end;
//--------------------------------------------------------------------------------------------------
function GetCommonStartupFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COMMON_STARTUP);
end;
//--------------------------------------------------------------------------------------------------
function GetCommonDesktopdirectoryFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COMMON_DESKTOPDIRECTORY);
end;
//--------------------------------------------------------------------------------------------------
// TODOC
// From: Jean-Fabien Connault
// Descr: Application data for all users. A typical path is C:\Documents and Settings\All Users\Application Data.
// Note: requires shell v 5.00 up
function GetCommonAppdataFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COMMON_APPDATA);
end;
//--------------------------------------------------------------------------------------------------
function GetAppdataFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_APPDATA);
end;
//--------------------------------------------------------------------------------------------------
function GetPrinthoodFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_PRINTHOOD);
end;
//--------------------------------------------------------------------------------------------------
function GetCommonFavoritesFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COMMON_FAVORITES);
end;
//--------------------------------------------------------------------------------------------------
function GetTemplatesFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_TEMPLATES);
end;
//--------------------------------------------------------------------------------------------------
function GetInternetCacheFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_INTERNET_CACHE);
end;
//--------------------------------------------------------------------------------------------------
function GetCookiesFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_COOKIES);
end;
//--------------------------------------------------------------------------------------------------
function GetHistoryFolder: string;
begin
Result := GetSpecialFolderLocation(CSIDL_HISTORY);
end;
// the following special folders are pure virtual and cannot be
// mapped to a directory path:
// CSIDL_INTERNET
// CSIDL_CONTROLS
// CSIDL_PRINTERS
// CSIDL_BITBUCKET
// CSIDL_DRIVES
// CSIDL_NETWORK
// CSIDL_ALTSTARTUP
// CSIDL_COMMON_ALTSTARTUP
//==================================================================================================
// Identification
//==================================================================================================
type
TVolumeInfoKind = (vikName, vikSerial, vikFileSystem);
function GetVolumeInfoHelper(const Drive: string; InfoKind: TVolumeInfoKind): string;
var
VolumeSerialNumber: DWORD;
MaximumComponentLength: DWORD;
Flags: DWORD;
Name: array [0..MAX_PATH] of Char;
FileSystem: array [0..15] of Char;
ErrorMode: Cardinal;
DriveStr: string;
begin
// TODO Perform better checking of Drive param or document that no checking is
// performed. RM Suggested:
// DriveStr := Drive;
// if (Length(Drive) < 2) or (Drive[2] <> ':') then
// DriveStr := GetCurrentFolder;
// DriveStr := DriveStr[1] + ':\';
Result := '';
DriveStr := Drive + ':\';
ErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
if GetVolumeInformation(PChar(DriveStr), Name, SizeOf(Name), @VolumeSerialNumber,
MaximumComponentLength, Flags, FileSystem, SizeOf(FileSystem)) then
case InfoKind of
vikName:
Result := StrPas(Name);
vikSerial:
begin
Result := IntToHex(HiWord(VolumeSerialNumber), 4) + '-' +
IntToHex(LoWord(VolumeSerialNumber), 4);
end;
vikFileSystem:
Result := StrPas(FileSystem);
end;
finally
SetErrorMode(ErrorMode);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetVolumeName(const Drive: string): string;
begin
Result := GetVolumeInfoHelper(Drive, vikName);
end;
//--------------------------------------------------------------------------------------------------
function GetVolumeSerialNumber(const Drive: string): string;
begin
Result := GetVolumeInfoHelper(Drive, vikSerial);
end;
//--------------------------------------------------------------------------------------------------
function GetVolumeFileSystem(const Drive: string): string;
begin
Result := GetVolumeInfoHelper(Drive, vikFileSystem);
end;
//--------------------------------------------------------------------------------------------------
function GetIPAddress(const HostName: string): string;
var
R: Integer;
WSAData: TWSAData;
HostEnt: PHostEnt;
Host: string;
SockAddr: TSockAddrIn;
begin
Result := '';
R := WSAStartup(MakeWord(1, 1), WSAData);
if R = 0 then
try
Host := HostName;
if Host = '' then
begin
SetLength(Host, MAX_PATH);
GetHostName(PChar(Host), MAX_PATH);
end;
HostEnt := GetHostByName(PChar(Host));
if HostEnt <> nil then
begin
SockAddr.sin_addr.S_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
Result := inet_ntoa(SockAddr.sin_addr);
end;
finally
WSACleanup;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetLocalComputerName: string;
var
Count: DWORD;
begin
Count := MAX_COMPUTERNAME_LENGTH + 1;
// set buffer size to MAX_COMPUTERNAME_LENGTH + 2 characters for safety
SetLength(Result, Count);
Win32Check(GetComputerName(PChar(Result), Count));
StrResetLength(Result);
end;
//--------------------------------------------------------------------------------------------------
function GetLocalUserName: string;
var
Count: DWORD;
begin
Count := 256 + 1; // UNLEN + 1
// set buffer size to 256 + 2 characters
SetLength(Result, Count);
Win32Check(GetUserName(PChar(Result), Count));
StrResetLength(Result);
end;
//--------------------------------------------------------------------------------------------------
function GetRegisteredCompany: string;
begin
Result := RegReadStringDef(HKEY_LOCAL_MACHINE, REG_CURRENT_VERSION, 'RegisteredOrganization', '');
end;
//--------------------------------------------------------------------------------------------------
function GetRegisteredOwner: string;
begin
Result := RegReadStringDef(HKEY_LOCAL_MACHINE, REG_CURRENT_VERSION, 'RegisteredOwner', '');
end;
//--------------------------------------------------------------------------------------------------
function GetUserDomainName(const CurUser: string): string;
var
Count1, Count2: DWORD;
Sd: PSecurityDescriptor;
Snu: SID_Name_Use;
begin
Count1 := 0;
Count2 := 0;
Sd := nil;
Snu := SIDTypeUser;
LookUpAccountName(nil, PChar(CurUser), Sd, Count1, PChar(Result), Count2, Snu);
// set buffer size to Count2 + 2 characters for safety
SetLength(Result, Count2 + 1);
Sd := AllocMem(Count1);
try
if LookUpAccountName(nil, PChar(CurUser), Sd, Count1, PChar(Result), Count2, Snu) then
StrResetLength(Result)
else
Result := EmptyStr;
finally
FreeMem(Sd);
end;
end;
//--------------------------------------------------------------------------------------------------
function GetDomainName: string;
begin
Result := GetUserDomainName(GetLocalUserName);
end;
//--------------------------------------------------------------------------------------------------
function GetBIOSName: string;
const
ADR_BIOSNAME = $FE061;
begin
try
Result := string(PChar(Ptr(ADR_BIOSNAME)));
except
Result := '';
end;
end;
//--------------------------------------------------------------------------------------------------
function GetBIOSCopyright: string;
const
ADR_BIOSCOPYRIGHT = $FE091;
begin
try
Result := string(PChar(Ptr(ADR_BIOSCOPYRIGHT)));
except
Result := '';
end;
end;
//--------------------------------------------------------------------------------------------------
function GetBIOSExtendedInfo: string;
const
ADR_BIOSEXTENDEDINFO = $FEC71;
begin
try
Result := string(PChar(Ptr(ADR_BIOSEXTENDEDINFO)));
except
Result := '';
end;
end;
//--------------------------------------------------------------------------------------------------
function GetBIOSDate : TDateTime;
const
REGSTR_PATH_SYSTEM = '\HARDWARE\DESCRIPTION\System';
REGSTR_SYSTEMBIOSDATE = 'SystemBiosDate';
var
RegStr, RegFormat: string;
RegSeparator: Char;
begin
Result := 0;
RegStr := RegReadString(HKEY_LOCAL_MACHINE, REGSTR_PATH_SYSTEM, REGSTR_SYSTEMBIOSDATE);
RegFormat := ShortDateFormat;
RegSeparator := DateSeparator;
try
DateSeparator := '/';
try
ShortDateFormat := 'm/d/y';
Result := StrToDate(RegStr);
except
try
ShortDateFormat := 'y/m/d';
Result := StrToDate(RegStr);
except
end;
end;
finally
ShortDateFormat := RegFormat;
DateSeparator := RegSeparator;
end;
end;
//==================================================================================================
// Processes, Tasks and Modules
//==================================================================================================
function RunningProcessesList(const List: TStrings; FullPath: Boolean): Boolean;
function ProcessFileName(PID: DWORD): string;
var
Handle: THandle;
begin
Result := '';
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
if Handle <> 0 then
try
SetLength(Result, MAX_PATH);
if FullPath then
begin
if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
StrResetLength(Result)
else
Result := '';
end
else
begin
if GetModuleBaseNameA(Handle, 0, PChar(Result), MAX_PATH) > 0 then
StrResetLength(Result)
else
Result := '';
end;
finally
CloseHandle(Handle);
end;
end;
function BuildListTH: Boolean;
var
SnapProcHandle: THandle;
ProcEntry: TProcessEntry32;
NextProc: Boolean;
FileName: string;
begin
SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
if Result then
try
ProcEntry.dwSize := SizeOf(ProcEntry);
NextProc := Process32First(SnapProcHandle, ProcEntry);
while NextProc do
begin
if ProcEntry.th32ProcessID = 0 then
begin
// PID 0 is always the "System Idle Process" but this name cannot be
// retrieved from the system and has to be fabricated.
FileName := RsSystemIdleProcess;
end
else
begin
if IsWin2k then
begin
FileName := ProcessFileName(ProcEntry.th32ProcessID);
if FileName = '' then
FileName := ProcEntry.szExeFile;
end
else
begin
FileName := ProcEntry.szExeFile;
if not FullPath then
FileName := ExtractFileName(FileName);
end;
end;
List.AddObject(FileName, Pointer(ProcEntry.th32ProcessID));
NextProc := Process32Next(SnapProcHandle, ProcEntry);
end;
finally
CloseHandle(SnapProcHandle);
end;
end;
function BuildListPS: Boolean;
var
PIDs: array [0..1024] of DWORD;
Needed: DWORD;
I: Integer;
FileName: string;
begin
Result := EnumProcesses(@PIDs, SizeOf(PIDs), Needed);
if Result then
begin
for I := 0 to (Needed div SizeOf(DWORD)) - 1 do
begin
case PIDs[I] of
0:
// PID 0 is always the "System Idle Process" but this name cannot be
// retrieved from the system and has to be fabricated.
FileName := RsSystemIdleProcess;
2:
// On NT 4 PID 2 is the "System Process" but this name cannot be
// retrieved from the system and has to be fabricated.
if IsWinNT4 then
FileName := RsSystemProcess
else
FileName := ProcessFileName(PIDs[I]);
8:
// On Win2K PID 8 is the "System Process" but this name cannot be
// retrieved from the system and has to be fabricated.
if IsWin2K then
FileName := RsSystemProcess
else
FileName := ProcessFileName(PIDs[I]);
else
FileName := ProcessFileName(PIDs[I]);
end;
if FileName <> '' then
List.AddObject(FileName, Pointer(PIDs[I]));
end;
end;
end;
begin
if GetWindowsVersion in [wvWinNT31, wvWinNT35, wvWinNT351, wvWinNT4] then
Result := BuildListPS
else
Result := BuildListTH;
end;
//--------------------------------------------------------------------------------------------------
function LoadedModulesList(const List: TStrings; ProcessID: DWORD; HandlesOnly: Boolean): Boolean;
procedure AddToList(ProcessHandle: THandle; Module: HMODULE);
var
FileName: array [0..MAX_PATH] of Char;
ModuleInfo: TModuleInfo;
begin
if GetModuleInformation(ProcessHandle, Module, @ModuleInfo, SizeOf(ModuleInfo)) then
begin
if HandlesOnly then
List.AddObject('', Pointer(ModuleInfo.lpBaseOfDll))
else
if GetModuleFileNameEx(ProcessHandle, Module, Filename, SizeOf(Filename)) > 0 then
List.AddObject(FileName, Pointer(ModuleInfo.lpBaseOfDll));
end;
end;
function EnumModulesVQ(ProcessHandle: THandle): Boolean;
var
MemInfo: TMemoryBasicInformation;
Base: PChar;
LastAllocBase: Pointer;
Res: DWORD;
begin
Base := nil;
LastAllocBase := nil;
FillChar(MemInfo, SizeOf(MemInfo), #0);
Res := VirtualQueryEx(ProcessHandle, Base, MemInfo, SizeOf(MemInfo));
Result := (Res = SizeOf(MemInfo));
while Res = SizeOf(MemInfo) do
begin
if MemInfo.AllocationBase <> LastAllocBase then
begin
if MemInfo.Type_9 = MEM_IMAGE then
AddToList(ProcessHandle, HMODULE(MemInfo.AllocationBase));
LastAllocBase := MemInfo.AllocationBase;
end;
Inc(Base, MemInfo.RegionSize);
Res := VirtualQueryEx(ProcessHandle, Base, MemInfo, SizeOf(MemInfo));
end;
end;
function EnumModulesPS: Boolean;
var
ProcessHandle: THandle;
Needed: DWORD;
Modules: array of THandle;
I, Cnt: Integer;
begin
Result := False;
ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ProcessID);
if ProcessHandle <> 0 then
try
Result := EnumProcessModules(ProcessHandle, nil, 0, Needed);
if Result then
begin
Cnt := Needed div SizeOf(HMODULE);
SetLength(Modules, Cnt);
if EnumProcessModules(ProcessHandle, @Modules[0], Needed, Needed) then
for I := 0 to Cnt - 1 do
AddToList(ProcessHandle, Modules[I]);
end
else
Result := EnumModulesVQ(ProcessHandle);
finally
CloseHandle(ProcessHandle);
end;
end;
function EnumModulesTH: Boolean;
var
SnapProcHandle: THandle;
Module: TModuleEntry32;
Next: Boolean;
begin
SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessID);
Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
if Result then
try
FillChar(Module, SizeOf(Module), #0);
Module.dwSize := SizeOf(Module);
Next := Module32First(SnapProcHandle, Module);
while Next do
begin
if HandlesOnly then
List.AddObject('', Pointer(Module.hModule))
else
List.AddObject(Module.szExePath, Pointer(Module.hModule));
Next := Module32Next(SnapProcHandle, Module);
end;
finally
CloseHandle(SnapProcHandle);
end;
end;
begin
if IsWinNT then
Result := EnumModulesPS
else
Result := EnumModulesTH;
end;
//--------------------------------------------------------------------------------------------------
function GetTasksList(const List: TStrings): Boolean;
function EnumWindowsProc(Wnd: HWND; List: TStrings): Boolean; stdcall;
var
Caption: array [0..1024] of Char;
begin
if IsMainAppWindow(Wnd) and (GetWindowText(Wnd, Caption, SizeOf(Caption)) > 0) then
List.AddObject(Caption, Pointer(Wnd));
Result := True;
end;
begin
Result := EnumWindows(@EnumWindowsProc, Integer(List));
end;
//--------------------------------------------------------------------------------------------------
function ModuleFromAddr(const Addr: Pointer): HMODULE;
var
MI: TMemoryBasicInformation;
begin
VirtualQuery(Addr, MI, SizeOf(MI));
if MI.State <> MEM_COMMIT then
Result := 0
else
Result := HMODULE(MI.AllocationBase);
end;
//--------------------------------------------------------------------------------------------------
function IsSystemModule(const Module: HMODULE): Boolean;
var
CurModule: PLibModule;
begin
Result := False;
if Module <> 0 then
begin
CurModule := LibModuleList;
while CurModule <> nil do
begin
if CurModule.Instance = Module then
begin
Result := True;
Break;
end;
CurModule := CurModule.Next;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
// Refernce: http://msdn.microsoft.com/library/periodic/period97/win321197.htm
function IsMainAppWindow(Wnd: HWND): Boolean;
var
ParentWnd: HWND;
ExStyle: DWORD;
begin
if IsWindowVisible(Wnd) then
begin
ParentWnd := GetWindowLong(Wnd, GWL_HWNDPARENT);
ExStyle := GetWindowLong(Wnd, GWL_EXSTYLE);
Result := ((ParentWnd = 0) or (ParentWnd = GetDesktopWindow)) and
((ExStyle and WS_EX_TOOLWINDOW = 0) or (ExStyle and WS_EX_APPWINDOW <> 0));
end
else
Result := False;
end;
//--------------------------------------------------------------------------------------------------
function IsWindowResponding(Wnd: HWND; Timeout: Integer): Boolean;
var
Res: DWORD;
begin
Result := SendMessageTimeout(Wnd, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, Timeout, Res) <> 0;
end;
//--------------------------------------------------------------------------------------------------
function GetWindowIcon(Wnd: HWND; LargeIcon: Boolean): HICON;
var
Width, Height: Integer;
TempIcon: HICON;
IconType: DWORD;
begin
if LargeIcon then
begin
Width := GetSystemMetrics(SM_CXICON);
Height := GetSystemMetrics(SM_CYICON);
IconType := ICON_BIG;
TempIcon := GetClassLong(Wnd, GCL_HICON);
end
else
begin
Width := GetSystemMetrics(SM_CXSMICON);
Height := GetSystemMetrics(SM_CYSMICON);
IconType := ICON_SMALL;
TempIcon := GetClassLong(Wnd, GCL_HICONSM);
end;
if TempIcon = 0 then
TempIcon := SendMessage(Wnd, WM_GETICON, IconType, 0);
if (TempIcon = 0) and not LargeIcon then
TempIcon := SendMessage(Wnd, WM_GETICON, ICON_BIG, 0);
Result := CopyImage(TempIcon, IMAGE_ICON, Width, Height, 0);
end;
//--------------------------------------------------------------------------------------------------
function GetWindowCaption(Wnd: HWND): string;
const
BufferAllocStep = 256;
var
Buffer: PChar;
Size, TextLen: Integer;
begin
Result := '';
Buffer := nil;
try
Size := GetWindowTextLength(Wnd) + 2 - BufferAllocStep;
repeat
Inc(Size, BufferAllocStep);
ReallocMem(Buffer, Size);
TextLen := GetWindowText(Wnd, Buffer, Size);
until TextLen < Size - 1;
if TextLen > 0 then
Result := Buffer;
finally
FreeMem(Buffer);
end;
end;
//--------------------------------------------------------------------------------------------------
// Q178893
function TerminateApp(ProcessID: DWORD; Timeout: Integer): TJclTerminateAppResult;
var
ProcessHandle: THandle;
function EnumWindowsProc(Wnd: HWND; ProcessID: DWORD): Boolean; stdcall;
var
PID: DWORD;
begin
GetWindowThreadProcessId(Wnd, @PID);
if ProcessID = PID then
PostMessage(Wnd, WM_CLOSE, 0, 0);
Result := True;
end;
begin
Result := taError;
if ProcessID <> GetCurrentProcessId then
begin
ProcessHandle := OpenProcess(SYNCHRONIZE or PROCESS_TERMINATE, False, ProcessID);
try
if ProcessHandle <> 0 then
begin
EnumWindows(@EnumWindowsProc, LPARAM(ProcessID));
if WaitForSingleObject(ProcessHandle, Timeout) = WAIT_OBJECT_0 then
Result := taClean
else
if TerminateProcess(ProcessHandle, 0) then
Result := taKill;
end;
finally
CloseHandle(ProcessHandle);
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function TerminateTask(Wnd: HWND; Timeout: Integer): TJclTerminateAppResult;
var
PID: DWORD;
begin
if GetWindowThreadProcessId(Wnd, @PID) <> 0 then
Result := TerminateApp(PID, Timeout)
else
Result := taError;
end;
//--------------------------------------------------------------------------------------------------
function GetProcessNameFromWnd(Wnd: HWND): string;
var
List: TStringList;
PID: DWORD;
I: Integer;
begin
Result := '';
if IsWindow(Wnd) then
begin
PID := INVALID_HANDLE_VALUE;
GetWindowThreadProcessId(Wnd, @PID);
List := TStringList.Create;
try
if RunningProcessesList(List, True) then
begin
I := List.IndexOfObject(Pointer(PID));
if I > -1 then
Result := List[I];
end;
finally
List.Free;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetPidFromProcessName(const ProcessName: string): DWORD;
var
List: TStringList;
I: Integer;
HasFullPath: Boolean;
begin
Result := INVALID_HANDLE_VALUE;
List := TStringList.Create;
try
HasFullPath := ExtractFilePath(ProcessName) <> '';
if RunningProcessesList(List, HasFullPath) then
begin
I := List.IndexOf(ProcessName);
if I > -1 then
Result := DWORD(List.Objects[I]);
end;
finally
List.Free;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetProcessNameFromPid(PID: DWORD): string;
var
List: TStringList;
I: Integer;
begin
// Note: there are other ways to retrieve the name of the process given it's
// PID but this implementation seems to work best without making assumptions
// although it may not be the most efficient implementation.
Result := '';
List := TStringList.Create;
try
if RunningProcessesList(List, True) then
begin
I := List.IndexOfObject(Pointer(PID));
if I > -1 then
Result := List[I];
end;
finally
List.Free;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetMainAppWndFromPid(PID: DWORD): HWND;
type
PSearch = ^TSearch;
TSearch = record
PID: DWORD;
Wnd: HWND;
end;
var
SearchRec: TSearch;
function EnumWindowsProc(Wnd: HWND; Res: PSearch): Boolean; stdcall;
var
WindowPid: DWORD;
begin
WindowPid := 0;
GetWindowThreadProcessId(Wnd, @WindowPid);
if (WindowPid = Res^.PID) and IsMainAppWindow(Wnd) then
begin
Res^.Wnd := Wnd;
Result := False;
end
else
Result := True;
end;
begin
SearchRec.PID := PID;
SearchRec.Wnd := 0;
EnumWindows(@EnumWindowsProc, Integer(@SearchRec));
Result := SearchRec.Wnd;
end;
//--------------------------------------------------------------------------------------------------
function GetShellProcessName: string;
const
cShellKey = 'Software\Microsoft\Windows NT\CurrentVersion\WinLogon';
cShellValue = 'Shell';
cShellDefault = 'explorer.exe';
begin
Result := RegReadStringDef(HKEY_LOCAL_MACHINE, cShellKey, cShellValue, '');
if Result = '' then
Result := cShellDefault;
end;
//--------------------------------------------------------------------------------------------------
function GetShellProcessHandle: THandle;
var
Pid: Longword;
begin
Pid := GetPidFromProcessName(GetShellProcessName);
Result := OpenProcess(PROCESS_ALL_ACCESS, False, Pid);
if Result = 0 then
RaiseLastOSError;
end;
//==================================================================================================
// Version Information
//==================================================================================================
{ Q159/238
Windows 95 retail, OEM 4.00.950 7/11/95
Windows 95 retail SP1 4.00.950A 7/11/95-12/31/95
OEM Service Release 2 4.00.1111* (4.00.950B) 8/24/96
OEM Service Release 2.1 4.03.1212-1214* (4.00.950B) 8/24/96-8/27/97
OEM Service Release 2.5 4.03.1214* (4.00.950C) 8/24/96-11/18/97
Windows 98 retail, OEM 4.10.1998 5/11/98
Windows 98 Second Edition 4.10.2222A 4/23/99
Windows Millennium 4.90.3000
TODO: Distinquish between all these different releases?
}
var
KernelVersionHi: DWORD;
function GetWindowsVersion: TWindowsVersion;
begin
Result := wvUnknown;
case Win32Platform of
VER_PLATFORM_WIN32_WINDOWS:
case Win32MinorVersion of
0..9:
if Trim(Win32CSDVersion) = 'B' then
Result := wvWin95OSR2
else
Result := wvWin95;
10..89:
// On Windows ME Win32MinorVersion can be 10 (indicating Windows 98
// under certain circumstances (image name is setup.exe). Checking
// the kernel version is one way of working around that.
if KernelVersionHi = $0004005A then // 4.90.x.x
Result := wvWinME
else
if Trim(Win32CSDVersion) = 'A' then
Result := wvWin98SE
else
Result := wvWin98;
90:
Result := wvWinME;
end;
VER_PLATFORM_WIN32_NT:
case Win32MajorVersion of
3:
case Win32MinorVersion of
1:
Result := wvWinNT31;
5:
Result := wvWinNT35;
51:
Result := wvWinNT351;
end;
4:
Result := wvWinNT4;
5:
case Win32MinorVersion of
0:
Result := wvWin2000;
1:
Result := wvWinXP;
end;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function NtProductType: TNtProductType;
const
ProductType = 'System\CurrentControlSet\Control\ProductOptions';
var
Product: string;
VersionInfo: TOSVersionInfoEx;
begin
Result := ptUnknown;
FillChar(VersionInfo, SizeOf(VersionInfo), 0);
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
// Favor documented API over registry
if IsWinNT4 and (GetWindowsServicePackVersion >= 6) then
begin
if JclWin32.GetVersionEx(@VersionInfo) then
begin
if (VersionInfo.wProductType = VER_NT_WORKSTATION) then
Result := ptWorkstation
else
Result := ptServer;
end;
end
else
if IsWin2K then
begin
if JclWin32.GetVersionEx(@VersionInfo) then
begin
if (VersionInfo.wProductType = VER_NT_SERVER) then
begin
{ Changes by Scott Price on 11-Jan-2002 }
if (VersionInfo.wSuiteMask and VER_SUITE_DATACENTER) = VER_SUITE_DATACENTER then
Result := ptDatacenterServer
{ Changes by Scott Price on 11-Jan-2002 }
else
if (VersionInfo.wSuiteMask and VER_SUITE_ENTERPRISE) = VER_SUITE_ENTERPRISE then
Result := ptAdvancedServer
else
result := ptServer;
end
else
if (VersionInfo.wProductType = VER_NT_WORKSTATION) then
Result := ptProfessional;
end;
end
else
if IsWinXP then
begin
if JclWin32.GetVersionEx(@VersionInfo) then
begin
if (VersionInfo.wProductType = VER_NT_WORKSTATION) then
begin
{ Changes by Scott Price on 10-Jan-2002 }
if (VersionInfo.wSuiteMask and VER_SUITE_PERSONAL) = VER_SUITE_PERSONAL then
Result := ptPersonal
else
Result := ptProfessional;
end;
end;
end;
if Result = ptUnknown then
begin
// Non Windows 2000/XP system or the above method failed, try registry
{ Changes by Scott Price on 11-Jan-2002 }
Product := RegReadStringDef(HKEY_LOCAL_MACHINE, ProductType, 'ProductType', '');
if CompareText(Product, 'WINNT') = 0 then
Result := ptWorkStation
else
if CompareText(Product, 'SERVERNT') = 0 then
Result := {ptServer} ptAdvancedServer
else
if CompareText(Product, 'LANMANNT') = 0 then
Result := {ptAdvancedServer} ptServer
else
Result := ptUnknown;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetWindowsVersionString: string;
begin
case GetWindowsVersion of
wvWin95: Result := RsOSVersionWin95;
wvWin95OSR2: Result := RsOSVersionWin95OSR2;
wvWin98: Result := RsOSVersionWin98;
wvWin98SE: Result := RsOSVersionWin98SE;
wvWinME: Result := RsOSVersionWinME;
wvWinNT31, wvWinNT35, wvWinNT351: Result := Format(RsOSVersionWinNT3, [Win32MinorVersion]);
wvWinNT4: Result := Format(RsOSVersionWinNT4, [Win32MinorVersion]);
wvWin2000: Result := RsOSVersionWin2000;
wvWinXP: Result := RsOSVersionWinXP;
else
Result := '';
end;
end;
//--------------------------------------------------------------------------------------------------
function NtProductTypeString: string;
begin
case NtProductType of
ptWorkStation: Result := RsProductTypeWorkStation;
ptServer: Result := RsProductTypeServer;
ptAdvancedServer: Result := RsProductTypeAdvancedServer;
ptPersonal: Result := RsProductTypePersonal;
ptProfessional: Result := RsProductTypeProfessional;
ptDatacenterServer: Result := RsProductTypeDatacenterServer;
else
Result := '';
end;
end;
//--------------------------------------------------------------------------------------------------
function GetWindowsServicePackVersion: Integer;
const
RegWindowsControl = '\SYSTEM\CurrentControlSet\Control\Windows\';
var
SP: Integer;
VersionInfo: TOSVersionInfoEx;
begin
Result := 0;
if IsWin2K or IsWinXP then
begin
FillChar(VersionInfo, SizeOf(VersionInfo), 0);
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
if JclWin32.GetVersionEx(@VersionInfo) then Result := VersionInfo.wServicePackMajor;
end
else
begin
SP := RegReadIntegerDef(HKEY_LOCAL_MACHINE, RegWindowsControl, 'CSDVersion', 0);
Result := StrToInt(IntToHex(SP, 4)) div 100;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetWindowsServicePackVersionString: string;
var
SP: Integer;
begin
SP := GetWindowsServicePackVersion;
if SP > 0 then
Result := 'SP' + IntToStr(SP)
else
Result := '';
end;
//==================================================================================================
// Hardware
//==================================================================================================
// Helper function for GetMacAddress()
// Converts the adapter_address array to a string
function AdapterToString(Adapter: TAdapterStatus): string;
begin
with Adapter do
Result := Format('%2.2x-%2.2x-%2.2x-%2.2x-%2.2x-%2.2x', [
Integer(adapter_address[0]), Integer(adapter_address[1]),
Integer(adapter_address[2]), Integer(adapter_address[3]),
Integer(adapter_address[4]), Integer(adapter_address[5])]);
end;
//--------------------------------------------------------------------------------------------------
function GetMacAddresses(const Machine: string; const Addresses: TStrings): Integer;
var
NCB: TNCB;
Enum: TLanaEnum;
I, L, NameLen: Integer;
Adapter: ASTAT;
MachineName: string;
begin
Result := -1;
Addresses.Clear;
MachineName := UpperCase(Machine);
if MachineName = '' then
MachineName := '*';
NameLen := Length(MachineName);
L := NCBNAMSZ - NameLen;
if L > 0 then
begin
SetLength(MachineName, NCBNAMSZ);
FillChar(MachineName[NameLen + 1], L, ' ');
end;
FillChar(NCB, SizeOf(NCB), #0);
NCB.ncb_command := NCBENUM;
NCB.ncb_buffer := Pointer(@Enum);
NCB.ncb_length := SizeOf(Enum);
if NetBios(@NCB) = NRC_GOODRET then
begin
Result := Enum.Length;
for I := 0 to Ord(Enum.Length) - 1 do
begin
FillChar(NCB, SizeOf(NCB), #0);
NCB.ncb_command := NCBRESET;
NCB.ncb_lana_num := Enum.lana[I];
if NetBios(@NCB) = NRC_GOODRET then
begin
FillChar(NCB, SizeOf(NCB), #0);
NCB.ncb_command := NCBASTAT;
NCB.ncb_lana_num := Enum.lana[I];
Move(MachineName[1], NCB.ncb_callname, SizeOf(NCB.ncb_callname));
NCB.ncb_buffer := PChar(@Adapter);
NCB.ncb_length := SizeOf(Adapter);
if NetBios(@NCB) = NRC_GOODRET then
Addresses.Add(AdapterToString(Adapter.adapt));
end;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function ReadTimeStampCounter: Int64; assembler;
asm
DW $310F
end;
//--------------------------------------------------------------------------------------------------
function GetIntelCacheDescription(const D: Byte): string;
var
I: Integer;
begin
Result := '';
if D <> 0 then
begin
for I := Low(IntelCacheDescription) to High(IntelCacheDescription) do
begin
if IntelCacheDescription[I].D = D then
begin
Result := IntelCacheDescription[I].I;
Break;
end;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
procedure GetCpuInfo(var CpuInfo: TCpuInfo);
begin
CpuInfo := CPUID;
CpuInfo.IsFDIVOK := TestFDIVInstruction;
if CpuInfo.HasInstruction then
begin
if (CpuInfo.Features and TSC_FLAG) = TSC_FLAG then
GetCpuSpeed(CpuInfo.FrequencyInfo);
CpuInfo.MMX := (CpuInfo.Features and MMX_FLAG) = MMX_FLAG;
end;
end;
//--------------------------------------------------------------------------------------------------
function RoundFrequency(const Frequency: Integer): Integer;
const
NF: array [0..8] of Integer = (0, 20, 33, 50, 60, 66, 80, 90, 100);
var
Freq, RF: Integer;
I: Byte;
Hi, Lo: Byte;
begin
RF := 0;
Freq := Frequency mod 100;
for I := 0 to 8 do
begin
if Freq < NF[I] then
begin
Hi := I;
Lo := I - 1;
if (NF[Hi] - Freq) > (Freq - NF[Lo]) then
RF := NF[Lo] - Freq
else
RF := NF[Hi] - Freq;
Break;
end;
end;
Result := Frequency + RF;
end;
//--------------------------------------------------------------------------------------------------
function GetCPUSpeed(var CpuSpeed: TFreqInfo): Boolean;
var
T0, T1: TULargeInteger;
CountFreq: TULargeInteger;
Freq, Freq2, Freq3, Total: Integer;
TotalCycles, Cycles: Int64;
Stamp0, Stamp1: Int64;
TotalTicks, Ticks: Cardinal;
Tries, Priority: Integer;
Thread: THandle;
begin
Stamp0 := 0;
Stamp1 := 0;
Freq := 0;
Freq2 := 0;
Freq3 := 0;
Tries := 0;
TotalCycles := 0;
TotalTicks := 0;
Total := 0;
Thread := GetCurrentThread();
Result := QueryPerformanceFrequency(Int64(CountFreq));
if Result then
begin
while ((Tries < 3 ) or ((Tries < 20) and ((Abs(3 * Freq - Total) > 3) or
(Abs(3 * Freq2 - Total) > 3) or (Abs(3 * Freq3 - Total) > 3)))) do
begin
Inc(Tries);
Freq3 := Freq2;
Freq2 := Freq;
QueryPerformanceCounter(Int64(T0));
T1.LowPart := T0.LowPart;
T1.HighPart := T0.HighPart;
Priority := GetThreadPriority(Thread);
if Priority <> THREAD_PRIORITY_ERROR_RETURN then
SetThreadPriority(Thread, THREAD_PRIORITY_TIME_CRITICAL);
try
while (T1.LowPart - T0.LowPart) < 50 do
begin
QueryPerformanceCounter(Int64(T1));
Stamp0 := ReadTimeStampCounter;
end;
T0.LowPart := T1.LowPart;
T0.HighPart := T1.HighPart;
while (T1.LowPart - T0.LowPart) < 1000 do
begin
QueryPerformanceCounter(Int64(T1));
Stamp1 := ReadTimeStampCounter;
end;
finally
if Priority <> THREAD_PRIORITY_ERROR_RETURN then
SetThreadPriority(Thread, Priority);
end;
Cycles := Stamp1 - Stamp0;
Ticks := T1.LowPart - T0.LowPart;
Ticks := Ticks * 100000;
Ticks := Round(Ticks / (CountFreq.LowPart / 10));
TotalTicks := TotalTicks + Ticks;
TotalCycles := TotalCycles + Cycles;
Freq := Round(Cycles / Ticks);
Total := Freq + Freq2 + Freq3;
end;
Freq3 := Round((TotalCycles * 10) / TotalTicks);
Freq2 := Round((TotalCycles * 100) / TotalTicks);
if Freq2 - (Freq3 * 10) >= 6 then
Inc(Freq3);
CpuSpeed.RawFreq := Round(TotalCycles / TotalTicks);
CpuSpeed.NormFreq := CpuSpeed.RawFreq;
Freq := CpuSpeed.RawFreq * 10;
if (Freq3 - Freq) >= 6 then
Inc(CpuSpeed.NormFreq);
CpuSpeed.ExTicks := TotalTicks;
CpuSpeed.InCycles := TotalCycles;
CpuSpeed.NormFreq := RoundFrequency(CpuSpeed.NormFreq);
Result := True;
end;
end;
//--------------------------------------------------------------------------------------------------
// Helper function for CPUID. Initializes Intel specific fields.
procedure IntelSpecific(var CpuInfo: TCpuInfo);
var
I: Integer;
begin
with CpuInfo do
begin
Manufacturer := 'Intel';
CpuType := CPU_TYPE_INTEL;
if HasCacheInfo then
with CPUInfo.IntelSpecific do
begin
L2Cache := 0;
for I := 1 to 15 do
case CacheDescriptors[I] of
$40:
L2Cache := 0;
$41:
L2Cache := 128;
$42:
L2Cache := 256;
$43:
L2Cache := 512;
$44:
L2Cache := 1024;
$45:
L2Cache := 2048;
end;
end;
if not HasExtendedInfo then
begin
case Family of
4:
case Model of
1:
CpuName := 'Intel 486DX Processor';
2:
CpuName := 'Intel 486SX Processor';
3:
CpuName := 'Intel DX2 Processor';
4:
CpuName := 'Intel 486 Processor';
5:
CpuName := 'Intel SX2 Processor';
7:
CpuName := 'Write-Back Enhanced Intel DX2 Processor';
8:
CpuName := 'Intel DX4 Processor';
else
CpuName := 'Intel 486 Processor';
end;
5:
CpuName := 'Pentium';
6:
case Model of
1:
CpuName := 'Pentium Pro';
3:
CpuName := 'Pentium II';
5:
case IntelSpecific.L2Cache of
0:
CpuName := 'Celeron';
1024:
CpuName := 'Pentium II Xeon';
2048:
CpuName := 'Pentium II Xeon';
else
CpuName := 'Pentium II';
end;
6:
case IntelSpecific.L2Cache of
0:
CpuName := 'Celeron';
128:
CpuName := 'Celeron';
else
CpuName := 'Pentium II';
end;
7:
case IntelSpecific.L2Cache of
1024:
CpuName := 'Pentium III Xeon';
2048:
CpuName := 'Pentium III Xeon';
else
CpuName := 'Pentium III';
end;
8:
case IntelSpecific.BrandID of
1: CpuName := 'Celeron';
2: CpuName := 'Pentium III';
3: CpuName := 'Pentium III Xeon';
4: CpuName := 'Pentium III';
else
CpuName := 'Pentium III';
end;
10:
CpuName := 'Pentium III Xeon';
11:
CpuName := 'Pentium III';
else
StrPCopy(CpuName, Format('P6 (Model %d)', [Model]));
end;
15:
case IntelSpecific.BrandID of
1:
CpuName := 'Celeron';
8:
CpuName := 'Pentium 4';
14:
CpuName := 'Xeon';
else
CpuName := 'Pentium 4';
end;
else
StrPCopy(CpuName, Format('P%d', [Family]));
end;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
// Helper function for CPUID. Initializes Cyrix specific fields.
procedure CyrixSpecific(var CpuInfo: TCpuInfo);
begin
with CpuInfo do
begin
Manufacturer := 'Cyrix';
CpuType := CPU_TYPE_CYRIX;
if not HasExtendedInfo then
begin
case Family of
4:
CpuName := 'Cyrix MediaGX';
5:
case Model of
2:
CpuName := 'Cyrix 6x86';
4:
CpuName := 'Cyrix GXm';
end;
6:
CpuName := '6x86MX';
else
StrPCopy(CpuName, Format('%dx86', [Family]));
end;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
// Helper function for CPUID. Initializes AMD specific fields.
procedure AMDSpecific(var CpuInfo: TCpuInfo);
begin
with CpuInfo do
begin
Manufacturer := 'AMD';
CpuType := CPU_TYPE_AMD;
if not HasExtendedInfo then
begin
case Family of
4:
CpuName := 'Am486(R) or Am5x86';
5:
case Model of
0:
CpuName := 'AMD-K5 (Model 0)';
1:
CpuName := 'AMD-K5 (Model 1)';
2:
CpuName := 'AMD-K5 (Model 2)';
3:
CpuName := 'AMD-K5 (Model 3)';
6:
CpuName := 'AMD-K6(R)';
7:
CpuName := 'AMD-K6';
8:
CpuName := 'AMD-K6(R) -2';
9:
CpuName := 'AMD-K6(R) -3';
else
CpuName := 'Unknown AMD Model';
end;
else
CpuName := 'Unknown AMD Chip';
end;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
procedure TransmetaSpecific(var CpuInfo: TCpuInfo);
begin
with CpuInfo do
begin
Manufacturer := 'Transmeta';
CpuType := CPU_TYPE_CRUSOE;
CpuName := 'Crusoe';
end;
end;
//--------------------------------------------------------------------------------------------------
function CPUID: TCpuInfo;
var
CPUInfo: TCpuInfo;
HiVal: Cardinal;
TimesToExecute, CurrentLoop: Byte;
begin
asm
MOV [CPUInfo.HasInstruction], 0
MOV [CPUInfo.HasExtendedInfo], 0
MOV [CPUInfo.HasCacheInfo], 0
MOV [CPUInfo.PType], 0
MOV [CPUInfo.Model], 0
MOV [CPUInfo.Stepping], 0
MOV [CPUInfo.Features], 0
MOV [CPUInfo.FrequencyInfo.RawFreq], 0
MOV [CPUInfo.FrequencyInfo.NormFreq], 0
MOV [CPUInfo.FrequencyInfo.InCycles], 0
MOV [CPUInfo.FrequencyInfo.ExTicks], 0
MOV [CPUInfo.IntelSpecific.BrandID],0
PUSH EAX
PUSH EBP
PUSH EBX
PUSH ECX
PUSH EDI
PUSH EDX
PUSH ESI
@@Check80486:
MOV [CPUInfo.Family], 4
PUSHFD
POP EAX
MOV ECX, EAX
XOR EAX, 200000H
PUSH EAX
POPFD
PUSHFD
POP EAX
XOR EAX, ECX
JE @@DoneCpuType
@@HasCPUIDInstruction:
MOV [CPUInfo.HasInstruction], 1
MOV EAX, 0
DB 0FH
DB 0A2H
MOV HiVal, EAX
MOV DWORD PTR [CPUInfo.VendorIDString], EBX
MOV DWORD PTR [CPUInfo.VendorIDString + 4], EDX
MOV DWORD PTR [CPUInfo.VendorIDString + 8], ECX
@@CheckIntel:
CMP DWORD PTR [CPUInfo.VendorIDString], 'uneG'
JNE @@CheckAMD
CMP DWORD PTR [CPUInfo.VendorIDString + 4], 'Ieni'
JNE @@CheckAMD
CMP DWORD PTR [CPUInfo.VendorIDString + 8], 'letn'
JNE @@CheckAMD
MOV [CPUInfo.CpuType], CPU_TYPE_INTEL
JMP @@StandardFunctions
@@CheckAMD:
CMP DWORD PTR [CPUInfo.VendorIDString], 'htuA'
JNE @@CheckCitrix
CMP DWORD PTR [CPUInfo.VendorIDString + 4], 'itne'
JNE @@CheckCitrix
CMP DWORD PTR [CPUInfo.VendorIDString + 8], 'DMAc'
JNE @@CheckCitrix
MOV [CPUInfo.CpuType], CPU_TYPE_AMD
JMP @@CheckAMDExtended
@@CheckCitrix:
CMP DWORD PTR [CPUInfo.VendorIDString], 'iryC'
JNE @@StandardFunctions
CMP DWORD PTR [CPUInfo.VendorIDString + 4], 'snIx'
JNE @@StandardFunctions
CMP DWORD PTR [CPUInfo.VendorIDString + 8], 'daet'
JNE @@StandardFunctions
MOV [CPUInfo.CpuType], CPU_TYPE_CYRIX
JMP @@CheckCitrixExtended
@@CheckAMDExtended:
MOV EAX, 80000000h
DB 0Fh
DB 0A2h
CMP EAX, 0
JE @@StandardFunctions
JMP @@AMDOnly
@@CheckCitrixExtended:
MOV EAX, 80000000h
DB 0Fh
DB 0A2h
CMP EAX, 0
JE @@StandardFunctions
JMP @@CitrixOnly
@@StandardFunctions:
CMP HiVal, 1
JL @@DoneCPUType
MOV EAX, 1
DB 0FH
DB 0A2H
MOV [CPUInfo.Features], EDX
MOV [CPUInfo.IntelSpecific.BrandID], BL
MOV ECX, EAX
AND EAX, 3000H
SHR EAX, 12
MOV [CPUInfo.PType], AL
MOV EAX, ECX
AND EAX, 0F00H
SHR EAX, 8
MOV [CPUInfo.Family], AL
MOV EAX, ECX
AND EAX, 00F0H
SHR EAX, 4
MOV [CPUInfo.MODEL], AL
MOV EAX, ECX
AND EAX, 000FH
MOV [CPUInfo.Stepping], AL
CMP DWORD PTR [CPUInfo.VendorIDString], 'uneG'
JNE @@DoneCPUType
CMP DWORD PTR [CPUInfo.VendorIDString + 4], 'Ieni'
JNE @@DoneCPUType
CMP DWORD PTR [CPUInfo.VendorIDString + 8], 'letn'
JNE @@DoneCPUType
@@IntelStandard:
CMP HiVal, 2
JL @@DoneCPUType
MOV CurrentLoop, 0
MOV [CPUInfo.HasCacheInfo], 1
PUSH ECX
@@RepeatCacheQuery:
POP ECX
MOV EAX, 2
DB 0FH
DB 0A2H
INC CurrentLoop
CMP CurrentLoop, 1
JNE @@DoneCacheQuery
MOV TimesToExecute, AL
CMP AL, 0
JE @@DoneCPUType
@@DoneCacheQuery:
PUSH ECX
MOV CL, CurrentLoop
SUB CL, TimesToExecute
JNZ @@RepeatCacheQuery
POP ECX
MOV DWORD PTR [CPUInfo.IntelSpecific.CacheDescriptors], EAX
MOV DWORD PTR [CPUInfo.IntelSpecific.CacheDescriptors + 4], EBX
MOV DWORD PTR [CPUInfo.IntelSpecific.CacheDescriptors + 8], ECX
MOV DWORD PTR [CPUInfo.IntelSpecific.CacheDescriptors + 12], EDX
JMP @@DoneCPUType
@@AMDOnly:
MOV HiVal, EAX
MOV EAX, 80000001h
CMP HiVal, EAX
JL @@DoneCPUType
MOV [CPUInfo.HasExtendedInfo], 1
DB 0Fh
DB 0A2h
MOV ECX, EAX
AND EAX, 0F000H
SHR EAX, 12
MOV [CPUInfo.PType], AL
MOV EAX, ECX
AND EAX, 0F00H
SHR EAX, 8
MOV [CPUInfo.Family], AL
MOV EAX, ECX
AND EAX, 00F0H
SHR EAX, 4
MOV [CPUInfo.MODEL], AL
MOV EAX, ECX
AND EAX, 000FH
MOV [CPUInfo.Stepping], AL
MOV [CPUInfo.Features], EDX
MOV EAX, 80000002h
CMP HiVal, EAX
JL @@DoneCPUType
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CpuName], EAX
MOV DWORD PTR [CPUInfo.CpuName + 4], EBX
MOV DWORD PTR [CPUInfo.CpuName + 8], ECX
MOV DWORD PTR [CPUInfo.CpuName + 12], EDX
MOV EAX, 80000003h
CMP HiVal, EAX
JL @@DoneCPUType
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CpuName + 16], EAX
MOV DWORD PTR [CPUInfo.CpuName + 20], EBX
MOV DWORD PTR [CPUInfo.CpuName + 24], ECX
MOV DWORD PTR [CPUInfo.CpuName + 28], EDX
MOV EAX, 80000004h
CMP HiVal, EAX
JL @@DoneCPUType
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CpuName + 32], EAX
MOV DWORD PTR [CPUInfo.CpuName + 36], EBX
MOV DWORD PTR [CPUInfo.CpuName + 40], ECX
MOV DWORD PTR [CPUInfo.CpuName + 44], EDX
MOV EAX, 80000005h
CMP HiVal, EAX
JL @@DoneCPUType
MOV [CPUInfo.HasCacheInfo], 1
DB 0Fh
DB 0A2h
MOV WORD PTR [CPUInfo.AMDSpecific.InstructionTLB], BX
SHR EBX, 16
MOV WORD PTR [CPUInfo.AMDSpecific.DataTLB], BX
MOV DWORD PTR [CPUInfo.AMDSpecific.L1DataCache], ECX
MOV DWORD PTR [CPUInfo.AMDSpecific.L1ICache], EDX
JMP @@DoneCPUType
@@CitrixOnly:
MOV HiVal, EAX
MOV EAX, 80000001h
CMP HiVal, EAX
JL @@DoneCPUType
MOV [CPUInfo.HasExtendedInfo], 1
DB 0Fh
DB 0A2h
MOV ECX, EAX
AND EAX, 0F000H
SHR EAX, 12
MOV [CPUInfo.PType], AL
MOV EAX, ECX
AND EAX, 0F00H
SHR EAX, 8
MOV [CPUInfo.Family], AL
MOV EAX, ECX
AND EAX, 00F0H
SHR EAX, 4
MOV [CPUInfo.MODEL], AL
MOV EAX, ECX
AND EAX, 000FH
MOV [CPUInfo.Stepping], AL
MOV [CPUInfo.Features], EDX
MOV EAX, 80000002h
CMP HiVal, EAX
JL @@DoneCPUType
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CpuName], EAX
MOV DWORD PTR [CPUInfo.CpuName + 4], EBX
MOV DWORD PTR [CPUInfo.CpuName + 8], ECX
MOV DWORD PTR [CPUInfo.CpuName + 12], EDX
MOV EAX, 80000003h
CMP HiVal, EAX
JL @@DoneCPUType
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CpuName + 16], EAX
MOV DWORD PTR [CPUInfo.CpuName + 20], EBX
MOV DWORD PTR [CPUInfo.CpuName + 24], ECX
MOV DWORD PTR [CPUInfo.CpuName + 28], EDX
MOV EAX, 80000004h
CMP HiVal, EAX
JL @@DoneCPUType
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CpuName + 32], EAX
MOV DWORD PTR [CPUInfo.CpuName + 36], EBX
MOV DWORD PTR [CPUInfo.CpuName + 40], ECX
MOV DWORD PTR [CPUInfo.CpuName + 44], EDX
MOV EAX, 80000005h
CMP HiVal, EAX
JL @@DoneCPUType
MOV [CPUInfo.HasCacheInfo], 1
DB 0Fh
DB 0A2h
MOV DWORD PTR [CPUInfo.CyrixSpecific.TLBInfo], EBX
MOV DWORD PTR [CPUInfo.CyrixSpecific.L1CacheInfo], ECX
@@DoneCpuType:
POP ESI
POP EDX
POP EDI
POP ECX
POP EBX
POP EBP
POP EAX
end;
if CPUInfo.VendorIDString = 'GenuineIntel' then
IntelSpecific(CpuInfo)
else
if CPUInfo.VendorIDString = 'CyrixInstead' then
CyrixSpecific(CpuInfo)
else
if CPUInfo.VendorIDString = 'AuthenticAMD' then
AMDSpecific(CpuInfo)
else
if CPUInfo.VendorIDString = 'GenuineTMx86' then
TransmetaSpecific(CpuInfo)
else
begin
CpuInfo.Manufacturer := 'Unknown';
CpuInfo.CpuName := 'Unknown';
end;
Result := CPUInfo;
end;
//--------------------------------------------------------------------------------------------------
function TestFDIVInstruction: Boolean;
var
TopNum: Double;
BottomNum: Double;
One: Double;
ISOK: Boolean;
begin
// The following code was found in Borlands fdiv.asm file in the
// Delphi 3\Source\RTL\SYS directory, (I made some minor modifications)
// therefore I cannot take credit for it.
TopNum := 2658955;
BottomNum := PI;
One := 1;
asm
PUSH EAX
FLD [TopNum]
FDIV [BottomNum]
FMUL [BottomNum]
FSUBR [TopNum]
FCOMP [One]
FSTSW AX
SHR EAX, 8
AND EAX, 01H
MOV ISOK, AL
POP EAX
end;
Result := ISOK;
end;
//==================================================================================================
// Alloc granularity
//==================================================================================================
procedure RoundToAllocGranularity64(var Value: Int64; Up: Boolean);
begin
if (Value mod AllocGranularity) <> 0 then
if Up then
Value := ((Value div AllocGranularity) + 1) * AllocGranularity
else
Value := (Value div AllocGranularity) * AllocGranularity;
end;
//--------------------------------------------------------------------------------------------------
procedure RoundToAllocGranularityPtr(var Value: Pointer; Up: Boolean);
begin
if (Cardinal(Value) mod AllocGranularity) <> 0 then
if Up then
Value := Pointer(((Cardinal(Value) div AllocGranularity) + 1) * AllocGranularity)
else
Value := Pointer((Cardinal(Value) div AllocGranularity) * AllocGranularity);
end;
//==================================================================================================
// Advanced Power Management (APM)
//==================================================================================================
function GetAPMLineStatus: TAPMLineStatus;
var
SystemPowerstatus: TSystemPowerStatus;
begin
Result := alsUnknown;
if not GetSystemPowerStatus(SystemPowerStatus) then
RaiseLastOSError
else
begin
case SystemPowerStatus.ACLineStatus of
0:
Result := alsOffline;
1:
Result := alsOnline;
255:
Result := alsUnknown;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetAPMBatteryFlag: TAPMBatteryFlag;
var
SystemPowerstatus: TSystemPowerStatus;
begin
Result := abfUnknown;
if not GetSystemPowerStatus(SystemPowerStatus) then
RaiseLastOSError
else
begin
case SystemPowerStatus.BatteryFlag of
1:
Result := abfHigh;
2:
Result := abfLow;
4:
Result := abfCritical;
8:
Result := abfCharging;
128:
Result := abfNoBattery;
255:
Result := abfUnknown;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function GetAPMBatteryLifePercent: Integer;
var
SystemPowerstatus: TSystemPowerStatus;
begin
Result := 0;
if not GetSystemPowerStatus(SystemPowerStatus) then
RaiseLastOSError
else
Result := SystemPowerStatus.BatteryLifePercent;
end;
//--------------------------------------------------------------------------------------------------
function GetAPMBatteryLifeTime: DWORD;
var
SystemPowerstatus: TSystemPowerStatus;
begin
Result := 0;
if not GetSystemPowerStatus(SystemPowerStatus) then
RaiseLastOSError
else
Result := SystemPowerStatus.BatteryLifeTime;
end;
//--------------------------------------------------------------------------------------------------
function GetAPMBatteryFullLifeTime: DWORD;
var
SystemPowerstatus: TSystemPowerStatus;
begin
Result := 0;
if not GetSystemPowerStatus(SystemPowerStatus) then
RaiseLastOSError
else
Result := SystemPowerStatus.BatteryFullLifeTime;
end;
//==================================================================================================
// Memory Information
//==================================================================================================
function GetMaxAppAddress: Integer;
var
SystemInfo: TSystemInfo;
begin
FillChar(SystemInfo, SizeOf(SystemInfo), #0);
GetSystemInfo(SystemInfo);
Result := Integer(SystemInfo.lpMaximumApplicationAddress);
end;
//--------------------------------------------------------------------------------------------------
function GetMinAppAddress: Integer;
var
SystemInfo: TSystemInfo;
begin
FillChar(SystemInfo, SizeOf(SystemInfo), #0);
GetSystemInfo(SystemInfo);
Result := Integer(SystemInfo.lpMinimumApplicationAddress);
end;
//--------------------------------------------------------------------------------------------------
function GetMemoryLoad: Byte;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwMemoryLoad;
end;
//--------------------------------------------------------------------------------------------------
function GetSwapFileSize: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
with MemoryStatus do
Result := Trunc(dwTotalPageFile - dwAvailPageFile);
end;
//--------------------------------------------------------------------------------------------------
function GetSwapFileUsage: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
with MemoryStatus do
Result := 100 - Trunc(dwAvailPageFile / dwTotalPageFile * 100);
end;
//--------------------------------------------------------------------------------------------------
function GetTotalPhysicalMemory: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwTotalPhys;
end;
//--------------------------------------------------------------------------------------------------
function GetFreePhysicalMemory: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwAvailPhys;
end;
//--------------------------------------------------------------------------------------------------
function GetTotalPageFileMemory: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwTotalPageFile;
end;
//--------------------------------------------------------------------------------------------------
function GetFreePageFileMemory: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwAvailPageFile;
end;
//--------------------------------------------------------------------------------------------------
function GetTotalVirtualMemory: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwTotalVirtual;
end;
//--------------------------------------------------------------------------------------------------
function GetFreeVirtualMemory: Integer;
var
MemoryStatus: TMemoryStatus;
begin
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Result := MemoryStatus.dwAvailVirtual;
end;
//==================================================================================================
// Keyboard Information
//==================================================================================================
function GetKeyState(const VirtualKey: Cardinal): Boolean;
var
Keys: TKeyboardState;
begin
GetKeyBoardState(Keys);
Result := Keys[VirtualKey] and $80 <> 0;
end;
//--------------------------------------------------------------------------------------------------
function GetNumLockKeyState: Boolean;
begin
Result := GetKeyState(VK_NUMLOCK);
end;
//--------------------------------------------------------------------------------------------------
function GetScrollLockKeyState: Boolean;
begin
Result := GetKeyState(VK_SCROLL);
end;
//--------------------------------------------------------------------------------------------------
function GetCapsLockKeyState: Boolean;
begin
Result := GetKeyState(VK_CAPITAL);
end;
//==================================================================================================
// Windows 95/98/Me system resources information
//==================================================================================================
var
ResmeterLibHandle: THandle;
MyGetFreeSystemResources: function (ResType: UINT): UINT; stdcall;
//--------------------------------------------------------------------------------------------------
procedure UnloadSystemResourcesMeterLib;
begin
if ResmeterLibHandle <> 0 then
begin
FreeLibrary(ResmeterLibHandle);
ResmeterLibHandle := 0;
@MyGetFreeSystemResources := nil;
end;
end;
//--------------------------------------------------------------------------------------------------
function IsSystemResourcesMeterPresent: Boolean;
procedure LoadResmeter;
var
OldErrorMode: UINT;
begin
OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
ResmeterLibHandle := LoadLibrary('rsrc32.dll');
finally
SetErrorMode(OldErrorMode);
end;
if ResmeterLibHandle <> 0 then
begin
@MyGetFreeSystemResources := GetProcAddress(ResmeterLibHandle, '_MyGetFreeSystemResources32@4');
if not Assigned(MyGetFreeSystemResources) then
UnloadSystemResourcesMeterLib;
end;
end;
begin
if not IsWinNT and (ResmeterLibHandle = 0) then
LoadResmeter;
Result := (ResmeterLibHandle <> 0);
end;
//--------------------------------------------------------------------------------------------------
function GetFreeSystemResources(const ResourceType: TFreeSysResKind): Integer;
const
ParamValues: array [TFreeSysResKind] of UINT = (0, 1, 2);
begin
if IsSystemResourcesMeterPresent then
Result := MyGetFreeSystemResources(ParamValues[ResourceType])
else
Result := -1;
end;
//--------------------------------------------------------------------------------------------------
function GetFreeSystemResources: TFreeSystemResources;
begin
with Result do
begin
SystemRes := GetFreeSystemResources(rtSystem);
GdiRes := GetFreeSystemResources(rtGdi);
UserRes := GetFreeSystemResources(rtUser);
end;
end;
//==================================================================================================
// Initialization
//==================================================================================================
procedure InitSysInfo;
var
SystemInfo: TSystemInfo;
Kernel32FileName: string;
VerFixedFileInfo: TVSFixedFileInfo;
begin
{ processor information related initialization }
FillChar(SystemInfo, SizeOf(SystemInfo), #0);
GetSystemInfo(SystemInfo);
ProcessorCount := SystemInfo.dwNumberOfProcessors;
AllocGranularity := SystemInfo.dwAllocationGranularity;
PageSize := SystemInfo.dwPageSize;
{ Windows version information }
IsWinNT := Win32Platform = VER_PLATFORM_WIN32_NT;
Kernel32FileName := GetModulePath(GetModuleHandle(kernel32));
if (not IsWinNT) and VersionFixedFileInfo(Kernel32FileName, VerFixedFileInfo) then
KernelVersionHi := VerFixedFileInfo.dwProductVersionMS
else
KernelVersionHi := 0;
case GetWindowsVersion of
wvUnknown: ;
wvWin95:
IsWin95 := True;
wvWin95OSR2:
IsWin95OSR2 := True;
wvWin98:
IsWin98 := True;
wvWin98SE:
IsWin98SE := True;
wvWinME:
IsWinME := True;
wvWinNT31:
begin
IsWinNT3 := True;
IsWinNT31 := True;
end;
wvWinNT35:
begin
IsWinNT3 := True;
IsWinNT35 := True;
end;
wvWinNT351:
begin
IsWinNT3 := True;
IsWinNT351 := True;
end;
wvWinNT4:
IsWinNT4 := True;
wvWin2000:
IsWin2K := True;
wvWinXP:
IsWinXP := True;
end;
end;
//==================================================================================================
// Finalization
//==================================================================================================
procedure FinalizeSysInfo;
begin
UnloadSystemResourcesMeterLib;
end;
//--------------------------------------------------------------------------------------------------
initialization
InitSysInfo;
finalization
FinalizeSysInfo;
end.
|
unit MyTools;
// Вспомогательные функции
// (c) 2004-2010 Петроченко Н.Ю.
interface
uses SysUtils, Classes, Dialogs;
type TBuffer = array of Char;
procedure ErrorMessage(Msg: string);
function AddBackslash(const S: String): String;
function RemoveBackslash(const S: String): String;
function RemoveBackslashUnlessRoot(const S: String): String;
function AddQuotes(const S: String): String;
function RemoveQuotes(const S: String): String;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
function RemoveAccelChar(const S: String): String;
function AddPeriod(const S: String): String;
function IntColorToHex(Color: integer): string;
function HexToInt(Color: string): integer;
function CheckHexForHash(const col: string):string ;
function tok(const sep: string; var s: string): string;
function MakeRect(Pt1: TPoint; Pt2: TPoint): TRect;
function SplitString(str: string; separator: Char): TStringList;
function FindMinString(list: TStringList): integer;
function FindMinInt(list: TStringList): integer;
function FindMaxString(list: TStringList): integer;
function FindMaxInt(list: TStringList): integer;
function Replace(Str, X, Y: string): string;
function ConvertQuotes(const source_text:string):string;
function CntChRepet(InputStr: string; InputSubStr: char): integer;
implementation
// Окно сообщения
procedure ErrorMessage(Msg: string);
begin
MessageDlg('Ошибка!', Msg, mtError, [mbClose], '');
end;
function GetParamStr(P: PChar; var Param: String): PChar;
var
Len: Integer;
Buffer: array[0..4095] of Char;
begin
while True do begin
while (P[0] <> #0) and (P[0] <= ' ') do Inc(P);
if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break;
end;
Len := 0;
while (P[0] > ' ') and (Len < SizeOf(Buffer)) do
if P[0] = '"' then begin
Inc(P);
while (P[0] <> #0) and (P[0] <> '"') do begin
Buffer[Len] := P[0];
Inc(Len);
Inc(P);
end;
if P[0] <> #0 then Inc(P);
end
else begin
Buffer[Len] := P[0];
Inc(Len);
Inc(P);
end;
SetString(Param, Buffer, Len);
Result := P;
end;
function AddBackslash(const S: String): String;
{ Adds a trailing backslash to the string, if one wasn't there already.
But if S is an empty string, the function returns an empty string. }
begin
Result := S;
if (Result <> '') and (AnsiLastChar(Result)^ <> '\') then
Result := Result + '\';
end;
function RemoveBackslash(const S: String): String;
{ Removes the trailing backslash from the string, if one exists }
begin
Result := S;
if (Result <> '') and (AnsiLastChar(Result)^ = '\') then
SetLength(Result, Length(Result)-1);
end;
function RemoveBackslashUnlessRoot(const S: String): String;
{ Removes the trailing backslash from the string, if one exists and does
not specify a root directory of a drive (i.e. "C:\"}
var
L: Integer;
begin
Result := S;
L := Length(Result);
if L < 2 then
Exit;
if (AnsiLastChar(Result)^ = '\') and
((Result[L-1] <> ':') or (ByteType(Result, L-1) <> mbSingleByte)) then
SetLength(Result, L-1);
end;
function AddQuotes(const S: String): String;
{ Adds a quote (") character to the left and right sides of the string if
the string contains a space and it didn't have quotes already. This is
primarily used when spawning another process with a long filename as one of
the parameters. }
begin
Result := Trim(S);
if (AnsiPos(' ', Result) <> 0) and
((Result[1] <> '"') or (AnsiLastChar(Result)^ <> '"')) then
Result := '"' + Result + '"';
end;
function RemoveQuotes(const S: String): String;
{ Opposite of AddQuotes; removes any quotes around the string. }
begin
Result := S;
while (Result <> '') and (Result[1] = '"') do
Delete(Result, 1, 1);
while (Result <> '') and (AnsiLastChar(Result)^ = '"') do
SetLength(Result, Length(Result)-1);
end;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
{ Returns True if successful. Returns False if buffer wasn't large enough,
and called AdjustLength to resize it. }
begin
Result := Integer(Res) < Length(S);
SetLength(S, Res);
end;
function RemoveAccelChar(const S: String): String;
var
I: Integer;
begin
Result := S;
I := 1;
while I <= Length(Result) do begin
if not(Result[I] in LeadBytes) then begin
if Result[I] = '&' then
System.Delete(Result, I, 1);
Inc(I);
end
else
Inc(I, 2);
end;
end;
function AddPeriod(const S: String): String;
begin
Result := S;
if (Result <> '') and (AnsiLastChar(Result)^ > '.') then
Result := Result + '.';
end;
// Преобразует Hex-цвет (HTML) в обычный TColor
function HexToInt(Color: string): integer;
var
rColor: integer;
begin
rColor:=0;
Color := CheckHexForHash(Color);
if (length(color) >= 6) then
begin
{незабудьте, что TColor это bgr, а не rgb: поэтому необходимо изменить порядок}
color := '$00' + copy(color,5,2) + copy(color,3,2) + copy(color,1,2);
rColor := StrToInt(color);
end;
result := rColor;
end;
// Просто проверяет первый сивол строки на наличие '#' и удаляет его, если он найден
function CheckHexForHash(const col: string): string;
var
rCol: string;
begin
rCol:=col;
if rCol[1] = '#' then
rCol := StringReplace(rCol,'#','',[rfReplaceAll]);
result := rCol;
end;
function tok(const sep: string; var s: string): string;
function isoneof(c, s: string): Boolean;
var
iTmp: integer;
begin
Result := False;
for iTmp := 1 to Length(s) do
begin
if c = Copy(s, iTmp, 1) then
begin
Result := True;
Exit;
end;
end;
end;
var
c, t: string;
begin
if s = '' then
begin
Result := s;
Exit;
end;
c := Copy(s, 1, 1);
while isoneof(c, sep) do
begin
s := Copy(s, 2, Length(s) - 1);
c := Copy(s, 1, 1);
end;
t := '';
while (not isoneof(c, sep)) and (s <> '') do
begin
t := t + c;
s := Copy(s, 2, length(s) - 1);
c := Copy(s, 1, 1);
end;
Result := t;
end;
// Преобразует TColor в Hex-цвет (Delphi - BGR)
function IntColorToHex(Color: integer): string;
var
temp: string;
begin
temp:=IntToHex(Color, 6);
result := copy(temp,5,2) + copy(temp,3,2) + copy(temp,1,2);
end;
// Получение Rect по координатам угловых точек
function MakeRect(Pt1: TPoint; Pt2: TPoint): TRect;
begin
if pt1.x < pt2.x then
begin
Result.Left := pt1.x;
Result.Right := pt2.x;
end
else
begin
Result.Left := pt2.x;
Result.Right := pt1.x;
end;
if pt1.y < pt2.y then
begin
Result.Top := pt1.y;
Result.Bottom := pt2.y;
end
else
begin
Result.Top := pt2.y;
Result.Bottom := pt1.y;
end;
end;
function SplitString(str: string; separator: Char): TStringList;
var
i: integer;
num: integer;
begin
// Создание объекта
Result:=TStringList.Create;
num:=0;
// Подчет количества
for i:=1 to Length(str) do
begin
if str[i]=separator then num:=num+1;
end;
// Нарезка
for i:=0 to num do
begin
result.Add( tok(separator, str) );
end;
end;
// Поиск в списке первой по алфавиту строки
function FindMinString(list: TStringList): integer;
var
min: integer; // номер минимального элемента массива
i: integer; // номер элемента, сравниваемого с минимальным
begin
min := 0; // пусть первый элемент минимальный
for i := 1 to list.Count-1 do
begin
if List[i] < List[min] then min := i;
end;
result:=min;
end;
// Поиск в списке минимального целого числа
function FindMinInt(list: TStringList): integer;
var
min: integer; // номер минимального элемента массива
i: integer; // номер элемента, сравниваемого с минимальным
begin
min := 0; // пусть первый элемент минимальный
for i := 1 to list.Count-1 do
begin
if StrToInt(List[i]) < StrToInt(List[min]) then min := i;
end;
result:=min;
end;
// Поиск в списке последней по алфавиту строки
function FindMaxString(list: TStringList): integer;
var
max: integer; // номер минимального элемента массива
i: integer; // номер элемента, сравниваемого с минимальным
begin
max := 0; // пусть первый элемент минимальный
for i := 1 to list.Count-1 do
begin
if List[i] > List[max] then max := i;
end;
result:=max;
end;
// Поиск в списке максимального целого числа
function FindMaxInt(list: TStringList): integer;
var
max: integer; // номер максимального элемента массива
i: integer; // номер элемента, сравниваемого с максимальным
begin
max:= 0; // пусть первый элемент максимальный
for i:= 1 to list.Count-1 do
begin
if StrToInt(List[i]) > StrToInt(List[max]) then max:=i;
end;
result:=StrToInt(list[max]);
end;
function Replace(Str, X, Y: string): string;
{Str - строка, в которой будет производиться замена.
X - подстрока, которая должна быть заменена.
Y - подстрока, на которую будет произведена заменена}
var
buf1, buf2, buffer: string;
begin
buf1 := '';
buf2 := Str;
Buffer := Str;
while Pos(X, buf2) > 0 do
begin
buf2 := Copy(buf2, Pos(X, buf2), (Length(buf2) - Pos(X, buf2)) + 1);
buf1 := Copy(Buffer, 1, Length(Buffer) - Length(buf2)) + Y;
Delete(buf2, Pos(X, buf2), Length(X));
Buffer := buf1 + buf2;
end;
Replace := Buffer;
end;
// Замена прямых кавычек на "лапки"
function ConvertQuotes(const source_text:string):string;
const
REPLACE_CHARS: array[boolean] of char = (#187,#171);
var
i: cardinal;
rpl: cardinal;
begin
result:= source_text;
rpl:= 0;
for i:=1 to length(result) do
if result[i] = '"' then
begin
inc(rpl);
result[i] := REPLACE_CHARS[ odd(rpl) ];
end;
end;
function CntChRepet(InputStr: string; InputSubStr: char): integer;
var
i: integer;
begin
result := 0;
for i := 1 to length(InputStr) do
if InputStr[i] = InputSubStr then
inc(result);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.