hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 163
values | lang
stringclasses 53
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
112
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
113
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
float64 1
116k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
113
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 3
1.05M
| avg_line_length
float64 1
966k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c33db13aec102d81f11ededd8bc1c82251f8efe0 | 35,211 | pas | Pascal | source/StyleTypes.pas | the-Arioch/HtmlViewer | 302b9a4ae9d4042eb1e99fbbd91ac484ac98de29 | [
"MIT"
]
| 3 | 2015-03-31T13:32:10.000Z | 2017-10-13T07:51:58.000Z | source/StyleTypes.pas | the-Arioch/HtmlViewer | 302b9a4ae9d4042eb1e99fbbd91ac484ac98de29 | [
"MIT"
]
| null | null | null | source/StyleTypes.pas | the-Arioch/HtmlViewer | 302b9a4ae9d4042eb1e99fbbd91ac484ac98de29 | [
"MIT"
]
| 1 | 2016-10-18T06:20:25.000Z | 2016-10-18T06:20:25.000Z | {
Version 11.6
Copyright (c) 1995-2008 by L. David Baldwin
Copyright (c) 2008-2010 by HtmlViewer Team
Copyright (c) 2011-2015 by Bernd Gabriel
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
{$I htmlcons.inc}
unit StyleTypes;
interface
uses
Windows, SysUtils, Math, Forms, Variants, Graphics,
//
HtmlGlobals;
const
varInt = [varInteger, varByte, varSmallInt, varShortInt, varWord, varLongWord];
varFloat = [varSingle, varDouble, varCurrency];
varNum = varInt + varFloat;
type
ThtAlignmentStyle = (
aNone,
aTop,
aMiddle,
aBaseline,
aBottom,
aLeft,
aRight,
aJustify,
aSub,
aSuper);
const
CAlignmentStyle: array[ThtAlignmentStyle] of ThtString = (
'none',
'top',
'middle',
'baseline',
'bottom',
'left',
'right',
'justify',
'sub',
'super');
type
ThtBoxSizing = (
ContentBox,
BorderBox);
const
CBoxSizing: array[ThtBoxSizing] of ThtString = (
'content-box',
'border-box');
type
ThtBackgroundPosition = (
bpTop,
bpCenter,
bpBottom,
bpLeft,
bpRight,
bpPercent,
bpDim);
PositionRec = record
PosType: ThtBackgroundPosition;
Value: Integer;
RepeatD: Boolean;
Fixed: Boolean;
end;
PPositionRec = ^PositionRec;
PtPositionRec = record
X, Y: PositionRec;
end;
type
ThtBoxFloatStyle = (
flNone,
flLeft,
flRight,
flTop,
flBottom);
const
CBoxFloatStyle: array[ThtBoxFloatStyle] of ThtString = (
'none',
'left',
'right',
'top',
'bottom');
type
ThtBoxPositionStyle = (
posStatic,
posRelative,
posAbsolute,
posFixed);
const
CBoxPositionStyle: array[ThtBoxPositionStyle] of ThtString = (
'static',
'relative',
'absolute',
'fixed');
type
ThtBorderStyle = (
bssNone,
bssSolid,
bssInset,
bssOutset,
bssGroove,
bssRidge,
bssDashed,
bssDotted,
bssDouble);
const
CBorderStyle: array[ThtBorderStyle] of ThtString = (
'none',
'solid',
'inset',
'outset',
'groove',
'ridge',
'dashed',
'dotted',
'double');
type
ThtBulletStyle = (
lbBlank,
lbCircle,
lbDecimal,
lbDisc,
lbLowerAlpha,
lbLowerRoman,
lbNone,
lbSquare,
lbUpperAlpha,
lbUpperRoman);
const
CBulletStyle: array[ThtBulletStyle] of ThtString = (
'blank',
'circle',
'decimal',
'disc',
'lower-alpha',
'lower-roman',
'none',
'square',
'upper-alpha',
'upper-roman');
type
ThtClearStyle = (
clrNone,
clLeft,
clRight,
clAll);
type
ThtDisplayStyle = (
pdUnassigned,
pdInline,
pdBlock,
pdInlineBlock,
pdListItem,
pdRunIn,
pdCompact,
pdTable,
pdInlineTable,
pdTableRowGroup,
pdTableHeaderGroup,
pdTableFooterGroup,
pdTableRow,
pdTableColumnGroup,
pdTableColumn,
pdTableCell,
pdTableCaption,
pdNone);
const
CDisplayStyle: array [ThtDisplayStyle] of ThtString = (
'',
'inline',
'block',
'inline-block',
'list-item',
'run-in',
'compact',
'table',
'inline-table',
'table-row-group',
'table-header-group',
'table-footer-group',
'table-row',
'table-column-group',
'table-column',
'table-cell',
'table-caption',
'none');
CRootDisplayStyle: array[ThtDisplayStyle] of ThtDisplayStyle = (
pdUnassigned,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdTable,
pdTable,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdBlock,
pdNone);
function ToRootDisplayStyle(Display: ThtDisplayStyle): ThtDisplayStyle; {$ifdef UseInline} inline; {$endif}
type
ThtTextTransformStyle = (
txNone,
txUpper,
txLower,
txCaps);
type
ThtVisibilityStyle = (
viInherit,
viHidden,
viVisible);
type
ThtWhiteSpaceStyle = (
wsNormal,
wsNoWrap,
wsPre,
wsPreWrap,
wsPreLine{, wsInherit});
const
CWhiteSpace: array [ThtWhiteSpaceStyle] of ThtString = (
'normal',
'nowrap',
'pre',
'pre-wrap',
'pre-line');
//BG, 16.09.2010: CSS2.2: same sizes like html font size:
type
ThtFontSizeIncrement = -6..6;
ThtFontConvBase = array[0..7] of Double;
ThtFontConv = array[1..7] of Double;
const
FontConvBase: ThtFontConvBase = (0.5833, 0.75, 0.8333, 1.0, 1.1667, 1.5, 2.0, 3.0);
PreFontConvBase: ThtFontConvBase = (0.5, 0.5833, 0.75, 0.8333, 1.0, 1.25, 1.6667, 2.5);
type
ThtRectEdge = (reLeft, reTop, reRight, reBottom);
ThtRectIntegers = packed array[ThtRectEdge] of Integer;
ThtRectColors = packed array[ThtRectEdge] of TColor;
ThtRectStyles = packed array[ThtRectEdge] of ThtBorderStyle;
const
NullIntegers: ThtRectIntegers = (0, 0, 0, 0);
NoneColors: ThtRectColors = (clNone, clNone, clNone, clNone);
NoneStyles: ThtRectStyles = (bssNone, bssNone, bssNone, bssNone);
function htRectIntegers(Left, Top, Right, Bottom: Integer): ThtRectIntegers;
function htRectColors(Left, Top, Right, Bottom: TColor): ThtRectColors;
function htRectStyles(Left, Top, Right, Bottom: ThtBorderStyle): ThtRectStyles;
//------------------------------------------------------------------------------
// media types
//------------------------------------------------------------------------------
type
// http://www.w3.org/TR/2010/WD-CSS2-20101207/media.html
ThtMediaType = (
mtAll, // Suitable for all devices.
mtBraille, // Intended for braille tactile feedback devices.
mtEmbossed, // Intended for paged braille printers.
mtHandheld, // Intended for handheld devices (typically small screen, limited bandwidth).
mtPrint, // Intended for paged material and for documents viewed on screen in print preview mode. Please consult the section on paged media for information about formatting issues that are specific to paged media.
mtProjection, // Intended for projected presentations, for example projectors. Please consult the section on paged media for information about formatting issues that are specific to paged media.
mtScreen, // Intended primarily for color computer screens.
mtSpeech, // Intended for speech synthesizers. Note: CSS2 had a similar media type called 'aural' for this purpose. See the appendix on aural style sheets for details.
mtTty, // Intended for media using a fixed-pitch character grid (such as teletypes, terminals, or portable devices with limited display capabilities). Authors should not use pixel units with the "tty" media type.
mtTv // Intended for television-type devices (low resolution, color, limited-scrollability screens, sound available).
);
ThtMediaTypes = set of ThtMediaType;
const
CMediaTypes: array[ThtMediaType] of ThtString = (
'all',
'braille',
'embossed',
'handheld',
'print',
'projection',
'screen',
'speech',
'tty',
'tv'
);
AllMediaTypes: ThtMediaTypes = [
//mtAll, // Suitable for all devices.
mtBraille, // Intended for braille tactile feedback devices.
mtEmbossed, // Intended for paged braille printers.
mtHandheld, // Intended for handheld devices (typically small screen, limited bandwidth).
mtPrint, // Intended for paged material and for documents viewed on screen in print preview mode. Please consult the section on paged media for information about formatting issues that are specific to paged media.
mtProjection, // Intended for projected presentations, for example projectors. Please consult the section on paged media for information about formatting issues that are specific to paged media.
mtScreen, // Intended primarily for color computer screens.
mtSpeech, // Intended for speech synthesizers. Note: CSS2 had a similar media type called 'aural' for this purpose. See the appendix on aural style sheets for details.
mtTty, // Intended for media using a fixed-pitch character grid (such as teletypes, terminals, or portable devices with limited display capabilities). Authors should not use pixel units with the "tty" media type.
mtTv // Intended for television-type devices (low resolution, color, limited-scrollability screens, sound available).
];
function MediaTypesToStr(const MediaTypes: ThtMediaTypes): ThtString;
function TranslateMediaTypes(const MediaTypes: ThtMediaTypes): ThtMediaTypes;
function TryStrToMediaType(const Str: ThtString; out MediaType: ThtMediaType): Boolean;
function TryStrToMediaTypes(const Str: ThtString; out MediaTypes: ThtMediaTypes): Boolean;
function StrToFontName(const Str: ThtString): ThtString;
function StrToFontSize(const Str: ThtString; const FontConvBase: ThtFontConvBase; DefaultFontSize, Base, Default: Double): Double; overload;
function StrToFontSize(const Str: ThtString; const FontConv: ThtFontConv; Base, Default: Double): Double; overload;
function StrToLength(const Str: ThtString; Relative: Boolean; Base, EmBase, Default: Double): Double;
function TryStrToAlignmentStyle(const Str: ThtString; out AlignmentStyle: ThtAlignmentStyle): Boolean;
function TryStrToBoxSizing(const Str: ThtString; out ABoxSizing: ThtBoxSizing): Boolean;
function TryStrToBorderStyle(const Str: ThtString; out BorderStyle: ThtBorderStyle): Boolean;
function TryStrToBoxFloatStyle(const Str: ThtString; out Float: ThtBoxFloatStyle): Boolean;
function TryStrToBoxPositionStyle(const Str: ThtString; out Position: ThtBoxPositionStyle): Boolean;
function TryStrToBulletStyle(const Str: ThtString; out BulletStyle: ThtBulletStyle): Boolean;
function TryStrToDisplayStyle(const Str: ThtString; out Display: ThtDisplayStyle): Boolean;
function TryStrToWhiteSpace(const Str: ThtString; out AWhiteSpace: ThtWhiteSpaceStyle): Boolean;
function GetPositionInRange(Which: ThtBackgroundPosition; Where, Range: Integer): Integer;
{
Returns a positon according to the given settings.
Which: which position in the range to get. pLeft and pTop return 0, pBottom and pRight return Range.
Where: percentage or pixels for Which = pPercentage resp. pDim.
Range: the range in which the result can vary.
In the usual alignment calculations the range is outer size - inner size.
If you have to consider an offset to outer's parent, add it to the function result afterwards.
}
procedure AdjustForTiling(Tiled: Boolean; TileAreaMin, TileAreaMax, TileSize: Integer;
var Pos: Integer; out TiledEnd: Integer);
{
Returns the start and end value for tiling an object of given size.
Tiled: if false returns a TiledEnd according to unmodified Pos, that allows to pass the tiling
process and depending on the visibility of the object in the cliparea the untiled object is
processes at most once. If true, Pos is moved to a position between ClipMin - ObjectSize and
ClipMin so that the tiling process will put one of the tiles to original Pos.
TileAreaMin, TileAreaMax: the area in with the object is to tile.
TileSize: the size of the tile.
Pos: on input: the position to consider for tiling. on output the new position shifted by multiples
of the object size to where the object covers the tile area minimum.
TiledEnd: a position on and after which no more tiles are processed.
}
procedure CalcBackgroundLocationAndTiling(const PRec: PtPositionRec; ARect: TRect;
XOff, YOff, IW, IH, BW, BH: Integer; out X, Y, X2, Y2: Integer);
{
PRec has the CSS information on the background image, it's starting location and
whether it is tiled in x, y, neither, or both.
ARect is the cliprect, no point in drawing tiled images outside it.
XOff, YOff are offsets which allow for the fact that the viewable area may not be at 0,0.
IW, IH are the total width and height of the document if you could see it all at once.
BW, BH are bitmap dimensions used to calc tiling.
X, Y are the position (window coordinates) where the first background iamge will be drawn.
X2, Y2 are tiling limits. X2 and Y2 may be such that 0, 1, or many images will
get drawn. They're calculated so that only images within ARect are drawn.
}
{Internal stuff we expose for inlining}
const
// CSS 2.1 defines a fixed ratio between pt and px at 96 dpi: 1px = 0.75pt.
// (see http://www.w3.org/TR/2010/WD-CSS2-20101207/syndata.html#value-def-length for details).
HTMLViewerPixelsPerInch = 96.0; // fixed assumption in CSS 2.1 as lots of designs rely on it.
HTMLViewerPointsPerInch = 72.0;
//BG, 16.06.2015: Issue 399: StyleTypes.pas: Code improvement for C++Builder
// HTMLViewerPointsPerPixel = HTMLViewerPointsPerInch / HTMLViewerPixelsPerInch;
// produces idiotic "static const System::Extended HTMLViewerPointsPerPixel = 7.500000E-01;"
// in StyleTypes.hpp which then produces "unused" warnings.
// The following declaration produces just another #define:
HTMLViewerPointsPerPixel = 0.75; // HTMLViewerPointsPerInch / HTMLViewerPixelsPerInch;
type
ThtLengthUnitInfo = record
Name: ThtString;
Factor: Double; // factor of length unit
Index: Integer; // index of font size
IsAbsolute: Boolean;
end;
ThtUnit = (
luNone, luEm, luEx, luPercent, luPt, luPx, luPc, luIn, luCm, luMm,
fsNone, fsSmaller, fsLarger,
fsXxSmall, fsXSmall, fsSmall, fsMedium, fsLarge, fsXLarge, fsXxLarge);
ThtLengthUnit = luNone..luMm;
ThtFontSize = fsNone..fsXxLarge;
const
CUnitInfo: array [ThtUnit] of ThtLengthUnitInfo = (
// length units
(Name: ''; Factor: 1.00; IsAbsolute: True),
(Name: 'em'; Factor: 1.00; IsAbsolute: False),
(Name: 'ex'; Factor: 0.50; IsAbsolute: False),
(Name: '%' ; Factor: 0.01; IsAbsolute: False),
(Name: 'pt'; Factor: 0.75; IsAbsolute: True),
(Name: 'px'; Factor: 1.00; IsAbsolute: True),
(Name: 'pc'; Factor: 9.00; IsAbsolute: True),
(Name: 'in'; Factor: HTMLViewerPixelsPerInch ; IsAbsolute: True),
(Name: 'cm'; Factor: HTMLViewerPixelsPerInch / 2.54; IsAbsolute: True),
(Name: 'mm'; Factor: HTMLViewerPixelsPerInch / 25.4; IsAbsolute: True),
// css font sizes
(Name: ''; Index: 3; IsAbsolute: True),
(Name: 'smaller'; Index: -1; IsAbsolute: False),
(Name: 'larger'; Index: 1; IsAbsolute: False),
(Name: 'xx-small'; Index: 0; IsAbsolute: True),
(Name: 'x-small'; Index: 1; IsAbsolute: True),
(Name: 'small'; Index: 2; IsAbsolute: True),
(Name: 'medium'; Index: 3; IsAbsolute: True),
(Name: 'large'; Index: 4; IsAbsolute: True),
(Name: 'x-large'; Index: 5; IsAbsolute: True),
(Name: 'xx-large'; Index: 6; IsAbsolute: True)
);
implementation
//-- BG ---------------------------------------------------------- 05.04.2011 --
function htRectIntegers(Left, Top, Right, Bottom: Integer): ThtRectIntegers;
{$ifdef UseInline} inline; {$endif}
begin
Result[reTop] := Top;
Result[reLeft] := Left;
Result[reRight] := Right;
Result[reBottom] := Bottom;
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
function htRectColors(Left, Top, Right, Bottom: TColor): ThtRectColors;
{$ifdef UseInline} inline; {$endif}
begin
Result[reTop] := Top;
Result[reLeft] := Left;
Result[reRight] := Right;
Result[reBottom] := Bottom;
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
function htRectStyles(Left, Top, Right, Bottom: ThtBorderStyle): ThtRectStyles;
{$ifdef UseInline} inline; {$endif}
begin
Result[reTop] := Top;
Result[reLeft] := Left;
Result[reRight] := Right;
Result[reBottom] := Bottom;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function MediaTypesToStr(const MediaTypes: ThtMediaTypes): ThtString;
{$ifdef UseInline} inline; {$endif}
var
I: ThtMediaType;
begin
SetLength(Result, 0);
for I := low(I) to high(I) do
if I in MediaTypes then
begin
if Length(Result) = 0 then
Result := CMediaTypes[I]
else
Result := Result + ', ' + CMediaTypes[I];
end;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function TranslateMediaTypes(const MediaTypes: ThtMediaTypes): ThtMediaTypes;
{$ifdef UseInline} inline; {$endif}
begin
if mtAll in MediaTypes then
Result := AllMediaTypes
else
Result := MediaTypes;
end;
//-- BG ---------------------------------------------------------- 15.03.2011 --
function TryStrToMediaType(const Str: ThtString; out MediaType: ThtMediaType): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtMediaType;
begin
for I := low(I) to high(I) do
if CMediaTypes[I] = Str then
begin
Result := True;
MediaType := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 17.04.2011 --
function TryStrToMediaTypes(const Str: ThtString; out MediaTypes: ThtMediaTypes): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I, J: Integer;
MediaType: ThtMediaType;
begin
Result := False;
MediaTypes := [];
I := 1;
repeat
J := PosX(',', Str, I);
if J = 0 then
// no more commas, try the rest
J := Length(Str) + 1;
if TryStrToMediaType(htLowerCase(Trim(Copy(Str, I, J - I))), MediaType) then
begin
Include(MediaTypes, MediaType);
Result := True;
end;
I := J + 1;
until J > Length(Str);
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
function TryStrToAlignmentStyle(const Str: ThtString; out AlignmentStyle: ThtAlignmentStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtAlignmentStyle;
begin
for I := low(I) to high(I) do
if CAlignmentStyle[I] = Str then
begin
Result := True;
AlignmentStyle := I;
exit;
end;
Result := False;
end;
//-- JPM --------------------------------------------------------- 03.02-2012 --
function TryStrToBoxSizing(const Str: ThtString; out ABoxSizing: ThtBoxSizing): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtBoxSizing;
begin
for I := low(I) to high(I) do
if CBoxSizing[I] = Str then
begin
Result := True;
ABoxSizing := I;
exit;
end;
Result := False;
end;
//-- JPM --------------------------------------------------------- 03.02-2012 --
function TryStrToWhiteSpace(const Str: ThtString; out AWhiteSpace: ThtWhiteSpaceStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtWhiteSpaceStyle;
begin
for I := low(I) to high(I) do
if CWhiteSpace[I] = Str then
begin
Result := True;
AWhiteSpace := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 16.03.2011 --
function TryStrToBorderStyle(const Str: ThtString; out BorderStyle: ThtBorderStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtBorderStyle;
begin
for I := low(I) to high(I) do
if CBorderStyle[I] = Str then
begin
Result := True;
BorderStyle := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TryStrToBoxFloatStyle(const Str: ThtString; out Float: ThtBoxFloatStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtBoxFloatStyle;
begin
for I := low(I) to high(I) do
if CBoxFloatStyle[I] = Str then
begin
Result := True;
Float := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TryStrToBoxPositionStyle(const Str: ThtString; out Position: ThtBoxPositionStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtBoxPositionStyle;
begin
for I := low(I) to high(I) do
if CBoxPositionStyle[I] = Str then
begin
Result := True;
Position := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
function TryStrToBulletStyle(const Str: ThtString; out BulletStyle: ThtBulletStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtBulletStyle;
begin
for I := low(I) to high(I) do
if CBulletStyle[I] = Str then
begin
Result := True;
BulletStyle := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 16.03.2011 --
function TryStrToDisplayStyle(const Str: ThtString; out Display: ThtDisplayStyle): Boolean;
{$ifdef UseInline} inline; {$endif}
var
I: ThtDisplayStyle;
begin
for I := low(I) to high(I) do
if CDisplayStyle[I] = Str then
begin
Result := True;
Display := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function ToRootDisplayStyle(Display: ThtDisplayStyle): ThtDisplayStyle; {$ifdef UseInline} inline; {$endif}
{$ifdef UseInline} inline; {$endif}
begin
Result := CRootDisplayStyle[Display];
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function StrToFontName(const Str: ThtString): ThtString;
function GetNextSplitter(const Str: ThtString; var I: Integer; out Splitter: ThtString): Boolean;
var
J: Integer;
Dlm: ThtChar;
begin
Result := I < Length(Str);
if Result then
begin
J := PosX(',', Str, I);
if J = 0 then
// no more commas, try the rest
J := Length(Str) + 1;
// trim left and detect string delimiters " or '
Dlm := #0;
while I < J do
begin
case Str[I] of
TabChar,
LfChar,
FfChar,
CrChar,
SpcChar:
Inc(I);
'''',
'"':
begin
Dlm := Str[I];
Inc(I);
break;
end;
else
break;
end;
end;
// trim right and detect matching string delimiter
while I < J do
begin
case Str[J - 1] of
TabChar,
LfChar,
FfChar,
CrChar,
SpcChar:
Dec(I);
else
if Str[J - 1] = Dlm then
Dec(J);
break;
end;
end;
if I < J then
Splitter := Copy(Str, I, J - I)
else
Result := False;
I := J + 1;
end;
end;
procedure TranslateGenericFontName(var Str: ThtString);
const
AMax = 5;
Generic1: array[1..AMax] of ThtString = ('serif', 'monospace', 'sans-serif', 'cursive', 'helvetica');
Generic2: array[1..AMax] of ThtString = ('Times New Roman', 'Courier New', 'Arial', 'Lucida Handwriting', 'Arial');
var
I: Integer;
F: ThtString;
begin
F := htLowerCase(Str);
for I := 1 to AMax do
if htCompareString(F, Generic1[I]) = 0 then
begin
Str := Generic2[I];
break;
end;
end;
var
Pos: Integer;
FontName: ThtString;
begin
Pos := 1;
while GetNextSplitter(Str, Pos, FontName) do
begin
TranslateGenericFontName(FontName);
if Screen.Fonts.IndexOf(FontName) >= 0 then
begin
Result := FontName;
break;
end;
end;
end;
//-- BG ---------------------------------------------------------- 14.07.2010 --
function DecodeSize(const Str: ThtString; out V: Double; out U: ThtString): Boolean;
{$ifdef UseInline} inline; {$endif}
{
Get a mandatory numerical value and an optional unit string from given Str.
Returns true, if at least the numerical value has been parsed from Str.
Str is the string to parse.
V returns the parsed numerical value.
U returns the parsed unit string or an empty string;
}
var
I, J, L: Integer;
begin
U := '';
Val(Str, V, I);
Result := I <> 1;
if Result then
begin
L := Length(Str);
if I = 0 then
I := L + 1;
J := Pos('e', Str); {'e' would be legal for Val but not for us}
if (J > 0) and (I > J) then
I := J;
if I <= L then
begin
Val(Copy(Str, 1, I - 1), V, J);
U := Trim(Copy(Str, I, L - I + 1)); // text after number, maybe a unit
end;
end;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TryStrToLenthUnit(const Str: ThtString; out LengthUnit: ThtLengthUnit): Boolean;
{$ifdef UseInline} inline; {$endif}
var
L: ThtString;
I: ThtLengthUnit;
begin
L := htLowerCase(Str);
for I := low(I) to high(I) do
if htCompareString(CUnitInfo[I].Name, L) = 0 then
begin
Result := True;
LengthUnit := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TryStrToFontSize(const Str: ThtString; out FontSize: ThtFontSize): Boolean;
{$ifdef UseInline} inline; {$endif}
var
L: ThtString;
I: ThtFontSize;
begin
L := htLowerCase(Str);
for I := low(I) to high(I) do
if htCompareString(CUnitInfo[I].Name, L) = 0 then
begin
Result := True;
FontSize := I;
exit;
end;
Result := False;
end;
//------------------------------------------------------------------------------
function StrToLength(const Str: ThtString; Relative: Boolean; Base, EmBase, Default: Double): Double;
{$ifdef UseInline} inline; {$endif}
{
Given a length string, return the appropriate pixel value.
Base is the base value for a relative value without unit or with percentage.
EmBase is the base value for units relative to the font.
Default returned if no match.
}
var
V: Double;
U: ThtString;
LU: ThtLengthUnit;
begin
Result := Default;
if DecodeSize(Str, V, U) then
begin
{U the units}
if U = '' then
begin
if Relative then
Result := V * Base;
end
else if TryStrToLenthUnit(U, LU) then
with CUnitInfo[LU] do
if IsAbsolute then
Result := V * Factor
else if LU = luPercent then
Result := V * Factor * Base
else
Result := V * Factor * EmBase
else
end;
end;
//------------------------------------------------------------------------------
function StrToFontSize(const Str: ThtString; const FontConv: ThtFontConv; Base, Default: Double): Double;
{given a font-size ThtString, return the point size}
function IncFontSize(Increment: ThtFontSizeIncrement): Double;
var
OldIndex, NewIndex: Byte;
D1, D2: Double;
begin
// get nearest old font size index
OldIndex := 4;
D1 := Base - FontConv[OldIndex];
repeat
case Sign(D1) of
-1:
begin
Dec(OldIndex);
D2 := Base - FontConv[OldIndex];
if D2 >= 0 then
begin
if Abs(D1) < Abs(D2) then
Inc(OldIndex);
break;
end;
D1 := D2;
end;
1:
begin
Inc(OldIndex);
D2 := Base - FontConv[OldIndex];
if D2 <= 0 then
begin
if Abs(D1) > Abs(D2) then
Dec(OldIndex);
break;
end;
D1 := D2;
end;
else
break;
end;
until (OldIndex = 1) or (OldIndex = 7);
NewIndex := OldIndex + Increment;
if NewIndex < 1 then
begin
Inc(OldIndex, 1 - NewIndex);
NewIndex := 1;
end
else if NewIndex > 7 then
begin
Dec(OldIndex, NewIndex - 7);
NewIndex := 7;
end;
if OldIndex = NewIndex then
Result := Base
else
Result := Base * FontConv[NewIndex] / FontConv[OldIndex];
end;
var
V: Double;
U: ThtString;
LU: ThtLengthUnit;
FS: ThtFontSize;
begin
Result := Default;
if DecodeSize(Str, V, U) then
begin
if TryStrToLenthUnit(U, LU) then
with CUnitInfo[LU] do
if IsAbsolute then
Result := V * Factor * HTMLViewerPointsPerPixel
else
Result := V * Factor * Base;
end
else
begin
if TryStrToFontSize(Str, FS) then
with CUnitInfo[FS] do
if IsAbsolute then
Result := FontConv[Index]
else
Result := IncFontSize(Index);
end;
end;
//------------------------------------------------------------------------------
function StrToFontSize(const Str: ThtString; const FontConvBase: ThtFontConvBase; DefaultFontSize, Base, Default: Double): Double;
{given a font-size ThtString, return the point size}
function IncFontSize(Increment: ThtFontSizeIncrement): Double;
var
OldIndex, NewIndex: Byte;
D1, D2: Double;
begin
// get nearest old font size index
OldIndex := 4;
D1 := Base - FontConvBase[OldIndex] * DefaultFontSize;
repeat
case Sign(D1) of
-1:
begin
Dec(OldIndex);
D2 := Base - FontConvBase[OldIndex] * DefaultFontSize;
if D2 >= 0 then
begin
if Abs(D1) < Abs(D2) then
Inc(OldIndex);
break;
end;
D1 := D2;
end;
1:
begin
Inc(OldIndex);
D2 := Base - FontConvBase[OldIndex] * DefaultFontSize;
if D2 <= 0 then
begin
if Abs(D1) > Abs(D2) then
Dec(OldIndex);
break;
end;
D1 := D2;
end;
else
break;
end;
until (OldIndex = 1) or (OldIndex = 7);
NewIndex := OldIndex + Increment;
if NewIndex < 1 then
begin
Inc(OldIndex, 1 - NewIndex);
NewIndex := 1;
end
else if NewIndex > 7 then
begin
Dec(OldIndex, NewIndex - 7);
NewIndex := 7;
end;
if OldIndex = NewIndex then
Result := Base
else
Result := Base * FontConvBase[NewIndex] / FontConvBase[OldIndex];
end;
var
V: Double;
U: ThtString;
LU: ThtLengthUnit;
FS: ThtFontSize;
begin
Result := Default;
if DecodeSize(Str, V, U) then
begin
if TryStrToLenthUnit(U, LU) then
with CUnitInfo[LU] do
if IsAbsolute then
Result := V * Factor * HTMLViewerPointsPerPixel
else
Result := V * Factor * Base;
end
else
begin
if TryStrToFontSize(Str, FS) then
with CUnitInfo[FS] do
if IsAbsolute then
Result := FontConvBase[Index] * DefaultFontSize
else
Result := IncFontSize(Index);
end;
end;
//-- BG ---------------------------------------------------------- 07.04.2011 --
function GetPositionInRange(Which: ThtBackgroundPosition; Where, Range: Integer): Integer;
{$ifdef UseInline} inline; {$endif}
{
Returns a positon according to the given settings.
Which: which position in the range to get. pLeft and pTop return 0, pBottom and pRight return Range.
Where: percentage or pixels for Which = pPercentage resp. pDim.
Range: the range in which the result can vary.
In the usual alignment calculations the range is outer size - inner size.
If you have to consider an offset to outer's parent, add it to the function result afterwards.
}
begin
case Which of
bpTop,
bpLeft:
Result := 0;
bpCenter:
Result := Range div 2;
bpBottom,
bpRight:
Result := Range;
bpPercent:
Result := (Range * Where) div 100;
bpDim:
Result := Where;
else
Result := 0;
end;
end;
//-- BG ---------------------------------------------------------- 07.04.2011 --
procedure AdjustForTiling(Tiled: Boolean; TileAreaMin, TileAreaMax, TileSize: Integer;
var Pos: Integer; out TiledEnd: Integer);
{$ifdef UseInline} inline; {$endif}
{
Returns the start and end value for tiling a tile of given size.
Tiled: if false returns a TiledEnd according to unmodified Pos, that allows to pass the tiling
process and depending on the visibility of the object in the cliparea the untiled object is
processes at most once. If true, Pos is moved to a position between ClipMin - ObjectSize and
ClipMin so that the tiling process will put one of the tiles to original Pos.
TileAreaMin, TileAreaMax: the area in which the object is to tile.
TileSize: the size of the tile.
Pos: on input: the position to consider for tiling. on output the new position shifted by multiples
of the object size to where the object covers the tile area minimum.
TiledEnd: a position on and after which no more tiles are processed.
}
var
TileAreaMinPos: Integer;
begin
if Tiled then
begin
TileAreaMinPos := TileAreaMin - Pos;
{figure a starting point for tiling. This will be less that one object size less than the tile area min}
if TileSize <= TileAreaMinPos then
Pos := TileAreaMin - TileAreaMinPos mod TileSize
else if TileAreaMinPos < 0 then
Pos := TileAreaMin - (TileSize - -TileAreaMinPos mod TileSize);
TiledEnd := TileAreaMax;
end
else
begin {a single image or row}
TiledEnd := Pos; {assume it's not in the tile area and won't be output}
if (TileAreaMin < Pos + TileSize) and (Pos < TileAreaMax) then
Inc(TiledEnd); {it is in the tile area, show it}
end;
end;
//-- BG ---------------------------------------------------------- 07.04.2011 --
procedure CalcBackgroundLocationAndTiling(const PRec: PtPositionRec; ARect: TRect;
XOff, YOff, IW, IH, BW, BH: Integer; out X, Y, X2, Y2: Integer);
{$ifdef UseInline} inline; {$endif}
{
PRec has the CSS information on the background image, it's starting location and
whether it is tiled in x, y, neither, or both.
ARect is the cliprect, no point in drawing tiled images outside it.
XOff, YOff are offsets which allow for the fact that the viewable area may not be at 0,0.
IW, IH are the total width and height of the document if you could see it all at once.
BW, BH are bitmap dimensions used to calc tiling.
X, Y are the position (window coordinates) where the first background iamge will be drawn.
X2, Y2 are tiling limits. X2 and Y2 may be such that 0, 1, or many images will
get drawn. They're calculated so that only images within ARect are drawn.
}
begin
with PRec.X do
begin
X := GetPositionInRange(PosType, Value, IW - BW) - XOff;
AdjustForTiling(RepeatD, ARect.Left, ARect.Right, BW, X, X2);
end;
with PRec.Y do
begin
Y := GetPositionInRange(PosType, Value, IH - BH) - YOff;
AdjustForTiling(RepeatD, ARect.Top, ARect.Bottom, BH, Y, Y2);
end;
end;
end.
| 29.941327 | 223 | 0.626963 |
83067875e4fb707f98342b384acde7480a546c41 | 11,066 | pas | Pascal | windows/src/ext/jedi/jvcl/tests/archive/jvcl/source/JvIColEdit.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/source/JvIColEdit.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/source/JvIColEdit.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {-----------------------------------------------------------------------------
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/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: JvIcoLEdit.PAS, released on 2002-07-04.
The Initial Developers of the Original Code are: Fedor Koshevnikov, Igor Pavluk and Serge Korolev
Copyright (c) 1997, 1998 Fedor Koshevnikov, Igor Pavluk and Serge Korolev
Copyright (c) 2001,2002 SGB Software
All Rights Reserved.
Last Modified: 2002-07-04
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.sourceforge.net
Known Issues:
-----------------------------------------------------------------------------}
{$I JVCL.INC}
unit JvIcoLEdit;
interface
uses
{$IFDEF WIN32}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
Messages, Classes, Graphics, Forms, Controls, Dialogs,
{$IFDEF COMPILER6_UP}
RTLConsts, DesignIntf, DesignEditors, VCLEditors,
{$ELSE}
LibIntf, DsgnIntf,
{$ENDIF}
StdCtrls, ExtCtrls,
{$IFDEF COMPILER3_UP}
ExtDlgs,
{$ELSE}
ImagPrvw,
{$ENDIF}
JvIcoList, JvSpeedbar, JvComponent;
type
TIconListDialog = class(TForm)
OK: TButton;
Cancel: TButton;
Holder: TPanel;
Slot0: TPanel;
Slot1: TPanel;
Slot2: TPanel;
Slot3: TPanel;
Slot4: TPanel;
Image0: TImage;
Image1: TImage;
Image2: TImage;
Image3: TImage;
Image4: TImage;
Bevel1: TBevel;
Label1: TLabel;
CntLabel: TLabel;
Label3: TLabel;
IdxLabel: TLabel;
ScrollBar: TScrollBar;
JvSpeedBar1: TJvSpeedBar;
JvSpeedbarSection1: TJvSpeedbarSection;
Load: TJvSpeedItem;
LoadAni: TJvSpeedItem;
Delete: TJvSpeedItem;
Clear: TJvSpeedItem;
Copy: TJvSpeedItem;
Paste: TJvSpeedItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure LoadClick(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure CopyClick(Sender: TObject);
procedure PasteClick(Sender: TObject);
procedure UpdateClipboard(Sender: TObject);
procedure ScrollBarChange(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure LoadAniClick(Sender: TObject);
private
FIcons: TJvIconList;
FTopIndex: Integer;
FSelected: Integer;
{$IFDEF COMPILER3_UP}
FileDialog: TOpenPictureDialog;
{$ELSE}
FileDialog: TOpenDialog;
{$ENDIF}
procedure SetSelectedIndex(Index: Integer; Force: Boolean);
procedure ListChanged(Sender: TObject);
function GetSelectedIcon: TIcon;
procedure CheckButtons;
procedure ValidateImage;
procedure CheckEnablePaste;
procedure LoadAniFile;
procedure WMActivate(var Msg: TWMActivate); message WM_ACTIVATE;
public
Modified: Boolean;
end;
TIconListProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
procedure EditIconList(IconList: TJvIconList);
implementation
uses
SysUtils, Clipbrd, Consts, Math,
JvClipIcon, JvVCLUtils, JvxDConst, JvAniFile;
{$B-}
{$IFDEF WIN32}
{$D-}
{$ENDIF}
{$R *.DFM}
const
sSlot = 'Slot%d';
sImage = 'Image%d';
procedure EditIconList(IconList: TJvIconList);
begin
with TIconListDialog.Create(Application) do
try
FIcons.Assign(IconList);
Modified := False;
if (ShowModal = mrOk) and Modified then
IconList.Assign(FIcons);
finally
Free;
end;
end;
//=== TIconListProperty ======================================================
procedure TIconListProperty.Edit;
var
Editor: TIconListDialog;
Comp: TPersistent;
CurDir: string;
Res: Integer;
begin
Editor := TIconListDialog.Create(nil);
try
Comp := GetComponent(0);
if Comp is TComponent then
Editor.Caption := TComponent(Comp).Name + '.' + GetName;
Editor.FIcons.Assign(TJvIconList(Pointer(GetOrdValue)));
Editor.Modified := False;
CurDir := GetCurrentDir;
try
Res := Editor.ShowModal;
finally
SetCurrentDir(CurDir);
end;
if (Res = mrOk) and Editor.Modified then
begin
TJvIconList(Pointer(GetOrdValue)).Assign(Editor.FIcons);
Designer.Modified;
end;
finally
Editor.Free;
end;
end;
function TIconListProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TIconListProperty.GetValue: string;
var
List: TJvIconList;
begin
List := TJvIconList(Pointer(GetOrdValue));
if (List = nil) or (List.Count = 0) then
Result := ResStr(srNone)
else
Result := '(' + List.ClassName + ')';
end;
procedure TIconListProperty.SetValue(const Value: string);
begin
if Value = '' then
SetOrdValue(0);
end;
//=== TIconListDialog ========================================================
procedure TIconListDialog.LoadAniFile;
var
Dialog: TOpenDialog;
AniCursor: TJvAnimatedCursorImage;
begin
Dialog := TOpenDialog.Create(Application);
try
with Dialog do
begin
Options := [ofHideReadOnly, ofFileMustExist];
DefaultExt := 'ani';
Filter := srAniCurFilter;
if Execute then
begin
AniCursor := TJvAnimatedCursorImage.Create;
try
AniCursor.LoadFromFile(FileName);
FIcons.Assign(AniCursor);
finally
AniCursor.Free;
end;
end;
end;
finally
Dialog.Free;
end;
end;
function TIconListDialog.GetSelectedIcon: TIcon;
begin
Result := nil;
if (FIcons.Count > 0) and (FSelected < FIcons.Count) then
Result := FIcons[FSelected];
end;
procedure TIconListDialog.CheckEnablePaste;
begin
Paste.Enabled := Clipboard.HasFormat(CF_ICON);
end;
procedure TIconListDialog.SetSelectedIndex(Index: Integer; Force: Boolean);
begin
if Force or (Index <> FSelected) then
begin
Index := Min(FIcons.Count, Max(Index, 0));
while (FTopIndex < Index - 4) do
Inc(FTopIndex);
if Index < FTopIndex then
FTopIndex := Index;
FSelected := Index;
if FSelected <> ScrollBar.Position then
ScrollBar.Position := FSelected;
ValidateImage;
end;
end;
procedure TIconListDialog.ListChanged(Sender: TObject);
begin
ScrollBar.Max := FIcons.Count;
SetSelectedIndex(FSelected, True);
Modified := True;
end;
procedure TIconListDialog.CheckButtons;
var
Enable: Boolean;
begin
Enable := (FIcons.Count > 0) and (FSelected < FIcons.Count) and
(FSelected >= 0);
Clear.Enabled := FIcons.Count > 0;
Delete.Enabled := Enable;
Copy.Enabled := Enable;
CheckEnablePaste;
end;
procedure TIconListDialog.ValidateImage;
var
Enable: Boolean;
I: Integer;
Image, Slot: TComponent;
begin
for I := 0 to 4 do
begin
Image := FindComponent(Format(sImage, [I]));
Slot := FindComponent(Format(sSlot, [I]));
if Image <> nil then
with TImage(Image).Picture do
begin
if FTopIndex + I < FIcons.Count then
Assign(FIcons[FTopIndex + I])
else
Assign(nil);
{$IFDEF COMPILER3_UP}
TImage(Image).Transparent := True;
{$ENDIF}
end;
if Slot <> nil then
TPanel(Slot).ParentColor := True;
end;
Slot := FindComponent(Format(sSlot, [FSelected - FTopIndex]));
if Slot <> nil then
TPanel(Slot).Color := clActiveCaption;
CntLabel.Caption := IntToStr(FIcons.Count);
Enable := (FIcons.Count > 0) and (FSelected <= FIcons.Count) and
(FSelected >= 0);
if Enable then
IdxLabel.Caption := IntToStr(FSelected)
else
IdxLabel.Caption := '';
CheckButtons;
end;
procedure TIconListDialog.FormCreate(Sender: TObject);
{$IFDEF COMPILER3_UP}
var
I: Integer;
Image: TComponent;
{$ENDIF}
begin
{$IFDEF COMPILER3_UP}
FileDialog := TOpenPictureDialog.Create(Self);
for I := 0 to 4 do
begin
Image := FindComponent(Format(sImage, [I]));
if Image <> nil then
TImage(Image).Transparent := True;
end;
{$ELSE}
FileDialog := TOpenDialog.Create(Self);
{$ENDIF}
with FileDialog do
begin
Title := srLoadIcon;
Options := [ofHideReadOnly, ofFileMustExist];
DefaultExt := GraphicExtension(TIcon);
Filter := GraphicFilter(TIcon);
end;
FIcons := TJvIconList.Create;
FIcons.OnChange := ListChanged;
FTopIndex := 0;
FSelected := 0;
Clear.Enabled := False;
Copy.Enabled := False;
Delete.Enabled := False;
CheckEnablePaste;
end;
procedure TIconListDialog.FormDestroy(Sender: TObject);
begin
FIcons.OnChange := nil;
FIcons.Free;
end;
procedure TIconListDialog.UpdateClipboard(Sender: TObject);
begin
CheckEnablePaste;
end;
procedure TIconListDialog.LoadClick(Sender: TObject);
var
Ico: TIcon;
I: Integer;
{$IFNDEF COMPILER3_UP}
FileName: string;
{$ENDIF}
begin
{$IFNDEF COMPILER3_UP}
FileName := '';
if SelectImage(FileName, GraphicExtension(TIcon), GraphicFilter(TIcon)) then
begin
FileDialog.Filename := FileName;
{$ELSE}
if FileDialog.Execute then
begin
{$ENDIF}
Ico := TIcon.Create;
try
Ico.LoadFromFile(FileDialog.Filename);
I := Min(FSelected + 1, FIcons.Count);
FIcons.Insert(I, Ico);
SetSelectedIndex(I, True);
finally
Ico.Free;
end;
end;
end;
procedure TIconListDialog.CopyClick(Sender: TObject);
begin
CopyIconToClipboard(GetSelectedIcon, clBtnFace);
CheckEnablePaste;
end;
procedure TIconListDialog.PasteClick(Sender: TObject);
var
Ico: TIcon;
begin
if Clipboard.HasFormat(CF_ICON) then
begin
Ico := CreateIconFromClipboard;
try
FIcons[FSelected] := Ico;
finally
Ico.Free;
end;
end;
end;
procedure TIconListDialog.WMActivate(var Msg: TWMActivate);
begin
if Msg.Active <> WA_INACTIVE then
CheckEnablePaste;
inherited;
end;
procedure TIconListDialog.ClearClick(Sender: TObject);
begin
FIcons.Clear;
end;
procedure TIconListDialog.ScrollBarChange(Sender: TObject);
begin
SetSelectedIndex(ScrollBar.Position, False);
end;
procedure TIconListDialog.DeleteClick(Sender: TObject);
begin
FIcons.Delete(FSelected);
end;
procedure TIconListDialog.ImageMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Index: Integer;
begin
if Button = mbLeft then
begin
for Index := 0 to 4 do
begin
if TComponent(Sender).Name = Format(sImage, [Index]) then
Break;
if TComponent(Sender).Name = Format(sSlot, [Index]) then
Break;
end;
SetSelectedIndex(FTopIndex + Index, True);
end;
end;
procedure TIconListDialog.LoadAniClick(Sender: TObject);
begin
LoadAniFile;
end;
end.
| 23.797849 | 97 | 0.680463 |
c3759bd9ce60f3d91eb6a7a40b6cca640661b7b5 | 344 | pas | Pascal | Games/Sokoban/LoadSettingsUnit.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 11 | 2017-06-17T05:13:45.000Z | 2021-07-11T13:18:48.000Z | Games/Sokoban/LoadSettingsUnit.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 2 | 2019-03-05T12:52:40.000Z | 2021-12-03T12:34:26.000Z | Games/Sokoban/LoadSettingsUnit.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 6 | 2017-09-07T09:10:09.000Z | 2022-02-19T20:19:58.000Z | unit LoadSettingsUnit;
interface
uses MainUnit, INIFiles, SysUtils;
procedure LoadSettings;
implementation
procedure LoadSettings;
var
SettingsFile: TIniFile;
begin
SettingsFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) +
'settings.ini');
try
finally
SettingsFile.Free;
end;
end;
end.
| 13.76 | 65 | 0.688953 |
fccaa2e0bab4cde23939365bc7698032815f8792 | 186,753 | dfm | Pascal | windows/src/ext/jedi/jvcl/jvcl/examples/JvXPControls/JvXPBar/BCB/MainForm.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/jvcl/examples/JvXPControls/JvXPBar/BCB/MainForm.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/jvcl/examples/JvXPControls/JvXPBar/BCB/MainForm.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | object frmMain: TfrmMain
Left = 192
Top = 107
Width = 571
Height = 465
Caption = 'JvXPBar Demo'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object spltMain: TSplitter
Left = 206
Top = 0
Width = 4
Height = 438
Cursor = crHSplit
ResizeStyle = rsUpdate
end
object cntWinXPBar: TJvXPContainer
Left = 0
Top = 0
Width = 206
Height = 438
BoundLines = [blLeft, blTop, blRight, blBottom]
Caption = 'cntWinXPBar'
Color = 14985086
ParentColor = False
Align = alLeft
object sbxWinXPBar: TScrollBox
Left = 1
Top = 1
Width = 204
Height = 436
HorzScrollBar.Smooth = True
HorzScrollBar.Style = ssFlat
HorzScrollBar.Tracking = True
VertScrollBar.Smooth = True
VertScrollBar.Style = ssFlat
VertScrollBar.Tracking = True
Align = alClient
BorderStyle = bsNone
TabOrder = 0
object JvXPContainer1: TJvXPContainer
Left = 0
Top = 0
Width = 204
Height = 183
AutoSize = True
BorderWidth = 4
Caption = 'JvXPContainer1'
Align = alTop
object dxWinXPBar4: TJvXPBar
Left = 4
Top = 144
Width = 196
Height = 35
Caption = 'Structure'
Collapsed = True
Colors.BodyColor = 4227327
Colors.GradientTo = 4227327
Colors.SeparatorColor = 4227327
Items = <
item
end
item
end
item
end
item
end
item
end
item
end
item
end
item
end
item
end
item
end
item
end
item
end>
RollImages = ilWhiteButtons
Font.Charset = DEFAULT_CHARSET
Font.Color = 17877
Font.Height = -13
Font.Name = 'MS Shell Dlg 2'
Font.Style = []
HeaderFont.Charset = DEFAULT_CHARSET
HeaderFont.Color = clWindowText
HeaderFont.Height = -13
HeaderFont.Name = 'MS Shell Dlg 2'
HeaderFont.Style = [fsBold]
HotTrackColor = 4227327
Icon.Data = {
0000010001002020040000000000E80200001600000028000000200000004000
0000010004000000000000020000000000000000000000000000000000000000
0000000080000080000000808000800000008000800080800000C0C0C0008080
80000000FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF000000
0000000000000000000000000000888888888888800008888888888888008F7A
A7700007800008F7AA77000078008F7777788887800008F77777888878008FFF
FFFFFFFF800008FFFFFFFFFFF800080000000000700000800000000007000888
888888880000008888888888800008F7777777780000008F77777777800008F8
044444780000008F80444447800008F80CCCC4780000008F80CCCC47800008F8
0CCCC4780000008F80CCCC47800008F80ECCC4780000008F80ECCC47800008F8
000000780000008F80000007800008F7777777780000008F7777777780000088
8888888800000008888888888000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000888888888888800000000000000000008F7AA7700007800000000000000
000008F7777788887800000000000000000008FFFFFFFFFFF800000000000000
0000008000000000070000000000000000000088888888888000000000000000
0000008F7777777780000000000000000000008F806666878000000000000000
0000008F8066668780000000000000000000008F806666878000000000000000
0000008F80E6668780000000000000000000008F800000878000000000000000
0000008F77777777800000000000000000000008888888888000000000008007
C003000380010003800100038001000380018003C0018007C0038007C0038007
C0038007C0038007C00380038003800440038006C003C00EE007FFFEFFFFFFFE
FFFFFFC003FFFF8001FFFF8001FFFF8001FFFF8001FFFFC001FFFFC003FFFFC0
03FFFFC003FFFFC003FFFFC003FFFFC003FFFFC003FFFFC003FFFFE007FF}
RollStep = 5
ShowItemFrame = False
RoundedItemFrame = 0
Align = alTop
ParentFont = False
object tvSelfView: TTreeView
Left = 4
Top = 36
Width = 188
Height = 55
Align = alClient
BorderStyle = bsNone
Images = imlWinXPBar
Indent = 19
TabOrder = 0
end
end
object JvXPBar1: TJvXPBar
Left = 4
Top = 74
Width = 196
Height = 35
Hint = 'This bar doesn'#39't use actions'
Caption = 'Synchronize'
Collapsed = True
Colors.BodyColor = 8421631
Colors.GradientTo = 8421631
Colors.SeparatorColor = clRed
Items = <
item
Caption = 'Unknown'
Hint = 'This is an unkown action'
ImageIndex = 6
ImageList = imlWinXPBar
end
item
Caption = 'Web'
Hint = 'This is a web synchronize'
ImageIndex = 7
ImageList = imlWinXPBar
end>
RollImages = ilRedButtons
Font.Charset = DEFAULT_CHARSET
Font.Color = 1573351
Font.Height = -13
Font.Name = 'MS Shell Dlg 2'
Font.Style = []
HeaderFont.Charset = DEFAULT_CHARSET
HeaderFont.Color = 1573351
HeaderFont.Height = -13
HeaderFont.Name = 'MS Shell Dlg 2'
HeaderFont.Style = [fsBold]
HotTrackColor = clMaroon
Icon.Data = {
0000010001002020000000000000A80800001600000028000000200000004000
0000010008000000000000040000000000000000000000010000000100000000
0000905007005C3D090005047F0006058800090691000D0AA200120EB200F3B8
7500A15F1300030377000A0892000D0A9B00100DA4001813BC002018D300261D
E2001C16CB00E9AF7900FDD9AF00FDC1730000006D0005047C0009068A002A21
EA001D17CF00FEE9D200FBE3C500F6C07700F9B4570009069200130FB5002D23
F200FFFAF300FDEAD400F9BE6F00E69C3600D991310000008F000A089B00534B
F4007670F5008C87F7003A3FD500FAC78D00F8B96500D68A24000E6240000D5B
3C0000008800050499005F58F500A6A3F800616DF500ECAA6B00F9DAB500F8B6
5B00C679140011754D0019AA7000000081000A08A300D5D4FB000F6945000A44
2D00BD7A3100F9CE9900F3A9440015915F0018A36B0018A86E00000077000B09
A7001383560015905F0011774E000F644200D4953B00EA9B2B00B8701300148C
5C0016986400179E680017A16A00000072000A09A4006861F500FFFFFF001382
5600A05F0B00AE6A12009E6112008D560E00148A5B00179C6700312DC6003530
CD00716BF600918DF8000C543700844E0900794C0C0071470B006B440B001487
590016956200169763009692F800EAE9FE0013855700159361006C65F500D0CE
FB00EAE9FD0010704A000D583A000E603F000F67440011724B0011744C00106D
48002CE1990059E7AE005BE8B0003AE39F0031E29B001FD68D000E5D3D002FE1
9A00A4F2D300CDF8E700E9FCF400F1FDF800E3FBF100ADF3D70095F0CC0077EC
BD0026E096001AB678000F664300138054001CC17F00CBF8E600D0F8E800D2F9
E900D9FAED00EAFCF500E2FBF100B6F5DC008EEFC8001ECF88000C523600127C
5200A1F2D200ABF3D600AFF4D800BDF6DF00C6F7E300B4F4DA0087EEC500106E
48009DF1CF007AECBE001AB476003BE3A00080EDC10073EBBB0056E7AD0018A5
6D005DE8B0006CEAB8008AEEC600106B47001FD98F0041E4A3003FE4A2004BE5
A70054E7AC0067E9B50069EAB60025E095002DE1990028E096002AE198001CBF
7E0020DB900020DF93001ED28A001AB376001FD48C001ECD87001ED0890019AD
72001BB8790011764E001AB4770017A26B001BBD7C001DCD86000C4F34001DCB
850018A66D001BBA7A001CC481001DC884000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000004C40404040404000000000
000000000000000000000000007272C7C7C74040407844C0C5CBC85040000000
000000000000C7C7C7C7C7C7C7775EC0C5C8C896BDBDBDBDBDBDBD4540400000
00000000009798C4C5C8BDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBD4940400000
000000009777A3BDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBD4097400000
0000000097C096BDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDC5404C400000
0000009749C8BD9696969696C8C8C8C8C8C8C8C8C8C8C8C8C89677404C400000
00000097A3BD969696969696C896C8C8C8C8C8C8C8C8C8C8C8BD40974C400000
00009750BDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBD8D404C4C400000
000097C5B4ADADADADADADADADADADADADADADADADADADADB444404C4C400000
00306979B7B7B7B7B7B7B7797979797979797979797979797940304C3F400000
0030ADAEAFAFAFAEAEAEAEAEAEAEAEAEB0B1B2B2B2B2B2B3B4404C3F78400000
30457B7B7B7B7B7B7B7B7B7B7B7B7B7BAA95A18E91919BAB69404CAC77400000
30AFA6A6A6A6A6A6A6A6A6A6A6A6A6A695A19FA6A6B1B444404C3F7777400030
8A959595959595959595959595959595A1A2A340404040404C3F787777400030
7B818181819A9B9C9D9D9D9D9D9D9D9E9F5E40972F3F4C3F3F7877777740308D
9A8E8E8E8E90909192848484858E9E959640974C7715044C7798989898403079
818E92848484858E9A87A67A7C7CB48A4C403F771504351F4C49494949403069
797A7B7B7C7DBD694C4040404040404040307715042034351F3F494949400040
404040404040404040302F4C7777777777771504206B6B3E351F785050400000
00000030777777777777496944444444441504206F2A6B7071351F7744400000
00000030440164656667020268696969150420336F616B715757351F77400000
0000003001595A5B5C02020202505E15045F606020616257351F1F1F1F970000
0000004C014D4E4F02505E52C4C4C41515150A06206F2A57351F49C450400000
00000001414243390244453B3B3B3B3B3B150A0620332A3E351F494477400000
00000001363738390277C0C0C0C0C0C0C015040620332A3E351F3F4040000000
010101012C222D2E020202024C3030303015043220332A34351F000000000000
000112212122232425090200000000000015040C2028292A2B1F000000000000
00000112221B1C1D090200000000000000161E1F102020201F00000000000000
0000000112131409020000001515151516170D10101018111F00000000000000
000000000108090200000000000A0B0C0D0E0F0F10111F1F0000000000000000
000000000001020000000000000016041E1E06061F1F0000000000000000FFFF
FE03FFFE0001FF000000FE000000FC000000FC000000F8000000F8000000F000
0000F0000000E0000000E0000000C0000000C000000080000000800000000000
0000000000000000000080000000F8000000F8000000F8000000F8000000F800
0000F8000001C000000FE007E00FF00FE01FF81C001FFC3E003FFE7F00FF}
RollStep = 5
ShowItemFrame = False
RoundedItemFrame = 0
Align = alTop
ParentFont = False
end
object dxWinXPBar3: TJvXPBar
Left = 4
Top = 109
Width = 196
Height = 35
Hint = 'This is a hint'
Caption = 'Information'
Collapsed = True
Colors.BodyColor = clInfoBk
Colors.GradientFrom = clBtnFace
Colors.GradientTo = clWindowText
Colors.SeparatorColor = clWindowText
Items = <
item
Action = acGettingStarted
end
item
Action = acCommonQuestions
end
item
Action = acHelp
end
item
Action = acHowDoI
end>
RollImages = ilWhiteButtons
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'MS Shell Dlg 2'
Font.Style = []
HeaderFont.Charset = DEFAULT_CHARSET
HeaderFont.Color = clWhite
HeaderFont.Height = -13
HeaderFont.Name = 'MS Shell Dlg 2'
HeaderFont.Style = [fsBold]
HotTrackColor = clNone
Icon.Data = {
0000010001002020040000000000E80200001600000028000000200000004000
0000010004000000000000020000000000000000000000000000000000000000
0000000080000080000000808000800000008000800080800000C0C0C0008080
80000000FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF000000
0000000000000008800000000000000000000000000000888000000000000000
000000000000000880000000000000000000000000000F088000000000000000
000000000000FF08800000000000000000000000080FFF088000000000000000
00000088880FFF08888800000000000000008880007FFF088888880000000000
00080007FFFFFF70008888800000000000007FFFFFFFFFFFF700888800000000
007FFFFFFFFFFFFFFFF70888800000000FFFFFFFFFFFFFFFFFFFF08888000000
FFFFFFFFFFFFFFFFFFFFFF088880008FFFFFFFFCCCCCCCCCFFFFFFF08880087F
FFFFFFFFFCCCCCFFFFFFFFF7088808FFFFFFFFFFFCCCCCFFFFFFFFFF088887FF
FFFFFFFFFCCCCCFFFFFFFFFF70888FFFFFFFFFFFFCCCCCFFFFFFFFFFF0888FFF
FFFFFFFFFCCCCCFFFFFFFFFFF0888FFFFFFFFFFFFCCCCCFFFFFFFFFFF0888FFF
FFFFFFFFFCCCCCFFFFFFFFFFF0888FFFFFFFFFFCCCCCCCFFFFFFFFFFF08087FF
FFFFFFFFFFFFFFFFFFFFFFFF708008FFFFFFFFFFFFFFFFFFFFFFFFFF0800087F
FFFFFFFF7CCCC7FFFFFFFFF70000008FFFFFFFFFCCCCCCFFFFFFFFF000000008
FFFFFFFFCCCCCCFFFFFFFF00000000008FFFFFFF7CCCC7FFFFFFF00000000000
087FFFFFFFFFFFFFFFF780000000000000887FFFFFFFFFFFF788000000000000
00008887FFFFFF7888000000000000000000000888888880000000000000FFFF
E7FFFFFFC7FFFFFF87FFFFFF07FFFFFE07FFFFF807FFFFC000FFFF00003FFE00
001FFC00000FF8000007F0000003E0000001C000000180000000800000000000
0000000000000000000000000000000000000000000100000001800000038000
0007C000000FE000001FF000003FF800007FFC0000FFFF0003FFFFE01FFF}
RollStep = 5
ShowItemFrame = False
RoundedItemFrame = 0
Align = alTop
ParentFont = False
end
object dxWinXPBar2: TJvXPBar
Left = 4
Top = 39
Width = 196
Height = 35
Caption = 'Settings'
Collapsed = True
Items = <
item
Action = acSettingsDatabase
end
item
Action = acSettingsUsers
end
item
Action = acSettingsStatistics
end
item
Action = acSettingsDownloads
end>
Icon.Data = {
0000010001002020000001000800A80800001600000028000000200000004000
0000010008000000000080040000000000000000000000000000000000000000
000000549900005497000054950000539500004F9000004E8E0000579B000055
9A002491DC0063C4FF0046B5F80000509100026CB7000A91E5000473C100004D
8B00004E8A00147AC4004FB5F40075CBFF004ABBFF003CB5FF0045AEEF000052
92000E97EC000F9FF7000C98F0000472BF00004B880049AFF10064C5FF0055C0
FF0040B8FF0036B3FF003DA3E5000E90E10012A2FA0010A2FA000D9FF600004A
87002192E20047BAFF003FB7FF0038B5FF002DB0FF0028AFFF000E7BC5001FAA
FF001AA9FE000C9DF6000B8CDF00004479003BB5FF0036B4FF0031B2FF0027B0
FF0022ADFF0019A9FE0015A8FE000BA1FB000980CE00003D6E00004780000055
9C0000569900004E8D00004881002B95E30049BBFF0044B9FF003AB7FF0035B4
FF0030B1FF002BB0FF001EACFF0011A7FF0000488200026BB6000780D2000046
7F0000589C003CADF6006FC7FE003FAAF2001D87D9000064B90043B1F6004DBD
FF0043B8FF0039ABF100309BDE001CAAFE0017A8FE0014A7FE000F97EB000791
E700099EF7000A8CE10000457C00BEE6FF0099D9FF0082D0FF0056BFFF0051BE
FF00318BC90000508F001B75B10010A5FF000EA1FB0000447A003690D1005EC3
FF005BC1FF002673AB000067B300007CD6000079D1000075C900005FA5001F7C
BA001BABFE0013A7FE000581D70000437800ACE0FF0068C5FF000077CD00007F
DA000080DD00007DD9000072CB000065B5000DA2FB00098FE7000042770070C7
FE006AC7FF0067C5FF0061C4FF0000599F000073C8000078D40016A7FE000074
CC001D9DF40048B6FB007BCDFF006FC8FF00004A84000065B300006DC5000068
BE000057A0000066B60000417600006AC20079CDFF000058A200005FB100005B
A6000C90E4000065B60000427500006EC400005DA8000A8FEC00297BB6000041
730015A6FC000896EE000882D8000062B0008FD5FF006DC8FF004AA1DA00003E
6F0025AEFF0021ACFF000C6DB2009AD8FF0085D1FF0071CAFF003181B9000056
970029B0FF00003F72002283C30081D0FF00DFF3FF0032B1FF001AAAFD00FFFF
FF0051A7DE000D65A70017A7FC00A1DCFF004EBDFF0054BFFF001D8EE1002194
E600249AEA002BA6F400A2DBFF00B0E1FF0049B9FD001D90E1007DCFFF005CC1
FF0058C0FF0053BFFF0050BDFF000061B100037CD700003F70000068B600199B
F2002FA5F2009BD9FF0060C3FF0056C1FF0043ADF400036DBF000061B200ACDF
FF0068C7FF0066C6FF0089D3FF002394E3000B7BD00077CDFF0073CAFF002DA4
F20070C9FF003DB6FF002999E4000067B400BCE6FF0097D8FF000B82DA000E90
EC00B9E5FF005BBDFA001484D9000061B400B7E5FF000389E8000774CC00027F
DB000073CD000063AC000D609B000070C1000078CF0000407100000000000000
00000000000000000000006E347C870000000000000000000000000000000000
000000000000000050636377FCFDFD8700000000BAFED6000000000000000000
0000000000000043FC8181818181817C000000A88183A0D6B000000000000000
000000000000004DFA818181818181FB8700A374819C565604B0000000000000
000000000000004DB8F8818181A691787C87F9818198565656A0B00000000000
0000001D000000004D8EA6CDB5EDF1F5E3568181F6D9C7F75656D60000000000
000010EC1D00000095E5B564ED65EEE314EF81F020F1C4F2F3F4D60000000000
00428181831D1D004DE564DAB4ADE614E7C6E8E9E3E3E3E3EAEBD60000000000
6A8181818183564D18CEE0DA669DB61FE1E1E1E1E1E1E2E3E4DED6D60000000C
D781818181D8CE56B8D9DA669D891FDBD0DCC668DCC61FDDDE049EDFD6000018
8181818191CBCCCDCECF66AE891F8BD0D1D2C5C5C6C6D3C799D497D5D6000018
81818191C4BDB4B4669394898A5A5B5B5B5B5AC5C6C636C7C8C9CACA6DBA0000
188191B5C064B4AD939DB6C1725063A37C3E3EC21636BE49BEBEBE39C3BA0000
0018BBBCBDB4AD939DB6B74D4300000000003E3E78BEBEBEBEBFA9A96DBA0000
000018B364B4B59DB6B7B8000000000000003E063E5AB9B2B2A9A96D61BA0000
03049CA591AD9DAEAF070000000000000000B0993E5BB1B25CA96D6161A80102
A48E9CA5A69D9489A70700000000000000A899A07C5B395CA96DAAABACA34181
818E9C91939D891F8C00000000000063349E9FA07C5B4B3AA1A22828A3000881
81919293947E8A8B8C0642111D95435196979899435A3A3B851B9A069B000008
88656666898A8B708C738D828081818E8383844378318F4C6D6D1B9087000007
657D66667E0A7071696A737F8081818283846A78795D7A856D6D618687000007
6F6465660A70712068726A73747576776A6A78795D7A7A6D6D61617B7C000000
07646566660A6768582A696A6A0642116B5B5C5D5E6C6D6D6161626E00000000
515253545556575845592B5A5B5B5B5A395C5D5E5F4E60616162630000000000
0040074142434445462B4748494A38394B3A3B4C1C3E4D4E4F50000000000000
0000000007082020213536372D3839303A3B263C3D3E003F3F00000000000000
00000000072920202A2B2C2D2E2F303126262632333400000000000000000000
00000000071E1F1F202122222305242526271A1A0E2800000000000000000000
00000000071213140A151617180005191A1A1B1C1D1D00000000000000000000
0000000000070801090A0B0400000C0D0E0F1011000000000000000000000000
0000000000000000010203040000000506060000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000FFF8
7FFFFFC03C7FFF80381FFF80100FFF800007FBC00007F1C00007E0400007C000
0003800000018000000180000000C0000000E001F000F007F000C00FF000000F
E000001F800100000001800000018000000180000001C0000003C0000007E000
000FFC00009FFC0000FFFC0000FFFC0100FFFE0303FFFFC38FFFFFFFFFFF}
RollStep = 5
ShowItemFrame = False
RoundedItemFrame = 0
Align = alTop
end
object dxWinXPBar1: TJvXPBar
Left = 4
Top = 4
Width = 196
Height = 35
Hint = 'Cick to see connection options'
Caption = 'Connect'
Collapsed = True
Colors.GradientTo = 16244694
Items = <
item
Action = acConnectRemoteServer
end
item
Action = acConnectLocalServer
end
item
Action = acConnectAdministrator
end>
RollImages = ilOldButtons
Icon.Data = {
0000010001002020000001000800A80800001600000028000000200000004000
0000010008000000000080040000000000000000000000000000000000000000
00000074900000708B00006D87000069820000647C00007F9E00007D9A00007A
97000097BD0000A0C900009CCC000080A4000085A50000A6D20000A3D000005F
750000AAD50000596E0000B3DB0000BCE10000ADD80000B6DF0000CBEF0000D8
F80000DDFB00009BB40000A0C30000B1DB0000B9E20039D9F40081EEFD00AEF4
FD0097F1FD0060EAFD0000AED20000C8EB0065E4F700BEF7FE00E4FCFF00C5F6
FD00AFF3FD008FF0FD0082EEFD0000B5D90006D9F700F4FEFF00C6F7FE00B4F5
FE0098F2FE0082EFFE0000B8DD006CEAFC00B3F5FE00A3F3FE00BEF6FE0092F1
FE0071EDFE0030E4FC0000ACC60003D8F70048E7FD0000B8D30065E9FC0054E9
FD0018CEE8000075910099F1FD0091F1FE007AEEFE0069ECFE0038DEF5000083
A3000092B5000099BB0000B1D50000D7F700127C920020E2FC008BEFFD001DC7
DF0000C6EA0072EDFD000DD3EF0000D1F3000CAEC60018C0D80006738800129E
BB0080EEFD0000D5F500E0FBFF0078EEFD00FFFFFF00007B9700C0F7FE0003AA
C5000070890050E8FD0003B1CD00009BBB0003B8D50002BFDD0000607600008E
B10002C3E20000657C0000A8C90001C7E800006B830000B1D200000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000610000000000000000000000000000000000000000
0000000000000000000000616100000000000000000000000000000000000000
0000000000000000000000616E61000000000000000000000000000000000000
0000000000000000000000616E6C610000000000000000000000000000000000
0000000000000000000000616B5A6C6D00000000000000000000000000000000
000000000000000000006168615A5A696A000000000000000000000000000000
000000000000000000006109615A5A5A66670000000000000000000000000000
0000000000000000616161616164195A5A651200000000000000000000000000
00000000000000006119596219191919195A6312000000000000000000000000
0000000000000000005E195F5C3A191919195A60120000000000000000000000
00000000000000000D090D225D5C3A3A1919195A1A1200000000000000000000
00000000000000000D2C090D225B5C3A3A3A19195A1A12000000000000000000
0000000000000D0D0D0D0D0D58593A3A3A3A3A3A195A1A120000000000000000
00000000000D1B193D3D3D3D3D3D3D3A56571212121212120000000000000000
000000000D1B235422223D3D3D3D3D3D19551242484912000000000000000000
0000000D1B232351225222223D3D3D3D3D531A12421200000000000000000000
00000D1B23234B2C4E4F392222223D3D3D3A501A120000000000000000000000
00000D4A234B2C2C4C354439222222224D121212121200000000000000000000
0000000D232C2C33244344324546222247124248491200000000000000000000
0000000D1B2C2C33333F35323232392240411242120000000000000000000000
000000000D2C3333333C373832323239223D3E12000000000000000000000000
000000000D233333142437353832323239223A3B120000000000000000000000
000000000D1B33141414342E35363232323222191A1200000000000000000000
00000000000D2C1414142D2E2E2F303132323222191A12000000000000000000
00000000000D2314141424252627272829202A2B22191A120000000000000000
00000000000D1B1414131111111C1D1E1F2020212122191A1200000000000000
0000000000000D141311111111110E0E0E0E1516171819191A12000000000000
0000000000000D1311111111110E0E0E0E0E0F0F0F0F0B0B0C12000000000000
0000000000000D09111111110E0E0E0E0E0F0F0F0F0B0B0C1200000000000000
000000000000000D0D0D0D0D090A0E0E0F0F0F0F0B0B0C100000000000000000
0000000000000000000000000606070808090A0B0B0C05000000000000000000
000000000000000000000000000000000001020304050000000000000000FFFB
FFFFFFF9FFFFFFF8FFFFFFF87FFFFFF83FFFFFF01FFFFFF00FFFFFC007FFFFC0
03FFFFE001FFFFC000FFFFC0007FFF00003FFE00003FFC00007FF80000FFF000
01FFF00000FFF80000FFF80001FFFC0003FFFC0001FFFC0000FFFE00007FFE00
003FFE00001FFF00000FFF00000FFF00001FFF80003FFFFC007FFFFFE0FF}
RollStep = 5
ShowItemFrame = False
RoundedItemFrame = 0
Align = alTop
end
end
end
end
object cntDetails: TJvXPContainer
Left = 210
Top = 0
Width = 353
Height = 438
BoundLines = [blLeft, blTop, blRight, blBottom]
Caption = 'cntDetails'
Color = clInfoBk
ParentColor = False
Align = alClient
object lbWelcome: TLabel
Left = 8
Top = 16
Width = 230
Height = 13
Caption = 'Welcome to the JVCL XP Controls Demo...'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Shell Dlg 2'
Font.Style = [fsBold]
ParentFont = False
end
object btnCollapseAll: TButton
Left = 8
Top = 48
Width = 75
Height = 25
Caption = 'Collapse All'
TabOrder = 0
OnClick = btnCollapseAllClick
end
object btnExpandAll: TButton
Left = 88
Top = 48
Width = 75
Height = 25
Caption = 'Expand All'
TabOrder = 1
OnClick = btnExpandAllClick
end
object btnToggleEnableMode: TButton
Left = 8
Top = 80
Width = 153
Height = 25
Caption = 'Toggle Enable Mode'
TabOrder = 2
OnClick = btnToggleEnableModeClick
end
object btnToggleVisibleMode: TButton
Left = 8
Top = 112
Width = 153
Height = 25
Caption = 'Toggle Visible Mode'
TabOrder = 3
OnClick = btnToggleVisibleModeClick
end
object chkGrouped: TCheckBox
Left = 24
Top = 152
Width = 97
Height = 17
Caption = 'Grouped'
TabOrder = 4
OnClick = chkGroupedClick
end
end
object imlWinXPBar: TImageList
Left = 288
Top = 280
Bitmap = {
494C010119001D00040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600
0000000000003600000028000000400000008000000001002000000000000080
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400FFFFFF00C6C6C6000084840000FFFF000000
0000FFFFFF00C6C6C60000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C6008484840084848400FFFFFF00C6C6C6000084840000FFFF000000
0000FFFFFF00C6C6C60000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60084848400FFFFFF00C6C6C60000848400008484000084
8400FFFFFF00C6C6C60000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00C6C6C600C6C6
C600C6C6C600C6C6C60084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00C6C6C6000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00C6C6C600C6C6
C600C6C6C6008484840000848400848484000084840000848400008484000084
8400008484000084840000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00C6C6C60084848400C6C6C60000FFFF000084840000FF
FF00008484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C6008484840084848400C6C6C60000FFFF000084
8400000000000000840000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6C60084848400848484000000
0000000084000000840000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00C6C6C600C6C6
C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6C600000000000000
00000000FF000000840000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00C6C6C6008484840084848400000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00C6C6C6008484840084848400000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6C60084848400000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C6008484840000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000084848400C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C60084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000008484840084848400848484008484
8400848484008484840084848400848484008484840084848400848484008484
84008484840084848400000000000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C6008484
8400848484008484840000000000000000000000000000000000848484008484
8400848484008484840084848400848484008484840084848400848484008484
8400848484008484840000000000000000008484840084848400848484008484
8400848484008484840084848400848484008484840084848400848484008484
840084848400848484000000000000000000C6C6C600C6C6C60000FFFF00C6C6
C6000084840000000000000000000000000000000000C6C6C60000FFFF00C6C6
C60000FFFF0084848400000000000000000000000000C6C6C600FFFFFF00FFFF
FF00C6C6C600FFFFFF00FFFFFF00C6C6C600FFFFFF00FFFFFF00C6C6C600FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000C6C6C600C6C6
C6000084840000000000000000000000000000000000C6C6C60000FFFF00C6C6
C60000FFFF00848484000000000000000000C6C6C600C6C6C60000FFFF00C6C6
C6000084840000000000000000000000000000000000C6C6C60000FFFF00C6C6
C60000FFFF00848484000000000000000000C6C6C600C6C6C600C6C6C6000084
8400848484008484840000000000C6C6C6008484840000000000C6C6C60000FF
FF00C6C6C60084848400000000000000000000000000C6C6C600FFFFFF00FFFF
FF00C6C6C600FFFFFF00FFFFFF00C6C6C600FFFFFF00FFFFFF00C6C6C600FFFF
FF00FFFFFF00C6C6C60084848400000000000000000084848400C6C6C6000084
8400848484008484840000000000C6C6C6008484840000000000C6C6C60000FF
FF00C6C6C600000000008484840000000000C6C6C600C6C6C600C6C6C6000084
8400848484008484840000000000C6C6C6008484840000000000C6C6C60000FF
FF00C6C6C600848484000000000000000000C6C6C600C6C6C60000FFFF008484
8400C6C6C600FFFFFF00C6C6C600C6C6C600008484000084840000000000C6C6
C60000FFFF008484840000000000000000000000000084848400C6C6C6008484
840000008400000084000000840084848400C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600848484000000000000000000C6C6C600C6C6C6008484
8400C6C6C600FFFFFF00C6C6C600C6C6C600008484000084840000000000C6C6
C60084848400000000008484840000000000C6C6C600C6C6C60000FFFF008484
8400C6C6C600FFFFFF00C6C6C600C6C6C600008484000084840000000000C6C6
C60000FFFF00848484000000000000000000C6C6C600C6C6C600848484008484
840084848400FFFFFF00C6C6C6000084840000848400008484000000000000FF
FF00C6C6C60084848400000000000000000000000000C6C6C600FFFFFF008484
840084848400C6C6C6008484840000008400FFFFFF00FFFFFF00C6C6C600FFFF
FF00FFFFFF00C6C6C600848484000000000084848400C6C6C600C6C6C6008484
840084848400FFFFFF00C6C6C6000084840000848400008484000000000000FF
FF0000000000848484008484840000000000C6C6C600C6C6C600848484008484
840084848400FFFFFF00C6C6C6000084840000848400008484000000000000FF
FF00C6C6C600848484000000000000000000C6C6C600C6C6C600848484008484
840000FFFF00FFFFFF00C6C6C60000000000000000000000000000000000C6C6
C60000FFFF0084848400000000000000000000000000C6C6C600FFFFFF00C6C6
C60084848400FFFFFF00C6C6C60084848400FFFFFF00FFFFFF00C6C6C600FFFF
FF00FFFFFF00C6C6C6008484840000000000C6C6C600FFFFFF00C6C6C6008484
840000FFFF00FFFFFF00C6C6C600000000000000000000000000000000008484
840000000000C6C6C6008484840000000000C6C6C600C6C6C600848484008484
840000FFFF00FFFFFF00C6C6C60000000000000000000000000000000000C6C6
C60000FFFF00848484000000000000000000C6C6C600FFFFFF0000FFFF0000FF
FF008484840084848400848484008484840000000000000000008484840000FF
FF00C6C6C6008484840000000000000000000000000084848400C6C6C6008484
840000008400848484000000840000008400C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C60084848400000000008484840084848400848484008484
8400848484008484840084848400848484000000000000000000848484008484
84008484840000FFFF008484840000000000C6C6C600FFFFFF0000FFFF0000FF
FF008484840084848400848484008484840000000000000000008484840000FF
FF00C6C6C600848484000000000000000000C6C6C600C6C6C60000FFFF0000FF
FF0000FFFF00848484008484840084848400008484000000000000FFFF00C6C6
C60000FFFF0084848400000000000000000000000000C6C6C600FFFFFF00C6C6
C60084848400C6C6C600C6C6C600C6C6C600FFFFFF00FFFFFF00C6C6C600FFFF
FF00FFFFFF00C6C6C60084848400000000000000000084848400C6C6C600C6C6
C60000FFFF00848484008484840084848400008484000000000000FFFF00C6C6
C60000FFFF00C6C6C6008484840000000000C6C6C600C6C6C60000FFFF0000FF
FF0000FFFF00848484008484840084848400008484000000000000FFFF00C6C6
C60000FFFF00848484000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600FFFFFF00FFFF
FF00C6C6C60084848400000000000000000000000000C6C6C600FFFFFF00FFFF
FF00C6C6C600FFFFFF00FFFFFF00C6C6C600FFFFFF00FFFFFF00C6C6C600FFFF
FF00FFFFFF00C6C6C600848484000000000000000000C6C6C600C6C6C60000FF
FF0000FFFF00848484008484840000FFFF00C6C6C600C6C6C600FFFFFF00FFFF
FF00FFFFFF00FFFFFF008484840000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600FFFFFF00FFFF
FF00C6C6C60084848400000000000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C6008484840000000000000000000000000084848400848484008484
8400848484008484840084848400848484008484840084848400848484008484
84008484840084848400848484000000000000000000C6C6C600C6C6C600C6C6
C60000FFFF00C6C6C60000FFFF00C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600848484000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C6008484840000000000000000000000000000FFFF0000FFFF00C6C6
C60000FFFF00C6C6C60000FFFF00848484000000000000000000000000000000
0000000000000000000000000000000000000000000084000000FF000000FF00
0000FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF00
0000FF000000FF00000084000000000000000000000000000000C6C6C600C6C6
C600C6C6C600FFFFFF00C6C6C600C6C6C6008484840000000000000000000000
0000000000000000000000000000000000000000000000FFFF0000FFFF00C6C6
C60000FFFF00C6C6C60000FFFF00848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000848484008484
8400848484008484840084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000840000008400
0000840000008400000084000000840000008400000084000000840000008400
000084000000840000008400000000000000000000000000000000000000C6C6
C600C6C6C600C6C6C600C6C6C600848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000848484008484
8400848484008484840084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400848484008484840000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000848484008484840000000000C6C6C600C6C6C6008484
8400000000000000000000000000000000000000000000000000000000000000
0000000000000000000084000000FF000000FF000000FF00000084000000FF00
0000FF0000000000000000000000000000000000000000000000000000008400
0000840000008400000084000000840000008400000084000000000000000000
000000008400FF00FF0000000000000000000000000000000000000000008484
8400C6C6C6008484840084848400000000000000000084848400848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000008484840000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008400000084000000FF000000FF00000084000000C6C6C6008400
0000000000000000000000000000000000000000000000000000008400000084
00000084000084000000FF000000840000008400000084000000840000000000
8400FF00FF000000FF0000008400000000000000000084848400C6C6C6008484
8400848484008484840084848400848484008484840000000000000000008484
8400848484000000000000000000000000000000000000000000000000000000
0000000000008484000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000840000008400000084000000FFFFFF00FFFFFF008484
84000000000000000000000000000000000000000000848484008484840000FF
000000840000008400000000000084848400000000000000000084848400C6C6
C6000000FF000000840000000000000000000000000084848400848484008484
8400C6C6C600C6C6C600C6C6C600848484008484840084848400848484000000
0000000000008484840000000000000000000000000000000000000000000000
0000848400008484840084848400848484008484840084848400848484000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000084000000FFFFFF00848484000000
0000000000000000000000000000000000000000000084848400848484000084
000000FF00000084000084848400C6C6C600FFFF000084848400000000008484
8400848484000000000000000000000000008484840084848400C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600848484008484840084848400848484008484
8400848484000000000000000000000000000000000000000000000000008484
8400FFFFFF00FFFFFF00FFFFFF00C6C6C600C6C6C60084848400848484008484
8400000000000000000000000000000000000000000000000000000000000000
00008400000084000000000000000000000000000000FFFFFF00C6C6C6008484
84008484840084848400000000000000000084848400C6C6C6008484840000FF
00000084000084848400C6C6C600FFFF0000C6C6C600FFFF0000848484000000
000000840000008400000000000000000000C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600848484008484840084848400848484008484
840084848400848484008484840000000000000000000000000084848400C6C6
C600FF00000084848400C6C6C60084848400FFFFFF00C6C6C600C6C6C6008484
8400848484000000000000000000000000000000000000840000008400000000
0000840000000000000000000000000000000000000084848400FFFFFF00FFFF
FF00FFFFFF00C6C6C600000000000000000084848400FFFFFF00848484008484
000084000000C6C6C600FFFFFF00C6C6C600FFFF0000C6C6C600FFFF00000000
000000840000008400000000000000000000C6C6C600FFFFFF00C6C6C600C6C6
C600FFFFFF00FFFFFF00C6C6C600C6C6C6008484840084848400848484008484
8400848484008484840084848400000000000000000000000000848484008484
840084840000FF00000084840000FFFF000084848400C6C6C600FFFFFF00C6C6
C600848484000000000000000000000000000000000000840000008400000084
00000000000000000000000000000000000000000000C6C6C600FFFFFF00FFFF
FF00FFFFFF00FFFFFF0084848400000000008484840000840000848400008484
0000FF000000C6C6C600FFFFFF00FFFF0000C6C6C600FFFF0000848484000000
000000840000008400000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00C6C6C600C6C6C6000000FF000000FF00C6C6C600C6C6C600848484008484
8400848484008484840084848400000000000000000000000000848400008484
8400840000008400000084848400848400008484000084848400C6C6C600FFFF
FF00848484008484840000000000000000000084000000FF000000FF00008484
00008400000000000000000000000000000000000000FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FF00000000000000000000008484840084000000FF000000FF00
0000FF00000084848400C6C6C600C6C6C600FFFF0000C6C6C600848484008484
840000840000008400000000000000000000C6C6C600FFFFFF00C6C6C600C6C6
C60000FF00008484840084848400C6C6C600C6C6C60084848400848484000000
0000C6C6C6008484840084848400000000000000000000000000848400008484
0000840000000000000084840000848400008484000084840000FFFF0000C6C6
C600FFFFFF00848484000000000000000000008400000084000084840000FF00
000084000000000000000000000000000000000000008484840084848400FFFF
FF00FFFFFF0084848400000000000000000084848400FF000000840000008484
000084000000FF00000084848400848484008484840084848400840000008484
8400848484000084000000000000000000000000000084848400C6C6C600C6C6
C60084848400C6C6C600C6C6C6008484840084848400C6C6C600C6C6C6000000
0000C6C6C6000000000000000000000000000000000000000000000000008484
00008400000000000000848484008484000084840000FFFF000084840000FFFF
0000FFFFFF008484840000000000000000008484840084000000FF000000FF00
0000FF0000008400000000000000000000000000000000000000000000008484
8400FFFFFF00C6C6C60000000000000000000000000084840000008400000084
000084840000FF000000FF000000840000008400000084000000840000008400
0000008400000000000000000000000000000000000000000000000000008484
8400C6C6C600C6C6C60084848400C6C6C600C6C6C600FFFFFF00FFFFFF008484
8400000000000000000000000000000000000000000000000000000000008484
000084000000000000008484000084840000FFFF000084840000FFFF00008484
0000FFFFFF00C6C6C600000000000000000084848400FF000000840000008400
0000FF0000008400000000000000000000000000000000000000000000000000
00008484840000000000000000000000000000000000848484000084000000FF
0000008400008484000084000000FF0000000084000084000000FF0000008400
0000840000000000000000000000000000000000000000000000000000000000
0000000000008484840084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00848484000000000000000000000000000000000000000000000000000000
000084840000000000008484840084848400848484008484000084840000FFFF
0000FFFFFF00C6C6C60000000000000000000000000084840000008400000084
0000848400008400000084000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000084848400C6C6
C60000FF0000008400000084000084840000008400000084000084000000FF00
0000840000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF008484840000000000000000000000000000000000000000000000
0000000000008484000084848400848484008484840084848400FFFF0000C6C6
C600FFFFFF00C6C6C6000000000000000000000000008484840000FF000000FF
0000008400000084000084840000000000008400000000000000000000000000
000000000000000000000000000000000000000000000000000000000000C6C6
C60084848400C6C6C60084848400008400000084000000840000008400008400
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00C6C6C600C6C6C60000000000000000000000000000000000840000000000
000000000000000000008484840084848400C6C6C600C6C6C600C6C6C600FFFF
FF00C6C6C6008484840000000000000000000000000000000000848484008484
840000FF00000084000000840000008400008400000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000C6C6C600C6C6C600848484008484840000840000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000C6C6C600C6C6C600C6C6
C600000000000000000000000000000000000000000000000000840000008400
00000000000000000000000000000000000084848400C6C6C600C6C6C6008484
8400848484000000000000000000000000000000000000000000000000000000
0000848484008484840000840000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000FF000000840000000000000000000000FF000000FF000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000084000000FF000000FF000000
FF000000FF000000840000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000FF000000FF000000FF000000FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000C6C6C600C6C6C600848484000000
0000848484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000008484000084
8400008484000084840000848400008484000084840000848400008484000084
8400008484000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000FF000000FF0000000000000000000000
0000000000000000000000000000000000000000000000000000000000008484
8400C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C60084848400000000000000000084848400C6C6C600C6C6C6008484
8400848484000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000084848400C6C6
C60000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FF
FF00008484000000000000000000000000000000000000000000000000000000
000000000000000084000000FF000000FF000000FF0000008400000000000000
000000000000000000000000000000000000000000000000000084000000C6C6
C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C600000000000000000000000000C6C6C600C6C6C6008484
8400000000008484840084848400848484008484840084848400848484008484
840084848400848484008484840000000000000000000000000084848400C6C6
C60000848400008484000084840000848400008484000084840000848400C6C6
C600008484000000000000000000000000008484840084848400848484008484
8400848484000000FF000000FF00C6C6C600848484000000FF000000FF008484
8400848484008484840084848400848484000000000084000000000000000000
0000000000000000000084848400C6C6C600FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000848484008484
8400C6C6C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF008484840000000000000000000000000084848400C6C6
C60000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FF
FF00008484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000848484000000000000000000000000000000
0000000000000000000000000000000000008400000084000000000000008400
0000FF000000FF000000FF000000FF00000084848400FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000084848400848484008484
840084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF008484840000000000000000000000000084848400C6C6
C60000848400008484000084840000848400008484000084840000848400C6C6
C600008484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000008484008400000084000000FF00
0000FF000000C6C6C6008484840084000000FF00000084848400FFFFFF00FFFF
FF00FFFFFF00C6C6C600000000000000000084848400C6C6C600848484000000
00008484840084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF008484840000000000000000000000000084848400C6C6
C60000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FF
FF00008484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000848484008484840084000000FF00
000084848400FFFFFF00FFFFFF00C6C6C600C6C6C600C6C6C600FFFFFF00FFFF
FF00FFFFFF00C6C6C6000000000000000000C6C6C600FFFFFF00C6C6C6008484
84008484840084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF008484840000000000000000000000000084848400FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6
C600008484000000000000000000000000008484840084848400C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C60084848400848484000000000000000000000000000084840084848400FF00
0000FF000000FF000000FF000000FF000000FF00000084848400FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000084848400848484000000
00000000000084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF0084848400000000000000000000000000000000008484
8400848484008484840084848400848484008484840084848400848484008484
84000084840000000000000000000000000084848400C6C6C600848484008484
8400848484008484840084848400848484008484840084848400848484008484
8400C6C6C6008484840084848400000000000000000000848400008484008484
8400FF000000C6C6C6008484840084000000FF00000084000000FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000840000008400000084000000
84000000840084848400FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF0084848400000000000000000000000000000000000000
0000008484000084840000848400008484000084840000848400008484000000
00000084840000000000000000000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C6008484840084848400000000000000000000000000008484000084
840084848400FF000000FF000000FF00000084000000C6C6C600FFFFFF00FFFF
FF00FFFFFF00C6C6C6000000000000000000000000000000000084848400C6C6
C600C6C6C600C6C6C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF0084848400000000000000000000000000000000000000
0000008484000000000000000000000000000000000000000000008484000000
00000000000000000000000000000000000084848400C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C6008484
8400C6C6C6008484840084848400000000000000000000000000000000008400
0000FF000000FF000000FF00000084000000C6C6C600C6C6C600FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000848484008484
8400C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C60084848400000000000000000000000000000000000000
0000008484000000000000000000000000000000000000000000008484000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6C600C6C6
C600C6C6C6008484840084848400000000000000000000000000000000008484
8400C6C6C600C6C6C60084848400FF00000084848400C6C6C600FFFFFF008484
8400848484008484840000000000000000000000000000000000848484008484
0000848400008484000084000000840000008400000084000000848484008484
8400000000008484840000000000000000000000000000000000000000000000
0000008484008484840000000000000000000000000000848400008484000000
00000000000000000000000000000000000000000000C6C6C600C6C6C600C6C6
C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C600848484008484840000000000000000000000000000000000C6C6
C600FFFFFF00FFFFFF00FFFFFF00C6C6C600C6C6C600FFFFFF00FFFFFF008484
8400848484008484840000000000000000000000000000000000848484008400
0000848484000084840084000000840000008400000084000000840000008484
8400840000008484840084000000000000000000000000000000000000000000
0000000000008484840084848400000000000000000000848400000000000000
0000000000000000000000000000000000000000000000000000848484008484
8400848484008484840084848400848484008484840084848400848484008484
840084848400848484008484840000000000000000000000000000000000C6C6
C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6
C600C6C6C6000000000000000000000000000000000000000000848484008484
8400848484008484840084848400848484008484840084848400848484008484
8400848484008484840084848400848484000000000000000000000000000000
0000000000000000000084848400008484000084840000848400000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000008484
8400C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C6008484
8400000000000000000000000000000000000000000000000000848484008484
8400848484008484840084848400848484008484840084848400848484008484
8400848484008484840084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000084848400848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400848484008484840084848400848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000848400000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484000000840000008400000084000000840000008400848484008484
8400848484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000084840000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0000000000848484000000000000000000000000000000
000000000000000000000000000000000000C6C6C60000000000848484000000
0000000000000000000000000000000000000000000000000000000000000000
8400000084000000FF000000FF000000FF000000FF000000FF00000084000000
8400848484008484840000000000000000000000000000000000000000008484
8400C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6
C600C6C6C6008484840000000000000000000084840000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0084848400000000008484840000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0000000000848484000000000000000000000000000000
0000000000000000000000000000C6C6C600C6C6C60000000000848484008484
8400000000000000000000000000000000000000000000000000000084000000
FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000
FF0000008400848484008484840000000000000000000000000000000000C6C6
C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000084840000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0084848400000000008484840000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0000000000000000000000000000000000000000000000
000000000000C6C6C600FFFFFF00FFFFFF00FFFFFF0084848400000000000000
00008484840084848400000000000000000000000000000084000000FF000000
FF00C6C6C6000000FF000000FF000000FF000000FF000000FF00C6C6C6000000
FF000000FF000000840084848400000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000084848400FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000FFFF0000FFFF0000FF
FF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FF
FF0000FFFF00000000008484840000000000000000000000000084848400C6C6
C600C6C6C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00C6C6C6008484
84000000000084848400848484000000000000000000000084000000FF00FFFF
FF00FFFFFF00C6C6C6000000FF000000FF000000FF00FFFFFF00FFFFFF00C6C6
C6000000FF00000084008484840084848400000000000084840000FFFF0000FF
FF0000FFFF00008484008484840000FFFF0000FFFF0000FFFF00008484008484
8400FFFFFF00C6C6C6000000000000000000000000000084840000FFFF0000FF
FF0000FFFF0000FFFF0000FFFF000084840000FFFF0000FFFF0000FFFF0000FF
FF0000FFFF000000000000000000000000000000000084848400C6C6C600FFFF
FF00C6C6C600FF000000FF000000FF000000FF000000FF000000FFFFFF00FFFF
FF0084848400000000008484840000000000000084000000FF000000FF00C6C6
C600FFFFFF00FFFFFF00C6C6C6000000FF00FFFFFF00FFFFFF00FFFFFF000000
FF000000FF000000FF000000840084848400000000000084840000FFFF0000FF
FF0000FFFF0084848400000000008484840000FFFF0000FFFF00848484000000
0000FFFFFF00C6C6C6000000000000000000000000000000000000FFFF0000FF
FF0000FFFF0000FFFF0000848400000000000084840000FFFF0000FFFF0000FF
FF000000000084848400000000000000000084848400C6C6C600FFFFFF00FFFF
FF00FFFFFF00C6C6C60084848400FF000000FF000000C6C6C600FFFFFF00FFFF
FF00FFFFFF00848484000000000084848400000084000000FF000000FF000000
FF00C6C6C600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000000FF000000
FF000000FF000000FF000000840084848400000000000000000000FFFF0000FF
FF0000FFFF0000FFFF008484840000FFFF0000FFFF0000FFFF0084848400C6C6
C600FFFFFF00C6C6C600000000000000000000000000000000000084840000FF
FF0000FFFF000084840000000000000000000084840000FFFF0000FFFF0000FF
FF0000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60084848400FF000000FF000000FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C6000000000084848400000084000000FF000000FF000000
FF000000FF00C6C6C600FFFFFF00FFFFFF00FFFFFF000000FF000000FF000000
FF000000FF000000FF00000084008484840000000000000000000084840000FF
FF0000FFFF008484840084848400C6C6C60000FFFF008484840000000000FFFF
FF00FFFFFF00C6C6C600000000000000000000000000000000000000000000FF
FF0000FFFF000084840000000000000000000000000000FFFF0000FFFF000084
840084848400000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C60084848400FF000000FF000000FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF000000000084848400000084000000FF000000FF000000
FF000000FF00C6C6C600FFFFFF00FFFFFF00FFFFFF00C6C6C6000000FF000000
FF000000FF000000FF00000084008484840000000000000000000000000000FF
FF0000FFFF0000848400000000000084840000FFFF0084848400C6C6C600FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000000000000084
840000FFFF000084840000000000000000000000000000FFFF0000FFFF000000
000000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00C6C6C60084848400FF000000FF000000FF000000FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF000000000084848400000084000000FF000000FF000000
FF00C6C6C600FFFFFF00C6C6C600C6C6C600FFFFFF00FFFFFF00C6C6C6000000
FF000000FF000000FF0000008400000000000000000000000000000000000084
840000FFFF000084840000000000848484008484840000000000FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000000000000000
000000FFFF0000FFFF0000848400000000000084840000FFFF00008484008484
840000000000000000000000000000000000C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C600C6C6C600C6C6C600C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF00C6C6C6000000000000000000000000000000FF000000FF00C6C6
C600FFFFFF00C6C6C6000000FF000000FF00C6C6C600FFFFFF00FFFFFF00C6C6
C6000000FF000000840084848400000000000000000000000000000000000084
84000084840000848400848484000084840084848400C6C6C600FFFFFF00FFFF
FF00FFFFFF00C6C6C60000000000000000000000000000000000000000000000
00000084840000FFFF0000FFFF000084840000FFFF0000FFFF00000000000000
00000000000000000000000000000000000000000000C6C6C600FFFFFF00FFFF
FF00FFFFFF00FFFFFF00C6C6C60084848400C6C6C600FFFFFF00FFFFFF00FFFF
FF00FFFFFF0084848400848484000000000000000000000084000000FF00C6C6
C600C6C6C6000000FF000000FF000000FF000000FF00C6C6C600FFFFFF000000
FF000000FF000000840000000000000000000000000000000000000000008484
84000084840000FFFF0000FFFF008484840000000000FFFFFF00FFFFFF008484
8400848484008484840000000000000000000000000000000000000000000000
00000000000000FFFF0000FFFF0000FFFF0000FFFF0000848400000000000000
00000000000000000000000000000000000000000000C6C6C600FFFFFF00FFFF
FF00FFFFFF00C6C6C600FF000000FF000000FF000000FFFFFF00FFFFFF00FFFF
FF00C6C6C60000000000000000000000000000000000000000000000FF000000
FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000
FF00000084000000000000000000000000000000000000000000000000008484
840084848400008484000084840084848400C6C6C600FFFFFF00FFFFFF008484
8400848484008484840000000000000000000000000000000000000000000000
0000000000000084840000FFFF0000FFFF0000FFFF0000000000000000000000
0000000000000000000000000000000000000000000000000000C6C6C600C6C6
C600FFFFFF00FFFFFF00C6C6C600C6C6C600C6C6C600FFFFFF00FFFFFF008484
8400848484000000000000000000000000000000000000000000000000000000
84000000FF000000FF000000FF000000FF000000FF000000FF00000084000000
840000000000000000000000000000000000000000000000000000000000C6C6
C600FFFFFF00C6C6C600C6C6C600C6C6C600FFFFFF00FFFFFF00FFFFFF00C6C6
C600C6C6C6000000000000000000000000000000000000000000000000000000
0000000000000000000000848400008484000084840000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000840000008400000084000000840000008400000000000000
0000000000000000000000000000000000000000000000000000000000008484
8400C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C600C6C6C6008484
84000000000000000000000000000000000000000000214A2100183118001831
1800000000001831180018311800183118001831180000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000005A4A42005A4A42005A4A42005A4A42005A4A4200423931000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000001818180018181800181818001818180018181800181818000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000522900004A310000522900005229000052310000522900000000
00000000000000000000000000000000000000000000214A21004AB539004AB5
3900183118004AB539008CCE7B0073C66300529C4A0018311800183118001831
18000000000000000000000000000000000000000000000000005A4A42005A4A
42005A4A42007B7363008C847300635A4A0094847300847363006B6352006B63
5A00000000000000000000000000000000000000000000000000000000001818
1800181818001818180018181800181818001818180018181800181818001818
1800181818000000000000000000000000000000000000000000000000006B39
00006339000084420000C6630000BD5A00008C5A08009C5A0000734200005229
00005229000000000000000000000000000000000000295A21004AB539004AB5
39001831180063BD5200ADDEA50084CE730063C65A0063C65A0042A531001831
180018311800000000000000000000000000635A4A00635A4A00847B6B00A59C
8C00BDADA500BDADA5006B6B73005A528C00736B94008C7B73008C847B00A59C
940000007B0000007B0000000000000000000000000000000000181818001818
180018181800CECECE00CECECE00CECECE00CECECE00ADADAD00ADADAD001818
18001818180018181800000000000000000000000000000000006B3100006352
1000EF730000FF7B0000FF8400007BA53900399C31004A9C31006B7B2100AD5A
00007B42000052290000000000000000000000000000295A21006BC65A004AB5
39001831180063BD5200DEF7DE0094CE84007BC66B0063C65A004AB53900398C
180018311800000000000000000000000000635A4A00BDB5AD00DED6CE00D6CE
C60039312900CEC6BD00635A7B000800FF008C8494008C7B7300A59C94000808
9C00738CF7002118EF0000007B00000000000000000018181800181818001818
1800CECECE00CECECE00CECECE000000C6000000C600CECECE00CECECE00CECE
CE00181818001818180018181800000000000000000073310000527321008CA5
2900E77B0000FF8C0000F7A5180031C64A0029B5290031B5310039A53100637B
2100B56300008C4A0000522900000000000000000000295A210084CE73004AB5
39002142210063BD5200EFFFEF009CD694007BC66B0063C65A004AB53900398C
180018311800183118001831180000000000635A4A00E7DEDE0039312900E7DE
D600B5AD9C00BDADA5006B6B7300524ACE00AD9CBD008C7B7300A59C94000808
9C00BDCEFF005A7BF70000007B0000000000000000001818180018181800D6D6
D600CECECE00CECECE00CECECE000000C6000000C600CECECE00CECECE00CECE
CE00CECECE00181818001818180000000000000000006B31000052C652005ABD
4200948C1000F78C0000CED67B0084EFB50031BD290029B5210018C652004AA5
3900BD630000C66300004A3100000000000000000000295A210094D68C0063BD
5200316B290063BD5200EFFFEF009CD694007BC66B0063C65A004AB53900398C
180018311800397B00001831180000000000635A4A00E7DEDE00C6BDB500D6CE
C60039312900D6CEC60052944200428C31007BAD6B008C8473008C847B00A59C
940008089C0008089C000000000000000000181818001818180021212100E7E7
E700CECECE00CECECE00CECECE00CECECE00CECECE00CECECE00CECECE00CECE
CE00CECECE00ADADAD001818180018181800844200008C6329004AE7630039DE
63009C941000DE840000FFA50000FFE79C00D6FFF7004AD65200B5AD2900EF94
1000EF630000BD6300007B4A00005229000000000000295A2100D6EFCE0073C6
6B00398C310052AD420084BD73006BB55A005AAD420063B54A004AB53900398C
180029521000397B00001831180000000000635A4A00E7DEDE004A423900E7DE
DE00B5AD9C00BDADA50052A5390042FF4200A5CE94008C8473008C8473008C84
7300C6C6BD00BDBDBD0000000000000000001818180018181800D6D6D600EFEF
EF00CECECE00CECECE00CECECE000000C6000000C600C6C6CE00CECECE00CECE
CE00CECECE00CECECE00181818001818180084420000C6AD5A0042EF7B004ABD
1800ADB50800FFAD0000FFA50000FFA50000E7941000FFAD1000FF8C0000FF84
0000EF7B0000CE6B0000BD6300005231000000000000295A210084CE730094D6
8C00429C2900398C1000317300003173000031730000398C1000429C2900398C
1800295A0800397B00001831180000000000635A4A00EFEFE700C6BDB500D6CE
C6005A4A4200DED6D60063944A0018C61000BDE7AD008C8473008C847B00A59C
940000007B0000007B0000000000000000001818180018181800EFEFEF00EFEF
EF00D6D6D600D6D6D600D6D6D6003939C6000000C6006B6BC600CECECE00CECE
CE00CECECE00CECECE00181818001818180084420000CEBD7B0084E77B00CEB5
0000FFBD0000FFBD0000FFBD0000B5C608005A940800C66B0000FF9C0000FF94
0000FF840000C65A000094520000522900000000000000000000295A2100398C
1800397B0800315A000018311800183118001831180018311800316B0000398C
1800316B0800397B000018311800000000006B5A5200EFEFE700635A4A00EFE7
E700BDB5AD00BDADA500948C7B00635A4A00E7DED6008C847300A59C94000808
9C003942EF002118EF0000007B00000000001818180018181800EFEFEF00F7F7
F700DEDEDE00D6D6D600D6D6D600CECED6003939C6000000C6007373C600CECE
CE00CECECE00CECECE00181818001818180084420000E7A53100FFCE2100FFC6
0000FFD60000FFE70800F7DE08005AFF7B0021EF210063941800E77B0000FF8C
0000E76B000084942100637B180052290000000000000000000000000000295A
21002952080018311800397B000052A5000052A500003173000018311800316B
0000397B0000316B080018311800000000006B5A5200F7F7F700D6CEC600D6CE
C600CEBDB500BDADA500948C7B006B5A4A00E7DED6008C847300A59C94000808
9C00425AF7002118EF0000007B00000000001818180018181800F7F7F700FFFF
FF00EFEFEF00DEDEDE00DEDEDE00D6D6D600CECED6000000C6000000C600CECE
CE00CECECE00CECECE001818180018181800844200009C8C0000C69C0000DEAD
0000FFE71000FFEF5A00FFDE0800E7FFFF0094FF94005ADE4200B56B0000CE73
0000739C210042AD3100B56B0000522900000000000000000000000000000000
000029420800398410004AAD18004AB539004AB5390052A50000317300001831
1800295A00002952100018311800000000006B5A5200F7F7F700EFEFE700D6CE
C600CEBDB500BDADA500948C7B00736B5A00B5ADA5008C847300A59C94000808
9C004A6BF7003139EF0000007B000000000018181800181818004A4A4A00FFFF
FF00EFEFEF002121C6000000C600A5A5D6009C9CCE000000C6003131C600D6D6
D600CECECE00A5A5A5001818180018181800844200009463000084DE3900DE9C
0000F7D60800FFEF5A00FFD60000FFC60000FFC629008CEF63004AB521004ABD
290021BD390094841000844A0000522900000000000000000000000000000000
0000295218006BB529007BC66B007BC66B0063BD52004AB5390052A500001831
1800183118001831180000000000000000006B5A5200FFFFFF00EFEFE700D6CE
C600CEBDB500BDADA500948C7B007B7363009C8C7B008C847300A59C94000808
9C006384F700394AF70000007B0000000000000000001818180039393900F7F7
F700FFFFFF00CECEEF003939CE000000C6000000C6004242CE00C6C6D600D6D6
D600D6D6D6001818180018181800000000000000000084390000A5FFB50084CE
1800D6A50000FFD60000F7DE0000BD8C0000D6941000E7FFEF0039D6390031C6
310052AD2900BD7300006B390000000000000000000000000000000000000000
0000295A210084BD4A00CEE7BD009CCE84007BC66B004AB5390052A500001831
18000000000000000000000000000000000073635200FFFFFF00DED6CE00C6BD
B500A59C8C0094847300847B6B00847B6B00847B6B00847B6B00A59C94000808
9C007B94F7005A73F70000007B00000000000000000018181800313131004A4A
4A00F7F7F700FFFFFF00FFFFFF00F7F7F700EFEFEF00EFEFEF00E7E7E700D6D6
D6001818180018181800181818000000000000000000844200006B733900DEFF
F700ADD61000DEA50000F7D6080063D65A00CE730000DEE7840031D6420031C6
31004AB531007B42000073390000000000000000000000000000000000000000
0000295A210073A54A00FFFFFF00B5D6A5007BC66B0052A50000317300001831
18000000000000000000000000000000000073635200A59C8C00948C7B00847B
6B00847B6B00847B6B0084736300847363008473630084736300A59C94000808
9C00BDCEFF006B8CF70000007B00000000000000000000000000181818003131
3100393939004A4A4A00F7F7F700EFEFEF00EFEFEF00D6D6D600212121001818
180018181800181818000000000000000000000000000000000084420000637B
29007BE76B00C6940000FFB50000ADCE4A009CAD1000DEDE6B0084F7940063CE
5200526B18007331000000000000000000000000000000000000000000000000
000000000000295A210073A54A0084BD4A006BB5290031730000183118000000
0000000000000000000000000000000000000000000073635200736352007363
520084736300847363007B6B5A007B6B5A007B6B5A007B736300A59C94000808
9C00FFFFFF0094A5FF0000007B00000000000000000000000000000000001818
1800181818001818180018181800181818001818180018181800181818001818
1800181818000000000000000000000000000000000000000000000000008442
000084390000A55A0000FFA50800BDD67B007BBD3900E79C10009C5A00006B31
0000733100000000000000000000000000000000000000000000000000000000
00000000000000000000295A210029522100214A2100214A2100000000000000
0000000000000000000000000000000000000000000000000000000000000000
00006B5A52006B5A5200635A4A00635A4A005A4A42005A4A42006B5A52000000
000008089C0008089C0000000000000000000000000000000000000000000000
0000000000001818180018181800181818001818180018181800181818000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008442000084420000844200008442000084420000844200000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000005A4A42005A4A42005A4A42005A4A42005A4A4200423931000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000005A4A42005A4A42005A4A42005A4A42005A4A42004239
3100000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000005A4A42005A4A
42005A4A42007B7363008C847300635A4A00948473007B7363005A5242004239
3100000000000000000000000000000000000000000000000000000000005A4A
42005A4A42005A4A42007B7363008C847300635A4A00948473007B7363005A52
4200423931000000000000000000000000000000000000000000000000000000
0000000000000000000000000000394229000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000004252000042520000425200004252000042520000425200000000000000
000000000000000000000000000000000000635A4A00635A4A00847B6B00A59C
8C00BDADA500BDADA5006B6B73005A528C00736B94007B736300635A4A00524A
42004239310000000000000000000000000000000000635A4A00635A4A00847B
6B00A59C8C00BDADA500BDADA5006B6B73005A528C00736B94007B736300635A
4A00524A42004239310000000000000000000000000000000000000000000000
0000000000000000000039633100399C39003942290000000000000000000000
0000000000000000000000000000000000000000000000425200004252000042
5200006B84000094AD00009CBD00009CBD00009CBD00009CBD00004252004A21
080000000000000000000000000000000000635A4A00BDB5AD00DED6CE00D6CE
C60039312900CEC6BD00635A7B000800FF008C8494007B736300635A4A005A52
42004A42390042393100000000000000000000000000635A4A00BDB5AD00DED6
CE00D6CEC60039312900CEC6BD00635A7B000800FF008C8494007B736300635A
4A005A5242004A42390042393100000000000000000000000000000000000000
00000000000039633100399C390039CE42003994420039422900000000000000
0000000000000000000000000000000000000000000000425200009CB500009C
BD00009CBD00009CBD00009CBD00009CBD00009CBD00009CBD00004252005A29
10004A2108004A2108000000000000000000635A4A00E7DEDE0039312900DEDE
D600B5AD9C00BDADA5006B6B7300524ACE00AD9CBD007B736300635A4A005A52
4200524A390042393100000000000000000000000000635A4A00E7DEDE003931
2900E7DED600B5AD9C00BDADA5006B6B7300524ACE00AD9CBD007B736300635A
4A005A524200524A390042393100000000000000000000000000000000000000
000039633100399C390039D64200BDFFBD0039BD420039844200394229000000
0000000000000000000000000000000000000000000000425200008CA500009C
BD00009CBD00009CBD00009CBD00009CB5000094AD0000738400004252006B39
10007B4218006B3910004A21080000000000635A4A00E7DEDE00C6BDB500D6CE
C60039312900D6CEC60052944200428C31007BAD6B00847B6B00635A4A005A52
4200524A390042393100000000000000000000000000635A4A00E7DEDE00C6BD
B500D6CEC60039312900D6CEC60052944200428C31007BAD6B00847B6B00635A
4A005A524200524A390042393100000000000000000000000000000000003963
3100399C390039EF4200F7FFF70073B5730039BD420039BD4200398442003942
2900000000000000000000000000000000005A29100052524200007B94000084
9C0000637300004A5A00004A5A00004A5A00004A5A0000425200213131006B39
10007B4218008C4A18007B4218004A210800635A4A00E7DEDE004A423900E7DE
DE00B5AD9C00BDADA50052A5390042FF42007BAD8C00636B6300635A4A005A52
4200524A390042393100000000000000000000000000635A4A00E7DEDE004A42
3900E7DEDE00B5AD9C00BDADA50052A5390042FF4200A5CE9400847B6B00635A
4A005A524200524A39004239310000000000000000000000000039633100399C
390039EF4200CEFFCE007BBD7B0039422900398C390039BD420039BD42003984
4200394229000000000000000000000000005A291000845A390000425200005A
6B000894AD0021BDCE0042EFF7004AF7FF004AF7FF0042CED600213131004A21
08006B3910008C4A18008C4A18004A210800635A4A00EFEFE700C6BDB500D6CE
C6005A4A4200DED6D60063944A0018C6100000425200003142004A524A005A52
4200524A420000314200003142000000000000000000635A4A00EFEFE700C6BD
B500D6CEC6005A4A4200DED6D60063944A0018C61000BDE7AD00847B6B00635A
4A005A524200524A390042393100000000000000000039633100399C390039D6
4200A5FFAD006BBD6B003963310039AD390039422900398C390039BD420039BD
4200398442003942290000000000000000005A291000A56331002939390029A5
B50039E7F7004AF7FF0042F7FF0042EFFF004AEFF70052A5A50031525200844A
29004A2108004A2108007B4218004A2108006B5A5200EFEFE700635A4A00EFE7
E700BDB5AD00BDADA500948C7B00635A4A0000425200109CB50000314200424A
4A0000314200109CB5000031420000000000000000006B5A5200EFEFE700635A
4A00EFE7E700BDB5AD00BDADA500948C7B00635A4A00E7DED6008C847300635A
4A005A524200524A390042393100000000003963310039633100396331003963
3100395A31003963310039AD390084F78400399C420039422900395A31003963
310039633100395A390039422900000000005A2910006B391000A5633900004A
5A0039A5B50039E7FF0039E7FF0039E7FF004ADEEF00004A5A00AD845A00FFAD
7B00DE9463009C6339004A2108004A2108006B5A5200F7F7F700D6CEC600D6CE
C600CEBDB500BDADA500948C7B006B5A4A000042520021CEE70021DEFF000884
9C0021DEFF0021C6DE000031420000000000000000006B5A5200F7F7F700D6CE
C600D6CEC600CEBDB500BDADA500948C7B006B5A4A00E7DED6009C8C7B00635A
4A005A524200524A390042393100000000000000000000000000000000000000
00003963310039AD3900CEFFCE0052A5520039BD4200399C4200394229000000
0000000000000000000000000000000000005A291000AD6B3900EF9C6300CE84
5200004A5A0039A5B50029D6EF0029D6EF004AADB500525A4A00EF9C6B00FFAD
7B00FFAD7B00FFAD7B00AD6B42004A2108006B5A5200F7F7F700EFEFE700D6CE
C600CEBDB500BDADA500948C7B00736B5A006B5A4A000042520094F7FF0031E7
FF0021DEFF00003142000000000000000000000000006B5A5200F7F7F700EFEF
E700D6CEC600CEBDB500BDADA500948C7B00736B5A00B5ADA5008C847300635A
4A005A524200524A390042393100000000000000000000000000000000003963
310039AD39009CF79C004AA54A0039422900398C390039BD4200399C42003942
2900000000000000000000000000000000006B391000D68C5200EF9C6300EF9C
6300C67B5200004A5A0039A5B50031C6D600004A5A00C67B4A00F7A56B00F7A5
6B00FFAD7B00FFAD7B00EF9C6B005A3110006B5A5200FFFFFF00EFEFE700D6CE
C600CEBDB500BDADA500948C7B007B7363000042520018ADC600CEFFFF009CF7
FF0031E7FF0018ADC6000031420000000000000000006B5A5200FFFFFF00EFEF
E700D6CEC600CEBDB500BDADA500948C7B007B7363009C8C7B008C847300635A
4A005A524200524A390042393100000000000000000000000000396331003963
310039633100395231003963310039AD39003942290039523100396331003963
3100394229000000000000000000000000007B421800C67B4200EF9C6300EF9C
6300EF9C6300C67B4A0000425A0039A5B500525A4A00DE8C5A00F7A56B00F7A5
6B00F7A56B00FFAD7B00FFAD7B006B39100073635200FFFFFF00DED6CE00C6BD
B500A59C8C0094847300847B6B000042520029D6EF009CF7FF00FFFFFF00CEFF
FF009CF7FF0021DEFF0029CEE700003142000000000073635200FFFFFF00DED6
CE00C6BDB500A59C8C0094847300847B6B00847B6B00847B6B0084736300736B
5A00635A4A00524A390042393100000000000000000000000000000000000000
0000000000003963310063CE630039EF4200398C390039422900000000000000
0000000000000000000000000000000000008C4A1800AD633100E7945A00EF9C
6300EF9C6300EF9C6300C67B4A0000425200CE845200EF9C6300EF9C6300F7A5
6B00F7A56B00F7A56B00C67B4A008C4A180073635200A59C8C00948C7B00847B
6B00847B6B00847B6B008473630000425200004252000042520031E7FF009CF7
FF0031E7FF000042520000425200004252000000000073635200A59C8C00948C
7B00847B6B00847B6B00847B6B008473630084736300847363007B7363007B6B
5A0073635A00635A4A0042393100000000000000000000000000000000000000
00003963310052CE5A00CEFFCE0039D6420039BD4200398C3900394229000000
000000000000000000000000000000000000000000008C4A1800AD633100D684
5200E7945A00EF9C6300EF9C6300BD7B4A00EF9C6300EF9C6300EF9C6300EF9C
6300E7945A00B56B39008C4A1800000000000000000073635200736352007363
520084736300847363007B6B5A007B6B5A007B6B5A00736352000042520031E7
FF000042520063736B0000000000000000000000000000000000736352007363
52007363520084736300847363007B6B5A007B6B5A007B6B5A00736352006B5A
52005A4A42005A4A42005A4A4200000000000000000000000000000000003963
3100396331003963310039633100396331003963310039633100396331003942
29000000000000000000000000000000000000000000000000008C4A18008C4A
1800B56B3900CE844A00E7945A00E7945A00E7945A00E7945A00CE844A00B56B
39008C4A18008C4A180000000000000000000000000000000000000000000000
00006B5A52006B5A5200635A4A00635A4A005A4A42005A4A42005A4A42000042
5200000000000000000000000000000000000000000000000000000000000000
0000000000006B5A52006B5A5200635A4A00635A4A005A4A42005A4A42005A4A
4200000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00008C4A18008C4A18008C4A18008C4A18008C4A18008C4A18008C4A18008C4A
180000000000000000000000000000000000424D3E000000000000003E000000
2800000040000000800000000100010000000000000400000000000000000000
000000000000000000000000FFFFFF0000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000FC010000000000000001000000000000
0001000000000000000100000000000000010000000000000001000000000000
0000000000000000000100000000000000030000000000000003000000000000
00030000000000000003000000000000000F000000000000001F000000000000
003F000000000000007F000000000000FFFF8000FFFFFFFFFFFF8000FFFFFFFF
80010000E000800100010000C000000100018000C00000010001800080000001
0001800080000001000180000000000100018000000000010001800000000001
00018000800000010001800080000001000380008001000380FF8000C07F80FF
C1FFC000E0FFC1FFFFFFFFFFFFFFFFFFFFFFFC7FFE0FFE07F839F01FFC87F803
E001C007FF5FF807C0018001F81FFC0780038001F00FF00380030001E007C001
00010000C003800100010000C003800000010000C001000100010000C0010001
00018001E00100008003E007E00100008003F803F0018001C007FE00F0018003
E00FFF03CC03C07FF83FFF8FCF07F1FF03FFFFFFF99FFFFF03FFC007FC3FE001
03FFC003FE7FE0010000C0030000C0018000C0030000A001C000C003FE7F0001
8000C003FE7F00010000C003800300010000C003000180010000E00300008001
0000F0070000C001C000F3CF0000E001C000F3CF0000E001C000F18F8000E003
C000F81FC001E007C000FC3FFFFFE00FC001FF9FFC1FFFFF8000FF1FF007E001
0000FE1FE003E0010000F80FC001E0010001E0038001C0018001C00180008001
8003800100008001C00300000000C001C00700000000C001E00700000000E001
E00F00000001E001F00F00018001E001F01F80018003E001F81F8003C007E003
F83FC007E00FE007FC7FF01FF83FE00F887FF81FF81FF81F800FC00FE007E007
80070003C003C003800700018001800180010001800180018001000300000000
80010003000000008001000300000000C001000100000000E001000100000000
F001000100000000F003000180018001F00F000180018001F00F0001C003C003
F81F8001E007E007FC3FF013F81FF81FF81FFC0FFFFFFFFFC00FE007FEFFF03F
00078003FC7F800F00038001F83F800300038001F01F800100038001E00F0000
00038001C00700000001800180030000000180010001000000018001F01F0000
00038001E00F000000018001C007000000008001F83F000000008001F01F8001
8003C001E00FC003F00FF80FFFFFF00F00000000000000000000000000000000
000000000000}
end
object aclWinXPBar: TActionList
Images = imlWinXPBar
Left = 220
Top = 280
object acConnectRemoteServer: TAction
Category = 'Connect'
Caption = 'Remote-Server'
Hint = 'Connect to remote server'
ImageIndex = 0
OnExecute = acConnectRemoteServerExecute
end
object acConnectLocalServer: TAction
Category = 'Connect'
Caption = 'Local-Server'
Hint = 'Connect to local server'
ImageIndex = 1
end
object acConnectAdministrator: TAction
Category = 'Connect'
Caption = 'Administrator'
Hint = 'Administrator login'
ImageIndex = 19
end
object acSettingsUsers: TAction
Category = 'Settings'
Caption = 'User-Management'
ImageIndex = 4
end
object acSettingsStatistics: TAction
Category = 'Settings'
Caption = 'Statistics'
ImageIndex = 3
end
object acSettingsDatabase: TAction
Category = 'Settings'
Caption = 'Database'
ImageIndex = 5
end
object acSettingsDownloads: TAction
Category = 'Settings'
Caption = 'Downloads'
ImageIndex = 2
end
object acSynchronizeUnknown: TAction
Category = 'Synchronize'
Caption = 'Unknown'
ImageIndex = 6
end
object acSynchronizeWeb: TAction
Category = 'Synchronize'
Caption = 'Web'
ImageIndex = 7
end
object acGettingStarted: TAction
Category = 'Information'
Caption = 'Getting started'
Hint = 'Show the Getting Started Help'
ImageIndex = 9
end
object acHelp: TAction
Category = 'Information'
Caption = 'Help'
Hint = 'Show the Help'
ImageIndex = 9
end
object acHowDoI: TAction
Category = 'Information'
Caption = 'How do I...'
Hint = 'Show the "How do I" document'
ImageIndex = 9
end
object acCommonQuestions: TAction
Category = 'Information'
Caption = 'Common Questions'
Hint = 'Show the Common Questions'
ImageIndex = 9
end
end
object ilOldButtons: TImageList
BkColor = clFuchsia
Height = 19
Width = 19
Left = 332
Top = 198
Bitmap = {
494C010102000400040013001300FF00FF00FF10FFFFFFFFFFFFFFFF424D3600
00000000000036000000280000004C0000001300000001002000000000009016
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00E7C6B500E7BD
AD00DEB5AD00E7BDAD00DEB5AD00DEB5AD00DEB5AD00DEB5AD00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00E7C6B500E7BDAD00DEB5AD00E7BDAD00DEB5AD00DEB5AD00DEB5
AD00DEB5AD00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00EFC6BD00E7BDAD00DEB5AD00DEBDB500DEC6C600E7CEC600E7CEC600DEC6
C600DEBDB500DEB5AD00DEB5AD00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00EFC6BD00E7BDAD00DEB5AD00DEBDB500DEC6
C600E7CEC600E7CEC600DEC6C600DEBDB500DEB5AD00DEB5AD00FF00FF00FF00
FF00FF00FF00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00FF00FF00FF00FF00EFCEBD00DEB5AD00DEB5AD00E7D6CE00F7EF
E700F7F7EF00FFF7F700F7F7EF00F7F7EF00EFE7DE00E7D6CE00DEBDB500DEB5
AD00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00EFCEBD00DEB5
AD00DEB5AD00E7D6CE00F7EFE700F7F7EF00FFF7F700F7F7EF00F7F7EF00EFE7
DE00E7D6CE00DEBDB500DEB5AD00FF00FF00FF00FF00FF00FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00E7CEC600DEB5
AD00DEBDB500EFE7DE00FFFFF700FFFFF700FFFFF700FFFFF700FFFFF700FFF7
F700F7F7EF00F7F7EF00EFDED600DEBDB500DEB5AD00FF00FF00FF00FF00FF00
FF00FF00FF00E7CEC600DEB5AD00DEBDB500EFE7DE00FFFFF700FFFFF700FFFF
F700FFFFF700FFFFF700FFF7F700F7F7EF00F7F7EF00EFDED600DEBDB500DEB5
AD00FF00FF00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00FF00FF00E7C6BD00DEB5AD00EFE7DE00FFFFFF00FFFFFF00FFFF
FF00FFFFF700A5390000FFFFFF00FFFFF700FFFFFF00FFF7F700F7F7EF00E7D6
CE00DEBDB500DEBDAD00FF00FF00FF00FF00FF00FF00E7C6BD00DEB5AD00EFE7
DE00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
F700FFF7F700F7F7EF00E7D6CE00DEBDB500DEB5AD00FF00FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00F7D6C600DEB5AD00E7D6
CE00FFFFFF00FFFFFF00FFFFFF00FFFFFF00A5390000A5390000A5390000FFFF
FF00FFFFFF00FFFFFF00FFF7F700FFF7EF00E7CEC600DEBDAD00FF00FF00FF00
FF00F7D6C600DEB5AD00E7D6CE00FFFFFF00FFFFFF00A5390000A5390000FFFF
FF00FFFFFF00FFFFFF00A5390000A5390000FFFFFF00FFF7F700F7F7EF00DEC6
C600DEB5AD00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00E7CEC600DEBDB500F7EFE700FFFFFF00FFFFFF00FFFFFF00A539
0000A5390000FFFFF700A5390000A5390000FFF7F700FFFFFF00FFFFFF00FFF7
F700EFDEDE00DEBDAD00EFC6BD00FF00FF00E7CEC600DEBDB500F7EFE700FFFF
FF00FFFFFF00FFFFFF00A5390000A5390000FFFFFF00A5390000A5390000FFFF
FF00FFFFFF00FFFFFF00FFF7F700EFDED600DEB5AD00E7C6B500000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00EFCEBD00DEC6BD00FFFF
FF00FFFFFF00FFFFFF00A5390000A5390000FFFFF700FFFFF700FFFFF700A539
0000A5390000FFFFFF00FFFFFF00FFFFF700F7EFEF00DEBDB500EFC6BD00FF00
FF00EFCEBD00DEC6BD00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00A539
0000A5390000A5390000FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFF700F7EF
E700DEBDB500E7C6B50000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00EFCEBD00E7CEC600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFF700A5390000F7F7EF00FFFFF700FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFF7EF00DEBDB500EFC6BD00FF00FF00EFCEBD00E7CEC600FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00A5390000FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00F7F7EF00DEBDB500E7C6B500000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00EFCEBD00E7CEC600FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFF700A5390000A5390000A5390000F7F7
EF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00F7EFEF00DEBDB500EFC6BD00FF00
FF00EFCEBD00E7CEC600FFFFFF00FFFFFF00FFFFFF00A5390000A5390000FFFF
FF00FFFFFF00FFFFFF00A5390000A5390000FFFFFF00FFFFFF00FFFFFF00F7EF
E700DEBDB500E7C6B50000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00EFCEBD00DEC6BD00FFFFFF00FFFFFF00FFFFFF00FFFFFF00A539
0000A5390000FFFFF700A5390000A5390000FFF7F700FFFFFF00FFFFFF00FFFF
FF00F7E7E700DEBDAD00EFC6BD00FF00FF00EFCEBD00DEC6BD00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00A5390000A5390000FFFFFF00A5390000A5390000FFFF
FF00FFFFFF00FFFFFF00FFFFFF00EFE7DE00DEB5AD00E7C6B500000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00F7CEC600DEC6BD00F7EF
E700FFFFFF00FFFFFF00A5390000A5390000FFFFFF00FFFFFF00FFFFFF00A539
0000A5390000FFFFFF00FFFFFF00FFFFFF00E7D6CE00DEBDAD00FF00FF00FF00
FF00F7CEC600DEC6BD00F7EFE700FFFFFF00FFFFFF00FFFFFF00FFFFFF00A539
0000A5390000A5390000FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00E7D6
CE00DEB5AD00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00FF00FF00DEBDB500E7D6CE00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFF7
EF00DEB5AD00EFC6B500FF00FF00FF00FF00FF00FF00DEBDB500E7D6CE00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00A5390000FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00F7F7EF00DEB5AD00E7C6B500FF00FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00EFCEBD00DEB5
AD00EFDED600FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00F7F7EF00DEC6BD00DEB5AD00FF00FF00FF00FF00FF00
FF00FF00FF00EFCEBD00DEB5AD00EFDED600FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00F7F7EF00DEC6BD00DEB5
AD00FF00FF00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00FF00FF00FF00FF00E7C6BD00DEB5AD00EFDED600FFFFF700FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00F7EFE700DEC6BD00DEB5
AD00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00E7C6BD00DEB5
AD00EFDED600FFFFF700FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00F7EFE700DEC6BD00DEB5AD00FF00FF00FF00FF00FF00FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00E7C6BD00DEBDB500DEC6C600EFDED600F7EFE700F7F7EF00F7EFE700EFE7
DE00E7D6CE00DEB5AD00E7BDAD00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00E7C6BD00DEBDB500DEC6C600EFDED600F7EF
E700F7F7EF00F7EFE700EFE7DE00E7D6CE00DEB5AD00E7BDAD00FF00FF00FF00
FF00FF00FF00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00E7C6BD00DEBD
B500DEBDB500DEBDB500DEBDB500DEBDB500DEBDB500EFCEBD00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00EFCEBD00E7C6BD00DEBDB500DEBDB500DEBDB500DEBDB500DEBDB500DEBD
B500EFCEBD00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000424D3E000000000000003E000000280000004C0000001300000001000100
00000000E40000000000000000000000000000000000000000000000FFFFFF00
FFFFFFFFFC00000000000000FC03FF807C00000000000000F001FE003C000000
00000000E000FC001C00000000000000C00078000C00000000000000C0003800
0400000000000000800030000400000000000000800010000000000000000000
8000100000000000000000008000100000000000000000008000100000000000
00000000800010000000000000000000800030000400000000000000C0003800
0400000000000000C00078000C00000000000000E000FC001C00000000000000
F001FE003C00000000000000FC03FF007C00000000000000FFFFFFFFFC000000
0000000000000000000000000000000000000000000000000000}
end
object ilWhiteButtons: TImageList
BkColor = clFuchsia
Left = 232
Top = 198
Bitmap = {
494C010104000900040010001000FF00FF00FF10FFFFFFFFFFFFFFFF424D3600
0000000000003600000028000000400000003000000001002000000000000030
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FFFFFF00FFFFFF00FF00FF00FFFFFF00FFFFFF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FFFFFF00FFFFFF00FFFFFF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FFFFFF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00424D3E000000000000003E000000
2800000040000000300000000100010000000000800100000000000000000000
000000000000000000000000FFFFFF0000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFEFFFFFFFEFFFFFFFC7FF39FFC7FF39FF93FF93FF93FF93F
F39FFC7FF39FFC7FFEFFFEFFFEFFFEFFFC7FF39FFC7FF39FF93FF93FF93FF93F
F39FFC7FF39FFC7FFFFFFEFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
000000000000}
end
object ilRedButtons: TImageList
BkColor = clFuchsia
Left = 264
Top = 198
Bitmap = {
494C010102000400040010001000FF00FF00FF10FFFFFFFFFFFFFFFF424D3600
0000000000003600000028000000400000001000000001002000000000000010
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF000000FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000FF000000FF000000FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000FF000000FF00FF00FF00FF00FF00FF00FF000000FF000000FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000FF000000FF00FF00FF000000FF000000FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000FF000000FF00FF00FF000000FF000000FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF000000FF000000FF00FF00FF00FF00FF00FF00FF000000FF000000FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000FF000000FF000000FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF000000FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF000000FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000FF000000FF000000FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000FF000000FF00FF00FF00FF00FF00FF00FF000000FF000000FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000FF000000FF00FF00FF000000FF000000FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000FF000000FF00FF00FF000000FF000000FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF000000FF000000FF00FF00FF00FF00FF00FF00FF000000FF000000FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000FF000000FF000000FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF000000FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000424D3E000000000000003E000000
2800000040000000100000000100010000000000800000000000000000000000
000000000000000000000000FFFFFF00FFFFFFFF00000000FFFFFFFF00000000
FFFFFFFF00000000FEFFFFFF00000000FC7FF39F00000000F93FF93F00000000
F39FFC7F00000000FEFFFEFF00000000FC7FF39F00000000F93FF93F00000000
F39FFC7F00000000FFFFFEFF00000000FFFFFFFF00000000FFFFFFFF00000000
FFFFFFFF00000000FFFFFFFF0000000000000000000000000000000000000000
000000000000}
end
object ilBlackButtons: TImageList
BkColor = clFuchsia
Left = 296
Top = 198
Bitmap = {
494C010106000900040010001000FF00FF00FF10FFFFFFFFFFFFFFFF424D3600
0000000000003600000028000000400000003000000001002000000000000030
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF00FF00FF00FF00FF00000000000000
0000FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000000000000000FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000000000000000FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF00FF00FF00FF00FF00000000000000
0000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF00FF00FF00FF00FF00000000000000
0000FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000000000000000FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF000000000000000000FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF00FF00FF00FF00FF00000000000000
0000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF000000000000000000FF00FF000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF000000000000000000FF00FF00FF00FF00FF00FF000000000000000000FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00000000000000000000000000FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF0000000000FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00424D3E000000000000003E000000
2800000040000000300000000100010000000000800100000000000000000000
000000000000000000000000FFFFFF0000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000FFFFFFFF00000000FFFFFFFF00000000
FF7FFFFF00000000FE3FF9CF00000000FC9FFC9F00000000F9CFFE3F00000000
FF7FFF7F00000000FE3FF9CF00000000FC9FFC9F00000000F9CFFE3F00000000
FFFFFF7F00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000
FFFFFFFF00000000FFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFEFFFFFFFEFFFFFFFC7FF39FFC7FF39FF93FF93FF93FF93F
F39FFC7FF39FFC7FFEFFFEFFFEFFFEFFFC7FF39FFC7FF39FF93FF93FF93FF93F
F39FFC7FF39FFC7FFFFFFEFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
000000000000}
end
end
| 64.4198 | 76 | 0.871809 |
f149c059519bb9d022d44859a08f0112249d6e1d | 3,296 | pas | Pascal | src/dco.rpc.ErrorObject.pas | stanleyxu2005/dco | 4bda8792d5111a00dfa3af0f8654e1836ba31572 | [
"MIT"
]
| 1 | 2018-12-20T07:12:28.000Z | 2018-12-20T07:12:28.000Z | src/dco.rpc.ErrorObject.pas | stanleyxu2005/dco | 4bda8792d5111a00dfa3af0f8654e1836ba31572 | [
"MIT"
]
| null | null | null | src/dco.rpc.ErrorObject.pas | stanleyxu2005/dco | 4bda8792d5111a00dfa3af0f8654e1836ba31572 | [
"MIT"
]
| null | null | null | (**
* $Id: dco.rpc.ErrorObject.pas 840 2014-05-24 06:04:58Z QXu $
*
* 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.
*)
unit dco.rpc.ErrorObject;
interface
uses
System.SysUtils,
superobject { An universal object serialization framework with Json support };
type
/// <summary>This immutable value class represents a RPC error.</summary>
TErrorObject = record
private
FCode: Integer;
FMessage_: string;
FData: ISuperObject;
public
property Code: Integer read FCode;
property Message_: string read FMessage_;
property Data: ISuperObject read FData;
public
function ToString: string;
class function Create(Code: Integer; const Message_: string; const Data: ISuperObject): TErrorObject; static;
class function CreateParseError(const Detail: string): TErrorObject; static;
class function CreateInvalidRequest(const Detail: string): TErrorObject; static;
class function CreateMethodNotFound(const Detail: string): TErrorObject; static;
class function CreateInvalidParams(const Detail: string): TErrorObject; static;
class function CreateInternalError(const Detail: string): TErrorObject; static;
class function CreateInvalidResult(const Detail: string): TErrorObject; static; deprecated 'non-standard error';
class function CreateNoResponseReceived(const Detail: string): TErrorObject; static;
end;
implementation
uses
dutil.text.Util;
class function TErrorObject.Create(Code: Integer; const Message_: string; const Data: ISuperObject): TErrorObject;
begin
Result.FCode := Code;
Result.FMessage_ := Message_;
Result.FData := Data;
end;
function TErrorObject.ToString: string;
var
Detail: string;
begin
Detail := '';
if FData <> nil then
Detail := TUtil.Strip(FData.AsJson, '"');
if Detail = '' then
Result := Format('%s (%d)', [FMessage_, FCode])
else
Result := Format('%s (%d): %s', [FMessage_, FCode, Detail]);
end;
class function TErrorObject.CreateParseError(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-32700, 'Parse error', SO(Detail));
end;
class function TErrorObject.CreateInvalidRequest(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-32600, 'Invalid request', SO(Detail));
end;
class function TErrorObject.CreateMethodNotFound(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-32601, 'Method not found', SO(Detail));
end;
class function TErrorObject.CreateInvalidParams(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-32602, 'Invalid params', SO(Detail));
end;
class function TErrorObject.CreateInternalError(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-32603, 'Internal error', SO(Detail));
end;
class function TErrorObject.CreateInvalidResult(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-2, 'Invalid result', SO(Detail));
end;
class function TErrorObject.CreateNoResponseReceived(const Detail: string): TErrorObject;
begin
Result := TErrorObject.Create(-1, 'No response received', SO(Detail));
end;
end.
| 32.633663 | 116 | 0.752124 |
f158c75a1d9693fc86e37325d36edcea6b7a59f0 | 19,804 | pas | Pascal | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/Options/fOptionsReportsCustom.pas | josephsnyder/VistA | 07cabf4302675991dd453aea528f79f875358d58 | [
"Apache-2.0"
]
| 1 | 2021-01-01T01:16:44.000Z | 2021-01-01T01:16:44.000Z | CPRSChart/OR_30_423_SRC/CPRS-chart/Options/fOptionsReportsCustom.pas | VHAINNOVATIONS/Transplant | a6c000a0df4f46a17330cec95ff25119fca1f472 | [
"Apache-2.0"
]
| null | null | null | CPRSChart/OR_30_423_SRC/CPRS-chart/Options/fOptionsReportsCustom.pas | VHAINNOVATIONS/Transplant | a6c000a0df4f46a17330cec95ff25119fca1f472 | [
"Apache-2.0"
]
| null | null | null | unit fOptionsReportsCustom;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Spin, ORCtrls, fOptions, ComCtrls, ORFn, ORNet, Grids, uConst,
ORDtTm, rCore, fBase508Form, VA508AccessibilityManager;
type
TfrmOptionsReportsCustom = class(TfrmBase508Form)
Panel1: TPanel;
Bevel3: TBevel;
btnApply: TButton;
btnCancel: TButton;
Panel2: TPanel;
grdReport: TCaptionStringGrid;
edtMax: TCaptionEdit;
odbStop: TORDateBox;
odbStart: TORDateBox;
odbTool: TORDateBox;
btnOK: TButton;
Panel3: TPanel;
edtSearch: TCaptionEdit;
Label1: TLabel;
function ValFor(ACol, ARow: Integer): string;
procedure FormCreate(Sender: TObject);
procedure grdReportMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure grdReportKeyPress(Sender: TObject; var Key: Char);
procedure grdReportDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure UMDelayEvent(var Message: TMessage); Message UM_DELAYEVENT;
procedure edtMaxExit(Sender: TObject);
procedure btnApplyClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure odbStartExit(Sender: TObject);
procedure odbStopExit(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure odbStartKeyPress(Sender: TObject; var Key: Char);
procedure odbStopKeyPress(Sender: TObject; var Key: Char);
procedure edtMaxKeyPress(Sender: TObject; var Key: Char);
procedure btnOKClick(Sender: TObject);
procedure edtSearchChange(Sender: TObject);
procedure edtSearchKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure grdReportKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
//startDate,endDate,
maxOcurs,signal: integer;
rptList: TStringList;
fDropColumn: Integer;
sDate,eDate: string;
procedure ShowEditor(ACol, ARow: Integer; AChar: Char);
public
{ Public declarations }
end;
var
frmOptionsReportsCustom: TfrmOptionsReportsCustom;
const
Col_StartDate = 1;
Col_StopDate = 2;
Col_Max = 3;
TAB = #9;
procedure DialogOptionsHSCustom(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
implementation
uses rOptions, uOptions, fReports, fLabs, uCore;
{$R *.DFM}
procedure TfrmOptionsReportsCustom.UMDelayEvent(var Message: TMessage);
{ after focusing events are completed for a combobox, set the key the user typed }
begin
case Message.LParam of
Col_StartDate:
begin
odbStart.Visible := True;
odbStart.Text := Chr(Message.WParam);
end;
COL_StopDate :
begin
odbStop.Visible := True;
odbStop.Text := Chr(Message.WParam);
end;
COL_Max :
begin
edtMax.Visible := True;
edtMax.Text := Chr(Message.WParam);
end;
end;
end;
procedure DialogOptionsHSCustom(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
var
frmOptionsReportsCustom: TfrmOptionsReportsCustom;
begin
frmOptionsReportsCustom := TfrmOptionsReportsCustom.Create(Application);
actiontype := 0;
try
with frmOptionsReportsCustom do
begin
if (topvalue < 0) or (leftvalue < 0) then
Position := poScreenCenter
else
begin
Position := poDesigned;
Top := topvalue;
Left := leftvalue;
end;
ResizeAnchoredFormToFont(frmOptionsReportsCustom);
// grdReport draws on the canvas which is a different font than the control;
// Default drawing set to true duplicated the text in each selected cell
grdReport.Canvas.Font := Label1.Font;
grdReport.DefaultRowHeight := 24;
ShowModal;
actiontype := btnApply.Tag;
end;
finally
frmOptionsReportsCustom.Release;
end;
end;
procedure TfrmOptionsReportsCustom.FormCreate(Sender: TObject);
begin
rptList := TStringList.Create;
end;
procedure TfrmOptionsReportsCustom.ShowEditor(ACol, ARow: Integer; AChar: Char);
procedure PlaceControl(AControl: TWinControl);
var
ARect: TRect;
begin
with AControl do
begin
ARect := grdReport.CellRect(ACol, ARow);
SetBounds(ARect.Left + grdReport.Left + 2, ARect.Top + grdReport.Top + 2,
ARect.Right - ARect.Left - 1 , ARect.Bottom-ARect.Top -1 );
Visible := True;
Tag := ARow;
BringToFront;
Show;
SetFocus;
end;
end;
procedure Synch(AEdit: TEdit; const edtText: string);
begin
AEdit.Text := edtText;
AEdit.SelectAll;
end;
begin
inherited;
if ARow = 0 then Exit; //header row
with grdReport do if (ARow = Pred(RowCount)) and (ACol > 4 ) then Exit;
case ACol of
Col_StartDate: begin
if (ARow > 0 ) then
begin
PlaceControl(odbStart);
Synch(odbStart,ValFor(Col_StartDate,ARow));
if AChar <> #0 then PostMessage(Handle, UM_DELAYEVENT, Ord(AChar), COL_StartDate);
end;
end;
Col_StopDate: begin
if (ARow > 0 ) then
begin
PlaceControl(odbStop);
Synch(odbStop, ValFor(Col_StopDate,ARow));
if AChar <> #0 then PostMessage(Handle, UM_DELAYEVENT, Ord(AChar), COL_StopDate);
end;
end;
Col_Max: begin
if (ARow > 0 ) and (StrToInt(ValFor(Col_Max,ARow)) > 0) then
begin
PlaceControl(edtMax);
Synch(edtMax, ValFor(Col_Max,ARow));
fDropColumn := Col_Max;
if AChar <> #0 then PostMessage(Handle, UM_DELAYEVENT, Ord(AChar), COL_Max);
end;
end;
end;
end;
function TfrmOptionsReportsCustom.ValFor(ACol, ARow: Integer): string;
begin
Result := grdReport.Cells[ACol, ARow];
end;
procedure TfrmOptionsReportsCustom.grdReportKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if grdReport.Col = 1 then
sDate := grdReport.Cells[grdReport.Col,grdReport.Row];
if grdReport.Col = 2 then
eDate := grdReport.Cells[grdReport.Col,grdReport.Row];
if (grdReport.Col = 3) and (grdReport.Cells[grdReport.Col, grdReport.Row]='') then
Exit else if Length(grdReport.Cells[3, grdReport.Row]) > 0 then maxOcurs := StrToInt( grdReport.Cells[3,grdReport.Row]);
if Key = #13 then ShowEditor(grdReport.Col, grdReport.Row, #0);
if Key = #9 then
begin
odbStart.Visible := False;
odbStop.Visible := False;
edtMax.Visible := False;
ShowEditor(grdReport.Col, grdReport.Row, #0);
end;
if CharInSet(Key, [#32..#127]) then ShowEditor(grdReport.Col, grdReport.Row, Key);
signal := 0;
end;
procedure TfrmOptionsReportsCustom.grdReportMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
ACol,ARow: integer;
begin
inherited;
if (not User.ToolsRptEdit) then // For users with Reports settings edit parameter not set.
begin
abort;
exit;
end;
grdReport.MouseToCell(X,Y,ACol,ARow);
if (ARow < 1) or (ACol < 1) then
begin
odbStop.Visible := False;
odbStart.Visible := False;
edtMax.Visible := False;
Exit;
end;
if ACol = 1 then
begin
odbStop.Visible := False;
edtMax.Visible := False;
sDate := grdReport.Cells[1,ARow];
ShowEditor(ACol, ARow, #0);
end;
if ACol = 2 then
begin
odbStart.Visible := False;
edtMax.Visible := False;
eDate := grdReport.Cells[2,ARow];
ShowEditor(ACol, ARow, #0);
end;
if (ACol = 3) and (grdReport.Cells[ACol,ARow]='') then
begin
odbStart.Visible := False;
odbStop.Visible := False;
Exit;
end
else if (ACol = 3) and (strtoint(grdReport.Cells[ACol,ARow])>0) then
begin
odbStart.Visible := False;
odbStop.Visible := False;
maxOcurs := strtoint(grdReport.Cells[ACol,ARow]);
ShowEditor(ACol, ARow, #0);
end
else
begin
grdReport.Col := 0;
grdReport.Row := ARow;
end;
signal := 0;
end;
procedure TfrmOptionsReportsCustom.grdReportDrawCell(Sender: TObject; ACol,
ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
inherited;
grdReport.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2,
Piece(grdReport.Cells[ACol, ARow], TAB, 1));
end;
procedure TfrmOptionsReportsCustom.edtMaxExit(Sender: TObject);
var
newValue: String;
code, I: integer;
begin
if edtMax.Modified then
begin
newValue := edtMax.Text;
if length(newValue) = 0 then
begin
InfoBox('Invalid value of max occurences', 'Warning', MB_OK or MB_ICONWARNING);
edtMax.Text := IntToStr(maxOcurs);
edtMax.SetFocus;
edtMax.SelectAll;
end;
if length(newValue) > 0 then
begin
Val(newValue, I, code);
if I = 0 then begin end; //added to keep compiler from generating a hint
if code <> 0 then
begin
InfoBox('Invalid value of max occurences', 'Warning', MB_OK or MB_ICONWARNING);
edtMax.Text := IntToStr(maxOcurs);
edtMax.SetFocus;
edtMax.SelectAll;
end;
if code = 0 then
begin
if strtoint(edtMax.Text) <= 0 then
begin
InfoBox('the value of max should be greater than 0', 'Warning', MB_OK or MB_ICONWARNING);
edtMax.Text := intToStr(maxOcurs);
edtMax.SetFocus;
edtMax.SelectAll;
exit;
end;
grdReport.Cells[Col_Max, edtMax.Tag] := edtMax.Text;
if compareStr(Piece(Piece(grdReport.Cells[0,edtMax.Tag],TAB,2),'^',2),'M')=0 then
begin
edtMax.Visible := False;
btnApply.Enabled := True;
Exit;
end;
grdReport.Cells[0,edtMax.Tag] := grdReport.Cells[0,edtMax.Tag] + '^M';
edtMax.Visible := False;
btnApply.Enabled := True;
end;
end;
end;
end;
procedure TfrmOptionsReportsCustom.btnApplyClick(Sender: TObject);
var
valueStartdate, valueStopdate,valueMax, rpt, values,name: string;
i: integer;
begin
for i := 1 to grdReport.RowCount do
begin
if CompareStr(Piece(Piece( grdReport.Cells[0,i],TAB,2),'^',2),'M')=0 then
begin
rpt := Piece(Piece( grdReport.Cells[0,i],TAB,2),'^',1);
name := Piece( grdReport.Cells[0,i],TAB,1);
odbTool.Text := grdReport.Cells[1,i];
valueStartDate := odbTool.RelativeTime;
odbTool.Text := grdReport.Cells[2,i];
valueStopDate := odbTool.RelativeTime;
valueMax := grdReport.Cells[3,i];
if Length(valueMax)<1 then
valueMax := '7';
values := valueStartdate + ';' + valueStopDate + ';' + valueMax;
{ if CompareStr(name,'Imaging (local only)')=0 then // imaging report id is hard coded to be 10000
values := valueStartdate + ';' + valueStopDate + ';;;' + valueMax
else}
rpcSetIndividualReportSetting(rpt, values);
end;
end;
btnApply.Enabled := False;
odbStart.Visible := False;
odbStop.Visible := False;
edtMax.Visible := False;
frmReports.LoadTreeView;
frmLabs.LoadTreeView;
with frmReports.tvReports do
begin
if Items.Count > 0 then
Selected := Items.GetFirstNode;
frmReports.tvReportsClick(Selected);
end;
with frmLabs.tvReports do
begin
if Items.Count > 0 then
Selected := Items.GetFirstNode;
frmReports.tvReportsClick(Selected);
end;
end;
procedure TfrmOptionsReportsCustom.btnCancelClick(Sender: TObject);
begin
rptList.Clear;
Close;
end;
procedure TfrmOptionsReportsCustom.odbStartExit(Sender: TObject);
const
TX_BAD_START = 'The start date is not valid.';
TX_STOPSTART = 'The start date must not be after the stop date.';
var
x,ErrMsg,datestart,datestop: String;
begin
if odbStart.text = '' then
begin
InfoBox(TX_BAD_START, 'Warning', MB_OK or MB_ICONWARNING);
odbStart.Visible := True;
odbStart.Text := sDate;
odbStart.Setfocus;
odbStart.SelectAll;
exit;
end;
if odbStart.Text = sDate then
exit;
ErrMsg := '';
odbStart.Validate(x);
if Length(x) > 0 then
begin
ErrMsg := TX_BAD_START;
InfoBox(TX_BAD_START, 'Warning', MB_OK or MB_ICONWARNING);
odbStart.Visible := True;
odbStart.Text := sDate;
odbStart.Setfocus;
odbStart.SelectAll;
exit;
end;
datestart := odbStart.RelativeTime;
datestop := MakeRelativeDateTime(
StrToFMDateTime(grdReport.Cells[Col_StopDate,odbStart.Tag])
);
delete(datestart,1,1);
delete(datestop,1,1);
if StrToIntDef(datestart,0)> StrToIntDef(datestop,0) then
begin
InfoBox(TX_STOPSTART, 'Warning', MB_OK or MB_ICONWARNING);
odbStart.Text := grdReport.Cells[Col_StopDate,odbStart.Tag];
odbStart.SetFocus;
odbStart.SelectAll;
exit;
end;
grdReport.Cells[Col_StartDate, odbStart.Tag] := DateToStr(FMDateTimeToDateTime(odbStart.FMDateTime));
odbStart.Visible := False;
btnApply.Enabled := True;
if compareStr(Piece(Piece(grdReport.Cells[0,odbStart.Tag],TAB,2),'^',2),'M')=0 then
Exit;
grdReport.Cells[0,odbStart.Tag] := grdReport.Cells[0,odbStart.Tag] + '^M';
end;
procedure TfrmOptionsReportsCustom.odbStopExit(Sender: TObject);
const
TX_BAD_STOP = 'The stop date is not valid.';
TX_BAD_ORDER = 'The stop date must not be earlier than start date.';
var
x, ErrMsg,datestart,datestop: string;
begin
if odbStop.text = '' then
begin
InfoBox(TX_BAD_STOP, 'Warning', MB_OK or MB_ICONWARNING);
odbStop.Visible := True;
odbStop.Text := eDate;
odbStop.Setfocus;
odbStop.SelectAll;
exit;
end;
if odbStop.Text = eDate then
exit;
ErrMsg := '';
odbStop.Validate(x);
if Length(x) > 0 then
begin
ErrMsg := TX_BAD_STOP;
InfoBox(TX_BAD_STOP, 'Warning', MB_OK or MB_ICONWARNING);
odbStop.Visible := True;
odbStop.Text := eDate;
odbStop.Setfocus;
odbStop.SelectAll;
exit;
end;
datestart := MakeRelativeDateTime(
StrToFMDateTime(grdReport.Cells[Col_StartDate,odbStop.Tag])
);
datestop := odbStop.RelativeTime;
delete(datestart,1,1);
delete(datestop,1,1);
if StrToIntDef(datestart,0)> StrToIntDef(datestop,0) then
begin
InfoBox(TX_BAD_ORDER, 'Warning', MB_OK or MB_ICONWARNING);
odbStop.Text := grdReport.Cells[Col_StartDate,odbStop.Tag];
odbStop.SetFocus;
odbStop.SelectAll;
exit;
end;
grdReport.Cells[Col_StopDate, odbStop.Tag] := DateToStr(FMDateTimeToDateTime(odbStop.FMDateTime));
odbStop.Visible := False;
btnApply.Enabled := True;
if compareStr(Piece(Piece(grdReport.Cells[0,odbStop.Tag],TAB,2),'^',2),'M')=0 then
Exit;
grdReport.Cells[0,odbStop.Tag] := grdReport.Cells[0,odbStop.Tag] + '^M';
end;
procedure TfrmOptionsReportsCustom.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Close;
rptList.Clear;
end;
procedure TfrmOptionsReportsCustom.odbStartKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
odbStart.Visible := False;
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
end;
procedure TfrmOptionsReportsCustom.odbStopKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
odbStop.Visible := False;
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
end;
procedure TfrmOptionsReportsCustom.edtMaxKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
edtMax.Visible := False;
Perform(WM_NextDlgCtl, 0, 0);
exit;
end;
end;
procedure TfrmOptionsReportsCustom.btnOKClick(Sender: TObject);
begin
if btnApply.Enabled then
btnApplyClick(self);
Close;
end;
procedure TfrmOptionsReportsCustom.edtSearchChange(Sender: TObject);
var
i: integer;
needle,hay: String;
selRect: TGridRect;
begin
if (edtSearch.Modified) and (signal=0) then
begin
needle := UpperCase(edtSearch.text);
if length(needle)=0 then
begin
selRect.Left := 0;
selRect.Top := 1;
selRect.Right := 0;
selRect.Bottom := 1;
grdReport.Selection := selRect;
grdReport.TopRow := 1;
exit;
end;
for i := 1 to grdReport.RowCount do
begin
hay := Piece(UpperCase(grdReport.Cells[0,i]),TAB,1);
hay := Copy(hay,0,length(needle));
if Pos(needle, hay) > 0 then
begin
selRect.Left := 0;
selRect.Top := i;
selRect.Right := 0;
selRect.Bottom := i;
grdReport.Selection := selRect;
grdReport.TopRow := i;
exit;
end;
end;
end;
if (edtSearch.Modified) and (signal=1) then
begin
signal := 0;
end;
Exit;
end;
procedure TfrmOptionsReportsCustom.edtSearchKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Perform(WM_NextDlgCtl, 0, 0);
edtSearch.Text := '';
exit;
end;
end;
procedure TfrmOptionsReportsCustom.FormShow(Sender: TObject);
var
i,rowNum: integer;
startOff,stopOff: string;
today: TFMDateTime;
begin
today := FMToday;
signal := 0;
rptList := TStringList.Create;
CallV('ORWTPD GETSETS',[nil]);
MixedCaseList( RPCBrokerV.Results );
rptList := TStringList(RPCBrokerV.Results);
SortByPiece(rptList,'^',2);
rowNum := rptList.Count;
grdReport.RowCount := rowNum + 1;
grdReport.Cells[0,0] := 'Report Name';
grdReport.Cells[1,0] := 'Start Date';
grdReport.Cells[2,0] := 'Stop Date';
grdReport.Cells[3 ,0] := 'Max';
for i := 1 to grdReport.RowCount-1 do
begin
grdReport.Cells[0,i] := Piece(rptList[i-1],'^',2)+ TAB + Piece(rptList[i-1],'^',1);
startOff := Piece(Piece(rptList[i-1],'^',3),';',1);
stopOff := Piece(Piece(rptList[i-1],'^',3),';',2);
delete(startOff,1,1);
delete(stopOff,1,1);
grdReport.Cells[1,i] := DateToStr(FMDateTimeToDateTime(FMDateTimeOffsetBy(today, StrToIntDef(startOff,0))));
grdReport.Cells[2,i] := DateToStr(FMDateTimeToDateTime(FMDateTimeOffsetBy(today, StrToIntDef(stopOff,0))));
grdReport.Cells[3,i] := Piece(Piece(rptList[i-1],'^',3),';',3);
end;
if not edtSearch.Focused then
edtSearch.SetFocus;
btnCancel.Caption := 'Cancel';
if (not User.ToolsRptEdit) then // For users with Reports settings edit parameter not set.
begin
grdReport.onKeyPress := nil;
grdReport.onMouseDown := nil;
odbStart.readOnly := true;
odbStart.onExit := nil;
odbStart.onKeyPress := nil;
odbStop.readOnly := true;
odbStop.onExit := nil;
odbStop.onKeyPress := nil;
edtMax.readOnly := true;
odbTool.readOnly := true;
btnOK.visible := false;
btnApply.visible := false;
btnCancel.Caption := 'Close';
end;
end;
procedure TfrmOptionsReportsCustom.grdReportKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key = VK_TAB) then
begin
if ssShift in Shift then
begin
EdtSearch.SetFocus;
Key := 0;
end
else if ssCtrl in Shift then
begin
if User.ToolsRptEdit then
btnApply.SetFocus
else
btnCancel.SetFocus;
Key := 0;
end;
end;
if Key = VK_ESCAPE then begin
EdtSearch.SetFocus;
Key := 0;
end;
end;
end.
| 29.602392 | 126 | 0.638356 |
fc55a7b64701b8ea74db273341e9feef5f6a8a40 | 264 | pas | Pascal | Program.pas | ThreeFx/ExpressionParser | 5f09d2dac43c9e182f190bb0956bccb47217906e | [
"MIT"
]
| 1 | 2017-06-12T18:58:09.000Z | 2017-06-12T18:58:09.000Z | Program.pas | ThreeFx/ExpressionParser | 5f09d2dac43c9e182f190bb0956bccb47217906e | [
"MIT"
]
| null | null | null | Program.pas | ThreeFx/ExpressionParser | 5f09d2dac43c9e182f190bb0956bccb47217906e | [
"MIT"
]
| null | null | null | PROGRAM test;
USES StackElement, Node, Parser, ExpressionStack, SysUtils;
VAR
tree : TNode;
BEGIN
tree := ParseExpr('1*1');
WriteLn('Jep');
WriteLn(IntToStr(tree.Evaluate));
WriteLn('Jep');
WriteLn(IntToStr(TExpressionStack.FromTree(tree).Evaluate));
END.
| 18.857143 | 61 | 0.731061 |
c3af440b9959d20499e94c37a11f1cb4ab55c152 | 23,668 | pas | Pascal | restudio/RegularExpressionsXMLBind.pas | cumtcdf/TRegExpr | 87bb0110f2e7b9967cb7561afdb11c18485eb062 | [
"MIT"
]
| 1 | 2022-03-20T16:05:54.000Z | 2022-03-20T16:05:54.000Z | restudio/RegularExpressionsXMLBind.pas | weblate/TRegExpr | 7e8742fab6a9f79e6cd1d5795d67fced831acafd | [
"MIT"
]
| null | null | null | restudio/RegularExpressionsXMLBind.pas | weblate/TRegExpr | 7e8742fab6a9f79e6cd1d5795d67fced831acafd | [
"MIT"
]
| 1 | 2021-01-19T08:46:57.000Z | 2021-01-19T08:46:57.000Z |
{*****************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 25.02.2006 11:51:20 }
{ Generated from: Q:\RegExpr\Test\Tests\RegularExpressionsXMLBind.xml }
{ Settings stored in: Q:\RegExpr\Test\Tests\RegularExpressionsXMLBind.xdb }
{ }
{*****************************************************************************}
unit RegularExpressionsXMLBind;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLRegularExpressionsType = interface;
IXMLRegularExpressionType = interface;
IXMLTestCaseType = interface;
IXMLTestCaseTypeList = interface;
IXMLSubjectType = interface;
IXMLSubstringType = interface;
IXMLMatchType = interface;
IXMLMatchTypeList = interface;
IXMLSubstitutionType = interface;
IXMLSubstitutionTypeList = interface;
IXMLReplaceType = interface;
IXMLReplaceTypeList = interface;
IXMLString_List = interface;
{ IXMLRegularExpressionsType }
IXMLRegularExpressionsType = interface(IXMLNodeCollection)
['{A7D5B1B3-C40D-4D63-8270-146EE0667E7F}']
{ Property Accessors }
function Get_RegularExpression(Index: Integer): IXMLRegularExpressionType;
{ Methods & Properties }
function Add: IXMLRegularExpressionType;
function Insert(const Index: Integer): IXMLRegularExpressionType;
property RegularExpression[Index: Integer]: IXMLRegularExpressionType read Get_RegularExpression; default;
end;
{ IXMLRegularExpressionType }
IXMLRegularExpressionType = interface(IXMLNode)
['{6CD4EDE6-B46D-4764-BD0E-61660204612A}']
{ Property Accessors }
function Get_Id: Integer;
function Get_Name: WideString;
function Get_Description: WideString;
function Get_Comment: WideString;
function Get_Expression: WideString;
function Get_Category: IXMLString_List;
function Get_TestCase: IXMLTestCaseTypeList;
procedure Set_Id(Value: Integer);
procedure Set_Name(Value: WideString);
procedure Set_Description(Value: WideString);
procedure Set_Comment(Value: WideString);
procedure Set_Expression(Value: WideString);
{ Methods & Properties }
property Id: Integer read Get_Id write Set_Id;
property Name: WideString read Get_Name write Set_Name;
property Description: WideString read Get_Description write Set_Description;
property Comment: WideString read Get_Comment write Set_Comment;
property Expression: WideString read Get_Expression write Set_Expression;
property Category: IXMLString_List read Get_Category;
property TestCase: IXMLTestCaseTypeList read Get_TestCase;
end;
{ IXMLTestCaseType }
IXMLTestCaseType = interface(IXMLNode)
['{A087D83F-28E1-486A-AE80-CA8AE4CFE8A8}']
{ Property Accessors }
function Get_Modifiers: WideString;
function Get_Subject: IXMLSubjectType;
function Get_Match: IXMLMatchTypeList;
function Get_Substitution: IXMLSubstitutionTypeList;
function Get_Replace: IXMLReplaceTypeList;
procedure Set_Modifiers(Value: WideString);
{ Methods & Properties }
property Modifiers: WideString read Get_Modifiers write Set_Modifiers;
property Subject: IXMLSubjectType read Get_Subject;
property Match: IXMLMatchTypeList read Get_Match;
property Substitution: IXMLSubstitutionTypeList read Get_Substitution;
property Replace: IXMLReplaceTypeList read Get_Replace;
end;
{ IXMLTestCaseTypeList }
IXMLTestCaseTypeList = interface(IXMLNodeCollection)
['{FFE9C8E6-06FA-42E8-B469-CF4B75B9CAFE}']
{ Methods & Properties }
function Add: IXMLTestCaseType;
function Insert(const Index: Integer): IXMLTestCaseType;
function Get_Item(Index: Integer): IXMLTestCaseType;
property Items[Index: Integer]: IXMLTestCaseType read Get_Item; default;
end;
{ IXMLSubjectType }
IXMLSubjectType = interface(IXMLNodeCollection)
['{B8582A18-07B0-4A22-8916-FDCC7CB7137A}']
{ Property Accessors }
function Get_Substring(Index: Integer): IXMLSubstringType;
{ Methods & Properties }
function Add: IXMLSubstringType;
function Insert(const Index: Integer): IXMLSubstringType;
property Substring[Index: Integer]: IXMLSubstringType read Get_Substring; default;
end;
{ IXMLSubstringType }
IXMLSubstringType = interface(IXMLNode)
['{F263D564-1EC6-4FCA-BEBB-4390B9E50734}']
{ Property Accessors }
function Get_RepeatCount: Integer;
function Get_FileName: WideString;
procedure Set_RepeatCount(Value: Integer);
procedure Set_FileName(Value: WideString);
{ Methods & Properties }
property RepeatCount: Integer read Get_RepeatCount write Set_RepeatCount;
property FileName: WideString read Get_FileName write Set_FileName;
end;
{ IXMLMatchType }
IXMLMatchType = interface(IXMLNodeCollection)
['{C484715D-A39C-49AF-85B5-C97E16022397}']
{ Property Accessors }
function Get_Position: Integer;
function Get_Length: Integer;
function Get_CapturedSubstring(Index: Integer): WideString;
procedure Set_Position(Value: Integer);
procedure Set_Length(Value: Integer);
{ Methods & Properties }
function Add(const CapturedSubstring: WideString): IXMLNode;
function Insert(const Index: Integer; const CapturedSubstring: WideString): IXMLNode;
property Position: Integer read Get_Position write Set_Position;
property Length: Integer read Get_Length write Set_Length;
property CapturedSubstring[Index: Integer]: WideString read Get_CapturedSubstring; default;
end;
{ IXMLMatchTypeList }
IXMLMatchTypeList = interface(IXMLNodeCollection)
['{9699FB75-7D5C-4906-9218-7CA89995B208}']
{ Methods & Properties }
function Add: IXMLMatchType;
function Insert(const Index: Integer): IXMLMatchType;
function Get_Item(Index: Integer): IXMLMatchType;
property Items[Index: Integer]: IXMLMatchType read Get_Item; default;
end;
{ IXMLSubstitutionType }
IXMLSubstitutionType = interface(IXMLNode)
['{B0E59E06-3FDB-48D7-857A-169599156F93}']
{ Property Accessors }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
{ Methods & Properties }
property Template: WideString read Get_Template write Set_Template;
property Result: WideString read Get_Result write Set_Result;
end;
{ IXMLSubstitutionTypeList }
IXMLSubstitutionTypeList = interface(IXMLNodeCollection)
['{4389D23C-1983-42D4-B37A-2DAD2CD8E05E}']
{ Methods & Properties }
function Add: IXMLSubstitutionType;
function Insert(const Index: Integer): IXMLSubstitutionType;
function Get_Item(Index: Integer): IXMLSubstitutionType;
property Items[Index: Integer]: IXMLSubstitutionType read Get_Item; default;
end;
{ IXMLReplaceType }
IXMLReplaceType = interface(IXMLNode)
['{20CBB304-7D53-40B9-87D2-5CB502AFE298}']
{ Property Accessors }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
{ Methods & Properties }
property Template: WideString read Get_Template write Set_Template;
property Result: WideString read Get_Result write Set_Result;
end;
{ IXMLReplaceTypeList }
IXMLReplaceTypeList = interface(IXMLNodeCollection)
['{845B6020-3A75-42D3-8BC4-EF7F9E6A34FF}']
{ Methods & Properties }
function Add: IXMLReplaceType;
function Insert(const Index: Integer): IXMLReplaceType;
function Get_Item(Index: Integer): IXMLReplaceType;
property Items[Index: Integer]: IXMLReplaceType read Get_Item; default;
end;
{ IXMLString_List }
IXMLString_List = interface(IXMLNodeCollection)
['{174F014A-A1B9-4FDC-BF2B-1D21F3D6E41A}']
{ Methods & Properties }
function Add(const Value: WideString): IXMLNode;
function Insert(const Index: Integer; const Value: WideString): IXMLNode;
function Get_Item(Index: Integer): WideString;
property Items[Index: Integer]: WideString read Get_Item; default;
end;
{ Forward Decls }
TXMLRegularExpressionsType = class;
TXMLRegularExpressionType = class;
TXMLTestCaseType = class;
TXMLTestCaseTypeList = class;
TXMLSubjectType = class;
TXMLSubstringType = class;
TXMLMatchType = class;
TXMLMatchTypeList = class;
TXMLSubstitutionType = class;
TXMLSubstitutionTypeList = class;
TXMLReplaceType = class;
TXMLReplaceTypeList = class;
TXMLString_List = class;
{ TXMLRegularExpressionsType }
TXMLRegularExpressionsType = class(TXMLNodeCollection, IXMLRegularExpressionsType)
protected
{ IXMLRegularExpressionsType }
function Get_RegularExpression(Index: Integer): IXMLRegularExpressionType;
function Add: IXMLRegularExpressionType;
function Insert(const Index: Integer): IXMLRegularExpressionType;
public
procedure AfterConstruction; override;
end;
{ TXMLRegularExpressionType }
TXMLRegularExpressionType = class(TXMLNode, IXMLRegularExpressionType)
private
FCategory: IXMLString_List;
FTestCase: IXMLTestCaseTypeList;
protected
{ IXMLRegularExpressionType }
function Get_Id: Integer;
function Get_Name: WideString;
function Get_Description: WideString;
function Get_Comment: WideString;
function Get_Expression: WideString;
function Get_Category: IXMLString_List;
function Get_TestCase: IXMLTestCaseTypeList;
procedure Set_Id(Value: Integer);
procedure Set_Name(Value: WideString);
procedure Set_Description(Value: WideString);
procedure Set_Comment(Value: WideString);
procedure Set_Expression(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLTestCaseType }
TXMLTestCaseType = class(TXMLNode, IXMLTestCaseType)
private
FMatch: IXMLMatchTypeList;
FSubstitution: IXMLSubstitutionTypeList;
FReplace: IXMLReplaceTypeList;
protected
{ IXMLTestCaseType }
function Get_Modifiers: WideString;
function Get_Subject: IXMLSubjectType;
function Get_Match: IXMLMatchTypeList;
function Get_Substitution: IXMLSubstitutionTypeList;
function Get_Replace: IXMLReplaceTypeList;
procedure Set_Modifiers(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLTestCaseTypeList }
TXMLTestCaseTypeList = class(TXMLNodeCollection, IXMLTestCaseTypeList)
protected
{ IXMLTestCaseTypeList }
function Add: IXMLTestCaseType;
function Insert(const Index: Integer): IXMLTestCaseType;
function Get_Item(Index: Integer): IXMLTestCaseType;
end;
{ TXMLSubjectType }
TXMLSubjectType = class(TXMLNodeCollection, IXMLSubjectType)
protected
{ IXMLSubjectType }
function Get_Substring(Index: Integer): IXMLSubstringType;
function Add: IXMLSubstringType;
function Insert(const Index: Integer): IXMLSubstringType;
public
procedure AfterConstruction; override;
end;
{ TXMLSubstringType }
TXMLSubstringType = class(TXMLNode, IXMLSubstringType)
protected
{ IXMLSubstringType }
function Get_RepeatCount: Integer;
function Get_FileName: WideString;
procedure Set_RepeatCount(Value: Integer);
procedure Set_FileName(Value: WideString);
end;
{ TXMLMatchType }
TXMLMatchType = class(TXMLNodeCollection, IXMLMatchType)
protected
{ IXMLMatchType }
function Get_Position: Integer;
function Get_Length: Integer;
function Get_CapturedSubstring(Index: Integer): WideString;
procedure Set_Position(Value: Integer);
procedure Set_Length(Value: Integer);
function Add(const CapturedSubstring: WideString): IXMLNode;
function Insert(const Index: Integer; const CapturedSubstring: WideString): IXMLNode;
public
procedure AfterConstruction; override;
end;
{ TXMLMatchTypeList }
TXMLMatchTypeList = class(TXMLNodeCollection, IXMLMatchTypeList)
protected
{ IXMLMatchTypeList }
function Add: IXMLMatchType;
function Insert(const Index: Integer): IXMLMatchType;
function Get_Item(Index: Integer): IXMLMatchType;
end;
{ TXMLSubstitutionType }
TXMLSubstitutionType = class(TXMLNode, IXMLSubstitutionType)
protected
{ IXMLSubstitutionType }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
end;
{ TXMLSubstitutionTypeList }
TXMLSubstitutionTypeList = class(TXMLNodeCollection, IXMLSubstitutionTypeList)
protected
{ IXMLSubstitutionTypeList }
function Add: IXMLSubstitutionType;
function Insert(const Index: Integer): IXMLSubstitutionType;
function Get_Item(Index: Integer): IXMLSubstitutionType;
end;
{ TXMLReplaceType }
TXMLReplaceType = class(TXMLNode, IXMLReplaceType)
protected
{ IXMLReplaceType }
function Get_Template: WideString;
function Get_Result: WideString;
procedure Set_Template(Value: WideString);
procedure Set_Result(Value: WideString);
end;
{ TXMLReplaceTypeList }
TXMLReplaceTypeList = class(TXMLNodeCollection, IXMLReplaceTypeList)
protected
{ IXMLReplaceTypeList }
function Add: IXMLReplaceType;
function Insert(const Index: Integer): IXMLReplaceType;
function Get_Item(Index: Integer): IXMLReplaceType;
end;
{ TXMLString_List }
TXMLString_List = class(TXMLNodeCollection, IXMLString_List)
protected
{ IXMLString_List }
function Add(const Value: WideString): IXMLNode;
function Insert(const Index: Integer; const Value: WideString): IXMLNode;
function Get_Item(Index: Integer): WideString;
end;
{ Global Functions }
function GetregularExpressions(Doc: IXMLDocument): IXMLRegularExpressionsType;
function LoadregularExpressions(const FileName: WideString): IXMLRegularExpressionsType;
function NewregularExpressions: IXMLRegularExpressionsType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetregularExpressions(Doc: IXMLDocument): IXMLRegularExpressionsType;
begin
Result := Doc.GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType;
end;
function LoadregularExpressions(const FileName: WideString): IXMLRegularExpressionsType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType;
end;
function NewregularExpressions: IXMLRegularExpressionsType;
begin
Result := NewXMLDocument.GetDocBinding('regularExpressions', TXMLRegularExpressionsType, TargetNamespace) as IXMLRegularExpressionsType;
end;
{ TXMLRegularExpressionsType }
procedure TXMLRegularExpressionsType.AfterConstruction;
begin
RegisterChildNode('regularExpression', TXMLRegularExpressionType);
ItemTag := 'regularExpression';
ItemInterface := IXMLRegularExpressionType;
inherited;
end;
function TXMLRegularExpressionsType.Get_RegularExpression(Index: Integer): IXMLRegularExpressionType;
begin
Result := List[Index] as IXMLRegularExpressionType;
end;
function TXMLRegularExpressionsType.Add: IXMLRegularExpressionType;
begin
Result := AddItem(-1) as IXMLRegularExpressionType;
end;
function TXMLRegularExpressionsType.Insert(const Index: Integer): IXMLRegularExpressionType;
begin
Result := AddItem(Index) as IXMLRegularExpressionType;
end;
{ TXMLRegularExpressionType }
procedure TXMLRegularExpressionType.AfterConstruction;
begin
RegisterChildNode('testCase', TXMLTestCaseType);
FCategory := CreateCollection(TXMLString_List, IXMLNode, 'category') as IXMLString_List;
FTestCase := CreateCollection(TXMLTestCaseTypeList, IXMLTestCaseType, 'testCase') as IXMLTestCaseTypeList;
inherited;
end;
function TXMLRegularExpressionType.Get_Id: Integer;
begin
Result := AttributeNodes['id'].NodeValue;
end;
procedure TXMLRegularExpressionType.Set_Id(Value: Integer);
begin
SetAttribute('id', Value);
end;
function TXMLRegularExpressionType.Get_Name: WideString;
begin
Result := AttributeNodes['name'].Text;
end;
procedure TXMLRegularExpressionType.Set_Name(Value: WideString);
begin
SetAttribute('name', Value);
end;
function TXMLRegularExpressionType.Get_Description: WideString;
begin
Result := ChildNodes['description'].Text;
end;
procedure TXMLRegularExpressionType.Set_Description(Value: WideString);
begin
ChildNodes['description'].NodeValue := Value;
end;
function TXMLRegularExpressionType.Get_Comment: WideString;
begin
Result := ChildNodes['comment'].Text;
end;
procedure TXMLRegularExpressionType.Set_Comment(Value: WideString);
begin
ChildNodes['comment'].NodeValue := Value;
end;
function TXMLRegularExpressionType.Get_Expression: WideString;
begin
Result := ChildNodes['expression'].Text;
end;
procedure TXMLRegularExpressionType.Set_Expression(Value: WideString);
begin
ChildNodes['expression'].NodeValue := Value;
end;
function TXMLRegularExpressionType.Get_Category: IXMLString_List;
begin
Result := FCategory;
end;
function TXMLRegularExpressionType.Get_TestCase: IXMLTestCaseTypeList;
begin
Result := FTestCase;
end;
{ TXMLTestCaseType }
procedure TXMLTestCaseType.AfterConstruction;
begin
RegisterChildNode('subject', TXMLSubjectType);
RegisterChildNode('match', TXMLMatchType);
RegisterChildNode('substitution', TXMLSubstitutionType);
RegisterChildNode('replace', TXMLReplaceType);
FMatch := CreateCollection(TXMLMatchTypeList, IXMLMatchType, 'match') as IXMLMatchTypeList;
FSubstitution := CreateCollection(TXMLSubstitutionTypeList, IXMLSubstitutionType, 'substitution') as IXMLSubstitutionTypeList;
FReplace := CreateCollection(TXMLReplaceTypeList, IXMLReplaceType, 'replace') as IXMLReplaceTypeList;
inherited;
end;
function TXMLTestCaseType.Get_Modifiers: WideString;
begin
Result := AttributeNodes['Modifiers'].Text;
end;
procedure TXMLTestCaseType.Set_Modifiers(Value: WideString);
begin
SetAttribute('Modifiers', Value);
end;
function TXMLTestCaseType.Get_Subject: IXMLSubjectType;
begin
Result := ChildNodes['subject'] as IXMLSubjectType;
end;
function TXMLTestCaseType.Get_Match: IXMLMatchTypeList;
begin
Result := FMatch;
end;
function TXMLTestCaseType.Get_Substitution: IXMLSubstitutionTypeList;
begin
Result := FSubstitution;
end;
function TXMLTestCaseType.Get_Replace: IXMLReplaceTypeList;
begin
Result := FReplace;
end;
{ TXMLTestCaseTypeList }
function TXMLTestCaseTypeList.Add: IXMLTestCaseType;
begin
Result := AddItem(-1) as IXMLTestCaseType;
end;
function TXMLTestCaseTypeList.Insert(const Index: Integer): IXMLTestCaseType;
begin
Result := AddItem(Index) as IXMLTestCaseType;
end;
function TXMLTestCaseTypeList.Get_Item(Index: Integer): IXMLTestCaseType;
begin
Result := List[Index] as IXMLTestCaseType;
end;
{ TXMLSubjectType }
procedure TXMLSubjectType.AfterConstruction;
begin
RegisterChildNode('substring', TXMLSubstringType);
ItemTag := 'substring';
ItemInterface := IXMLSubstringType;
inherited;
end;
function TXMLSubjectType.Get_Substring(Index: Integer): IXMLSubstringType;
begin
Result := List[Index] as IXMLSubstringType;
end;
function TXMLSubjectType.Add: IXMLSubstringType;
begin
Result := AddItem(-1) as IXMLSubstringType;
end;
function TXMLSubjectType.Insert(const Index: Integer): IXMLSubstringType;
begin
Result := AddItem(Index) as IXMLSubstringType;
end;
{ TXMLSubstringType }
function TXMLSubstringType.Get_RepeatCount: Integer;
begin
Result := AttributeNodes['repeatCount'].NodeValue;
end;
procedure TXMLSubstringType.Set_RepeatCount(Value: Integer);
begin
SetAttribute('repeatCount', Value);
end;
function TXMLSubstringType.Get_FileName: WideString;
begin
Result := AttributeNodes['fileName'].Text;
end;
procedure TXMLSubstringType.Set_FileName(Value: WideString);
begin
SetAttribute('fileName', Value);
end;
{ TXMLMatchType }
procedure TXMLMatchType.AfterConstruction;
begin
ItemTag := 'capturedSubstring';
ItemInterface := IXMLNode;
inherited;
end;
function TXMLMatchType.Get_Position: Integer;
begin
Result := AttributeNodes['position'].NodeValue;
end;
procedure TXMLMatchType.Set_Position(Value: Integer);
begin
SetAttribute('position', Value);
end;
function TXMLMatchType.Get_Length: Integer;
begin
Result := AttributeNodes['length'].NodeValue;
end;
procedure TXMLMatchType.Set_Length(Value: Integer);
begin
SetAttribute('length', Value);
end;
function TXMLMatchType.Get_CapturedSubstring(Index: Integer): WideString;
begin
Result := List[Index].Text;
end;
function TXMLMatchType.Add(const CapturedSubstring: WideString): IXMLNode;
begin
Result := AddItem(-1);
Result.NodeValue := CapturedSubstring;
end;
function TXMLMatchType.Insert(const Index: Integer; const CapturedSubstring: WideString): IXMLNode;
begin
Result := AddItem(Index);
Result.NodeValue := CapturedSubstring;
end;
{ TXMLMatchTypeList }
function TXMLMatchTypeList.Add: IXMLMatchType;
begin
Result := AddItem(-1) as IXMLMatchType;
end;
function TXMLMatchTypeList.Insert(const Index: Integer): IXMLMatchType;
begin
Result := AddItem(Index) as IXMLMatchType;
end;
function TXMLMatchTypeList.Get_Item(Index: Integer): IXMLMatchType;
begin
Result := List[Index] as IXMLMatchType;
end;
{ TXMLSubstitutionType }
function TXMLSubstitutionType.Get_Template: WideString;
begin
Result := ChildNodes['template'].Text;
end;
procedure TXMLSubstitutionType.Set_Template(Value: WideString);
begin
ChildNodes['template'].NodeValue := Value;
end;
function TXMLSubstitutionType.Get_Result: WideString;
begin
Result := ChildNodes['result'].Text;
end;
procedure TXMLSubstitutionType.Set_Result(Value: WideString);
begin
ChildNodes['result'].NodeValue := Value;
end;
{ TXMLSubstitutionTypeList }
function TXMLSubstitutionTypeList.Add: IXMLSubstitutionType;
begin
Result := AddItem(-1) as IXMLSubstitutionType;
end;
function TXMLSubstitutionTypeList.Insert(const Index: Integer): IXMLSubstitutionType;
begin
Result := AddItem(Index) as IXMLSubstitutionType;
end;
function TXMLSubstitutionTypeList.Get_Item(Index: Integer): IXMLSubstitutionType;
begin
Result := List[Index] as IXMLSubstitutionType;
end;
{ TXMLReplaceType }
function TXMLReplaceType.Get_Template: WideString;
begin
Result := ChildNodes['template'].Text;
end;
procedure TXMLReplaceType.Set_Template(Value: WideString);
begin
ChildNodes['template'].NodeValue := Value;
end;
function TXMLReplaceType.Get_Result: WideString;
begin
Result := ChildNodes['result'].Text;
end;
procedure TXMLReplaceType.Set_Result(Value: WideString);
begin
ChildNodes['result'].NodeValue := Value;
end;
{ TXMLReplaceTypeList }
function TXMLReplaceTypeList.Add: IXMLReplaceType;
begin
Result := AddItem(-1) as IXMLReplaceType;
end;
function TXMLReplaceTypeList.Insert(const Index: Integer): IXMLReplaceType;
begin
Result := AddItem(Index) as IXMLReplaceType;
end;
function TXMLReplaceTypeList.Get_Item(Index: Integer): IXMLReplaceType;
begin
Result := List[Index] as IXMLReplaceType;
end;
{ TXMLString_List }
function TXMLString_List.Add(const Value: WideString): IXMLNode;
begin
Result := AddItem(-1);
Result.NodeValue := Value;
end;
function TXMLString_List.Insert(const Index: Integer; const Value: WideString): IXMLNode;
begin
Result := AddItem(Index);
Result.NodeValue := Value;
end;
function TXMLString_List.Get_Item(Index: Integer): WideString;
begin
Result := List[Index].NodeValue;
end;
end. | 29.846154 | 149 | 0.763774 |
fc715b1e49777efc2a413ff819ab747b2edc8349 | 1,988 | pas | Pascal | JAbout.pas | HeikoStudt/GoldFind2 | 1c976d3164915d70d4e30bfab1ff30eed589f3ac | [
"MIT"
]
| null | null | null | JAbout.pas | HeikoStudt/GoldFind2 | 1c976d3164915d70d4e30bfab1ff30eed589f3ac | [
"MIT"
]
| null | null | null | JAbout.pas | HeikoStudt/GoldFind2 | 1c976d3164915d70d4e30bfab1ff30eed589f3ac | [
"MIT"
]
| null | null | null | unit JAbout;
interface
uses Windows, ExtCtrls, StdCtrls, Controls, Classes, Forms, Graphics;
type
TAboutBox = class(TForm)
Panel1: TPanel;
ProductName: TLabel;
Version: TLabel;
Copyright: TLabel;
OKButton: TButton;
Shape1: TShape;
ProgramIcon: TImage;
Memo1: TMemo;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AboutBox: TAboutBox = nil;
implementation
{$R *.DFM}
uses SysUtils;
function GetMyVersionInfo : String;
var vlen, dw: DWORD;
vstr : Pointer;
p : Pointer;
s : String;
begin
// Versionsnummer ermitteln
GetMyVersionInfo := '?.?';
vlen := GetFileVersionInfoSize( PChar(Application.ExeName), dw );
if vlen=0 then exit;
GetMem( vstr, vlen + 1 );
if GetFileVersionInfo( PChar(Application.ExeName), dw, vlen, vstr ) then begin
if VerQueryValue( vstr, '\', p, dw ) then begin
s := 'Vr. ' + inttostr( hiword(PVSFixedFileInfo(p)^.dwProductVersionMS) ) + '.'
+ inttostr( loword(PVSFixedFileInfo(p)^.dwProductVersionMS) );
s := s + ' (Build ' + inttostr( hiword(PVSFixedFileInfo(p)^.dwFileVersionMS) ) + '.'
+ inttostr( loword(PVSFixedFileInfo(p)^.dwFileVersionMS) ) + '.'
+ inttostr( hiword(PVSFixedFileInfo(p)^.dwFileVersionLS) ) + '.'
+ inttostr( loword(PVSFixedFileInfo(p)^.dwFileVersionLS) ) + ')';
GetMyVersionInfo := s;
end;
end;
FreeMem( vstr, vlen + 1 );
end;
procedure TAboutBox.FormCreate(Sender: TObject);
begin
Version.Caption := GetMyVersionInfo;
end;
procedure TAboutBox.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
AboutBox := nil;
end;
end.
| 26.506667 | 106 | 0.604125 |
47455abd59f49f519e8a8ed98ce4a228045f1602 | 32,286 | pas | Pascal | core/bs.window.linux.pas | PVV-BS/BlackShark | 34dc339146ba1596f4db813a0fe95d103a0a8bf3 | [
"Linux-OpenIB"
]
| 1 | 2022-02-11T06:49:00.000Z | 2022-02-11T06:49:00.000Z | core/bs.window.linux.pas | PVV-BS/BlackShark | 34dc339146ba1596f4db813a0fe95d103a0a8bf3 | [
"Linux-OpenIB"
]
| null | null | null | core/bs.window.linux.pas | PVV-BS/BlackShark | 34dc339146ba1596f4db813a0fe95d103a0a8bf3 | [
"Linux-OpenIB"
]
| null | null | null | {
-- Begin License block --
Copyright (C) 2019-2022 Pavlov V.V. (PVV)
"Black Shark Graphics Engine" for Delphi and Lazarus (named
"Library" in the file "License(LGPL).txt" included in this distribution).
The Library is free software.
Last revised June, 2022
This file is part of "Black Shark Graphics Engine", and may only be
used, modified, and distributed under the terms of the project license
"License(LGPL).txt". By continuing to use, modify, or distribute this
file you indicate that you have read the license and understand and
accept it fully.
"Black Shark Graphics Engine" 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.
-- End License block --
}
unit bs.window.linux;
{$I BlackSharkCfg.inc}
interface
uses
bs.collections
, bs.basetypes
, bs.events
, bs.gl.egl
, bs.linux
, bs.window
{$ifndef FPC} // for inlining in Delphi
, bs.config
, bs.gl.context
, bs.renderer
{$endif}
;
type
TEventHandler = procedure(AWindow: BSWindow; const AEvent: TXEvent) of object;
TListHandlers = TListVec<TEventHandler>;
{ TWindowContextLinux }
TWindowContextLinux = class(TWindowContext)
private
protected
function UpdateWmProperties: TXSizeHints;
function GetDC: EGLNativeDisplayType; override;
procedure SetDC(const AValue: EGLNativeDisplayType); override;
procedure SetHandle(const AValue: EGLNativeWindowType); override;
public
ExposeEvent: TXEvent;
constructor Create;
destructor Destroy; override;
function GetSizeHints: TXSizeHints;
end;
{ BSApplicationLinux }
BSApplicationLinux = class(BSApplicationSystem)
private
FHandlers: TListHandlers;
LastTimeMouseUp: uint32;
CurrentShiftState: TBSShiftState;
FTimeMouseDown: uint64;
FDisplayName: AnsiString;
FDisplay: PDisplay;
FDisplayHeightMM: int32;
FDisplayWidthMM: int32;
FColorDepth: int32;
FScreen: int32;
// Visual from X11
FVisual: PVisual;
FRootWindow: TWindow;
LeaderWindow: TWindow;
ClientLeaderAtom: TAtom;
//FWMProtocols: TAtom; // Atom for "WM_PROTOCOLS"
FWMDeleteWindow: TAtom; // Atom for "WM_DELETE_WINDOW"
FWMHints: TAtom; // Atom for "_MOTIF_WM_HINTS"
FWMTransientFor: TAtom; // Atom for "WM_TRANSIENT_FOR"
//FWMPaint: TAtom; // Atom for "WM_PAINT"
FWMModalState: TAtom; // Atom for "_NET_WM_STATE_MODAL"
FWMState: TAtom; // Atom for "_NET_WM_STATE"
FWMStateAbove: TAtom; // Atom for "_NET_WM_STATE_ABOVE"
FWMStateFullScreen: TAtom; // Atom for "_NET_WM_STATE_FULLSCREEN"
FWMActiveState: TAtom; // Atom for "NET_ACTIVE_WINDOW"
// For composing character events
ComposeBuffer: UTF8String;
ComposeStatus: TStatus;
InputMethod: PXIM;
InputContext: PXIC;
// XConnections list
FConnections: TListVec<cint>;
procedure ProcessEvent(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerKeyPress(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerKeyUp(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerPaint(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerClientMessage(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerMouseEnter(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerMouseMove(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerMouseLeave(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerMouseDown(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerMouseUp(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerConfigureNotify(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerResizeRequest(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerUnmapNotify(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerDestroyNotify(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerFocusIn(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerFocusOut(AWindow: BSWindow; const AEvent: TXEvent);
procedure HandlerUnknownEvent(AWindow: BSWindow; const AEvent: TXEvent);
procedure CreateHandle(AWindow: BSWindow);
procedure UpdateClientRect(AWindow: BSWindow);
function StartComposing(const Event: TXKeyEvent): TKeySym;
protected
procedure InitMonitors; override;
procedure InitHandlers; override;
function GetMousePointPos: TVec2i; override;
//procedure SetShowCursor(const Value: boolean); override;
procedure DoShow(AWindow: BSWindow; AInModalMode: boolean); override;
procedure DoClose(AWindow: BSWindow); override;
procedure DoInvalidate(AWindow: BSWindow); override;
procedure DoResize(AWindow: BSWindow; AWidth, AHeight: int32); override;
procedure DoSetPosition(AWindow: BSWindow; ALeft, ATop: int32); override;
procedure DoFullScreen(AWindow: BSWindow); override;
procedure DoActive(AWindow: BSWindow); override;
procedure DoShowCursor(AWindow: BSWindow); override;
public
constructor Create;
destructor Destroy; override;
function CreateWindow(AWindowClass: BSWindowClass; AOwner: TObject; AParent: BSWindow; APositionX, APositionY, AWidth, AHeight: int32): BSWindow; overload; override;
function CreateWindow(AWindow: BSWindow): BSWindow; overload; override;
procedure AddConnection(AConnection: cint);
procedure RemoveConnection(AConnection: cint);
procedure Update; override;
procedure UpdateWait; override;
property Display: PDisplay read FDisplay;
property RootWindow: TWindow read FRootWindow;
property Visual: PVisual read FVisual;
property DisplayName: AnsiString read FDisplayName write FDisplayName;
property DisplayWidthMM: int32 read FDisplayWidthMM;
property DisplayHeightMM: int32 read FDisplayHeightMM;
property ColorDepth: int32 read FColorDepth;
end;
implementation
uses
Classes
{$ifdef FPC}
, Math
{$endif}
, SysUtils
, Types
, bs.exceptions
, bs.strings
, bs.thread
;
var
ApplicationLinux: BSApplicationLinux;
function XStateToBSState(XKeyState: cuint): TShiftState;
begin
Result:= [];
if (XKeyState and bs.linux.ShiftMask) <> 0 then
Include(Result,ssShift);
if (XKeyState and bs.linux.ControlMask) <> 0 then
Include(Result,ssCtrl);
if (XKeyState and bs.linux.Mod1Mask) <> 0 then
Include(Result,ssAlt);
//if (XKeyState and bs.linux.Mod5Mask) <> 0 then
// Include(Result, ssAltGr);
end;
function ComparatorConnectons(const Item1, Item2: cint): int8;
begin
Result := Item2 - Item1;
end;
procedure BSConnectionWatchProc(display: PDisplay; client_data: TXPointer; fd: cint; opening: TBool; watch_data: PXPointer); cdecl;
begin
if opening <> 0 then
ApplicationLinux.AddConnection(fd)
else
ApplicationLinux.RemoveConnection(fd);
end;
{ BSApplicationLinux }
constructor BSApplicationLinux.Create;
var
classHint: PXClassHint;
begin
inherited;
ApplicationLinux := Self;
FConnections := TListVec<cint>.Create;
FHandlers := TListHandlers.Create;
if FDisplayName = '' then
FDisplayName := XDisplayName(nil);
FDisplay := XOpenDisplay(nil);
if not Assigned(FDisplay) then
raise EBlackShark.Create('[class constructor BSApplicationLinux.Create] XOpenDisplay failed');
// if we have a Display then we should have a Screen too
FScreen:= XDefaultScreen(FDisplay);
FRootWindow := XDefaultRootWindow(FDisplay);
// keyboard input
InputMethod := XOpenIM(FDisplay, nil, nil, nil);
if InputMethod <> nil then
InputContext := XCreateIC(InputMethod, @XNInputStyle[1], XIMPreeditNothing or XIMStatusNothing, 0);
// Initialize ScreenInfo
// Screen Metrics
DisplayWidth := XDisplayWidth(FDisplay, FScreen);
FDisplayWidthMM := XDisplayWidthMM(FDisplay,FScreen);
PixelsPerInchX := round(FDisplayWidth / (FDisplayWidthMM / 25.4));
DisplayHeight := XDisplayHeight(FDisplay, FScreen);
FDisplayHeightMM := XDisplayHeightMM(FDisplay,FScreen);
PixelsPerInchY:= round(FDisplayHeight / (FDisplayHeightMM / 25.4));
// Color Depth
FColorDepth := XDefaultDepth(FDisplay, FScreen);
// Screen Pixmap Format
// ScreenFormat is just a hint to tell controls to use the screen format
// because using the same format as the screen increases the speed of canvas copy operations
FVisual := XDefaultVisual(FDisplay,FScreen);
{ScreenFormat := clfARGB32; // Standard value with alpha blending support if we don't find a enum which matches the screen format
if (ScreenInfo.ColorDepth = 16) then
ScreenFormat:= clfRGB16_R5G6B5
else if (ScreenInfo.ColorDepth = 24) then
begin
if (FVisual.blue_mask = $FF) and
(FVisual.green_mask = $FF00) and
(FVisual.red_mask = $FF0000) then
ScreenFormat:= clfBGR24
else if (FVisual.red_mask = $FF) and
(FVisual.green_mask = $FF00) and
(FVisual.blue_mask = $FF0000) then
ScreenFormat:= clfRGB24;
end
else if (ScreenInfo.ColorDepth = 32) then begin
if (FVisual.blue_mask = $FF) and
(FVisual.green_mask = $FF00) and
(FVisual.red_mask = $FF0000) then
ScreenFormat:= clfBGRA32
else if (FVisual.red_mask = $FF) and
(FVisual.green_mask = $FF00) and
(FVisual.blue_mask = $FF0000) then
ScreenFormat:= clfRGBA32
else if (FVisual.red_mask = $FF00) and
(FVisual.green_mask = $FF0000) and
(FVisual.blue_mask = $FF000000) then
ScreenFormat:= clfARGB32;
end;}
LeaderWindow := XCreateSimpleWindow(FDisplay, FRootWindow, 0, 0, 1, 1, 0, 0, 0);
classHint := XAllocClassHint;
classHint^.res_name := 'BlackShark';
classHint^.res_class := 'BlackShark class';
XFree(classHint);
ClientLeaderAtom := XInternAtom(FDisplay, 'WM_CLIENT_LEADER', ord(False));
//FWMProtocols := XInternAtom(Display, 'WM_PROTOCOLS', Ord(False));
// We want to get a Client Message when the user tries to close this window
FWMState := XInternAtom(Display, '_NET_WM_STATE', Ord(True));
FWMModalState := XInternAtom(Display, '_NET_WM_STATE_MODAL', Ord(True));
FWMStateAbove := XInternAtom(Display, '_NET_WM_STATE_ABOVE', Ord(True));
FWMActiveState := XInternAtom(Display, '_NET_ACTIVE_WINDOW', Ord(false));
FWMStateFullScreen := XInternAtom(Display, '_NET_WM_STATE_FULLSCREEN', Ord(True));
FWMDeleteWindow := XInternAtom(Display, 'WM_DELETE_WINDOW', Ord(False));
FWMHints := XInternAtom(Display, '_MOTIF_WM_HINTS', Ord(False));
FWMTransientFor := XInternAtom(Display, 'WM_TRANSIENT_FOR', Ord(False));
//if FWMPaint = 0 then
// FWMPaint := XInternAtom(ApplicationLinux.Display, 'WM_PAINT', Ord(False));
// Add watches to the XConnection
XAddConnectionWatch(FDisplay, @BSConnectionWatchProc, nil);
end;
procedure BSApplicationLinux.CreateHandle(AWindow: BSWindow);
var
colorMap: TColormap;
sizeHints: TXSizeHints;
attr: TXSetWindowAttributes;
mask: longword;
windowHints: TXWMHints;
title: TXTextProperty;
str: UTF8String;
pstr: PAnsiChar;
begin
colorMap := XCreateColormap(Display, RootWindow, Visual, AllocNone);
FillChar(attr, SizeOf(attr), 0);
attr.Colormap := Colormap;
attr.Override_Redirect := 0;
attr.event_mask := KeyPressMask or KeyReleaseMask
or ButtonPressMask or ButtonReleaseMask
or EnterWindowMask or LeaveWindowMask
or ButtonMotionMask or PointerMotionMask
or ExposureMask
or FocusChangeMask
or StructureNotifyMask
// or PropertyChangeMask
;
sizeHints := TWindowContextLinux(AWindow.WindowContext).GetSizeHints;
mask := CWColormap;// or CWEventMask or CWOverrideRedirect or CWBorderPixel or CWBackPixel;
AWindow.Handle := XCreateWindow(
Display,
XDefaultRootWindow(Display), // parent
SizeHints.x, SizeHints.x, // position (top, left)
SizeHints.width, SizeHints.height, // default size (width, height)
0, // border size
ColorDepth, // CopyFromParent, depth
bs.linux.InputOutput, // class
XDefaultVisual(Display, XDefaultScreen(Display)), // visual
mask,
@attr);
if AWindow.Handle = 0 then
raise EBlackShark.Create('[class constructor BSApplicationLinux.Create] XOpenDisplay failed');
FillChar(windowHints, SizeOf(windowHints), 0);
windowHints.flags := StateHint OR WindowGroupHint OR InputHint;//WindowGroupHint; //InputHint or StateHint or
windowHints.input := 1;
windowHints.initial_state := bs.linux.NormalState;
windowHints.window_group := LeaderWindow;
XSetWMHints(FDisplay, AWindow.Handle, @windowHints);
XSelectInput(Display, AWindow.Handle, attr.event_mask);
XSetWMProtocols(Display, AWindow.Handle, @FWMDeleteWindow, 1);
str := UTF8String(WINDOW_CAPTION);
pstr := @str[1];
Xutf8TextListToTextProperty(Display, @pstr, 1, XUTF8StringStyle, @title);
XSetWMName(Display, AWindow.Handle, @title);
XSetWMIconName(Display, AWindow.Handle, @title);
XFree(title.value);
//XSetStandardProperties(ApplicationLinux.Display, FHandle, nil, nil, 0, nil, 0, @SizeHints);
//XSetWMNormalHints(ApplicationLinux.Display, FHandle, @SizeHints);
//WindowHints.flags := WindowGroupHint;
//WindowHints.window_group := CDWidgetSet.LeaderWindow;
//XSetWMHints(ApplicationLinux.Display, FHandle, @WindowHints);
XChangeProperty(FDisplay, AWindow.Handle, ClientLeaderAtom, 33, 32, PropModeReplace, @LeaderWindow, 1);
TWindowContextLinux(AWindow.WindowContext).UpdateWmProperties;
{
XSetClassHint(ApplicationLinux.Display, FHandle, @winClass); }
end;
function BSApplicationLinux.CreateWindow(AWindow: BSWindow): BSWindow;
begin
//TWindowContextLinux(AWindow.WindowContext).UpdateWmProperties;
Result := AWindow;
UpdateClientRect(Result);
end;
function BSApplicationLinux.CreateWindow(AWindowClass: BSWindowClass; AOwner: TObject; AParent: BSWindow; APositionX, APositionY, AWidth, AHeight: int32): BSWindow;
begin
Result := AWindowClass.Create(TWindowContextLinux.Create, AOwner, AParent, APositionX, APositionY, AWidth, AHeight);
Result.DC := Display;
CreateHandle(Result);
UpdateClientRect(Result);
AddWindow(Result);
end;
destructor BSApplicationLinux.Destroy;
begin
XDestroyIC(InputContext);
XCloseIM(InputMethod);
XCloseDisplay(FDisplay);
FConnections.Free;
FHandlers.Free;
inherited;
end;
procedure BSApplicationLinux.DoActive(AWindow: BSWindow);
var
event: TXClientMessageEvent;
begin
inherited;
if AWindow.IsActive then
begin
FillChar(event, SizeOf(TXClientMessageEvent), 0);
event._type := ClientMessage;
event.send_event := Ord(true);
event.window := AWindow.Handle;
event.display := Display;
event.message_type := FWMActiveState;
event.format := 32;
XSendEvent(Display, FRootWindow, Ord(false), SubstructureRedirectMask or SubstructureNotifyMask, @event);
end;
end;
procedure BSApplicationLinux.DoClose(AWindow: BSWindow);
begin
XUnmapWindow(Display, AWindow.Handle);
inherited;
end;
procedure BSApplicationLinux.DoFullScreen(AWindow: BSWindow);
var
event: TXClientMessageEvent;
sizeHint: TXSizeHints;
begin
inherited;
XSync(Display, Ord(true));
sizeHint := TWindowContextLinux(AWindow.WindowContext).UpdateWmProperties;
if AWindow.FullScreen then
begin
AWindow.BegingFromOSChange;
try
AWindow.SetPosition(0, 0);
AWindow.Resize(sizeHint.width, sizeHint.height);
finally
AWindow.EndFromOSChange;
end;
FillChar(event, SizeOf(TXClientMessageEvent), 0);
event._type := ClientMessage;
event.send_event := Ord(true);
event.window := AWindow.Handle;
event.display := Display;
event.message_type := FWMState;
event.format := 32;
event.data.l[0] := _NET_WM_STATE_ADD;
event.data.l[1] := FWMStateFullScreen;
XSendEvent(Display, FRootWindow, Ord(false), SubstructureRedirectMask or SubstructureNotifyMask, @event );
end else
begin
end;
UpdateClientRect(AWindow);
end;
procedure BSApplicationLinux.DoInvalidate(AWindow: BSWindow);
begin
inherited;
end;
procedure BSApplicationLinux.DoResize(AWindow: BSWindow; AWidth, AHeight: int32);
var
mask: Cardinal;
changes: TXWindowChanges;
begin
mask := 0;
if AWidth <> AWindow.Width then
mask := CWWidth;
if AHeight <> AWindow.Height then
mask := mask or CWHeight;
inherited;
if mask <> 0 then
begin
FillChar(Changes, SizeOf(Changes), 0);
Changes.Width := AWidth;
Changes.Height := AHeight;
XConfigureWindow(FDisplay, AWindow.Handle, mask, @Changes);
end;
UpdateClientRect(AWindow);
end;
procedure BSApplicationLinux.DoShowCursor(AWindow: BSWindow);
begin
end;
procedure BSApplicationLinux.DoSetPosition(AWindow: BSWindow; ALeft, ATop: int32);
var
Supplied: NativeInt;
SizeHints: TXSizeHints;
begin
inherited;
XGetWMNormalHints(FDisplay, AWindow.Handle, @SizeHints, @Supplied);
SizeHints.flags := SizeHints.flags or PPosition;
SizeHints.x := ALeft;
SizeHints.y := ATop;
XSetWMNormalHints(FDisplay, AWindow.Handle, @SizeHints);
XMoveWindow(FDisplay, AWindow.Handle, ALeft, ATop);
end;
procedure BSApplicationLinux.DoShow(AWindow: BSWindow; AInModalMode: boolean);
var
event: TXClientMessageEvent;
begin
inherited;
XMapRaised(Display, AWindow.Handle);
if Assigned(AWindow.Parent) then
begin
if AInModalMode then
begin
XSetTransientForHint(Display, AWindow.Handle, AWindow.Parent.Handle);
FillChar(event, sizeOf(event), 0);
event._type := bs.linux.ClientMessage;
event.message_type := FWMState;
event.window := AWindow.Handle;
event.display := Display;
event.format := 32;
event.data.l[0] := _NET_WM_STATE_ADD;
event.data.l[1] := FWMModalState;
XSendEvent(Display, FRootWindow, Ord(false), SubstructureRedirectMask or SubstructureNotifyMask, @event);
XFlush(Display);
end;
end;
end;
function BSApplicationLinux.GetMousePointPos: TVec2i;
var
root_return: TWindow;
child_return: TWindow;
root_x_return: Integer;
root_y_return: Integer;
mask_return: LongWord;
begin
XQueryPointer(Display, 0, @root_return, @child_return, @root_x_return, @root_y_return, @Result.x, @Result.y, @mask_return);
end;
procedure BSApplicationLinux.HandlerClientMessage(AWindow: BSWindow; const AEvent: TXEvent);
var
w: BSWindow;
i: int32;
begin
if TAtom(AEvent.xclient.Data.l[0]) = FWMDeleteWindow then
begin
// checks whether contains visible child in modal mode
// if it is then ban close
for i := 0 to AWindow.Children.Count - 1 do
begin
w := AWindow.Children.Items[i];
if w.WindowState = wsShownModal then
exit;
end;
AWindow.BegingFromOSChange;
try
AWindow.Close;
XUnmapWindow(Display, AWindow.Handle);
finally
AWindow.EndFromOSChange;
end;
end;
end;
procedure BSApplicationLinux.HandlerConfigureNotify(AWindow: BSWindow; const AEvent: TXEvent);
var
event: TXConfigureEvent;
modified: boolean;
begin
modified := false;
event := AEvent.xconfigure;
while XCheckTypedWindowEvent(Display, AEvent.xconfigure.window, bs.linux.NotifyPointer, @event) do;
if (event.x <> AWindow.Left) or (event.y <> AWindow.Top) then
begin
AWindow.BegingFromOSChange;
try
modified := true;
AWindow.SetPosition(event.x, event.y);
finally
AWindow.EndFromOSChange;
end;
end;
if (event.width <> AWindow.Width) or (event.height <> AWindow.Height) then
begin
AWindow.BegingFromOSChange;
try
modified := true;
AWindow.ClientRect := Rect(0, 0, event.width, event.height);
AWindow.Resize(event.width, event.height);
finally
AWindow.EndFromOSChange;
end;
end;
if modified then
TWindowContextLinux(AWindow.WindowContext).UpdateWmProperties;
end;
procedure BSApplicationLinux.HandlerDestroyNotify(AWindow: BSWindow; const AEvent: TXEvent);
begin
XDestroyWindow(Display, AWindow.Handle);
XSync(Display, Ord(FALSE));
AWindow.Handle := 0;
end;
procedure BSApplicationLinux.HandlerFocusIn(AWindow: BSWindow; const AEvent: TXEvent);
begin
AWindow.BegingFromOSChange;
try
AWindow.IsActive := true;
finally
AWindow.EndFromOSChange;
end;
end;
procedure BSApplicationLinux.HandlerFocusOut(AWindow: BSWindow; const AEvent: TXEvent);
begin
AWindow.BegingFromOSChange;
try
AWindow.IsActive := false;
finally
AWindow.EndFromOSChange;
end;
end;
procedure BSApplicationLinux.HandlerUnknownEvent(AWindow: BSWindow; const AEvent: TXEvent);
begin
end;
function BSApplicationLinux.StartComposing(const Event: TXKeyEvent): TKeySym;
var
len: int32;
begin
SetLength(ComposeBuffer, 64);
// Xutf8LookupString returns the size of FComposeBuffer in bytes.
len := Xutf8LookupString(InputContext, @Event, @ComposeBuffer[1],
Length(ComposeBuffer), @Result, @ComposeStatus);
SetLength(ComposeBuffer, len);
// if overflow occured, then previous SetLength() would have fixed the buffer
// size, so run Xutf8LookupString again to read correct value.
if ComposeStatus = XBufferOverflow then
Xutf8LookupString(InputContext, @Event, @ComposeBuffer[1],
Length(ComposeBuffer), @Result, @ComposeStatus);
end;
procedure BSApplicationLinux.HandlerKeyPress(AWindow: BSWindow; const AEvent: TXEvent);
var
key: word;
ss: TBSShiftState;
keySym: TKeySym;
endComposing: boolean;
i: Integer;
s: WideString;
begin
//xkey := XLookupKeysym(@AEvent.xkey, 0);
keySym := StartComposing(AEvent.xkey);
ss := XStateToBSState(AEvent.xkey.state);
key := XKeyToBSKey(keySym, AEvent.xkey.keycode);
AWindow.KeyDown(key, ss);
// EndComposing embedded here
endComposing := (ComposeStatus <> XLookupNone) and ((AEvent.xkey.state and (ControlMask or Mod1Mask)) = 0);
if endComposing then
begin
{$ifdef FPC}
s := UTF8ToString(ComposeBuffer);
{$else}
s := UTF8ToWideString(ComposeBuffer);
{$endif}
for i := 1 to length(s) do
AWindow.KeyPress(s[i], ss);
end;
end;
procedure BSApplicationLinux.HandlerKeyUp(AWindow: BSWindow; const AEvent: TXEvent);
var
xkey: TKeySym;
key: word;
ss: TBSShiftState;
begin
xkey := XLookupKeysym(@AEvent.xkey, 0);
key := XKeyToBSKey(xkey, AEvent.xkey.keycode);
ss := XStateToBSState(AEvent.xkey.state);
AWindow.KeyUp(key, ss);
end;
procedure BSApplicationLinux.HandlerMouseDown(AWindow: BSWindow; const AEvent: TXEvent);
var
ss: TBSShiftState;
mb: TBSMouseButton;
begin
FTimeMouseDown := TBTimer.CurrentTime.Counter;
ss := XStateToBSState(AEvent.xbutton.state);
case AEvent.xbutton.button of
2: begin
mb := TBSMouseButton.mbBsMiddle;
CurrentShiftState := CurrentShiftState + [ssMiddle];
end;
3: begin
mb := TBSMouseButton.mbBsRight;
CurrentShiftState := CurrentShiftState + [ssRight];
end else
begin
mb := TBSMouseButton.mbBsLeft;
CurrentShiftState := CurrentShiftState + [ssLeft];
end;
end;
ss := ss + CurrentShiftState;
AWindow.MouseDown(mb, AEvent.xbutton.x, AEvent.xbutton.y, ss);
end;
procedure BSApplicationLinux.HandlerMouseEnter(AWindow: BSWindow; const AEvent: TXEvent);
begin
AWindow.MouseEnter(AEvent.xmotion.x, AEvent.xmotion.y);
end;
procedure BSApplicationLinux.HandlerMouseLeave(AWindow: BSWindow; const AEvent: TXEvent);
begin
AWindow.MouseLeave;
end;
procedure BSApplicationLinux.HandlerMouseMove(AWindow: BSWindow; const AEvent: TXEvent);
var
event: TXEvent;
ss: TBSShiftState;
begin
while XCheckTypedWindowEvent(Display, AEvent.xmotion.window, bs.linux.MotionNotify, @event) do;
ss := XStateToBSState(AEvent.xmotion.state) + CurrentShiftState;
AWindow.MouseMove(AEvent.xmotion.x, AEvent.xmotion.y, ss);
end;
procedure BSApplicationLinux.HandlerMouseUp(AWindow: BSWindow; const AEvent: TXEvent);
var
ss: TBSShiftState;
mb: TBSMouseButton;
begin
ss := XStateToBSState(AEvent.xbutton.state);
case AEvent.xbutton.button of
2: begin
mb := TBSMouseButton.mbBsMiddle;
CurrentShiftState := CurrentShiftState - [ssMiddle];
end;
3: begin
mb := TBSMouseButton.mbBsRight;
CurrentShiftState := CurrentShiftState - [ssRight];
end else
begin
mb := TBSMouseButton.mbBsLeft;
CurrentShiftState := CurrentShiftState - [ssLeft];
end;
end;
ss := ss + CurrentShiftState;
if AEvent.xbutton.button = 4 then
AWindow.MouseWheel(4*(TBTimer.CurrentTime.Counter - FTimeMouseDown), AEvent.xbutton.x, AEvent.xbutton.y, ss)
else
if AEvent.xbutton.button = 5 then
AWindow.MouseWheel(-4*Integer((TBTimer.CurrentTime.Counter - FTimeMouseDown)), AEvent.xbutton.x, AEvent.xbutton.y, ss)
else
begin
AWindow.MouseUp(mb, AEvent.xbutton.x, AEvent.xbutton.y, ss);
if TBTimer.CurrentTime.Low - LastTimeMouseUp < MOUSE_DOUBLE_CLICK_DELTA then
AWindow.MouseDblClick(AEvent.xbutton.x, AEvent.xbutton.y);
end;
LastTimeMouseUp := TBTimer.CurrentTime.Low;
end;
procedure BSApplicationLinux.HandlerPaint(AWindow: BSWindow; const AEvent: TXEvent);
var
event: TXEvent;
begin
// This repeat really helps speeding up when maximized for example
while XCheckTypedWindowEvent(Display, AEvent.xexpose.window, bs.linux.Expose, @event) do;
AWindow.Draw;
end;
procedure BSApplicationLinux.HandlerResizeRequest(AWindow: BSWindow; const AEvent: TXEvent);
var
changed: boolean;
begin
changed := (AWindow.Width <> AEvent.xresizerequest.width) or (AWindow.Height <> AEvent.xresizerequest.height);
if changed then
begin
//???
//AWindow.Resize(AEvent.xresizerequest.width, AEvent.xresizerequest.height);
//TWindowContextLinux(AWindow.WindowContext).UpdateWmProperties;
end;
end;
procedure BSApplicationLinux.HandlerUnmapNotify(AWindow: BSWindow; const AEvent: TXEvent);
begin
{AWindow.BegingFromOSChange;
try
AWindow.Close;
finally
AWindow.EndFromOSChange;
end; }
end;
procedure BSApplicationLinux.InitHandlers;
begin
FHandlers.Items[bs.linux.KeyPress] := HandlerKeyPress;
FHandlers.Items[bs.linux.KeyRelease] := HandlerKeyUp;
FHandlers.Items[bs.linux.Expose] := HandlerPaint;
FHandlers.Items[bs.linux.ClientMessage] := HandlerClientMessage;
FHandlers.Items[bs.linux.EnterNotify] := HandlerMouseEnter;
FHandlers.Items[bs.linux.MotionNotify] := HandlerMouseMove;
FHandlers.Items[bs.linux.LeaveNotify] := HandlerMouseLeave;
FHandlers.Items[bs.linux.ButtonPress] := HandlerMouseDown;
FHandlers.Items[bs.linux.ButtonRelease] := HandlerMouseUp;
FHandlers.Items[bs.linux.ConfigureNotify] := HandlerConfigureNotify;
FHandlers.Items[bs.linux.ResizeRequest] := HandlerResizeRequest;
FHandlers.Items[bs.linux.UnmapNotify] := HandlerUnmapNotify;
FHandlers.Items[bs.linux.DestroyNotify] := HandlerDestroyNotify;
FHandlers.Items[bs.linux.FocusIn] := HandlerFocusIn;
FHandlers.Items[bs.linux.FocusOut] := HandlerFocusOut;
end;
procedure BSApplicationLinux.InitMonitors;
begin
inherited;
end;
procedure BSApplicationLinux.ProcessEvent(AWindow: BSWindow; const AEvent: TXEvent);
var
handler: TEventHandler;
begin
handler := FHandlers.Items[AEvent._type];
if Assigned(handler) then
handler(AWindow, AEvent)
else
HandlerUnknownEvent(AWindow, AEvent);
{
bs.linux.FocusIn:
begin
end;
bs.linux.FocusOut:
begin
end;
bs.linux.ReparentNotify:
begin
end;
}
end;
procedure BSApplicationLinux.Update;
var
event: TXEvent;
window: BSWindow;
i: int32;
begin
if FWindows.Count = 0 then
exit;
if XPending(Display) > 0 then
begin
XNextEvent(Display, @event);
if FWindows.Count > 1 then
begin
if FWindows.Find(event.xany.window, window) then
begin
ProcessEvent(window, event);
for i := 0 to window.Children.Count - 1 do
window.Children.Items[i].Draw;
end;
end else
begin
ProcessEvent(FMainWindow, event);
end;
end else
begin
// send redraw event
XSendEvent(Display, FMainWindow.Handle, ord(False), bs.linux.ExposureMask, @TWindowContextLinux(FMainWindow.WindowContext).ExposeEvent);
for i := 0 to FMainWindow.Children.Count - 1 do
FMainWindow.Children.Items[i].Draw;
end;
inherited;
end;
procedure BSApplicationLinux.UpdateClientRect(AWindow: BSWindow);
begin
AWindow.ClientRect := Rect(0, 0, AWindow.Width, AWindow.Height);
end;
procedure BSApplicationLinux.UpdateWait;
var
event: TXEvent;
window: BSWindow;
i: int32;
begin
if FWindows.Count = 0 then
exit;
XPeekEvent(Display, @event);
XNextEvent(Display, @event);
if FWindows.Count > 1 then
begin
if FWindows.Find(event.xany.window, window) then
ProcessEvent(window, event);
end else
ProcessEvent(FMainWindow, event);
FMainWindow.Draw;
for i := 0 to FMainWindow.Children.Count - 1 do
FMainWindow.Children.Items[i].Draw;
inherited;
end;
procedure BSApplicationLinux.AddConnection(AConnection: cint);
begin
FConnections.Add(AConnection);
end;
procedure BSApplicationLinux.RemoveConnection(AConnection: cint);
begin
FConnections.Remove(AConnection);
end;
{ TWindowContextLinux }
constructor TWindowContextLinux.Create;
begin
ExposeEvent._type := bs.linux.Expose;
end;
destructor TWindowContextLinux.Destroy;
begin
if Window.Handle > 0 then
begin
XDestroyWindow(ApplicationLinux.Display, Window.Handle);
XSync(ApplicationLinux.Display, Ord(FALSE));
end;
inherited;
end;
function TWindowContextLinux.GetDC: EGLNativeDisplayType;
begin
Result := ApplicationLinux.Display;
end;
function TWindowContextLinux.GetSizeHints: TXSizeHints;
begin
FillChar(Result, SizeOf(Result), 0);
Result.max_width := ApplicationLinux.DisplayWidth;
Result.max_height := ApplicationLinux.DisplayHeight;
Result.min_width := 10;
Result.min_height := 10;
if Window.FullScreen or ((Window.Width >= ApplicationLinux.DisplayWidth) and (Window.Height >= ApplicationLinux.DisplayHeight)) then
begin
Result.flags := bs.linux.PBaseSize or bs.linux.PWinGravity;
Result.x := 0;
Result.y := 0;
Result.width := ApplicationLinux.DisplayWidth;
Result.height := ApplicationLinux.DisplayHeight;
end else
begin
Result.flags := bs.linux.PPosition or bs.linux.PSize or bs.linux.PMinSize or bs.linux.PMaxSize;
Result.x := Window.Left;
Result.y := Window.Top;
Result.width := Window.Width;
Result.height := Window.Height;
end;
end;
procedure TWindowContextLinux.SetDC(const AValue: EGLNativeDisplayType);
begin
inherited;
ExposeEvent.xexpose.display := AValue;
end;
procedure TWindowContextLinux.SetHandle(const AValue: EGLNativeWindowType);
begin
inherited;
ExposeEvent.xexpose.window := AValue;
end;
function TWindowContextLinux.UpdateWmProperties: TXSizeHints;
begin
//XGetWindowProperty(ApplicationLinux.Display, FHandle,
// ApplicationLinux.FWMHints, 0, 5, Ord(False), bs.linux.AnyPropertyType, @PropType,
// @PropFormat, @PropItemCount, @PropBytesAfter, @Hints);
if not Window.IsVisible then
exit;
Result := GetSizeHints;
XSetWMNormalHints(ApplicationLinux.Display, Handle, @Result);
//winClass.res_name := 'BlackShark';
///winClass.res_class := 'BlackShark class';
//XSetWMProperties(ApplicationLinux.Display, Handle, nil, nil, nil, 0, @SizeHints, @WindowHints, nil);//@winClass
end;
end.
| 31.808867 | 170 | 0.710927 |
fce2571dded2c76855fc7e8d96f7f05a8d71db92 | 1,985 | pas | Pascal | src/CanRxSaveForm.pas | kuba2k2/CANcool | 3b3d72418b78c4124e71ddbc26002896d7a2931f | [
"MIT"
]
| 38 | 2016-03-25T19:04:21.000Z | 2022-03-02T10:57:13.000Z | src/CanRxSaveForm.pas | kuba2k2/CANcool | 3b3d72418b78c4124e71ddbc26002896d7a2931f | [
"MIT"
]
| null | null | null | src/CanRxSaveForm.pas | kuba2k2/CANcool | 3b3d72418b78c4124e71ddbc26002896d7a2931f | [
"MIT"
]
| 12 | 2016-08-29T22:18:33.000Z | 2021-11-07T22:43:14.000Z | {***************************************************************************
CanRxSaveForm.pas - description
-------------------
begin : 10.01.2016
copyright : (C) 2016 by MHS-Elektronik GmbH & Co. KG, Germany
http://www.mhs-elektronik.de
autho : Klaus Demlehner, klaus@mhs-elektronik.de
***************************************************************************}
{***************************************************************************
* *
* This program is free software, you can redistribute it and/or modify *
* it under the terms of the MIT License <LICENSE.TXT or *
* http://opensource.org/licenses/MIT> *
* *
***************************************************************************}
unit CanRxSaveForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TTraceSaveProgress = class(TForm)
ProgressBar: TProgressBar;
CancelButton: TButton;
MessageLabel: TLabel;
procedure CancelButtonClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
NewPosition: Integer;
procedure SetPosition;
end;
var
TraceSaveProgress: TTraceSaveProgress;
implementation
{$R *.dfm}
uses
CanRx;
procedure TTraceSaveProgress.SetPosition;
begin
ProgressBar.Position := NewPosition;
end;
procedure TTraceSaveProgress.CancelButtonClick(Sender: TObject);
var rx_can_list: TRxCanList;
begin
rx_can_list := TRxCanList(Owner);
if rx_can_list.SaveThread <> nil then
rx_can_list.SaveThread.Terminate;
end;
end.
| 29.626866 | 91 | 0.466499 |
c39dade2ad2a0c263f0f7a5cd8f877d00ddf538b | 2,045 | pas | Pascal | Source/Range.pas | remobjects/RTL2 | 261d80146a018ef24b07822b647b80c7cdcb673b | [
"BSD-2-Clause"
]
| 19 | 2017-03-30T19:54:37.000Z | 2021-09-28T05:31:48.000Z | Source/Range.pas | remobjects/RTL2 | 261d80146a018ef24b07822b647b80c7cdcb673b | [
"BSD-2-Clause"
]
| 3 | 2017-05-26T08:36:20.000Z | 2017-08-11T15:50:13.000Z | Source/Range.pas | remobjects/RTL2 | 261d80146a018ef24b07822b647b80c7cdcb673b | [
"BSD-2-Clause"
]
| 14 | 2017-01-24T04:10:46.000Z | 2021-11-11T00:47:55.000Z | namespace RemObjects.Elements.RTL;
interface
type
Range = public record {$IF TOFFEE}mapped to Foundation.NSRange{$ENDIF}
public
constructor(aLocation, aLength: Integer);
{$IFNDEF TOFFEE}
property Location: Integer;
property Length: Integer;
{$ELSE}
property Location: Integer read mapped.location write mapped.location;
property Length: Integer read mapped.length write mapped.length;
{$ENDIF}
property &End: Integer read Location+Length;
method OverlappingSubRange(aRange: Range): nullable Range;
begin
if (aRange.Location ≥ &End) then
exit nil;
if (aRange.End ≤ Location) then
exit nil;
var lNewStart := Math.Max(&Location, aRange.Location);
var lNewEnd := Math.Min(&End, aRange.End);
result := new Range(lNewStart, lNewEnd-lNewStart);
end;
end;
RangeHelper = public static class
public
method Validate(aRange: Range; BufferSize: Integer);
end;
implementation
{ Range }
constructor Range(aLocation, aLength: Integer);
begin
{$IF TOFFEE}
result := NSMakeRange(aLocation, aLength);
{$ELSE}
Location := aLocation;
Length := aLength;
{$ENDIF}
end;
{ RangeHelper }
class method RangeHelper.Validate(aRange: Range; BufferSize: Integer);
begin
if aRange.Location < 0 then
raise new ArgumentOutOfRangeException(RTLErrorMessages.NEGATIVE_VALUE_ERROR, "Location");
if aRange.Length < 0 then
raise new ArgumentOutOfRangeException(RTLErrorMessages.NEGATIVE_VALUE_ERROR, "Length");
if aRange.Location >= BufferSize then
raise new ArgumentOutOfRangeException(RTLErrorMessages.ARG_OUT_OF_RANGE_ERROR, "Location");
if aRange.Length > BufferSize then
raise new ArgumentOutOfRangeException(RTLErrorMessages.ARG_OUT_OF_RANGE_ERROR, "Length");
if aRange.Location + aRange.Length > BufferSize then
raise new ArgumentOutOfRangeException(RTLErrorMessages.OUT_OF_RANGE_ERROR, aRange.Location, aRange.Length, BufferSize);
end;
end. | 29.214286 | 124 | 0.708068 |
fc20d6f96264698fbaf4613b019e3dd27e424c2e | 22,229 | dfm | Pascal | source/uCadUsuarios.dfm | roneysousa/infocartao_firebird | 98c9c9477869d6e6b0a46ed74ec8e01f3dedf62b | [
"MIT"
]
| null | null | null | source/uCadUsuarios.dfm | roneysousa/infocartao_firebird | 98c9c9477869d6e6b0a46ed74ec8e01f3dedf62b | [
"MIT"
]
| null | null | null | source/uCadUsuarios.dfm | roneysousa/infocartao_firebird | 98c9c9477869d6e6b0a46ed74ec8e01f3dedf62b | [
"MIT"
]
| 1 | 2021-03-10T09:31:46.000Z | 2021-03-10T09:31:46.000Z | object frmCadUsuarios: TfrmCadUsuarios
Left = 192
Top = 114
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
Caption = 'Usu'#225'rios'
ClientHeight = 307
ClientWidth = 500
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnActivate = FormActivate
OnClose = FormClose
PixelsPerInch = 96
TextHeight = 13
object Panel2: TPanel
Left = 0
Top = 0
Width = 500
Height = 32
Align = alTop
Color = clBlue
TabOrder = 0
object DBText1: TDBText
Left = 10
Top = 4
Width = 91
Height = 24
AutoSize = True
DataField = 'SEN_NMUSUA'
DataSource = dsUsuario
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -19
Font.Name = 'MS Sans Serif'
Font.Style = [fsBold, fsItalic]
ParentFont = False
Transparent = True
end
end
object Panel1: TPanel
Left = 0
Top = 32
Width = 500
Height = 234
Align = alClient
TabOrder = 1
object Label1: TLabel
Left = 16
Top = 16
Width = 36
Height = 13
Caption = 'Codigo:'
FocusControl = DBEdit1
Transparent = True
end
object Label2: TLabel
Left = 16
Top = 56
Width = 31
Height = 13
Caption = 'Nome:'
FocusControl = edtNome
Transparent = True
end
object Label3: TLabel
Left = 16
Top = 96
Width = 31
Height = 13
Caption = 'Cargo:'
FocusControl = edtCargo
Transparent = True
end
object Label4: TLabel
Left = 16
Top = 136
Width = 34
Height = 13
Caption = 'Senha:'
FocusControl = edtSenha
Transparent = True
end
object DBEdit1: TDBEdit
Left = 16
Top = 32
Width = 65
Height = 21
TabStop = False
Color = clSilver
DataField = 'SEN_CDUSUA'
DataSource = dsUsuario
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = [fsBold]
ParentFont = False
ReadOnly = True
TabOrder = 0
end
object edtNome: TDBEdit
Left = 16
Top = 72
Width = 400
Height = 21
CharCase = ecUpperCase
DataField = 'SEN_NMUSUA'
DataSource = dsUsuario
TabOrder = 1
end
object edtCargo: TDBEdit
Left = 16
Top = 112
Width = 400
Height = 21
CharCase = ecUpperCase
DataField = 'SEN_NMCARG'
DataSource = dsUsuario
TabOrder = 2
end
object edtSenha: TDBEdit
Left = 16
Top = 152
Width = 82
Height = 21
DataField = 'SEN_SNATUA'
DataSource = dsUsuario
MaxLength = 6
PasswordChar = '*'
TabOrder = 3
end
end
object Panel3: TPanel
Left = 0
Top = 266
Width = 500
Height = 41
Align = alBottom
TabOrder = 2
object btAdicionar: TBitBtn
Left = 5
Top = 8
Width = 75
Height = 25
Caption = 'Adicionar'
TabOrder = 0
OnClick = btAdicionarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000E30E0000E30E0000000100000001000031319C003131
A5003131AD003131B5003131BD003131C6003131CE003131D6003131DE003131
E7003131EF003131F700FF00FF003131FF003139FF003939FF003942FF00424A
FF004A4AFF005252FF006363FF006B6BFF006B73FF007B84FF00848CFF009C9C
FF00C6CEFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000C1B1B1B1B1B
1B1B1B1B1B1B1B1B1B0C1B16030404040505040403030201141B1B05080A0B0B
0A0B0A0A0A090805001B1B070A0E0E0E0E0E0E0E0E0E0906021B1B090E0E0E0E
0E1B180E0E0E0B08031B1B0A0E0E0E0E0E1B180E0E0E0E09041B1B0E0E0E0E0E
0E1B180E0E0E0E0A051B1B0E0E181818181B181818180B0A061B1B0E0E1B1B1B
1B1B1B1B1B1B0A0A061B1B0E10100E0E0E1B180E0E0B0A0A061B1B0E1313100E
0E1B180E0E0B0A0A061B1B1015141110101B180E0E0E0B0B061B1B1318151312
111B180E0E0E0E0B061B1B1419181514131211100E0E0E0B041B1B1A1412100E
0E0E0E0E0E0E0B08171B0C1B1B1B1B1B1B1B1B1B1B1B1B1B1B0C}
end
object btEditar: TBitBtn
Left = 83
Top = 8
Width = 75
Height = 25
Caption = 'Editar'
TabOrder = 1
OnClick = btEditarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000E30E0000E30E0000000100000001000031319C003131
A5003131AD003131B5003131BD003131C6003131CE003131D6003131DE003131
E7003131EF003131F700FF00FF003131FF003139FF003939FF003942FF00424A
FF004A4AFF005252FF006363FF006B6BFF006B73FF007B84FF00848CFF009C9C
FF00C6CEFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000C1B1B1B1B1B
1B1B1B1B1B1B1B1B1B0C1B16030404040505040403030201141B1B05080A0B0B
0A0B0A0A0A090805001B1B070A0E0E0E0E0E0E0E0E0E0906021B1B090E0E0E0E
0E0E0E0E0E0E0B08031B1B0A0E1818181818181818181809041B1B0E0E181B1B
1B1B1B1B1B1B180A051B1B0E0E0E181B1B1B1B1B1B180B0A061B1B0E0E0E0E18
1B1B1B1B180B0A0A061B1B0E10100E0E181B1B180E0B0A0A061B1B0E1313100E
0E18180E0E0B0A0A061B1B1015141110100E0E0E0E0E0B0B061B1B1318151312
11110E0E0E0E0E0B061B1B1419181514131211100E0E0E0B041B1B1A1412100E
0E0E0E0E0E0E0B08171B0C1B1B1B1B1B1B1B1B1B1B1B1B1B1B0C}
end
object btExcluir: TBitBtn
Left = 161
Top = 8
Width = 75
Height = 25
Caption = 'Excluir'
TabOrder = 2
OnClick = btExcluirClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000E30E0000E30E0000000100000001000031319C003131
A5003131AD003131B5003131BD003131C6003131CE003131D6003131DE003131
E7003131EF003131F700FF00FF003131FF003139FF003939FF003942FF00424A
FF004A4AFF005252FF006363FF006B6BFF006B73FF007B84FF00848CFF009C9C
FF00C6CEFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF000C1B1B1B1B1B
1B1B1B1B1B1B1B1B1B0C1B16030404040505040403030201141B1B05080A0B0B
0A0B0A0A0A090805001B1B070A0E0E0E0E0E0E0E0E0E0906021B1B090E0E0E0E
0E0E0E0E0E0E0B08031B1B0A0E0E0E0E0E0E0E0E0E0E0E09041B1B0E0E0E0E0E
0E0E0E0E0E0E0E0A051B1B0E0E1818181818181818180B0A061B1B0E0E1B1B1B
1B1B1B1B1B1B0A0A061B1B0E10100E0E0E0E0E0E0E0B0A0A061B1B0E1313100E
0E0E0E0E0E0B0A0A061B1B1015141110100E0E0E0E0E0B0B061B1B1318151312
11110E0E0E0E0E0B061B1B1419181514131211100E0E0E0B041B1B1A1412100E
0E0E0E0E0E0E0B08171B0C1B1B1B1B1B1B1B1B1B1B1B1B1B1B0C}
end
object btLocalizar: TBitBtn
Left = 252
Top = 8
Width = 75
Height = 25
Caption = 'Localizar'
TabOrder = 3
OnClick = btLocalizarClick
Glyph.Data = {
36040000424D3604000000000000360000002800000010000000100000000100
2000000000000004000000000000000000000000000000000000FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00840000008400
0000840000008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF008400000084000000840000008400000084000000FF00FF008400000000FF
FF00840000008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF008400000000FFFF00840000008400000084000000FF00FF008400000000FF
FF00840000008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF008400000000FFFF00840000008400000084000000FF00FF00840000008400
00008400000084000000840000008400000084000000FF00FF00840000008400
00008400000084000000840000008400000084000000FF00FF00840000008400
000000FFFF0084000000840000008400000084000000840000008400000000FF
FF008400000084000000840000008400000084000000FF00FF00840000008400
000000FFFF00840000008400000084000000FF00FF00840000008400000000FF
FF008400000084000000840000008400000084000000FF00FF00840000008400
000000FFFF00840000008400000084000000FF00FF00840000008400000000FF
FF008400000084000000840000008400000084000000FF00FF00FF00FF008400
0000840000008400000084000000840000008400000084000000840000008400
000084000000840000008400000084000000FF00FF00FF00FF00FF00FF00FF00
FF008400000000FFFF00840000008400000084000000FF00FF008400000000FF
FF00840000008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF008400000084000000840000008400000084000000FF00FF00840000008400
0000840000008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00840000008400000084000000FF00FF00FF00FF00FF00FF008400
00008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF008400000000FFFF0084000000FF00FF00FF00FF00FF00FF008400
000000FFFF0084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00840000008400000084000000FF00FF00FF00FF00FF00FF008400
00008400000084000000FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00
FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00}
end
object btCancelar: TBitBtn
Left = 422
Top = 8
Width = 75
Height = 25
Caption = 'Cancelar'
TabOrder = 5
OnClick = btCancelarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000E30E0000E30E00000001000000010000104A7B00184A
840018528C0018529400185A9C00185AA5001863AD001863B500186BBD00186B
C6001873CE001873D600187BDE00187BE7001884E7001884EF001884F700188C
F700FF00FF00188CFF001894FF002194FF00299CFF00319CFF0039A5FF004AAD
FF0052ADFF0063B5FF006BBDFF0084C6FF00ADDEFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00121F1F1F1F1F
1F1F1F1F1F1F1F1F1F121F1A030404040505040403030201191F1F05080A0A0A
0A0A0A0A0A090805001F1F060A0C0C0D0E111111110C0906021F1F090C0F1F1D
111111111D1F0A08031F1F0A0E11131F1D11111D1F0E0B09041F1F0C11131111
1F1D1D1F110E0B0A051F1F0E13111111111F1D110F0C0A0A061F1F0F13131111
1D1F1F1D0E0B0A0A061F1F131515131D1F100F1F1D0A0A0A061F1F1318181D1F
13130F0E1F1D0A0A061F1F151A191F151514110F0E1F0A0A061F1F181C1A1817
16161513100F0C0A061F1F191D1C1A191817161514110F0A041F1F1E19171513
1311110F0E0C0A081B1F121F1F1F1F1F1F1F1F1F1F1F1F1F1F12}
end
object btGravar: TBitBtn
Left = 342
Top = 8
Width = 75
Height = 25
Caption = 'Gravar'
TabOrder = 4
OnClick = btGravarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000E30E0000E30E00000001000000010000104A7B00184A
840018528C0018529400185A9C00185AA5001863AD001863B500186BBD00186B
C6001873CE001873D600187BDE00187BE7001884E7001884EF001884F700188C
F700FF00FF00188CFF001894FF002194FF00299CFF00319CFF0039A5FF004AAD
FF0052ADFF0063B5FF006BBDFF0084C6FF00ADDEFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00121F1F1F1F1F
1F1F1F1F1F1F1F1F1F121F1A030404040505040403030201191F1F05080A0A0A
0A0A0A0A0A090805001F1F060A0C0C0D0E111111110C0906021F1F090C0F0F0F
1D111111110E0A08031F1F0A0E11131D1F1D1111110E0B09041F1F0C11131D1F
1D1F1D11110E0B0A051F1F0E131D1F1D11111F1D0F0C0A0A061F1F0F13131D11
1111111F1D0B0A0A061F1F131515131311100F0F1F1D0A0A061F1F1318181514
13130F0E0C1F1D0A061F1F151A1916151514110F0E0C1F0A061F1F181C1A1817
16161513100F0C0A061F1F191D1C1A191817161514110F0A041F1F1E19171513
1311110F0E0C0A081B1F121F1F1F1F1F1F1F1F1F1F1F1F1F1F12}
end
end
object dsUsuario: TDataSource
AutoEdit = False
DataSet = dmInfoCartao.cdsUsuarios
OnStateChange = dsUsuarioStateChange
OnDataChange = dsUsuarioDataChange
Left = 168
Top = 64
end
end
| 48.323913 | 72 | 0.812992 |
c380009ba90daa57012fda46b379479fd2db3d5e | 2,428 | pas | Pascal | windows/src/unit-tests/jsonutil/Keyman.System.Test.JsonUtilTest.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/unit-tests/jsonutil/Keyman.System.Test.JsonUtilTest.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/unit-tests/jsonutil/Keyman.System.Test.JsonUtilTest.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | unit Keyman.System.Test.JsonUtilTest;
interface
uses
System.Classes,
System.SysUtils,
DUnitX.TestFramework;
type
[TestFixture]
TJsonUtilTest = class(TObject)
private
function DateTimeString(d: TDateTime): string;
public
[Setup]
procedure Setup;
[Test]
procedure TestJsonDateToDateTime;
[Test]
procedure TestDateTimeToJsonDate;
end;
implementation
uses
System.DateUtils,
JsonUtil,
Soap.XsBuiltIns;
// We moved from using Soap.XsBuiltIns to DateToISO8601 in order to avoid having
// a massive dependency on Soap units. This validates that the changeover is
// identical.
function SoapBasedJSONDateToDateTime(const Value: string; var DateTime: TDateTime): Boolean;
begin
try
with TXSDateTime.Create do
try
XSToNative(Value);
DateTime := AsDateTime;
Result := True;
finally
Free;
end;
except
Result := False;
end;
end;
function SoapBasedDateTimeToJSONDate(const ADateTime: TDateTime): string;
begin
try
with TXSDateTime.Create do
try
AsDateTime := ADateTime;
Result := NativeToXS;
finally
Free;
end;
except
Result := '';
end;
end;
procedure TJsonUtilTest.Setup;
begin
Assert.IgnoreCaseDefault := False;
end;
procedure TJsonUtilTest.TestDateTimeToJsonDate;
const
tests: array[0..2] of string = (
'2020-06-29',
'2020-06-12T00:36:29',
'2020-06-12T00:36:29.888Z'
);
var
test: string;
dt: TDateTime;
sSoap, sOurs: string;
begin
for test in tests do
begin
Assert.IsTrue(SoapBasedJSONDateToDateTime(test, dt));
sSoap := SoapBasedDateTimeToJSONDate(dt);
sOurs := DateTimeToJSONDate(dt);
Assert.AreEqual(sSoap, sOurs);
end;
end;
procedure TJsonUtilTest.TestJsonDateToDateTime;
var
dtOurs, dtSoap: TDateTime;
test, sOurs, sSoap: string;
const
tests: array[0..2] of string = (
'2020-06-29',
'2020-06-12T00:36:29',
'2020-06-12T00:36:29.888Z'
);
begin
for test in tests do
begin
Assert.IsTrue(SoapBasedJSONDateToDateTime(test, dtSoap));
Assert.IsTrue(JSONDateToDateTime(test, dtOurs));
sOurs := DateTimeString(dtOurs);
sSoap := DateTimeString(dtSoap);
Assert.AreEqual(sSoap, sOurs);
end;
end;
function TJsonUtilTest.DateTimeString(d: TDateTime): string;
begin
Result := FormatDateTime('yyyy-mm-dd''T''hh:nn:ss.zzz', d);
end;
initialization
TDUnitX.RegisterTestFixture(TJsonUtilTest);
end.
| 19.580645 | 92 | 0.699753 |
c3b58d6ce08912d05a8087e69c936a206204d3b5 | 11,332 | pas | Pascal | Tools/FilePackageWithZDB/FilePackageWithZDBMainFrm.pas | atkins126/zChinese | 47d7654ebc335767031473ccd308c508f351bd1c | [
"Apache-2.0"
]
| 35 | 2018-04-18T06:38:15.000Z | 2021-02-25T10:00:40.000Z | Tools/FilePackageWithZDB/FilePackageWithZDBMainFrm.pas | atkins126/zChinese | 47d7654ebc335767031473ccd308c508f351bd1c | [
"Apache-2.0"
]
| null | null | null | Tools/FilePackageWithZDB/FilePackageWithZDBMainFrm.pas | atkins126/zChinese | 47d7654ebc335767031473ccd308c508f351bd1c | [
"Apache-2.0"
]
| 9 | 2018-04-20T08:03:49.000Z | 2021-03-13T11:31:06.000Z | unit FilePackageWithZDBMainFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
ObjectDataManagerFrameUnit, MemoryStream64, ObjectDataHashField, ObjectDataManager,
UnicodeMixedLib, CoreClasses, DoStatusIO, PascalStrings, FileIndexPackage;
type
TFilePackageWithZDBMainForm = class(TForm, IMemoryStream64ReadWriteTrigger)
TopPanel: TPanel;
NewButton: TButton;
OpenButton: TButton;
SaveButton: TButton;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
SaveAsButton: TButton;
Memo: TMemo;
MD5Edit: TMemo;
CacheStateMemo: TMemo;
Timer: TTimer;
RecalcMD5Button: TButton;
CompressAsButton: TButton;
Bevel3: TBevel;
SaveAsCompressedDialog: TSaveDialog;
Splitter1: TSplitter;
Bevel4: TBevel;
Bevel5: TBevel;
Bevel7: TBevel;
BuildIndexPackageButton: TButton;
Bevel8: TBevel;
NewCustomButton: TButton;
ParallelCompressAsButton: TButton;
SaveAsParallelCompressedDialog: TSaveDialog;
procedure BuildIndexPackageButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NewButtonClick(Sender: TObject);
procedure NewCustomButtonClick(Sender: TObject);
procedure OpenButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure SaveAsButtonClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure RecalcMD5ButtonClick(Sender: TObject);
procedure CompressAsButtonClick(Sender: TObject);
procedure ParallelCompressAsButtonClick(Sender: TObject);
private
FDBEng: TObjectDataManager;
FDBManFrame: TObjectDataManagerFrame;
FTotalRead, FTotalWrite: Int64;
FOpenFile: U_String;
procedure DoStatusNear(AText: SystemString; const ID: Integer);
procedure TriggerWrite64(Count: Int64);
procedure TriggerRead64(Count: Int64);
public
procedure OpenFile(fileName: SystemString);
end;
var
FilePackageWithZDBMainForm: TFilePackageWithZDBMainForm;
implementation
{$R *.dfm}
uses BuildIndexPackageOptFrm, NewDBOptFrm;
procedure TFilePackageWithZDBMainForm.BuildIndexPackageButtonClick(Sender: TObject);
var
destDB: TObjectDataManager;
begin
if BuildIndexPackageOptForm.ShowModal <> mrOk then
exit;
destDB := TObjectDataManager.CreateNew(FDBEng.Handle^.FixedStringL, BuildIndexPackageOptForm.DestDBEdit.Text, DBMarshal.ID);
destDB.OverWriteItem := False;
BuildIndexPackage(FDBEng, destDB, ParallelCompressStream_Call, BuildIndexPackageOptForm.DataPathEdit.Text);
if CheckIndexPackage(destDB, BuildIndexPackageOptForm.DataPathEdit.Text) then
DoStatus('check index package: no error.');
disposeObject(destDB);
if messageDlg(Format('Do you want to open the "%s" file?', [BuildIndexPackageOptForm.DestDBEdit.Text]), mtInformation, [mbYes, mbNO], 0) <> mrYes then
exit;
OpenFile(BuildIndexPackageOptForm.DestDBEdit.Text);
end;
procedure TFilePackageWithZDBMainForm.FormCreate(Sender: TObject);
begin
FTotalRead := 0;
FTotalWrite := 0;
AddDoStatusHook(Self, DoStatusNear);
FDBEng := nil;
FDBManFrame := TObjectDataManagerFrame.Create(Self);
FDBManFrame.Parent := Self;
FDBManFrame.Align := alClient;
FDBManFrame.ResourceData := nil;
FOpenFile := '';
MD5Edit.Text := '';
NewButtonClick(NewButton);
end;
procedure TFilePackageWithZDBMainForm.FormDestroy(Sender: TObject);
begin
DeleteDoStatusHook(Self);
disposeObject(FDBManFrame);
disposeObject(FDBEng);
end;
procedure TFilePackageWithZDBMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := True;
end;
procedure TFilePackageWithZDBMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFilePackageWithZDBMainForm.NewButtonClick(Sender: TObject);
begin
FTotalRead := 0;
FTotalWrite := 0;
FDBManFrame.ResourceData := nil;
disposeObject(FDBEng);
FDBEng := TObjectDataManager.CreateAsStream(TMemoryStream64OfReadWriteTrigger.Create(Self), '', ObjectDataMarshal.ID, False, True, True);
FDBManFrame.ResourceData := FDBEng;
FOpenFile := '';
FDBEng.UpdateIO;
FDBEng.StreamEngine.Position := 0;
MD5Edit.Text := umlStreamMD5String(FDBEng.StreamEngine);
DoStatus('new DB. [fixed string size: %d]', [FDBEng.Handle^.FixedStringL]);
end;
procedure TFilePackageWithZDBMainForm.NewCustomButtonClick(Sender: TObject);
var
l: Integer;
begin
if NewDBOptForm.ShowModal <> mrOk then
exit;
l := umlClamp(umlStrToInt(NewDBOptForm.FixedStringEdit.Text, 65), 10, $FF);
FTotalRead := 0;
FTotalWrite := 0;
FDBManFrame.ResourceData := nil;
disposeObject(FDBEng);
FDBEng := TObjectDataManager.CreateAsStream(Byte(l), TMemoryStream64OfReadWriteTrigger.Create(Self), '', ObjectDataMarshal.ID, False, True, True);
FDBManFrame.ResourceData := FDBEng;
FOpenFile := '';
FDBEng.UpdateIO;
FDBEng.StreamEngine.Position := 0;
MD5Edit.Text := umlStreamMD5String(FDBEng.StreamEngine);
DoStatus('new DB. [fixed string size: %d]', [FDBEng.Handle^.FixedStringL]);
end;
procedure TFilePackageWithZDBMainForm.OpenButtonClick(Sender: TObject);
begin
if not OpenDialog.Execute then
exit;
OpenFile(OpenDialog.fileName);
end;
procedure TFilePackageWithZDBMainForm.SaveButtonClick(Sender: TObject);
var
stream: TFileStream;
begin
if FOpenFile = '' then
if not SaveDialog.Execute then
exit;
if FOpenFile = '' then
begin
FOpenFile := SaveDialog.fileName;
end;
stream := TFileStream.Create(FOpenFile, fmCreate);
try
FDBEng.SaveToStream(stream);
stream.Position := 0;
MD5Edit.Text := umlStreamMD5String(stream);
finally
disposeObject(stream);
end;
DoStatus('save %s', [FOpenFile.Text]);
Caption := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
Application.Title := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
end;
procedure TFilePackageWithZDBMainForm.SaveAsButtonClick(Sender: TObject);
var
stream: TFileStream;
begin
if not SaveDialog.Execute then
exit;
FOpenFile := SaveDialog.fileName;
stream := TFileStream.Create(FOpenFile, fmCreate);
try
FDBEng.SaveToStream(stream);
stream.Position := 0;
MD5Edit.Text := umlStreamMD5String(stream);
finally
disposeObject(stream);
end;
DoStatus('save %s', [FOpenFile.Text]);
Caption := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
Application.Title := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
end;
procedure TFilePackageWithZDBMainForm.TimerTimer(Sender: TObject);
begin
CacheStateMemo.Text := Format('File Size:%s IO Read:%s IO Write:%s',
[umlSizeToStr(FDBEng.Size).Text, umlSizeToStr(FTotalRead).Text, umlSizeToStr(FTotalWrite).Text]);
end;
procedure TFilePackageWithZDBMainForm.RecalcMD5ButtonClick(Sender: TObject);
begin
MD5Edit.Text := umlStreamMD5String(FDBEng.StreamEngine);
DoStatus('recalc md5:%s', [MD5Edit.Text]);
end;
procedure TFilePackageWithZDBMainForm.CompressAsButtonClick(Sender: TObject);
var
m64, C64: TMemoryStream64;
fn: string;
begin
SaveAsCompressedDialog.fileName := umlChangeFileExt(FOpenFile, SaveAsCompressedDialog.DefaultExt);
if not SaveAsCompressedDialog.Execute then
exit;
fn := SaveAsCompressedDialog.fileName;
m64 := TMemoryStream64.Create;
C64 := TMemoryStream64.Create;
try
FDBEng.SaveToStream(m64);
m64.Position := 0;
MD5Edit.Text := umlStreamMD5String(m64);
m64.Position := 0;
MaxCompressStream(m64, C64);
C64.SaveToFile(fn);
DoStatus('save as Compressed %s (source:%s compressed:%s)', [fn, umlSizeToStr(m64.Size).Text, umlSizeToStr(C64.Size).Text]);
finally
disposeObject([m64, C64]);
end;
end;
procedure TFilePackageWithZDBMainForm.ParallelCompressAsButtonClick(Sender: TObject);
var
m64, C64: TMemoryStream64;
fn: string;
begin
SaveAsParallelCompressedDialog.fileName := umlChangeFileExt(FOpenFile, SaveAsParallelCompressedDialog.DefaultExt);
if not SaveAsParallelCompressedDialog.Execute then
exit;
fn := SaveAsParallelCompressedDialog.fileName;
m64 := TMemoryStream64.Create;
C64 := TMemoryStream64.Create;
try
FDBEng.SaveToStream(m64);
m64.Position := 0;
MD5Edit.Text := umlStreamMD5String(m64);
m64.Position := 0;
ParallelCompressStream(TSelectCompressionMethod.scmZLIB_Max, m64, C64);
C64.SaveToFile(fn);
DoStatus('save as Compressed %s (source:%s compressed:%s)', [fn, umlSizeToStr(m64.Size).Text, umlSizeToStr(C64.Size).Text]);
finally
disposeObject([m64, C64]);
end;
end;
procedure TFilePackageWithZDBMainForm.DoStatusNear(AText: SystemString; const ID: Integer);
begin
Memo.Lines.Add(AText);
end;
procedure TFilePackageWithZDBMainForm.TriggerWrite64(Count: Int64);
begin
Inc(FTotalWrite, Count);
end;
procedure TFilePackageWithZDBMainForm.TriggerRead64(Count: Int64);
begin
Inc(FTotalRead, Count);
end;
procedure TFilePackageWithZDBMainForm.OpenFile(fileName: SystemString);
var
m64, C64: TMemoryStream64;
begin
FOpenFile := fileName;
FDBManFrame.ResourceData := nil;
disposeObject(FDBEng);
if umlMultipleMatch(True, '*.OXC', FOpenFile) then
begin
C64 := TMemoryStream64.Create;
m64 := TMemoryStream64OfReadWriteTrigger.Create(Self);
try
C64.LoadFromFile(FOpenFile);
C64.Position := 0;
DecompressStream(C64, m64);
m64.Position := 0;
FOpenFile := umlChangeFileExt(FOpenFile, '.OX').Text;
except
disposeObject(C64);
C64 := nil;
m64.Clear;
m64.LoadFromFile(FOpenFile);
m64.Position := 0;
end;
disposeObject(C64);
end
else if umlMultipleMatch(True, '*.OXP', FOpenFile) then
begin
C64 := TMemoryStream64.Create;
m64 := TMemoryStream64OfReadWriteTrigger.Create(Self);
try
C64.LoadFromFile(FOpenFile);
C64.Position := 0;
ParallelDecompressStream(C64, m64);
m64.Position := 0;
FOpenFile := umlChangeFileExt(FOpenFile, '.OX').Text;
except
disposeObject(C64);
C64 := nil;
m64.Clear;
m64.LoadFromFile(FOpenFile);
m64.Position := 0;
end;
disposeObject(C64);
end
else
begin
m64 := TMemoryStream64OfReadWriteTrigger.Create(Self);
m64.LoadFromFile(FOpenFile);
m64.Position := 0;
end;
MD5Edit.Text := umlStreamMD5String(m64);
FTotalRead := 0;
FTotalWrite := 0;
m64.Position := 0;
FDBEng := TObjectDataManager.CreateAsStream(m64, '', ObjectDataMarshal.ID, False, False, True);
FDBManFrame.ResourceData := FDBEng;
DoStatus('open %s [fixed string size: %d]', [FOpenFile.Text, FDBEng.Handle^.FixedStringL]);
Caption := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
Application.Title := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
BuildIndexPackageOptForm.DestDBEdit.Text := umlChangeFileExt(fileName, '') + '_index.OX';
BuildIndexPackageOptForm.DataPathEdit.Text := umlCombinePath(umlGetFilePath(fileName), 'DataCache\');
end;
end.
| 29.433766 | 152 | 0.733586 |
c35ad7b226f844806a72c98698a3851bcfa934de | 5,090 | pas | Pascal | windows/src/ext/jedi/jvcl/tests/archive/jvcl/examples/JvColorComboDemo/JvColorComboDemoMainFormU.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/examples/JvColorComboDemo/JvColorComboDemoMainFormU.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/examples/JvColorComboDemo/JvColorComboDemoMainFormU.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | unit JvColorComboDemoMainFormU;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, JvColorCombo, StdCtrls, JvCombobox;
type
TJvColorComboDemoMainForm = class(TForm)
JvColorComboBox1: TJvColorComboBox;
memInfo: TMemo;
btnColorNames: TButton;
Label1: TLabel;
Label2: TLabel;
edNameTemplate: TEdit;
chkAllowCustom: TCheckBox;
btnCustColors: TButton;
Label3: TLabel;
cbDisplayStyle: TComboBox;
procedure FormCreate(Sender: TObject);
procedure btnColorNamesClick(Sender: TObject);
procedure JvColorComboBox1NewColor(Sender: TObject; Color: TColor;
var DisplayName: string; var AllowAdd: Boolean);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnCustColorsClick(Sender: TObject);
procedure cbDisplayStyleChange(Sender: TObject);
private
{ Private declarations }
procedure LoadSettings;
procedure SaveSettings;
end;
var
JvColorComboDemoMainForm: TJvColorComboDemoMainForm;
implementation
uses
IniFiles;
{$R *.dfm}
procedure TJvColorComboDemoMainForm.FormCreate(Sender: TObject);
begin
JvColorComboBox1.Options := [coText, coSysColors, coCustomColors];
JvColorComboBox1.GetColors;
LoadSettings;
cbDisplayStyle.ItemIndex := 1;
cbDisplayStyleChange(nil);
end;
procedure TJvColorComboDemoMainForm.btnColorNamesClick(Sender: TObject);
begin
memInfo.Lines := JvColorComboBox1.ColorNameMap;
end;
procedure TJvColorComboDemoMainForm.JvColorComboBox1NewColor(Sender: TObject; Color: TColor;
var DisplayName: string; var AllowAdd: Boolean);
begin
// make sure the new color isn't already in the list
AllowAdd := JvColorComboBox1.FindColor(Color) < 0;
if AllowAdd then
begin
if edNameTemplate.Text <> '' then
// CustomColorCount isn't incremented until *after* this event has finished with AllowAdd = true, so add 1 here:
DisplayName := Format(edNameTemplate.Text, [JvColorComboBox1.CustomColorCount + 1]);
end;
end;
procedure TJvColorComboDemoMainForm.LoadSettings;
var CurColor: TColor;
S: string;
SL: TStringlist;
i: integer;
begin
// load color name map and saved custom colors
CurColor := JvColorComboBox1.ColorValue;
JvColorComboBox1.Options := JvColorComboBox1.Options - [coCustomColors];
try
S := ChangeFileExt(Application.ExeName, '.ini');
if FileExists(S) then
begin
SL := TStringlist.Create;
try
with TIniFile.Create(S) do
try
edNameTemplate.Text := ReadString('Settings', 'Custom Template', edNameTemplate.Text);
ReadSectionValues('Color Names', JvColorComboBox1.ColorNameMap);
ReadSection('Custom Colors', SL);
for i := 0 to SL.Count - 1 do
JvColorComboBox1.AddColor(StringToColor(SL[i]),'');
finally
Free;
end;
finally
SL.Free;
end;
end;
finally
JvColorComboBox1.ColorValue := CurColor;
cbDisplayStyleChange(nil);
end;
end;
procedure TJvColorComboDemoMainForm.SaveSettings;
var i: integer; AList: TList;
begin
// save color name map and current custom colors
JvColorComboBox1.Options := JvColorComboBox1.Options - [coCustomColors];
try
with TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini')) do
try
AList := TList.Create;
try
JvColorComboBox1.GetCustomColors(AList);
EraseSection('Custom Colors');
for i := 0 to AList.Count - 1 do
WriteString('Custom Colors', ColorToString(integer(AList[i])), '');
finally
AList.Free;
end;
WriteString('Settings', 'Custom Template', edNameTemplate.Text);
// save color map so users can translate them if they wish
// no need to save the custom names since they are
// set dynamically at load time (see JvColorComboBox1NewColor)
EraseSection('Color Names');
with JvColorComboBox1.ColorNameMap do
for i := 0 to Count - 1 do
WriteString('Color Names', Names[i], Values[Names[i]]);
finally
Free;
end;
finally
cbDisplayStyleChange(nil);
end;
end;
procedure TJvColorComboDemoMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
SaveSettings;
end;
procedure TJvColorComboDemoMainForm.btnCustColorsClick(Sender: TObject);
var AList: TList; i: integer;
begin
AList := TList.Create;
memInfo.Lines.Clear;
try
// the returned TList contains a list of TColor items
JvColorComboBox1.GetCustomColors(AList);
for i := 0 to AList.Count - 1 do
memInfo.Lines.Add(ColorToString(integer(AList[i])));
finally
AList.Free;
end;
end;
procedure TJvColorComboDemoMainForm.cbDisplayStyleChange(Sender: TObject);
var O: TJvColorComboOptions;
begin
O := JvColorComboBox1.Options;
O := O - [coText, coHex, coRGB, coCustomColors];
if chkAllowCustom.Checked then
Include(O, coCustomColors);
case cbDisplayStyle.ItemIndex of
1:
Include(O, coText);
2:
Include(O, coHex);
3:
Include(O, coRGB);
end;
JvColorComboBox1.Options := O;
end;
end.
| 28.595506 | 116 | 0.708841 |
85824994beeffef581312a2b54f10c67337a4164 | 8,265 | pas | Pascal | crossinstallers/m_any_to_embeddedarm.pas | cybersmurf/fpcupdeluxe | 7c0de3a67cfb2510d89d217b9cf9ecea1d62feb1 | [
"zlib-acknowledgement"
]
| 1 | 2021-01-01T07:57:29.000Z | 2021-01-01T07:57:29.000Z | crossinstallers/m_any_to_embeddedarm.pas | cybersmurf/fpcupdeluxe | 7c0de3a67cfb2510d89d217b9cf9ecea1d62feb1 | [
"zlib-acknowledgement"
]
| null | null | null | crossinstallers/m_any_to_embeddedarm.pas | cybersmurf/fpcupdeluxe | 7c0de3a67cfb2510d89d217b9cf9ecea1d62feb1 | [
"zlib-acknowledgement"
]
| null | null | null | unit m_any_to_embeddedarm;
{ Cross compiles from any platform with correct binutils to Embedded ARM
Copyright (C) 2017 Alf
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
implementation
uses
FileUtil, m_crossinstaller, fpcuputil;
type
{ TAny_Embeddedarm }
TAny_Embeddedarm = class(TCrossInstaller)
private
FAlreadyWarned: boolean; //did we warn user about errors and fixes already?
public
function GetLibs(Basepath:string):boolean;override;
{$ifndef FPCONLY}
function GetLibsLCL(LCL_Platform:string; Basepath:string):boolean;override;
{$endif}
function GetBinUtils(Basepath:string):boolean;override;
constructor Create;
destructor Destroy; override;
end;
{ TAny_Embeddedarm }
function TAny_Embeddedarm.GetLibs(Basepath:string): boolean;
const
LibName='libgcc.a'; // is this correct ??
begin
// Arm-embedded does not need libs by default, but user can add them.
result:=FLibsFound;
if result then exit;
if length(FSubArch)>0
then ShowInfo('Cross-libs: We have a subarch: '+FSubArch)
else ShowInfo('Cross-libs: No subarch defined. Expect fatal errors.',etError);
// begin simple: check presence of library file in basedir
result:=SearchLibrary(Basepath,LibName);
// search local paths based on libraries provided for or adviced by fpc itself
if not result then
if length(FSubArch)>0 then result:=SimpleSearchLibrary(BasePath,IncludeTrailingPathDelimiter(DirName)+FSubArch,LibName);
if not result then
result:=SimpleSearchLibrary(BasePath,DirName,LibName);
if result then
begin
FLibsFound:=True;
//todo: check if -XR is needed for fpc root dir Prepend <x> to all linker search paths
AddFPCCFGSnippet('-Fl'+IncludeTrailingPathDelimiter(FLibsPath)); {buildfaq 1.6.4/3.3.1: the directory to look for the target libraries ... just te be safe ...}
SearchLibraryInfo(result);
end;
if not result then
begin
//libs path is optional; it can be empty
ShowInfo('Libspath ignored; it is optional for this cross compiler.');
FLibsPath:='';
FLibsFound:=True;
result:=true;
end;
end;
{$ifndef FPCONLY}
function TAny_Embeddedarm.GetLibsLCL(LCL_Platform: string; Basepath: string): boolean;
begin
// todo: get gtk at least, add to FFPCCFGSnippet
ShowInfo('Todo: implement lcl libs path from basepath '+BasePath,etdebug);
result:=inherited;
end;
{$endif}
function TAny_Embeddedarm.GetBinUtils(Basepath:string): boolean;
var
AsFile,aOption: string;
BinPrefixTry: string;
i:integer;
begin
result:=inherited;
if result then exit;
// Start with any names user may have given
AsFile:=FBinUtilsPrefix+'as'+GetExeExt;
result:=SearchBinUtil(BasePath,AsFile);
if not result then result:=SimpleSearchBinUtil(BasePath,DirName,AsFile);
{$ifdef unix}
// User may also have placed them into their regular search path:
if not result then
begin
for i:=Low(UnixBinDirs) to High(UnixBinDirs) do
begin
result:=SearchBinUtil(IncludeTrailingPathDelimiter(UnixBinDirs[i])+DirName, AsFile);
if not result then result:=SearchBinUtil(UnixBinDirs[i], AsFile);
if result then break;
end;
end;
{$endif unix}
// Now also allow for arm-none-eabi- binutilsprefix (e.g. launchpadlibrarian)
if not result then
begin
BinPrefixTry:='arm-none-eabi-';
AsFile:=BinPrefixTry+'as'+GetExeExt;
result:=SearchBinUtil(BasePath,AsFile);
if not result then result:=SimpleSearchBinUtil(BasePath,DirName,AsFile);
if result then FBinUtilsPrefix:=BinPrefixTry;
end;
// Now also allow for empty binutilsprefix in the right directory:
if not result then
begin
BinPrefixTry:='';
AsFile:=BinPrefixTry+'as'+GetExeExt;
result:=SearchBinUtil(BasePath,AsFile);
if not result then result:=SimpleSearchBinUtil(BasePath,DirName,AsFile);
if result then FBinUtilsPrefix:=BinPrefixTry;
end;
SearchBinUtilsInfo(result);
if not result then
begin
ShowInfo('Suggestion for cross binutils:');
{$ifdef mswindows}
ShowInfo('The crossfpc binutils (arm-embedded) at http://svn.freepascal.org/svn/fpcbuild/binaries/i386-win32');
{$else}
ShowInfo('Tools from https://launchpad.net/gcc-arm-embedded.');
{$endif}
ShowInfo('Tools from https://github.com/gnu-mcu-eclipse/arm-none-eabi-gcc');
FAlreadyWarned:=true;
end
else
begin
FBinsFound:=true;
{
if length(FSubArch)>0 then
begin
ShowInfo('Cross-bins: We have a subarch: '+FSubArch);
i:=StringListStartsWith(FCrossOpts,'-Cp');
if i=-1 then
begin
aOption:='-Cp'+FSubArch;
FCrossOpts.Add(aOption+' ');
ShowInfo('Did not find any -Cp architecture parameter; using '+aOption);
end else aOption:=Trim(FCrossOpts[i]);
AddFPCCFGSnippet(aOption);
end else ShowInfo('Cross-bins: No subarch defined. Expect fatal errors.',etError);
}
// Configuration snippet for FPC
AddFPCCFGSnippet('-FD'+IncludeTrailingPathDelimiter(FBinUtilsPath));
AddFPCCFGSnippet('-XP'+FBinUtilsPrefix); {Prepend the binutils names};
i:=StringListStartsWith(FCrossOpts,'-Cp');
if i=-1 then
begin
if length(FSubArch)=0 then FSubArch:='armv6m';
aOption:='-Cp'+FSubArch;
FCrossOpts.Add(aOption+' ');
ShowInfo('Did not find any -Cp architecture parameter; using -Cp'+FSubArch+' and SUBARCH='+FSubArch+'.');
end else aOption:=Trim(FCrossOpts[i]);
AddFPCCFGSnippet(aOption);
(*
if length(FSubArch)=0 then
begin
aOption:='armv6m';
ShowInfo('Did not find any subarch definition; using '+aOption+' (cortex-m0/embed default).');
FSubArch:=aOption;
aOption:='-Cp'+aOption;
FCrossOpts.Add(aOption+' ');
AddFPCCFGSnippet(aOption);
end;
*)
(*
// Set some defaults if user hasn't specified otherwise
// Architecture: e.g. ARMv6, ARMv7,...
i:=StringListStartsWith(FCrossOpts,'-Cp');
if i=-1 then
begin
aOption:='-CpARMV7M'; // cortex-m3/embed default
FCrossOpts.Add(aOption+' ');
// When compiling for arm-embedded, a sub-architecture (e.g. SUBARCH=armv4t or SUBARCH=armv7m) must be defined)
FSubArch:='armv7m';
ShowInfo('Did not find any -Cp architecture parameter; using '+aOption+' (cortex-m3/embed default).');
end else aOption:=Trim(FCrossOpts[i]);
AddFPCCFGSnippet(aOption);
*)
end;
end;
constructor TAny_Embeddedarm.Create;
begin
inherited Create;
FTargetCPU:=TCPU.arm;
FTargetOS:=TOS.embedded;
Reset;
FAlreadyWarned:=false;
ShowInfo;
end;
destructor TAny_Embeddedarm.Destroy;
begin
inherited Destroy;
end;
var
Any_Embeddedarm:TAny_Embeddedarm;
initialization
Any_Embeddedarm:=TAny_Embeddedarm.Create;
RegisterCrossCompiler(Any_Embeddedarm.RegisterName,Any_Embeddedarm);
finalization
Any_Embeddedarm.Destroy;
end.
| 32.159533 | 163 | 0.729341 |
4730ffd03aacdc17f0cbc4fd5113d95c2efe3097 | 25,852 | pas | Pascal | src/Common/AutoAdd.pas | beroset/dss_capi | a1be467609314cb4d5b164c3e088591a9fa25567 | [
"BSD-3-Clause"
]
| null | null | null | src/Common/AutoAdd.pas | beroset/dss_capi | a1be467609314cb4d5b164c3e088591a9fa25567 | [
"BSD-3-Clause"
]
| null | null | null | src/Common/AutoAdd.pas | beroset/dss_capi | a1be467609314cb4d5b164c3e088591a9fa25567 | [
"BSD-3-Clause"
]
| null | null | null | unit AutoAdd;
{
----------------------------------------------------------
Copyright (c) 2008-2015, Electric Power Research Institute, Inc.
All rights reserved.
----------------------------------------------------------
}
{ Unit for processing the AutoAdd Solution FUNCTIONs
Note: Make sure this class in instantiated after energymeter class
There is one of these per circuit
6/11/00 - reorganized object
6/14/00 - resolved sign issue with normal and Newton solution in AddCurrents
9/13/03 - Modified to use pu improvement in losses and EEN instead of kW
}
{$M+}
interface
uses
uComplex,
EnergyMeter,
HashList,
Arraydef,
Generator,
Capacitor,
Classes,
DSSClass;
type
TAutoAdd = class(TObject)
PRIVATE
GeneratorClass: TGenerator;
CapacitorClass: TCapacitor;
BusIdxList: pIntegerArray;
BusIdxListSize: Integer;
BusIdxListCreated: Boolean;
LastAddedGenerator,
LastAddedCapacitor: Integer;
BusIndex,
Phases: Integer;
Ycap: Double;
GenVA: Complex;
kWLosses, BaseLosses, puLossImprovement: Double;
kWEEN, BaseEEN, puEENImprovement: Double;
FLog: TFileStream; // Log File
function Get_WeightedLosses: Double;
procedure ComputekWLosses_EEN;
procedure SetBaseLosses;
function GetUniqueGenName: String;
function GetUniqueCapName: String;
PROTECTED
PUBLIC
{Autoadd mode Variables}
GenkW,
GenPF,
Genkvar,
Capkvar: Double;
AddType: Integer;
ModeChanged: Boolean;
DSS: TDSSContext;
constructor Create(dssContext: TDSSContext);
destructor Destroy; OVERRIDE;
procedure MakeBusList;
procedure AppendToFile(const WhichFile, S: String);
procedure AddCurrents(SolveType: Integer);
function Solve: Integer; // Automatically add caps or generators
property WeightedLosses: Double READ Get_WeightedLosses;
PUBLISHED
end;
implementation
uses
DSSClassDefs,
DSSGlobals,
PDElement,
Utilities,
SysUtils,
Executive,
{$IFDEF FPC}
CmdForms,
{$ELSE}
DSSForms,
{$ENDIF}
{ProgressForm, Forms,} Solution,
DSSHelper;
function SumSelectedRegisters(Mtr: TEnergyMeterObj; Regs: pIntegerArray; count: Integer): Double;
var
i: Integer;
begin
Result := 0.0;
with Mtr do
for i := 1 to count do
begin
Result := Result + Registers[regs^[i]] * TotalsMask[Regs^[i]];
end;
end;
constructor TAutoAdd.Create(dssContext: TDSSContext);
begin
DSS := dssContext;
BusIdxListCreated := FALSE;
GeneratorClass := DSS.DSSClassList.Get(DSS.ClassNames.Find('generator'));
CapacitorClass := DSS.DSSClassList.Get(DSS.ClassNames.Find('capacitor'));
// AutoAdd defaults
GenkW := 1000.0;
GenPF := 1.0;
Capkvar := 600.0;
AddType := GENADD;
LastAddedGenerator := 0;
LastAddedCapacitor := 0;
ModeChanged := TRUE;
end;
destructor TAutoAdd.Destroy;
begin
if BusIdxListCreated then
ReallocMem(BusIdxList, 0);
inherited;
end;
procedure TAutoAdd.MakeBusList;
// Make a list of unique busnames
// IF AutoAddBusList in ActiveCircuit is not nil, use this list.
// ELSE, Use the element lists in Energy Meters
// IF no Energy Meters, use all the buses in the active circuit
var
pMeter: TEnergyMeterObj;
retval: Integer;
Bname: String;
i: Integer;
PDElem: TPDElement;
FBusList: TBusHashListType;
FBusListCreatedHere: Boolean;
begin
if (BusIdxListCreated) then
ReallocMem(BusIdxList, 0);
FBusListCreatedHere := FALSE;
BusIdxListCreated := FALSE;
// Autoaddbuslist exists in Active Circuit, use it (see set Autobuslist=)
if DSS.ActiveCircuit.AutoAddBusList.Count > 0 then
FBusList := DSS.ActiveCircuit.AutoAddBusList
else
if DSS.ActiveCircuit.EnergyMeters.Count = 0 then
begin
// No energymeters in circuit
// Include all buses in the circuit
BusIdxListSize := DSS.ActiveCircuit.BusList.Count;
BusIdxList := AllocMem(Sizeof(BusIdxList^[1]) * BusIdxListSize);
for i := 1 to BusIdxListSize do
begin
BusIdxList^[i] := i;
end;
BusIdxListCreated := TRUE;
Exit;
end
else
begin
{Construct Bus List from Energy Meters Zone Lists}
// Include only buses in EnergyMeter lists
// Consider all meters
FBusListCreatedHere := TRUE;
FBusList := TBusHashListType.Create(DSS.ActiveCircuit.NumBuses);
pMeter := DSS.ActiveCircuit.EnergyMeters.First;
while pMeter <> NIL do
begin
if pMeter.BranchList <> NIL then
begin
PDElem := pMeter.BranchList.First;
while PDElem <> NIL do
begin // add only unique busnames
for i := 1 to PDElem.Nterms do
begin
Bname := StripExtension(PDElem.GetBus(i));
retval := FBusList.Find(Bname);
if retval = 0 then
begin
FBusList.Add(BName); // return value is index of bus
end;
end;
PDElem := pMeter.BranchList.GoForward;
end;
end;
pMeter := DSS.ActiveCircuit.EnergyMeters.Next;
end;
end;
// Make busIdxList from FBusList
BusIdxListSize := FBusList.Count;
BusIdxList := AllocMem(Sizeof(BusIdxList^[i]) * BusIdxListSize);
for i := 1 to BusIdxListSize do
begin
BusIdxList^[i] := DSS.ActiveCircuit.BusList.Find(FBusList.NameOfIndex(i));
end;
if FBusListCreatedHere then
FBusList.Free;
BusIdxListCreated := TRUE;
end;
function TAutoAdd.Get_WeightedLosses: Double;
// Returns losses in metered part of circuit +
// weighted EEN values
{If no meters, returns just total losses in circuit}
{Base everything on gen kW}
begin
ComputekWLosses_EEN;
if DSS.ActiveCircuit.EnergyMeters.Count = 0 then
begin
// No energymeters in circuit
// Just go by total system losses
puLossImprovement := (BaseLosses - kWLosses) / GenkW;
puEENImprovement := 0.0;
Result := puLossImprovement;
end
else
with DSS.ActiveCircuit do
begin
puLossImprovement := (BaseLosses - kWLosses) / GenkW;
puEENImprovement := (BaseEEN - kWEEN) / GenkW;
Result := LossWeight * puLossImprovement + UEWeight * puEENImprovement;
end;
end;
procedure TAutoAdd.AppendToFile(const WhichFile, S: String);
var
F: TFileStream;
Fname: String;
begin
F := nil;
try
FName := DSS.OutputDirectory + DSS.CircuitName_ + 'AutoAdded' + WhichFile + '.txt';
if FileExists(FName) then
begin
F := TFileStream.Create(Fname, fmOpenReadWrite);
F.Seek(0, soEnd);
end
else
F := TFileStream.Create(Fname, fmCreate);
FSWriteLn(F, S);
except
On E: EXCEPTion do
DoSimpleMsg(DSS, 'Error TRYing to append to ' + Fname + CRLF +
E.Message, 438);
end;
if F <> nil then
F.Free();
end;
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function TAutoAdd.GetUniqueGenName: String;
var
// TimeStmp: TTimeStamp;
TrialName: String;
Done: Boolean;
begin
repeat
Done := TRUE;
Inc(LastAddedGenerator);
TrialName := 'Gadd' + IntToStr(LastAddedGenerator);
if GeneratorClass.Find(TrialName) <> NIL then
Done := FALSE;
until Done;
Result := TrialName;
end;
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function TAutoAdd.GetUniqueCapName: String;
var
// TimeStmp: TTimeStamp;
TrialName: String;
Done: Boolean;
begin
// TimeStmp := DateTimeToTimeStamp(Now);
// Result := IntToStr(TimeStmp.date-730000)+'_'+IntToStr(TimeStmp.time);
repeat
Done := TRUE;
Inc(LastAddedCapacitor);
TrialName := 'Cadd' + IntToStr(LastAddedCapacitor);
if CapacitorClass.Find(TrialName) <> NIL then
Done := FALSE;
until Done;
Result := TrialName;
end;
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function TAutoAdd.Solve: Integer; // Automatically add caps or generators
{
Automatically add a specified size of generator or capacitor at the location
that results in the lowest losses in either metered part of circuit or
total circuit, if no meters.
If metered, EEN is also added in WITH a selected weighting factor (see
set ueweight= ... command).
Thus, this algorithm placed generators and capacitors to minimize losses and
potential unserved energy.
}
var
LossImproveFactor,
MaxLossImproveFactor: Double;
MinLossBus,
MinBusPhases: Integer;
Testbus: String;
i: Integer;
CommandString: String;
kVrat, TestGenkW,
TestCapkvar: Double;
ProgressMax: Integer;
begin
FLog := nil;
{ Algorithm:
1) makes a list of buses to check, either
a. Previously defined list
b. Meter zone lists
c. All buses, if neither of the above
2) Inject a current corresponding to the generator
3) Check test criteria
4) Save result
5) Add generator/capacitor to circuit
}
Result := 0;
try
with DSS.ActiveCircuit, DSS.ActiveCircuit.Solution do
begin
if (LoadModel = ADMITTANCE) then
begin
LoadModel := POWERFLOW;
SystemYChanged := TRUE; // Force rebuild of System Y without Loads
end;
{Do a preliminary snapshot solution to Force definition of meter zones
And set bus lists}
DSS.EnergyMeterClass.ResetAll;
if SystemYChanged or DSS.ActiveCircuit.BusNameRedefined then
begin
SolveSnap;
ModeChanged := TRUE;
end;
DSS.EnergyMeterClass.SampleAll;
{ Check to see if bus base voltages have been defined }
if Buses^[NumBuses].kVBase = 0.0 then
SetVoltageBases;
if ModeChanged then
begin
MakeBusList; // Make list of buses to check
ModeChanged := FALSE; {Keep same BusIdxList if no changes}
end;
IntervalHrs := 1.0;
{Start up Log File}
FLog := TFileStream.Create(DSS.OutputDirectory + DSS.CircuitName_ + 'AutoAddLog.CSV', fmCreate);
FSWriteLn(FLog, '"Bus", "Base kV", "kW Losses", "% Improvement", "kW UE", "% Improvement", "Weighted Total", "Iterations"');
// for this solution mode, only the peak load condition is taken into account
// load is adjusted for growth by year.
SetGeneratorDispRef;
{Turn regulators and caps off while we are searching}
ControlMode := CONTROLSOFF;
SetBaseLosses; {Establish base values}
case AddType of
GENADD:
begin
if DSS.ActiveCircuit.PositiveSequence then
TestGenkW := GenkW / 3.0
else
TestGenkW := GenkW;
if GenPF <> 0.0 then
begin
Genkvar := TestGenkW * sqrt(1.0 / sqr(GenPF) - 1.0);
if GenPF < 0.0 then
Genkvar := -Genkvar;
end
else
begin // Someone goofed and specified 0.0 PF
GenPF := 1.0;
Genkvar := 0.0;
end;
MinLossBus := 0; // null string
MaxLossImproveFactor := -1.0e50; // Some very large neg number
MinBusPhases := 3;
{Progress meter}
ProgressCaption('AutoAdding Generators');
ProgressMax := BusIdxListSize;
ProgressCount := 0;
ProgressFormCaption(Format('Testing %d buses. Please Wait... ', [BusIdxListSize]));
ShowPctProgress(0);
for i := 1 to BusIdxListSize do
begin
Inc(ProgressCount);
BusIndex := BusIdxList^[i];
if BusIndex > 0 then
begin
TestBus := BusList.NameOfIndex(BusIndex);
// ProgressFormCaption( 'Testing bus ' + TestBus);
if ((ProgressCount mod 20) = 0) or (i = BusIdxListSize) then
begin
ProgressFormCaption(Format('Testing bus %d/%d. ', [i, BusIdxListSize]));
ShowPctProgress(Round((100 * ProgressCount) / ProgressMax));
end;
DSS.EnergyMeterClass.ResetAll;
{Get the Number of Phases at this bus and the Node Ref and add into the Aux Current Array}
{Assume either a 3-phase or 1-phase generator}
if Buses^[BusIndex].NumNodesThisBus < 3 then
Phases := 1
else
Phases := 3;
GenVA := Cmplx(1000.0 * TestGenkW / Phases, 1000.0 * Genkvar / Phases);
{ - -- - - - - - - Solution - - - - - - - - - - - - - - -}
Issolved := FALSE;
UseAuxCurrents := TRUE; // Calls InjCurrents on callback
SolveSnap;
if IsSolved then
begin
{Only do this if solution converged ELSE something might break
in meter sampling}
DSS.EnergyMeterClass.SampleAll;
LossImproveFactor := WeightedLosses;
FSWrite(Flog, Format('"%s", %-g', [TestBus, Buses^[BusIndex].kVBase * SQRT3]));
FSWrite(Flog, Format(', %-g, %-g', [kWLosses, puLossImprovement * 100.0]));
FSWrite(Flog, Format(', %-g, %-g', [kWEEN, puEENImprovement * 100.0]));
FSWriteln(Flog, Format(', %-g, %d', [LossImproveFactor, Iteration]));
if LossImproveFactor > MaxLossImproveFactor then
begin
MaxLossImproveFactor := LossImproveFactor;
MinLossBus := BusIndex;
MinBusPhases := Phases;
end;
end;
end;
if DSS.SolutionAbort then
Break;
end;
{Put Control mode back to default before inserting Generator for real}
ControlMode := CTRLSTATIC;
UseAuxCurrents := FALSE;
if MinLossBus > 0 then
with DSS.DSSExecutive do
begin
if MinBusPhases >= 3 then
kVrat := Buses^[MinLossBus].kVBase * SQRT3
else
kVrat := Buses^[MinLossBus].kVBase;
CommandString := 'New, generator.' + GetUniqueGenName +
', bus1="' + BusList.NameOfIndex(MinLossBus) +
'", phases=' + IntToStr(MinBusPhases) +
', kv=' + Format('%-g', [kVrat]) +
', kw=' + Format('%-g', [TestGenkW]) +
', ' + Format('%5.2f', [GenPF]) +
Format('! Factor = %-g (%-.3g, %-.3g)', [MaxLossImproveFactor, LossWeight, UEWeight]);
Command := CommandString; // Defines Generator
// AppEnd this command to '...AutoAddedGenerators.Txt'
AppendToFile('Generators', CommandString);
SolveSnap; // Force rebuilding of lists
end;
// Return location of added generator so that it can
// be picked up through the result string of the COM interface
DSS.GlobalResult := BusList.NameOfIndex(MinLossBus) +
Format(', %-g', [MaxLossImproveFactor]);
ProgressHide;
// note that the command that added the generator can be
// picked up from the Command property of the COM interface.
end;
CAPADD:
begin
MinLossBus := 0; // null string
MaxLossImproveFactor := -1.0e50; // Some very large number
MinBusPhases := 3;
if DSS.ActiveCircuit.PositiveSequence then
TestCapkvar := Capkvar / 3.0
else
TestCapkvar := Capkvar;
{Progress meter}
ProgressCaption('AutoAdding Capacitors');
ProgressMax := BusIdxListSize;
ProgressCount := 0;
for i := 1 to BusIdxListSize do
begin
Inc(ProgressCount);
{Make sure testbus is actually in the circuit}
BusIndex := BusIdxList^[i];
if BusIndex > 0 then
begin
TestBus := BusList.NameOfIndex(BusIndex);
ProgressFormCaption('Testing bus ' + TestBus);
ShowPctProgress(Round((100 * ProgressCount) / ProgressMax));
DSS.EnergyMeterClass.ResetAll;
{Get the Number of Phases at this bus and the Node Ref and add into the Aux Current Array}
{Assume either a 3-phase or 1-phase Capacitor}
if Buses^[BusIndex].NumNodesThisBus < 3 then
Phases := 1
else
Phases := 3;
// Apply the capacitor at the bus rating
kVrat := Buses^[BusIndex].kVBase; // L-N Base kV
Ycap := (TestCapkvar * 0.001 / Phases) / (kVRat * kVRat);
{ - -- - - - - - - Solution - - - - - - - - - - - - - - -}
Issolved := FALSE;
UseAuxCurrents := TRUE; // Calls InjCurrents on callback
SolveSnap;
if IsSolved then
begin
{Only do this if solution converged ELSE something might break
in meter sampling}
DSS.EnergyMeterClass.SampleAll;
LossImproveFactor := WeightedLosses;
FSWrite(Flog, Format('"%s", %-g', [TestBus, Buses^[BusIndex].kVBase * SQRT3]));
FSWrite(Flog, Format(', %-g, %-g', [kWLosses, puLossImprovement * 100.0]));
FSWrite(Flog, Format(', %-g, %-g', [kWEEN, puEENImprovement * 100.0]));
FSWriteln(Flog, Format(', %-g, %d', [LossImproveFactor, Iteration]));
if LossImproveFactor > MaxLossImproveFactor then
begin
MaxLossImproveFactor := LossImproveFactor;
MinLossBus := BusIndex;
MinBusPhases := Phases;
end;
end;
end;
if DSS.SolutionAbort then
Break;
end;
{Put Control mode back to default before inserting Capacitor for real}
ControlMode := CTRLSTATIC;
UseAuxCurrents := FALSE;
if MinLossBus > 0 then
with DSS.DSSExecutive do
begin
if MinBusPhases >= 3 then
kVrat := Buses^[MinLossBus].kVBase * SQRT3
else
kVrat := Buses^[MinLossBus].kVBase;
CommandString := 'New, Capacitor.' + GetUniqueCapName +
', bus1="' + BusList.NameOfIndex(MinLossBus) +
'", phases=' + IntToStr(MinBusPhases) +
', kvar=' + Format('%-g', [TestCapkvar]) +
', kv=' + Format('%-g', [kVrat]);
Command := CommandString; // Defines capacitor
// AppEnd this command to 'DSSAutoAddedCapacitors.Txt'
AppendToFile('Capacitors', CommandString);
SolveSnap; // for rebuilding of lists, etc.
end;
// Return location of added generator so that it can
// be picked up through the result string of the COM interface
DSS.GlobalResult := BusList.NameOfIndex(MinLossBus);
// note that the command that added the generator can be
// picked up from the Command property of the COM interface.
end;
end;
end;
finally
FreeAndNil(FLog);
end;
end;
procedure TAutoAdd.AddCurrents(SolveType: Integer);
{ Compute injection Currents for generator or capacitor and add into
system Currents array
}
var
BusV: Complex;
i,
Nref: Integer;
begin
case AddType of
GENADD:
with DSS.ActiveCircuit, DSS.ActiveCircuit.Solution do
begin
{For buses with voltage <> 0, add into aux current array}
for i := 1 to Phases do
begin
Nref := Buses^[BusIndex].GetRef(i);
if Nref > 0 then
begin // add in only non-ground currents
BusV := NodeV^[Nref];
if (BusV.re <> 0.0) or (BusV.im <> 0.0) then
{Current INTO the system network}
case SolveType of
NEWTONSOLVE:
Caccum(Currents^[NRef], Cnegate(Conjg(Cdiv(GenVA, BusV)))); // Terminal Current
NORMALSOLVE:
Caccum(Currents^[NRef], Conjg(Cdiv(GenVA, BusV))); // Injection Current
end;
end;
end;
end;
CAPADD:
with DSS.ActiveCircuit, DSS.ActiveCircuit.Solution do
begin
{For buses with voltage <> 0, add into aux current array}
for i := 1 to Phases do
begin
Nref := Buses^[BusIndex].GetRef(i);
if Nref > 0 then
begin
BusV := NodeV^[Nref];
if (BusV.re <> 0.0) or (BusV.im <> 0.0) then
{Current INTO the system network}
case SolveType of
NEWTONSOLVE:
Caccum(Currents^[NRef], Cmul(Cmplx(0.0, Ycap), BusV)); // Terminal Current
NORMALSOLVE:
Caccum(Currents^[NRef], Cmul(Cmplx(0.0, -Ycap), BusV)); // Injection Current
end; // Constant Y model
end;
end;
end;
end; {CASE}
end;
procedure TAutoAdd.ComputekWLosses_EEN;
var
pMeter: TEnergyMeterObj;
begin
if DSS.ActiveCircuit.EnergyMeters.Count = 0 then
begin
// No energymeters in circuit
// Just go by total system losses
kWLosses := DSS.ActiveCircuit.Losses.re * 0.001;
kWEEN := 0.0;
end
else
begin // Sum losses in energy meters and add EEN
kWLosses := 0.0;
kWEEN := 0.0;
with DSS.ActiveCircuit do
begin
pMeter := DSS.ActiveCircuit.Energymeters.First;
while pMeter <> NIL do
begin
kWLosses := kWLosses + SumSelectedRegisters(pMeter, LossRegs, NumLossRegs);
kWEEN := kWEEN + SumSelectedRegisters(pMeter, UEregs, NumUEregs);
pMeter := DSS.ActiveCircuit.EnergyMeters.Next;
end;
end;
end;
end;
procedure TAutoAdd.SetBaseLosses;
begin
ComputekWLosses_EEN;
BaseLosses := kWLosses;
BaseEEN := kWEEN;
end;
initialization
end.
| 31.798278 | 136 | 0.498298 |
c364e93a2ad20b81c26861e7114e6ba7aa51a09f | 1,460 | pas | Pascal | SH01/App/SH_SelectMarkDlgU.pas | federgraph/SudokuHelper | 331e9069232350cd5454b2fb01b82f17382e1d36 | [
"CC0-1.0"
]
| null | null | null | SH01/App/SH_SelectMarkDlgU.pas | federgraph/SudokuHelper | 331e9069232350cd5454b2fb01b82f17382e1d36 | [
"CC0-1.0"
]
| null | null | null | SH01/App/SH_SelectMarkDlgU.pas | federgraph/SudokuHelper | 331e9069232350cd5454b2fb01b82f17382e1d36 | [
"CC0-1.0"
]
| null | null | null | {!
<summary>
This unit implements a simple modal dialog to select one of the defined
stack marks from.
</summary>
<author>Dr. Peter Below</author>
<history>
Version 1.0 created 2021-11-07<p>
Last modified 2021-11-07<p>
</history>
<copyright>Copyright 2021 by Dr. Peter Below</copyright>
<licence> The code in this unit is released to the public domain without
restrictions for use or redistribution. Just leave the copyright note
above intact. The code carries no warranties whatsoever, use at your
own risk!</licence>
}
unit SH_SelectMarkDlgU;
interface
uses
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.ExtCtrls,
SH_SelectFromListDlgU,
SH.Interfaces;
type
TSelectMarkDlg = class(TSelectFromListDlg)
public
class function Execute(var aMark: string; const aSudoku: ISudokuHelper; aControl: TControl): Boolean;
property SelectedMark: string read GetSelectedValue;
end;
implementation
uses
SH.Strings;
{$R *.dfm}
class function TSelectMarkDlg.Execute(var aMark: string; const aSudoku: ISudokuHelper; aControl: TControl): Boolean;
var
Dlg: TSelectMarkDlg;
begin
Dlg:= TSelectMarkDlg.Create(nil);
try
Dlg.Caption := SSelectMarkCaption;
aSudoku.GetMarks(Dlg.ValueList.Items);
Dlg.PositionBelow(aControl);
Result := Dlg.ShowModal = mrOK;
if Result then
aMark := Dlg.SelectedMark;
finally
Dlg.Free;
end;
end;
end.
| 22.461538 | 116 | 0.739041 |
47ba842bd096505e998aef99791dca0d5ae7bb43 | 1,486 | pas | Pascal | GrijjyLogViewer/Forms/Form.Options.pas | grijjy/GrijjyCloudLogger | 29161f1288cf30d4e2b6205728a25d966232ff79 | [
"BSD-2-Clause"
]
| 85 | 2017-08-22T16:35:40.000Z | 2022-03-08T14:44:44.000Z | GrijjyLogViewer/Forms/Form.Options.pas | kevind7/GrijjyCloudLogger | 29161f1288cf30d4e2b6205728a25d966232ff79 | [
"BSD-2-Clause"
]
| 11 | 2017-08-22T21:03:56.000Z | 2021-02-05T09:50:14.000Z | GrijjyLogViewer/Forms/Form.Options.pas | kevind7/GrijjyCloudLogger | 29161f1288cf30d4e2b6205728a25d966232ff79 | [
"BSD-2-Clause"
]
| 18 | 2017-08-25T10:27:13.000Z | 2022-02-09T18:02:07.000Z | unit Form.Options;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Settings;
type
TFormOptions = class(TForm)
PanelButtons: TPanel;
ButtonOK: TButton;
ButtonCancel: TButton;
RadioGroupTimeColumn: TRadioGroup;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FSettings: TgoSettings;
public
{ Public declarations }
constructor Create(const ASettings: TgoSettings); reintroduce;
class function Execute(const ASettings: TgoSettings): Boolean; static;
end;
implementation
{$R *.dfm}
{ TFormOptions }
constructor TFormOptions.Create(const ASettings: TgoSettings);
begin
Assert(Assigned(ASettings));
inherited Create(Application);
FSettings := ASettings;
RadioGroupTimeColumn.ItemIndex := Ord(FSettings.TimeDisplay);
end;
class function TFormOptions.Execute(const ASettings: TgoSettings): Boolean;
var
Form: TFormOptions;
begin
Form := TFormOptions.Create(ASettings);
try
Result := (Form.ShowModal = mrOk);
finally
Form.Release;
end;
end;
procedure TFormOptions.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if (ModalResult = mrOk) then
FSettings.TimeDisplay := TgoTimeDisplay(RadioGroupTimeColumn.ItemIndex);
end;
end.
| 21.852941 | 77 | 0.706595 |
c30f7ecc8d1e41783d9860bc780c15348787d9bd | 819 | pas | Pascal | delphi/ExerDlp5MatrizesVetores/UnLoop2.pas | vitorebatista/my-tests | 696b2290259d8179d0b3399569dd9e77e6eaa750 | [
"MIT"
]
| null | null | null | delphi/ExerDlp5MatrizesVetores/UnLoop2.pas | vitorebatista/my-tests | 696b2290259d8179d0b3399569dd9e77e6eaa750 | [
"MIT"
]
| null | null | null | delphi/ExerDlp5MatrizesVetores/UnLoop2.pas | vitorebatista/my-tests | 696b2290259d8179d0b3399569dd9e77e6eaa750 | [
"MIT"
]
| null | null | null | unit UnLoop2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
N, I, R: Integer;
N1, I1, R1: String;
begin
ListBox1.Items.Clear;
N := StrToInt(Edit1.Text);
I := 1;
repeat
R := N * I;
Str(N:2, N1);
Str(I:2, I1);
Str(R:3, R1);
ListBox1.Items.Add(N1 + ' X ' + I1 + ' = ' + R1);
I := I + 1;
until (I > 10);
Edit1.SetFocus;
end;
end.
| 16.714286 | 76 | 0.576313 |
fc080940dacd1aa47a1fcb97266d2ffeb71d87ad | 418 | pas | Pascal | contrib/mORMot/SQLite3/Samples/36 - Simple REST Benchmark/RESTModel.pas | Razor12911/bms2xtool | 0493cf895a9dbbd9f2316a3256202bcc41d9079c | [
"MIT"
]
| 11 | 2022-01-17T22:05:37.000Z | 2022-02-23T19:18:19.000Z | contrib/mORMot/SQLite3/Samples/36 - Simple REST Benchmark/RESTModel.pas | Razor12911/xtool | 4797195ad310e8f6dc2eae8eb86fe14683f77cf0 | [
"MIT"
]
| 1 | 2022-02-17T07:17:16.000Z | 2022-02-17T07:17:16.000Z | contrib/mORMot/SQLite3/Samples/36 - Simple REST Benchmark/RESTModel.pas | Razor12911/bms2xtool | 0493cf895a9dbbd9f2316a3256202bcc41d9079c | [
"MIT"
]
| 2 | 2020-08-18T09:42:33.000Z | 2021-04-22T08:15:27.000Z | unit RESTModel;
interface
uses
SynCommons,
SynTable, // for TSynValidateText
mORMot;
type
TPerson = class(TSQLRecord) // TSQLRecord has already ID: integer primary key
private
fName: RawUTF8;
published
/// ORM will create a NAME VARCHAR(80) column
property Name: RawUTF8 index 80 read fName write fName;
end;
const
SERVER_ROOT = 'root';
SERVER_PORT = '888';
implementation
end.
| 14.413793 | 79 | 0.703349 |
fc0d270adc22ba9b66e04aee6523c7f72cfc6f6e | 364 | lpr | Pascal | examples/getMe/getMe.lpr | lgadina/fp-telegram | 3f3e557ff53792f90595a490454c9de46adeacb5 | [
"MIT"
]
| 54 | 2017-11-25T13:22:42.000Z | 2022-03-11T20:37:13.000Z | examples/getMe/getMe.lpr | lgadina/fp-telegram | 3f3e557ff53792f90595a490454c9de46adeacb5 | [
"MIT"
]
| 5 | 2019-08-25T19:56:22.000Z | 2021-12-23T09:26:39.000Z | examples/getMe/getMe.lpr | lgadina/fp-telegram | 3f3e557ff53792f90595a490454c9de46adeacb5 | [
"MIT"
]
| 14 | 2018-02-07T13:26:23.000Z | 2021-11-28T07:28:11.000Z | program getMe;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Interfaces, // this includes the LCL widgetset
Forms, getMeForm
{ you can add units after this };
{$R *.res}
begin
RequireDerivedFormResource:=True;
Application.Initialize;
Application.CreateForm(TFrmMain, FrmMain);
Application.Run;
end.
| 16.545455 | 48 | 0.706044 |
c3440b3a31cc22faefc5b538dcf40402a624bbc9 | 4,248 | dfm | Pascal | fZeeBeTestCLI.dfm | syconpmm/DelphiZeeBeClient | 9ba90bb0eae10f7bcc524a7f37b618e14297867d | [
"Apache-2.0"
]
| 4 | 2020-05-26T21:48:04.000Z | 2021-01-31T22:45:10.000Z | fZeeBeTestCLI.dfm | camunda-community-hub/DelphiZeeBeClient | 9ba90bb0eae10f7bcc524a7f37b618e14297867d | [
"Apache-2.0"
]
| 1 | 2021-02-28T22:27:15.000Z | 2021-02-28T22:27:15.000Z | fZeeBeTestCLI.dfm | camunda-community-hub/DelphiZeeBeClient | 9ba90bb0eae10f7bcc524a7f37b618e14297867d | [
"Apache-2.0"
]
| 1 | 2021-04-04T19:14:16.000Z | 2021-04-04T19:14:16.000Z | object Form1: TForm1
Left = 0
Top = 0
Caption = 'ZeeBe CLI Client'
ClientHeight = 412
ClientWidth = 770
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnClick = FormClick
OnCreate = FormCreate
DesignSize = (
770
412)
PixelsPerInch = 96
TextHeight = 13
object lblOrderID: TLabel
Left = 119
Top = 68
Width = 42
Height = 13
Caption = 'Order ID'
end
object lblAmount: TLabel
Left = 167
Top = 68
Width = 37
Height = 13
Caption = 'Amount'
end
object lblJob2: TLabel
Left = 246
Top = 139
Width = 93
Height = 13
Caption = 'ship-with-insurance'
end
object mmoCLIResults: TMemo
Left = 8
Top = 213
Width = 754
Height = 191
Anchors = [akLeft, akTop, akRight, akBottom]
Lines.Strings = (
'mmoCLIResults')
TabOrder = 0
end
object btnDeployBPMFile: TButton
Left = 8
Top = 54
Width = 105
Height = 25
Caption = 'DeployBPMFile'
TabOrder = 1
OnClick = btnDeployBPMFileClick
end
object lbledtBPMNFileFolder: TLabeledEdit
Left = 536
Top = 32
Width = 226
Height = 21
Anchors = [akLeft, akTop, akRight]
EditLabel.Width = 79
EditLabel.Height = 13
EditLabel.Caption = 'BPMN File Folder'
LabelPosition = lpLeft
TabOrder = 2
OnDblClick = lbledtBPMNFileFolderDblClick
end
object lbledtBINFolder: TLabeledEdit
Left = 536
Top = 8
Width = 226
Height = 21
Anchors = [akLeft, akTop, akRight]
EditLabel.Width = 69
EditLabel.Height = 13
EditLabel.Caption = 'BIN File Folder'
LabelPosition = lpLeft
TabOrder = 3
OnDblClick = lbledtBPMNFileFolderDblClick
end
object lbledworkFlowBPMNFile: TLabeledEdit
Left = 8
Top = 27
Width = 106
Height = 21
Anchors = [akLeft, akTop, akRight]
EditLabel.Width = 95
EditLabel.Height = 13
EditLabel.Caption = 'Workflow BPMN-File'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
ReadOnly = True
TabOrder = 4
Text = 'order-process'
OnDblClick = lbledtBPMNFileFolderDblClick
end
object btnCreateWFInstance: TButton
Left = 8
Top = 87
Width = 105
Height = 25
Caption = 'Create WF Instance'
TabOrder = 5
OnClick = btnCreateWFInstanceClick
end
object btnGetStatus: TButton
Left = 536
Top = 59
Width = 226
Height = 25
Caption = 'Status'
TabOrder = 6
OnClick = btnGetStatusClick
end
object medtOrderID: TMaskEdit
Left = 119
Top = 87
Width = 38
Height = 21
Alignment = taCenter
EditMask = '99999;1;_'
MaxLength = 5
TabOrder = 7
Text = '12345'
end
object medtAmount: TMaskEdit
Left = 167
Top = 87
Width = 35
Height = 21
Alignment = taRightJustify
EditMask = '999;1;_'
MaxLength = 3
TabOrder = 8
Text = '999'
end
object btnCreateWorker: TButton
Left = 8
Top = 134
Width = 105
Height = 25
Caption = 'Create Worker'
TabOrder = 9
OnClick = btnCreateWorkerClick
end
object lbledtJobName: TLabeledEdit
Left = 119
Top = 136
Width = 121
Height = 21
EditLabel.Width = 48
EditLabel.Height = 13
EditLabel.Caption = 'Job-Name'
TabOrder = 10
Text = 'initiate-payment'
end
object btnPublishMessage: TButton
Left = 8
Top = 182
Width = 105
Height = 25
Caption = 'Publish Message'
TabOrder = 11
OnClick = btnPublishMessageClick
end
object lbledtMessage: TLabeledEdit
Left = 119
Top = 184
Width = 121
Height = 21
EditLabel.Width = 42
EditLabel.Height = 13
EditLabel.Caption = 'Message'
TabOrder = 12
Text = 'payment-received'
end
object lbledtCorrKey: TLabeledEdit
Left = 246
Top = 184
Width = 67
Height = 21
EditLabel.Width = 18
EditLabel.Height = 13
EditLabel.Caption = 'Key'
TabOrder = 13
Text = '12345'
end
object dlgBrowseForFolder: TJvBrowseForFolderDialog
Left = 672
Top = 8
end
end
| 20.926108 | 53 | 0.628531 |
85e71757b26ff779384a4811f30db8ea9864a071 | 55,087 | dfm | Pascal | dcus/FormAbout.dfm | atkins126/GLibWMI | e719b0f8cff946675e09344aa8a4c2dac25c92de | [
"Apache-2.0"
]
| 87 | 2019-04-04T06:23:14.000Z | 2022-03-19T16:44:26.000Z | dcus/FormAbout.dfm | atkins126/GLibWMI | e719b0f8cff946675e09344aa8a4c2dac25c92de | [
"Apache-2.0"
]
| 2 | 2020-09-04T01:54:26.000Z | 2020-10-27T15:52:04.000Z | dcus/FormAbout.dfm | atkins126/GLibWMI | e719b0f8cff946675e09344aa8a4c2dac25c92de | [
"Apache-2.0"
]
| 14 | 2019-04-08T13:59:48.000Z | 2022-01-13T08:12:38.000Z | object FAbout: TFAbout
Left = 370
Top = 192
BorderStyle = bsToolWindow
Caption = 'Acerca de GLibWMI...'
ClientHeight = 389
ClientWidth = 428
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsStayOnTop
OldCreateOrder = False
Position = poScreenCenter
OnClose = FormClose
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object pnSuperior: TPanel
Left = 0
Top = 0
Width = 428
Height = 142
Align = alTop
AutoSize = True
BevelOuter = bvNone
Color = clWhite
TabOrder = 0
object imgBlog: TImage
Left = 0
Top = 64
Width = 432
Height = 78
Align = alTop
AutoSize = True
Center = True
Picture.Data = {
0A544A504547496D61676508290000FFD8FFE000104A46494600010101006000
600000FFE100704578696600004D4D002A000000080006013100020000000A00
0000560301000500000001000000600303000100000001000000005110000100
00000101000000511100040000000100000EC3511200040000000100000EC300
000000477265656E73686F7400000186A00000B18FFFDB004300080606070605
080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E27
20222C231C1C2837292C30313434341F27393D38323C2E333432FFDB00430109
09090C0B0C180D0D1832211C2132323232323232323232323232323232323232
32323232323232323232323232323232323232323232323232323232323232FF
C0001108004E01B003012200021101031101FFC4001F00000105010101010101
00000000000000000102030405060708090A0BFFC400B5100002010303020403
050504040000017D01020300041105122131410613516107227114328191A108
2342B1C11552D1F02433627282090A161718191A25262728292A343536373839
3A434445464748494A535455565758595A636465666768696A73747576777879
7A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6
B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EA
F1F2F3F4F5F6F7F8F9FAFFC4001F010003010101010101010101000000000000
0102030405060708090A0BFFC400B51100020102040403040705040400010277
000102031104052131061241510761711322328108144291A1B1C109233352F0
156272D10A162434E125F11718191A262728292A35363738393A434445464748
494A535455565758595A636465666768696A737475767778797A828384858687
88898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3
C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5E6E7E8E9EAF2F3F4F5F6F7F8
F9FAFFDA000C03010002110311003F00F12FE0DB8EDF733EFEB4A7AE739C679F
EEFF008D27F06DC76FB99F7F5A53D739CE09E7FBBFE340003CE738C91CE3EF7F
8527F06DC76FB99F7F5A377CD9CE338E7FBDFE149FC1B71DBEE7E3EB40087E67
CFDEC31E7A6DFF001A4078DF9FE1FBF8FE94EC02D9FBD86EBD36FF008D2718DD
EDF7FF00FAD400E1C37F772DFF007D7F8528FBBB71FC3F733FD68180DFDDC9FA
EEFF000A41F776E3B7DDCFF5A009072718DD8238E9B7FC69C0F1BB39C03F3E3A
7E14CCE4E3EF608E3A6DA50DFC59CF07E6F4FC28025070739DB923E6F5A70381
B718CE7E5F5FC6A2DD839CEDCE3E6EB9A50D81B718CE7E5F5FC68027073F2E33
8C7C99E9F8D3C364E7EF609E7A6DFF001AADB891B719C63E5F4FC69FBC939CE7
04F3D31401637606ECE3207CF8EBF853C1DA71F7727A75DDFE1553CC6FBD9C64
7DFC75FC29E246071C0C9E9D73FE1401681E36E3B7DCCF4FC6A4DFB8FF007B0D
F4DBFE354448DB76FB7DCFFEBD3FCE6247F160FD36FF008D005C0FC6EDDFC3F7
FF00FAD5207C1CE76E48E7AEEFF0ACFF0039B1BB776FBF8FE94F13B83F7B6E48
E71F7BFC2802F86C0DBD383F267AFE35206C9C7DEC11F2F4DBFE359A277036F4
183F2FFF005E9DF6890F19CE31C7A5006987FE2CE700FCDE9F853C3E3E6CE338
F9BD7F0ACB17326436E0719F9B1D3F0A77DAA5073BB19C7CD8EBF85303583E38
FBB9CFCBD777E3DA9E1F8DB8CE00F933D3F1AC717528E338C93C63AD2FDAA5DB
B73D87C9E9F8D0236D5F2739DD8279E9B7FC69DE6F1BB76323EFE3AFE158BF6C
9890778383D718C7F8D2FDB660376FC647DFDBFD280B1B9E66D3FDDC9FAEEFF0
A37FCBB71FC3F733FD6B145ECE1BEFEDC9F4CE68FB64FB76EEEDF771FD68B858
DC1264E3EF608E3A6DFF001A5F378DDBB3C1F9F1FD2B13EDB3938DC0E08E303E
5FF1A3EDD3FDEDE3A1F9B68FE545C0DCF37073BB6E48E7AEEFF0A512606DC632
0FC99EBF8D620BD981CEFC648E700E68179385DBBB1D7E5C75FC68B858DDF333
F2F5C63E5CE31F8D2F9B9E73BB19F9BA63FC6B0FEDB3918DD9C63E5C74A5FB74
E581DE1B19E71D28B8CDCF370376EC671F3FAFE14EF37071D324F1D777F85617
DBA71F37998C81F363FA528BD9C71BF19278C75A00DDF378DB8EDF733D3F1A77
9B96EBBB07E9B7FC6B03EDB3EDDBBBA0FBB8FEB4EFB6CE5BEFE707D318A2E2B1
BA26C8DDBBB7DFC7F4A779DB4F5DB93D7AEEFF000AC0FB74DF7BCC1D3EF63FA5
3BEDB386277E371EB8FBDFE145C2C6E89703674E0FC99FEB4E12E4E3EF608E3A
6DFF001AE7FEDB3EDDBBBB1F9703F9D3BEDB39E37038238C018A2E1637FCEE37
673807E7F4FC297CFC1CE719C7CDEBF8573FF6E9FAEF0783F36D1C7E14EFB7CF
9DDBC0CE3E6DA39A2E1637C4B8F97EEE73F2E739FC697CEFE1C6718F933D3F1A
E7C5F4E0637019CFCB81CD1F6E9F18DDE9F2E07F3A2E163A2FB412739DD8279C
636FF8D1E79C6EDDD40F9F1D7F0AE7FEDD3939DE0E09E7038A4FB7CFF7BCC1C8
FBFB7FA5170B1D179D83D76E4F4EBBBFC28F3B8D98FE1FB9FF00D7AE785FCE0F
DFC64FA67347DBAE36EDDDDBEEE07F3A2E163A3F3F27FBD86E9D36FF008D1F68
E376EE80FCF8FE95CEFDBE727EF8383D3006DA3FB42E33BBCC1D3EF6DFE945C2
C713FC1B71DBEE67DFD694F5CE738279FEEFF8D27F06DC76FB99F7F5A53D739C
E33CFF0077FC690C68E0E738CE39FEF7F850012BB00EDF73F1F5A5EF9CE32473
8FBDFE15D378034B8752F1858ADD60595A66F6E81E42C717CE727D0E00FC69AB
5F5D84EF6D0A5AA786350D2FC491E8523433EA0CD12EC89F011E40084258019F
9867B7BD55BAD22E34ED6E4D2F53922B1B885FCA9A59497588F7CF961B3F8035
D9F86BE24C9A7EBDAD5EEA735DC967A848F3BDA4304322C9267E557320C84032
3E5E7A555F1D78F7FE12BD3EC2DEDA4B886DD479F716CF6F0A451CF8C131141B
8A9CB7DF39E6A75B27FD7F5FF0076DD13EA5F09F50D16D6C6F6FFC45A0DBDB5F
C8AB6F334B39590B2E464F958518E72702B07C57E0BD67C197515AEAD0461265
2619217DD1CA063386EBC64704035EC9F11ACACAFBE19F83E3D4357834CB7CC0
5A69619242C3C9E42AA29E7BF381EF581E2DF1C683E34F137863C3D67686FB49
86E52299EE37C7E76FC27CBB486181CE4E327B63AD38BE7715DEC28BBC549F6B
9E35D4E3EF608E3A63FC6977670D9CF07E6C74FC2BD8FC73A47C3AF07F886E34
B9F41BE99E6B1125B882E9B6C121DC14FCCF93923249240C0C2F26A7B9F00F86
FC3BADF84FC3BA8E9BF6FBBD591C5DDE9B8911E262001E5AAB05C027B83C0A4B
5DBAE9F3FE90E5EEEE78B83839CE3247CDEB4A3A6DC6339F97D7F1AF63F0EFC2
AD2A2F1878A2DB56924BCB4D191248A10FB0CE1D0B2962BC8C018E3193F9550D
4343F0E49F0623F145AE816767A84D318597ED170E3EFB2E50193AF00F391C1E
293692BFA7E3B0ECEF6FEBB9E7767A2EA1A86977D7F6D6E24B4B0086E4F98ABE
586385EA72727D3355628DEE278E2894C923BED5007393C018EF5EABA47C5BB5
834DD3EDF53FB7DDDDAA15B9B91696BBED801FBBF232B86E40CEFCFB560785AE
9B5EF88573E25D5256BA874E497519E5911509118F9015500649D838AAD14B5D
BFCBFAFF0087275E5F3FEBFAFF002397D73489B40D6AEB4CBA9A0927B660924B
092C9BBB81903A743C7515D5C3F0BAFE6F0D3788E2D7745FEC900B34DBA73D0E
D395F2B775F6AE22F2F25BEBDB8BD9DF74D3B9924931F7998E4F1F535EE3A37F
C9B45EF18F966FFD1D50DB54DB7BA455939A4B66CF35D57E1FEB3A66811EB503
5A6A5A4BAF3736129744E7F8B2030FCB8E86B98CE48FE2C37D315EE9F01C0BDF
0A6BFA6DDA07B23200D1BF2B8742187E405733A0F8174F4F87B2F8A2F2DADF50
9E5B8F2ED60BBBD16B0C681F69667DE993C3606EF4E0D5B5695BA69F88A2EF1B
F9D8E43C23E13BBF196A4F61A7DED9C374B1175FB4975DE01E71B548E38EB8EB
C66B3755D3E5D1B58BCD3AE590CD6D3B42ED19255994E0E32071F857B2F83746
D1347F8CE8BE1FBFB7BCD3E7D3A4957C9B959842D900A1604E718C8CF3834CF0
D786741F13F8EFC7116B3A525C1B5BD7923944F22372CC08F9580C7CBE99E4D4
B7B7A3FC06968EFDD7E28F12070BB718E0FCBFFD7AEAF58F026A1A47852CFC46
F7B6173A7DDBA2C420793702413C8641FDD35D0D9F85F42F13FC2FD5F5BD3F4B
1A65FE992B9C25C4922CB1A80D86DE4F3827918E4760715D64BFD95FF0A5BC26
358B39AEED9AEA2510452F97B98971F337500024F1C9C01C673556D2DD6EBF12
5357D76B3FC0F15D2EC26D5F55B4B0B778C4D7328891E56DAAA49C0CFB55CF12
787EEFC2BAE4DA5DF4B6EF711052D240FBD4E467B8047E2057A1F897C15A1E85
F15F43D361D3C4BA5EA21435BCB34988C962A76B060DE87927926B17E20F828D
978DA7D3FC2FA2DE3DBC76F148E96D1C97054B6793F788CE2A5BD13EEDAFB8AB
59B4FB2FC4E73C31E1C97C51A90D36DAFECAD6EA427CA8AE99C79DC127695560
30077C7B66AC7897C19AA784F55834ED55A0449802970859A1233C9CEDDDC771
8CFB722A5F0CE9DA968DE30B58EFECAEAC27682E24449E268D88F264C30C807A
8FD2BD3BC35AC58FC59F07CFE1BD719535AB640F1CC472D8E1651EE3A30F7F7E
1EFB7416CF5EA793EBBE1D3A0C76AF26ADA75EB5C209A35B4690958D870C7722
8EDD339F6AC5CF1BB38E3EFF00FF005ABD0752F085D5F7C40D07C2F74E23996C
E28A6910E76850C588F5E01C56B6BDE0FF000BDB27886CF769FA55C69F1A9B09
DB54579AE58292CAF1973824E31F2A9E475A9BE8DFAFE0EC349BB2F4FC4E4BC3
FE02D5F5FD3BFB46292D6CEC9A758239AE9D8095D8ED0142AB1EA40CE00FC8D6
76ADE1AD4F459AFE0B985592C665B79648DF29BD816500F7C804FB77C57A8BDD
C23F6778E6FECEB6F2FCCDBE4EE93667CE2377DFDD9CF3D719ED8E2A3D7A7B2B
5F815A2CE9A2D8949E7526DF32AA0621FE6CAB862DC7726AA5A5FC9A5F7FF4C5
0D5A5DEEFEE3C733938EB8238E98ADFF000A785AEFC5FA8BD8D8DDDA4372B197
5FB4175DE01E71B548E38EB8EB5DB7853C2DE17D513408E1B4FED6FB4EEFED39
6479A2368FB32AAA54AAF5E30724F51C55DF05E8D6FE1FF8E37FA5DA176B782D
E4F2CB9C901951B1EF8CE29DBDEB3F3FC096F4BFA1E791F84B589F5CD4B4BB58
A39A7D3CB7DA6412AA46150E09DCE5401F5AC460519A33804123682083F88AF6
CF0D689A66BFE29F1DDA6A366D22477A5F725CCB1F99F33E032AB852015C8C8E
E6BC3C1C0DBD339F97D7F1A95D3D11A492526BCCD5B7D1AE6E742BCD583C4B6B
6924711576219DDB380BC72401939238A6B6937EBA347ACB420D83CC6059B7AF
DF0338DB9CF4F6AE8758BA97C3BE19F0CE9B6C7CBBCC8D5E5E01DAEC71175F45
5E9EF5D24BF15AD0C32AC0FA80BB16E4C7A89B4B6F38DC770C31B7CBC051C0DD
C537D7FAF5FD7F02574FEBFAE870DE1BF0C6A7E29BD920D395008A3F3269E53B
5235F7EA7F204D74371F0B35BB6D1E7D545EE99259C76FF6ADC9336644209E03
2820E077C5751F05AE84F6BE2367B789A631A3BCC0B6E973BF823380073D003C
FD2B2FC1FA0683E20F03F88B53BAD1208AEACC4AD0B433CC00FDD961C173D0FA
FE39A25A27E4AE38EB24BBBB1E659F976FB7DDFF00EBD59B4892EEEE3864BA86
DD4B60CD36ED89C77DA09FC81AF49D3BC3FE153F08E3F126A3A3B1B889B6B8B7
B8914CA449B40E5881BBB9038C9C638ACFF8A9E14D2BC39369171A45BBC10DDC
6C5A232170A576F20B127F8BF4A1E8C4B52BEA1F0CB50D266B28EFB5BD1A092F
495B766925C3918EFE5E0751D48EB581E21F0DEA9E15D47EC9AA422277F9A391
0EE4947A83FE4D7AD7C51B5D3EE60F0CBEA5AB45A75BC7BCB3B4523BB0C26768
45233F523AF7AC5D67C57A378F3C7FA1E9AB63F69D2D1DA02D31743217C65976
9046368C67D4E453B5DD977B05D28F33ED73C9F3C6DF63F2FF00F5E973938EB8
238F4AF4AF1669DE09F0FEB3AA685168F7725ECB02FD8CA5C36C86565E01CB67
19C31249EB8C0C568CFE0AF0E697E26D0BC2975606EE7BDB767B8BDF3E44911F
0D82801DB8CA9E083DBF14B5F983D0F25DD9E739C67E6C74FC297760E738CE3E
6F5AF4FD17E1EE9B6B7BE289757637CBA22B79502B98FCC1B0B82DB791C63A77
CD53D6B49D053E16E9FE24B3D22DAD2FAF251139F3A76C60B0CA06908FE1CF39
E0D17D2FE9F8EC349B7F7FE07156FA45F5CE9577A9C3066CAD582CCFBD7E52DC
2F04E79F6155ADA096F2E61B58577CB2BAC691FB9381CD7A5597C52B54B6B38E
FDAFA6BAF2CFDA2EC5ADB7991381F2795C60A8CB67773CF1581E14BB96F7C4FA
87897517F38E9F0BDF485942EF97A4638E012C474F4A367AEC2D5C7CCE7354B0
934BD56E6C259629A4B695A37922276823AE32013CF1D2A9EEFE2CF6FBD8FE94
92CEF713BCD23991D99999C9E727AFD69BBBF8B3D87CDFFD6A4AF6D46ED7D097
383DD727EB9A407E5DB83D3EE7FF005E981B07D327EB9A407E5DB8EDF773FD69
8897393EB83D3D28DDFC59EDF7BFFAD51EECFBE0FF00DF3FE346EFE2CF6FBDFF
00D6A00E63F836E3B7DCCFBFAD2F7CE738CF3FDDFF001A4FE0DB8EDF733EFEB4
BDF39CE33CFF0077FC6800EF9CE324738FBDFE15BFA26B96BA4786B5DB448A63
A96A30A5B46C00D91C3BB3202D9CE5B0A318AC0070739C648E71F7BFC2AF69BA
7DB5F2C8971AB5969DB00DA974B336FC939C18A37E98EF8EA3AF3474B0147A90
7EF61BAF4DBFE3525B0B76B98CDD4D2C56E7EFCD1461D947B212A09FC456D7F6
0E9AC73FF097E8A76B75F26F063FF25F9A6FF60E9BB77FFC261A2F4FBDE4DE7F
2FB3D00777E36F1F7857C51E0DD3B43B6FED9B79B4FDBE4C92DAC45652B19501
B12FCA0FA8CE3D0D79E7866F6CF4CF1269B7D7C675B6B59D67748235773B5B70
032CA39200EBC7BF4AB5FD83A686CFFC25FA28DC7FE795E73FF92FC527F6069B
8D9FF097E8B8C7DDF2AF3F9FD9E9A6D4B9BA8ACB9794DAF89FE2BD23C67E2287
56D2D6F9196258A486E6144DBB492086576CE73D30318EF9AE8FFE168685AAEA
3E1BD735AB6D47FB53458DD596DA28DA2B838C024B302BC8CFDD35C1FF006069
AC71FF00097E8A7691C7957831FF0092FCD27F60E9A46FFF0084C3453807E6F2
6F38FC3ECF4968B4F51BD773D27C07ABFF00C255E30F14F89AF3539345B97B75
F26E3936F003F2AF999C2B6D0170AE4063938E384F18783AE752F0BDC5E5A78F
74DD6EDF4988CA6C2D208A18E35EE42C4C541EBD473EB5C5E912BE80B7034EF1
D68B0C774AA93C6F6B752C7281D3723DB153F977A96F2EA4BCB17D3DFC69E1DB
7B498EE92DECF4E9ED965C74DDE5DAAEEC7BE6949696434F5BB38BEA36E338C7
CBE9F8D745A7EBD6DA7F83755D321599B50D4678D6597680890265B6839CE4B6
33C6303AD43FD83A61F93FE12ED14E31F2F9579C7E3F67A5FEC1D35B9FF84BF4
538279F26F063FF25E9F4B0BADCC4C8FBDBB1903E7C75FC2BD6ECBC7DE12B3F8
692F834B6B64CAAE0DD7D8E2EACFBB3B7CEE9DBAD79FFF006169A06FFF0084BF
451903E6F26F39FC3ECF4EFEC2D395B03C5DA2AEE3D3CABC39FF00C97E287AA6
9F505A34FB1D545F10B4EF0DF82A6F0E784ED6EC4B7418DCDF5E6D490EE183B5
54B01C74F9B8FAF3563C2BF10F4583C0D3F847C4FA7DDDD58EE26292CF6EF4CB
6EE7711C86E4119FA7AF1BFD83A6E367FC25BA2F4FBBE55E7F3FB3D3BFB0B4E6
3FF23768C76B7FCF2BC18FFC81477BF50DAD6E8753E0EF19F86FC35E306D5FEC
57D169F05A9B7B648A34925972725E562CA377D011DB8039EEBE156A167AB78C
3C6DA9D909FECD77B27513A0471B8B92080CC382719CFE5D2BC6FF00B0F4DDBB
FF00E12FD1BA7DEF26F3F97915D0681AB5E785A29A3D1BC75A15A2DC30691858
CF2349C7425AD49C7B671C9F5A2D75F27F887F9A7F71621F1B691A27C3DD47C3
5A1417EF71A948CD34B76A8A234600155DAC771C0C64E3A9381D2B4EE7C73E15
BAF02E89E1B6FED857D3678666945A44439524918F37FDA3DFB0AE36EB4BB1BC
BA92697C57A0AC9212CC915ADD469F82ADB803F01517F6169C7E5FF84B74638C
71E55E71FF0090284DEFE9F86C2697E7F8EE77DE23F88BE1AD7BC71A07881135
58A1D34E648CDB4659B0770C7EF3B9E0FA7BD62F8DFC7FFDADE276D67C35A86A
DA72CF04714C377924EDCE3EE39DC393D718AE6FFB0F4E2377FC25DA31C67E6F
26F063FF002052FF006269C3E6FF0084BB4619C73E55E73F87914ACAC976D7EF
2AFADCD3F0F7892D8EBCBA978AB52D66EDA289E2895089DD832B29F9A471B40D
D90067F0EF8D6DA93687AE477BA25DDC66D9C3C0F2C6237FF8100CC3D4119391
537F61E9A0E3FE12CD18649E3CABCE7FF2052FF61E9D8D9FF09668C7007CBE55
E7F3F229AD1DD09EAACCE8F53F88AD77F1034EF16DADA626B689126858E01214
AB807D082707F4AB1E34F1778475FB99B58D3749BE4D62E22F2E47B9D9E42F18
DFB41259C0E0741DF1915CAFF6269C4E4F8B7463B4F5F2AF063FF2051FD89A76
37FF00C25BA374FBDE4DE7F2F229595ADFD6A17D6E7687C6DE1BFF0085583C21
BB5513FDEFB47D963DA5FCCF3318F3738CF19FC71DAA03E3CD0EEFE185AF8675
1D2EEE5BDB3CB4011C2C4CDF36D666CEEE3774039C75AE53FB134E56FF0091B3
471B8FFCF2BBE7FF002051FD87A76367FC259A374FBBE55DFF003F229BD6F7EA
0B469F63D0E0F89DE1AB7B2F0CC70E8F7EB3690E0BC71BA244094DAEC39CB9E4
919DBC939350D9FC44F0D41F136F3C59F67D51609ADFCB11848D999B001246E1
B461471F3679E474AE0FFB134E271FF095E8E7691C79577C7FE40A51A2E9C46F
FF0084B74738046EF26EFF0097914EFADFFAD456D2C7A0F877E23786B42D7FC4
9A93A6AB22EAF3878D45B46360E4F3FBDEB9623E801EF81E6117D8D3504591A6
6B2F37E6C20123479E4E3380D8ED9EBDEAFF00F62E9C3E6FF84B34719C73E55D
F3FF009028FEC4D387C9FF00095E8E339F97CABBE7F1F2292D1A7D8A6EF7BF51
DE28D687883C4779A8468C90C8E0430B70638D46D41C719C01591BB2739CE33C
E3A56B7F6269E7E5FF0084AF4738C71E55DF1F8F9147F62E9C7E6FF84AF47382
79F2AEF8FF00C81492B08EB7E1C78D743F075AEA2DA80D4269AF422E20810AA8
5DD8392E0927774C0E9DEA7F0A78CFC35E1CF0C6B3A2CADAACA751322ACAB6B1
8DAA536838F37AE39C67FC6B8CFEC6D380DDFF00095E8FC81F379577FCBC8A5F
EC5D394E3FE12AD1C6E278F2AEF9FF00C814DEBBFA02D1A6BA6A75F0F8C3C39F
F0ABC784253AA09891234C96D1950DE66FC01E68C8ED9E3E9DAA4F1D78CFC39E
315D1E38CEAB6E9625965636B1B12A5472079A39CA8E3DCFA60F19FD89A76367
FC255A3E31F77CABBFE7E453BFB174F27FE46AD20ED3FF003CAEF8FF00C81402
D363B2F881E37F0E78BF49B28ED7FB56DEE2C55BCA32DBC651F200C1C4991F74
7383F4AE4BC25AA5968BE29B2D4EFCDC082DE5126208D5DA420703058003DEA1
FEC6D3F6EFFF0084AF48E9F7BCABBFE5E454577A6D9DADBBCD178834DB97C8C4
30C771BDFB71BE2551EBC91D285A3BA06AF1E57B1B5E3AF10E9FE21F143EB1A5
B5E466555DD15C44A8519400082ACD9E99ED5D41F893A2DFEB9A4788751B4BE1
AB69D0346D040886295882036F2C0A8F989C60F5F6E7CA437CBB718E0FC99FEB
4BBB3C75C638E98A168AC81BBBBB3D77C0DA81D7F54F13F882EF576D26EA5501
2E5D7FD1A20C48C3862118800001BD73CF687C5FE18B8BAF0E49AA5BF8D2C759
834C4506DEDA28E38E24271F2AC6C541FC0671ED5E79A5F89354D1EDEE21B2BB
02DEE06268E489248DF1D328E083F5C52DE789753BDB26B39278A1B5665668ED
ADA3812423A6E58D573F8D29256B21C5EB7650CE323819CF1EB5B906B36D6BE0
CBBD2218E5FB6DE5CC6F3B606CF25065541CE73B8E7A76AE7B776C6339E3D68D
DF2EDC6781F27A7E34FA5844DBB273D704F3D3146FFE2CF6FBD8FE9516EC9CE7
38279F4A377F167B0F9FFF00AD401306C37F7727EB9FF0A4CFCBB71DBEE7FF00
5EA30D86FEEE4FD775267E5DBB7B7DDCFF005A009B39E3AE0FD31FE346EFE2CF
63F37FF5AA2DD93EB83D3A6DFF001A4DFF00C59EDF7FFF00AD40185FC1B71DBE
E67DFD697BE739C679FEEFF8D27F06DC76FB99F7F5A5EF9CE719E7FBBFE34000
3839CE324738FBDFE1428E898FF807E3EB403839CE324738FBDFE1498F936E3B
7DCCFBFAD38BB3B81EDBA8E911C1E26B361A79B55B6F115B7D9DE5D1A2B05319
908D90BA1CCE3EE9CB01C2E6B8BB4F0959DDE931DE343A8BACD6D34F2EAD1BA8
B4B4752F88A45D87E63B57ABA9FDE0C03C6787EA73F7B0DD7A6DFF001A4CFF00
167B7DFC7F4A9B696FEB61A76FEBD7FCCEEAF7C1D6969E1BBCBF5B1D5BF73696
F731EA4CE3ECB72D218F28ABE5F6DE47DF272A781D056F04F852DBC476D75E7D
A6A333C6CA88B0798910CE73BA54826C1E9C30500739F4C2935FBF7D33FB3435
B436CDB55FC8B48A37982F203BA286619E7E627900F51597FC1B718F97EE7FF5
E9F562E88EE6CFC1D6571A4433BDBEA2E92412CD26A514C86D2C9D37E2293087
737C8BCEF5CF98B8078DDA1ACF87EDAFB49B5D42E6C753B6F2B47B568F526907
D9A57DB1AF94AA63196209E8E7A138C671E6FD4E3EF608E3A6DFF1A339C36738
07E7C74FC29FF5F9FF009FF9DC3FAFCBFCBFCAC7A458F82B41BFD7359B5B6FED
23FD9D38B716E2669269B0CC0CBFBAB690AA8DA0636756FBE3807953A1DAA78E
93415967FB23DFADBE5A368E4285C0C90EA0AB60F7039ED5839C1CEEDB923E6C
673535A5D4D61790DCDB37953C320963E037CCA720F3C751DE92DD360F6763BC
9BC19A4C3247F6CB0D6B4E082E99AC6EA74F3A54862DEB22318976A9236E4AB0
F43C1155ED7C29A6DF69715EC56BAA9B79A09E73A90991ADEC4AEFDB14BFBB1B
9BE55C9DC99DE30BD33C3C8ED33B339DCCCDB8AF4E4F7A6F539FBD8279E9B7FC
696B61BB5F43BCB8F06DA41A0DC5EFD8F56FDDDA5B4E9AA961F65B8691A30515
7CBEC1C8FBE4E54F03A0B9A7F82B49D47C43AC595B596A6D6BA7DC7D99985DB3
C8EFB986FDB15AC84290BDC000FF0011CE071327883507D27FB3C3DB456A5555
DE0B38A279429E03BAA86719E7E627900F5159DD188FBB93D3AEEFF0AABAB93D
2C77D6BE13D0E2BF5D3AF97509DA6D6E4D2A3786E52208AA500720C6C58FCD9C
6474A86CBC35A56B33694FA75BDFF9735D5C4134135D82FF00BA8D1F7232424F
21FEE8473C715C363E4DB8FE1FB99FEB4ECE48FE2DADF4DBFE34969B8DFF005F
8FFC0FBBCCF48BDF01D8DA6AD2451DAEAD76C34E5BA8EC2062B72EC652840DF0
2B6001B8FEEB3CFA7CD50D8F87E232D84C9697CF710DA3DD47A742917DA6575B
A78F667CA3B8A81B9B7231C291803EEF9EE7F8B3DBEFE3FA53812A49CEDC91CF
5DDFE142D3FAF507A9DDDFE87A4DACBAADEEA8355B86436CEF6DF6A449E39260
CCEB2B98DB2CA57D07B81DB165D06D93C772787DAED96DA3D43ECBE73819550E
5413D0135CE8FBBB718C83F267AFE34EEBC75C11F2FA7E342D1A07A9E9D2F86E
DAEADFC3FA65D596A7A2C4F717AFE5EA0C5A6908488855C440FCC46D184639E8
1BA5733E32D02D7C3D7D6A96DF6B8BCE877BA5D4528653B88E0C90C458118E42
0C7239AE5F7670D9CE01F9B1D3F0A5DD83BB76338F9B1D7F0A1F419E9F16925E
D1E3B5B089343FECDF363BD1A447731CAFE49690CB724878983E40C1E0803007
5A773E07D2E1F0AADFC73DECCFF678A51711C73340CCC57299106C5C64AE7CE3
CAF206703CF46471F7724FCBD7349FC3B719C01F27A7E34EFADC477379A3F86E
D2E35B636DAB4D0E977696807DBA356762D202F9F24803083E5C1EFC9A92F7C2
DA4B5FDD5A69CB7C27B3D5A2D3DDAE2E936CE1CC8323118D87F77FED75E9DAB8
4CE4E73BB04F3D36FF008D1BBF8B3DBEFF00AFE1497F5F87FC1FBC19EA3AD785
6DA3BDD02DAEE4D463B3686E945BB165655890C9F2992DE2C6E2C724A1FA9EDC
4EB965636B069B71A725CC705F5A99BC8B895646422474237AAA823E4CF41D6B
141C37F7727EBBBFC2907DCDB8EDF73FFAF47F5F98CF51D474517165A3C1FD9D
A88B29E0B2DCD69E1E8B692D1A162B74BFBC662739E0F391838E5BFF0008AE9F
A7DE6A566745D46EA4934BF3A08967267C89D012AAF6C8EA719E767DD0DC9CF1
E65D4E3EF608E3FBBFE346EFE2CE783F37A7E143D5BF989696F2B7E07A5DCF86
ED34FF0003CB3C5797D25BC890DD4B2C11CA629DF8F90916FB176EE65C99480C
3EE82481463F07E92358B2D3E4BF9156F8CB736FF38264B6D99887CAACC24739
5E01C11C2B640AE0F386CE71923E6F5A3381B7A673F2FAFE34FADC3A58F4BFF8
40ACCEBA9651E9DACDC402D84F3C6A648DADC062BB817B50D283C602C60E73CE
0135C6EA76B6969E229AD5E2D4ACACE3948C5D420DCC49DB727CA0B639C7039E
BDEB1F391B7AE31F2FA7E3467273BB38CF3E9480EE345B7D1E4D1353846268EE
6EE0B6B7BEB9B758E48D99242A782DB177AA8386E5735BFF00F084695A86B1AB
33FDA14A6A1242D6D611487ECCA31862B1C12F5C9C0253EE9C13CE3CA777F167
1903E7C75FC2943738FBB9278EB9A1EAEFFD7403D3F4B5D39B4FD0F446B2BEBA
8E5B5BE94DB25C0093CAA265561198CFEF3E5014F2471C1C7356DBC0F6F73E1E
BAD426B4BFB69628AE2642F2BB88FCBDD84702DC206F97041914F7C0E0579CE7
E4DB8EDF73FF00AF4EDD96FEF60FD36FF8D0F543BEA77DAA845D36E6792F2E2D
E17B7D2609DA18D5CB46D6C58FCA704E0A29C6E00F7E831C6DD7D963BB716734
D25B9236C93442367E39CA866039F7354F771BB77F0FDFC7F4A50D86273B7247
3D777F850F577174B120381B718E0FC9FF00D7A339E3EF608E3A6DFF001A8B3F
2EDF63F27FF5E9739E3EF631C74DB4012EECFCD9CE01F9B1D3F0A5DF839CE338
F9BD7F0A8776486CE783F37A7E14BBF0776EC671F37AFE14012EEC6474CE7E5F
5A33F2EDEB803E5F4FC6A2DD8C8E9927E5F5A33F2EDC67007C99E9F8D004DBB2
73F7B04F3FDDA4DDFC59EA07CFEBF8547BB2D9EB8279E9B7FC68DDFC5BBB0F9F
1D7F0A0098361BFBB93F5CFF0085373F2EDC76FB99FEB4CDD86EBB727FEFAFF0
A4CFCBB71DBEE7FF005E8026CE4E3AE0F4E9B7FC68DDFC5BB3C1F9F1FD2A2DD9
3FDEC1E9D36FF8D26FFE2CF63F3FFF005A80333F836E3B7DCCFBFAD2F7CE738C
F3FDDFF1A6E47919C7CBFDDFC7D69C73BD413927383E940003839CE324738FBD
FE1498F936E3B7DCCFBFAD397264600E181193EB4CC8F2338F97FBBF8FAD003B
A9CFDEC375E9B7FC6933FC59EDF7F1FD29CDC32679C9F94FA5260F99B73F3EDF
BDFF00D6A003A37A65BFEFAFF0A4FE0DB8C7CBF73FFAF4E5E59B1C61BE6F7A60
23C8DC3EE60FCBF8FAD003BA9C7DEC11C74DBFE3467386CE700FCF8E9F850DC0
5279048DA3D2839122A93962A70DE940067073BB6E48F9B19CD1D06DC6DCE7E4
F5FC6957264600E1811938EB4D5FF56C470A09CAFAFE3400751B719C63E4F4FC
697A9CFDEC13CF4DBFE3487FD52B1E54E30BE94ADC3A83CB1CE0FA500267F8B3
8C81F3E3AFE14BD091F7727A75DDFE140CF98403F36065BD7F0A179DE4700372
3D68013F876E3F87EE7FF5E9D9CB0FE2C30F6DBFE34CFF00977DD8F931F77F1F
5A7370C9BB9C918F6A0033C6ECF6FBF8FE94E07049CEDC91CF5DDFE14DE7CDDB
9F9F6FDEFF00EB52AF2EE01C10793EB400A0FCBB718E0FC9EBF8D2E7381D7047
CBE94C18F24B01F2E0FCBFFD7A09F9149E549181E9400FDD9C36ECE01F9B1D3F
0A5CE0EEDD8CE3E6C75FC29A721D4139620E1B1D2819F31941C30032DEB400EE
9C7DDC93F2F5DD47F0EDC7403E4F4FC69AA728CC38504E47AD191E486C7C9818
5F4FC68024CE4E73BB07AF4DBFE349BB8DD9FE1FBF8FE94370EA0F249E0FA527
3E6EDCFCFB7EF7FF005A801E386FEEE5BEBBBFC293F876E3B7DCCFF5A13967DB
F2E1B9EF9A6023C8DDFC18FBBF8FAD004B9C9C7DEC11C74DBFE3499FE2CE783F
3E3FA52371B777209181E941CF98149CBE0E1B1FD2801C0E0E73B72473D77500
E06DC6339F97D7F1A45C9918038208C9F5A45398891C2F395F5A007E7236E338
C7CBE9F8D2EEC9CE738CFCD8E951B1C4618F2A7185F4A56243A83C939C1F4A00
7EEFE2DD8C81F3E3AFE14B9C1C74C93C7F7A9832642A0E180196F5FC285390C5
78009C8F5A0077F0EDC76FB9FF00D7A5CE5BAE707E9B7FC6A3CFEE3763E4C7DD
FF00EBD389C32E79C9E3DA801D9FE2CFF0FDFC7F4A5070C79DB9239EBBBFC299
CF99B73F36DFBDFF00D6A5524BBE0E30793EB400EFE1DBEC7E4FFEBD2E7381F7
B0471D315103FB92D8F9707E5FFEBD2B1C2A93C824607A50049BB3F36738CFCD
8E9F851BB0739C671F363AFE14C390EA09CB1070DE94A33BD8038618C9C75A00
7E7191D324F1EB499E36F5C01F2FA7E34C53946238009C8F5A09C421B1F29C61
7D28024DD939CEEC13CFA51BBF8B3D87CFEBF85309F9D4139249C1F4A5E7CC23
3F3607CDEBF85003F761BFBB93FF007D5267E5DB8EDF73FF00AF4D53F33E38C3
73DF34DDDFB8DDFC38FBBFFD7A009739FF006B07A74DBFE349BBF8B7763F3E3F
A5358E366EE41231ED464F98173F36D3F37FF5A803FFD9}
Proportional = True
ExplicitWidth = 428
end
object pnlSuperior: TPanel
Left = 0
Top = 0
Width = 428
Height = 64
Align = alTop
TabOrder = 0
DesignSize = (
428
64)
object lblLibreria: TLabel
Left = 99
Top = 18
Width = 204
Height = 23
Anchors = [akLeft, akTop, akRight]
Caption = 'Componentes GLibWMI'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -16
Font.Name = 'Arial Black'
Font.Style = [fsBold]
ParentFont = False
end
object lbVersion: TLabel
Left = 324
Top = 39
Width = 82
Height = 16
Alignment = taCenter
Anchors = [akRight, akBottom]
Caption = ' [versi'#243'n] '
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'MS Sans Serif'
Font.Style = [fsBold]
ParentFont = False
end
object imgLogo: TImage
Left = 10
Top = 6
Width = 58
Height = 52
Picture.Data = {
07544269746D617036070000424D360700000000000076000000280000003C00
0000360000000100040000000000C00600000000000000000000100000000000
0000000000000000800000800000008080008000000080008000808000008080
8000C0C0C0000000FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFF
FF00FFFFFFFFFFFFFFFFFFFFFFFF8F8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
0000FFF8F88888787878888877FFFFFFFFFFFF78888887877787887887878887
0000FFF8F00000787007700007FFF7787FF8F780000000000000000000000000
0000FF8FFFFFFFF800FF87FF8FF787880FFF8787FFFF8FFFFFFF8FFFFFFFF8FF
0000FFFF88FF8FF80FFF8FFF7F8800F77F8FFF8877FFFFFFF8FF88F8FFFFF8FF
0000FF888FFF8FF870087788FF70FFF77FFF8FF877FFFFFFFFFFFFFFFFFFFFFF
0000FF8FFF8FFFF8000F877887777F8778FFFFFF888878888788888788878887
000088FFFFFFFFF807FF70FF7780FF880FFFFFFF870000000000000000000008
0000FFFFF888FFF807F870F88808FF870FFF8FF870FF8FFFFFF8FFFFFFFFFFF8
0000FFFFFFF8FFF78F870FF7808F7700FFF8FFFFFFFFF88FFFF8FF8FFF8F8FFF
0000FFFFFFFFF8F77770FF8807FF870FFF88FFFFFFFFFFFFFF8FFFFFFFFFF8F8
0000FFF8FF8FFFF7880FFF707FF700FFFFFFFF88787878FFFFFFFF88787887FF
0000FF88FFFF8FF800FF8708FF808FFFFFF8F700000077888877877F0007788F
0000FF8FFFFFFF7807F7808FF87088FFFFF8F0007707F8888788788807087808
00008FFFFFFFF870FFF707FF770FF8FFFFFFFFFF8FFFF70000778F70FFFF870F
0000FFFFFFFFF780F7708FF770F8FFFFF8FFFFFFFFF87078FFFFFF878F88808F
0000FFFF8888F87F7F7FFF870F8FF8FFFFF8FF8FFF800FF80F788888FF8870FF
0000FFFFFFFFF80F00077800F8FFFFFFF8FFFFFFF887F7F0FF700007888808FF
0000FFF8F8FFF80FFFFF007FFFFFFFFF8FFFFFFFFF880F0FF70F8F87070088FF
0000FFFFFFFFF808F8F808FFFFF88FFFF8FF88F88F8877FF7088FFFFFFF8F8FF
00008F8F8FFF880FF8F70FFFFFFFFFFFFFFFFFFF8FF888F800F8F8FFFF88F8FF
0000FF8FFFFF8808FFF80FF8FF8F8F8FFF8FF8FFFFF8F78708FF8FF8F8FFFF8F
0000F8F8FF8700F8F8F80F8FF8FFFFF8F8FFFF8FF88FF070FF8FFFFFF8FF8FF8
0000F8FFF777FFF8FFF80FFFF8F8FFFF8FFF8FFF8FFFFFFFF8FFFFFFFF88FFFF
000088FF78887878878708FFFF8F8FFFFFFFFFFFF888FFF80F88F8FFFF7FFFFF
0000FFFFF000000000808FF8FFF88F7FFFFF80F8FFFFFFF808FFFFFFF7000FFF
0000FFFFF07F7700007088FFFFFFFF8FFFFF70FFFFFFF8F80FF8FF8FF700FFFF
0000F8FFFFFFF7FFFFFFFFF8FF8F8FFFFFFF70F8F8FFFFF808FFFFFFF8078FF8
0000FFFF88FF78F8FFF80FFFFFFFFFF8FFFF80FF88FFFFF80FFF8FFFF7078FF8
0000FFFFFFFF780F88F7088FFF8FFFFFFF8F708FFF8FFFF70F8F8FFFF800FFF8
0000FF8FFFFF87FFFFF80FFF8FFF8F88FFFF80FFF8FFF8880FFFFFFFF807FFF8
0000FFFFF87880FFF88808FF8FF8FFFFFF8870F8FFFF77880F8F8FFFF8078FF0
0000FFFF808F80F880770FFFF8FFF8FF777780FF8FF880F70FFFFF8FF700FFF8
0000FFF780FF87F880F70F8FF8FFFFFF780880F8FFF770F708FFFFFF8800FFF8
0000FF8707FF87F800F808FFFFFFFFF7008F80FFFF707FF70FFFFFFF77088FF8
0000FFF87FFF80F807F80FFF8FFFFFF80F8F70FFF78088F80FFFFFFF887FFFFF
0000FFF87FFF70F707F70FFFFF8F88F80FFF70FFFF80FFF80FFFFFFF88FFFFF8
0000FFF80FFF87F780F70FFFFFFFFFF8088F80F88F80FFF808F888888877788F
0000FFF70FFF87F880F80FFFFF8F8FF77FFF80FFFF70FFF808F70008787007F8
0000FFF80FFF708F80F80F88F8FFF8F878FF808F8F887FF80FFF8FFF8800FFFF
0000FFF80FFF808F80F80F88FFFFF8F808FF808F8F870FF80FFFFFFF8878FFFF
00008FFF8FF770FF77F808F8F8FF8FF70F8F70FFFF877FF808FFF8FF8780FFFF
0000FFFF7F8808FF88F80FFFFFFFFFF80FFF80FFFFF708F80FFFFFF80F70FFFF
0000FFFF88008FFF88870FF8FFF8FFF70FFF8088F8F80FF80FFFFFF80F880FF8
0000FF8F8707FFFF78707FFFFFFFFFF808FF70FFFFF87FF80FF8F8F80F8888FF
0000FFFF808FFF8F8008FFFFFF8FFFF880FF70FFFFF80FF808FFFFF80F780F8F
0000FF8F08FFFFF8888FFFFFF8FF88FF808F80F8FFF70FF808FFFFF70F870FF8
0000888F8FFFFF8FFFFFFFFFFFF7788F80FF80FFFFF80FF808FFFFF87F8888F8
0000FFFFF7FF87FFF88FFF877F888FFFF7FF8088FFF70FF80FF8F8F80F8880FF
0000FFFFFFF877877777F788887880FF87FF70FFFFF8887078FFFFF80F8F70FF
0000088F878778878887F77F877F00FF8F8708FFFFF77707FFFFFF808F8F08FF
0000FF808870FF70077880FF707707FF88707FF8FFF8708FFFFF8877F8FFFFFF
0000FF87F000F700FF8870FF7FFFFFF770078FF8FFF80F8F8FFFF88FFFFF88FF
0000F8FFFF78FFF8FF8FF7FFFFFFFF8FF8FFFFF8FFFF8FFF8FFF8FFFF8FF8FFF
0000}
Proportional = True
Stretch = True
Transparent = True
end
end
end
object pnlInfo: TPanel
Left = 0
Top = 142
Width = 428
Height = 247
Align = alClient
TabOrder = 1
DesignSize = (
428
247)
object lblMail: TLabel
Left = 16
Top = 206
Width = 119
Height = 13
Cursor = crHandPoint
Hint = 'german_ral@hotmail.com'
Anchors = [akLeft, akBottom]
Caption = 'german_ral@hotmail.com'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = [fsUnderline]
ParentFont = False
ParentShowHint = False
ShowHint = True
OnClick = lblMailClick
end
object lblWeb: TLabel
Left = 16
Top = 221
Width = 138
Height = 13
Cursor = crHandPoint
Anchors = [akLeft, akBottom]
Caption = 'http://neftali.clubdelphi.com/'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = [fsUnderline]
ParentFont = False
OnClick = lblWebClick
end
object imgBuildwith: TImage
Left = 10
Top = 103
Width = 231
Height = 74
Picture.Data = {
0A544A504547496D616765CC240000FFD8FFE000104A46494600010101006000
600000FFE100704578696600004D4D002A000000080006013100020000000A00
0000560301000500000001000000600303000100000001000000005110000100
00000101000000511100040000000100000EC3511200040000000100000EC300
000000477265656E73686F7400000186A00000B18FFFDB004300080606070605
080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E27
20222C231C1C2837292C30313434341F27393D38323C2E333432FFDB00430109
09090C0B0C180D0D1832211C2132323232323232323232323232323232323232
32323232323232323232323232323232323232323232323232323232323232FF
C00011080075017E03012200021101031101FFC4001F00000105010101010101
00000000000000000102030405060708090A0BFFC400B5100002010303020403
050504040000017D01020300041105122131410613516107227114328191A108
2342B1C11552D1F02433627282090A161718191A25262728292A343536373839
3A434445464748494A535455565758595A636465666768696A73747576777879
7A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6
B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EA
F1F2F3F4F5F6F7F8F9FAFFC4001F010003010101010101010101000000000000
0102030405060708090A0BFFC400B51100020102040403040705040400010277
000102031104052131061241510761711322328108144291A1B1C109233352F0
156272D10A162434E125F11718191A262728292A35363738393A434445464748
494A535455565758595A636465666768696A737475767778797A828384858687
88898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3
C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5E6E7E8E9EAF2F3F4F5F6F7F8
F9FAFFDA000C03010002110311003F00F69D374DB09B4AB3965B1B6791E04666
68949625464938AB5FD91A6FFD03AD3FEFC2FF00851A47FC816C7FEBDE3FFD04
55CA00A7FD91A6FF00D03AD3FEFC2FF851FD91A6FF00D03AD3FEFC2FF855CA28
029FF6469BFF0040EB4FFBF0BFE147F6469BFF0040EB4FFBF0BFE15728A00A7F
D91A6FFD03AD3FEFC2FF00851FD91A6FFD03AD3FEFC2FF00855CA28029FF0064
69BFF40EB4FF00BF0BFE147F6469BFF40EB4FF00BF0BFE15728A00A7FD91A6FF
00D03AD3FEFC2FF851FD91A6FF00D03AD3FEFC2FF855CA28029FF6469BFF0040
EB4FFBF0BFE147F6469BFF0040EB4FFBF0BFE15728A00A7FD91A6FFD03AD3FEF
C2FF00851FD91A6FFD03AD3FEFC2FF00855CA28029FF006469BFF40EB4FF00BF
0BFE147F6469BFF40EB4FF00BF0BFE15728A00A7FD91A6FF00D03AD3FEFC2FF8
51FD91A6FF00D03AD3FEFC2FF855CA28029FF6469BFF0040EB4FFBF0BFE147F6
469BFF0040EB4FFBF0BFE15728A00A7FD91A6FFD03AD3FEFC2FF00851FD91A6F
FD03AD3FEFC2FF00855CA28029FF006469BFF40EB4FF00BF0BFE147F6469BFF4
0EB4FF00BF0BFE15728A00A7FD91A6FF00D03AD3FEFC2FF851FD91A6FF00D03A
D3FEFC2FF855A92448A3692460A8A0B33138000EA6BCC2EBC69E27F13DECF078
42C4AD9C2DB4DCBA8CB7BE5B81F4E4D6752A286E76E0F015716DB8B4A2B76DD9
2F99E8BFD91A6FFD03AD3FEFC2FF00851FD91A6FFD03AD3FEFC2FF008579A7FC
24BE3CF0A94B9F10590BBD3B7012380B95CFFB4BD0FD463B57503E28F82B76C9
3C416B0C9B37B473654AF19C1C8EB8EDF9510AAA6EDB3F32B199755C2C54DB52
8BD9C5DD5FB7A9D1FF006469BFF40EB4FF00BF0BFE147F6469BFF40EB4FF00BF
0BFE15CFC5F137C153584D7A9E23B2F22160AE598AB02738C29193D0F41DAB9A
F881F1322B7F87EDAEF83B56B5B8923BC8E077081F682189055871D076AD0E03
D17FB234DFFA075A7FDF85FF000A3FB234DFFA075A7FDF85FF000AF37F027C5E
D1AF3C2B63278A35FB2875899DC488576003790B9C0C2F18EB8F5AEE35BF1978
73C38B0B6AFAC5ADAF9EBBA20CF92EBEA00C923DFA500687F6469BFF0040EB4F
FBF0BFE147F6469BFF0040EB4FFBF0BFE158FA4F8FFC29AEC9345A6EB96B7124
51995D0121B6819240201207B551FF0085AFE04085FF00E125B3C0207F1679CF
6C67B50074DFD91A6FFD03AD3FEFC2FF00851FD91A6FFD03AD3FEFC2FF008561
6A5F123C1DA45C2DBDEF882CE398A07D8AC5C80464676838C820F3EB5A16BE2C
F0FDEE892EB36DAC59C9A6C5FEB6E04A02C678E1B3D0F2383CF22802EFF6469B
FF0040EB4FFBF0BFE147F6469BFF0040EB4FFBF0BFE15CCC5F15FC092CCB12F8
96CC3336D05F728FC491803DEB575CF19F873C3420FED8D5EDAD4CE3744ACC58
B8F50064E3DFA50068FF006469BFF40EB4FF00BF0BFE147F6469BFF40EB4FF00
BF0BFE15E2D61F15F59D53E33C3A1D86A36D71A04D75B2331C4A7726CCF0DD7A
D7A56A3F12FC19A55F496779E21B34B88CE1D1497DA7D0950467DA8037FF00B2
34DFFA075A7FDF85FF000A3FB234DFFA075A7FDF85FF000ACABDF1D785B4FD36
D751B9D72CD6CEECB082757DCB215EA015CF22A1B1F88BE0FD4AE64B7B4F1059
48F144667F9CAAAA01924B1C0E075E78A00DBFEC8D37FE81D69FF7E17FC28FEC
8D37FE81D69FF7E17FC2B9EB5F89FE09BCBD4B383C4764D33B6D50CC5413E9B8
803F5AD9D135FB2F1043752D90982DB5CBDB49E6C657E65C671EDCD0058FEC8D
37FE81D69FF7E17FC2B07C5B6B6F63A54525A5BC3048670A5A28C29236B71C57
555CD78DFF00E40B0FFD7C2FFE82D401B3A47FC816C7FEBDE3FF00D0455CAA7A
47FC816C7FEBDE3FFD0455CA0028A2A2B9664B499D4E1951883E8714012D15F3
B68FE23F1B5F78066F15BFC46B6B79A01230B09ED6125F69C019EB93DBE5AEBB
C57E34F10C5F0A7C39AF4321D3752BDB8816E0246304306CE030380700FAF340
1EB745715F15759D4740F8777FA969774D6D79118F64AAAA48CB8078208E958B
E20F136B369AFF00C3A82DEFDD22D51945EA845FDF6550F3C71D4F4C75A00F4F
A2BCFB43D7F55BAF8CFE22D127BC67D36D6CA3961B72AB8463B32738CF73DFBD
61FC505F1CF8734ED5BC4FA7F8C3C9D3E178FCAB05B44254332A637907B9CD00
7AED15C5F81F48F16599FB6EBFE291AB5BDC5BAB4707D9562F2D8E0E723AF1C5
50F8ADAF6B1E158343D72C2F1E2D3E1BE58F518422B09226C727233C6D238FEF
5007A1D15E3DF15FC7BAE683E23D36DB4095FECF6508BFD5163453BA1322A804
90719E7A73F356E78A3C4DA8DD78DFC1DA16817E614BE3F6EBC74556DD6C39C7
2380D86008A00F45A2BCBB49BFF13F89B52F1D69369AFB594D67A8245653B408
E204C924018E720639AE7AD2DFE245D78F6FBC2C3C7DB5ED2D12E4DC7D823218
31031B71EFEB401EE5457976A1E21D6740F89DE0CD0B50D715ACE6D3A43A848E
A8893CAB1C9F39247CB9650700D5CF1A78BA5B7F13783ED345D621315E6A1E55
DA40E926F4F9783D48EFD31401E8B45145001451450014514500145145006078
DCC83C13AB98B3BBECCDD3D3BFE99ACFF010B74F875646DCB0CC4E64308CBEFC
9CE07396F4FC2BAC9A18EE209219903C52294753D083C115E5EFE1DF18782EEA
7FF8461C5E6992B6E103E18A1FF74E39F7079EF5CF52F19F3DAEAD63DAC0FB3C
46165847351973292BE89E96B5FF0023AD17368FE159A195754BBB592290192F
2DD8B9073F7815071EE474AF9CB41D034DF12FC50D0749D451A4B6B8490CE8AE
54B0547703239192BDABD75ED3E2178BE3FB0EA2B1E9960FFEB9B6842C3D3192
C7E9C0AEA748F86BE18D1758B5D5ED6C5BFB46D9484B869589E54A938CE3904F
6EF4A9DE7352B59246B8DF6786C2CA873294A724F477492BF5B25777E87CD5F0
F7C2BA5F88BC73A8695A84723DAC36D73246A921521978539F6CD62694CDFF00
083F889327699AD091EE0C98FE66BEB3D23E1CF85F42D525D4B4ED3BC9BB951E
3793CD7390FF007BA9AA317C22F04C36571691E91882E0A1957CF7F98AE76F7F
735D27807CC9776FE145F86361716F2B1F14B5F32DC26F6E21C363E5E98FB9CF
5C935336AD637D1E8360FA3472EAB045144D77AA5DB2425776E452BB8011852B
C92320FE7F48B7C1AF01B4B6F21D09018060012B80DCE7E619F9BF1ABBAFFC30
F08789678A7D47478CCB146225685DA2F900C01F291C01C0A00F99F400F6FF00
15E151269E58492296D30836FCC4C08423823923F3AD5F839E0BD2FC617BAD7F
69DBB5C1B3B50F6F1872A3CC24E09C75E9D0F1CD7BE27C24F04C37515CC1A32C
1344A02B4333A1F4EC7AFAD69F86BC0BE1EF08CF71368961F667B850B29F319B
700491D4FBD007CCBF0CEDFC2777E23D53FE13B9563510314FB53B2FEF777CD9
3D77019C03FCEAF49AA7C36D2FC27A843A55AF88F526B89A30D6D7D308620C37
ED7263F41BB0A724E7DB23DEF5CF851E0BF10EA2F7F7DA3A7DA6424C8F048D16
F27A9214804FBD594F86BE104F0E49A0AE896FF609183B2F3BCB8180DBFEF6E0
09E73DCFAD007C9DACA03E1BD36748F4182391DF643672EFBA03D66E4903B007
1F4AB486DEF3C63A02F8A26986946DED11DD89188046A300F5DB9C8E3DEBE948
7E0C780A1B5680686AC19C397799D9C63B0627207B55BD47E14F83754B0B2B3B
BD24347649E5C0CB2BABAA649DA581C95049C0278CF1401F32AFD9AD3E27DC7F
C21ACEF6F1CB2FD81949271E5B74279F5C1EBD2A9F85E21369DAC4663F0F1DD1
28F335698C7247F7B9830C32DEBC1EDEF5F54E9DF0BFC1FA46B106AB61A3A417
76EC1A27491B0A40C74CE3A553D4BE0DF81754BE92F27D1563964396104CF12E
7D76A9005007CBFA9D9DE58785ADE07D46CEEEC8DDB3C62DA52E124283767818
C80BC5763E28F06D9687F06B40D7B4DB797ED5A8EC17F71BC9CAB02C171D1572
00E3D066BDFAF3E19F842FB49B5D2E5D1615B3B5769228A2664F99800589072C
4803939E95B51F877498FC3C9A09B28A4D2D22108B7946F5D83A0E6803E4DF10
DBF8353E19787A6D26546F1134A7EDCA1D8B01839DC0F0390B8FC6BE9BF868F7
727C37D01EFB79B86B4524C9F788FE127FE038ACDB5F835E03B4BF1769A1248E
0E44734AF247FF007C138C7B62BBB501542A80140C00074A005AE6BC6FFF0020
587FEBE17FF416AE96B9AF1BFF00C8161FFAF85FFD05A8036748FF00902D8FFD
7BC7FF00A08AB954F48FF902D8FF00D7BC7FFA08AB940054179FF1E371FF005C
DBF954F45007C9FE14B9F86E7C0AD65AE6937577E236F34C5F674937B1E7660A
903FA57A0EB5A2F8AF54F803A51D46DEEAE759B19D6E9E0906E99E2576DB9EE4
8420FAE073CD7B7D1401E13E37F88DA6FC44F0A2F85FC35697B73AC5FC918681
A023C801816DC7A718C64715B5E38B5365E37F863699DDE45C7959F5DA107F4A
F5ADA8859C2AA93F78E319FAD2EE5C67231EB401E1F71E31D23C19F1D7C4B79A
CC93470CF670C486388BE5B087B7D0D6BFC49F1369BE2DF817AC6A9A4BC8F6AD
2C3186910A1C89E3CF06BD6723D6968029691FF204B0FF00AF68FF00F41158FF
00103421E24F01EB1A5EDCC925B978BFEBA27CEBFAA8AE968A00F0FF00855A2C
FE32F0BF89B57D600697558174C8C91F7638A30B91F8E3F15A8BE07D9EA3AA78
8EFF0057D597F79A359C7A2C03D369E7F1000FFBE8D7BAD1401E67F0DBFE47BF
885FF6131FC9A9749FF9382D7FFEC110FF00E84B5E97450078F78F348B0D7BE3
AF8434DD4ED96E6CE6B19FCC89B386C2CAC3A7B806ABF8C7C1BE1EF0BF8CFC0D
2E89A5C566F3EA9B6468CB1DC06DC0E49AF69A2800A28A2800A28A2800A28A28
00A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A28
00A28A2800A28A2800A28A2800AE6BC6FF00F20587FEBE17FF00416AE96B9AF1
BFFC8161FF00AF85FF00D05A8036748FF902D8FF00D7BC7FFA08AB954F48FF00
902D8FFD7BC7FF00A08AB9400514514015AFF50B5D2EC65BCBD9D20B788659DC
F03FFAFED5E3FE22F8ABA8DF48F0E8ABF62B6E825650657F7F45FD6B3BE2278A
9F5FD71ED2094FF67D9B948C29E246EEE7D79C81EDF5A9FC25E079AEE5D3F54D
5EDC0D366B811881F2AD202AD86F65DC17EBF4EBE7D5AD3A92E4A7B1F6F97E53
85C0E1D62F1CAF27AA4FEFB5BABF5DBF139613EAFADDEA422E2F2F6E646DAAA6
56724F5C727D8FE55AA3C3FE2FD2E17BC5B5D46D523EAEB2EC23F5C9AF685D22
CADB5AD3E2B4B482DADACA2926DB1A0501DB08A78EF8DFCD5A9211AB6A51971B
ACACE4DCA3B4930E87DC2FFE85FEED0B09DDEA4D4E25D52A749285B5BFAEDA59
6BA7DE796D978E7C4DE1D9D60F11D94F2419C6F961D8E3E87186FF003CD7A6E9
1AFDA6AD691DCDACEB246E38E7A7B1F43ED5CEF8EBC7963A3C526996B1C379A8
32E195C078E1FF007BD4FF00B3F9D798785BC47368DAB6E67C5B5C3FEF5146D5
527F8801C0FC3B7D2B48D654A7ECE52BAFC8E6AD95CB30C2BC5D3A3ECE6B5B2D
A4BC974F2EFF0089F452B061914B591A6EA22E235390491EB5ACA772E6BB5AB1
F249A685A2BCB3E2378B75BD0BC4B15A69D79E4C0D6A9215F2D4FCC59C13C8F6
15CAAF8FFC62CA196F25653D08B6041FD2B9258A8464E2D33E8B0DC378AC4518
D68CA294B5D5BFF23DF68AF0683E27F8A6D64024B8825C1E526807F4C1AEFF00
C27F12ACB5E9D2C6FA21657CFC27CD98E43E80F63EC7F33550C5539BB6C658BE
1EC6E1A0EA34A4976FE933BAA28A2BA0F0C28A28A006BBA46BB9D95547763814
892C7267CB911B1D76B035C9FC4FFF009106FF00FDE8BFF435AE57E0C8024D63
00748BFF0066AC6556D5553B6E7AD472C5532F9E379BE176B5BD3ADFCFB1EB34
51456C7921451450046F3C51B6D79514E33866029EACAEA19482A79041E0D789
FC6000F8BED7233FE809FF00A324AF53F087FC89BA2FFD7945FF00A08AC215B9
AA385B63D6C5658A860E962B9AFCFD2DB7E26D514543772BC16734D1C6649123
66541FC440E056E79495DD913515E25E1CF883E25BCF14D9C73CFF00688AE661
1BDB0880001EBB71C8C75EBDABDB6B2A55A3555E27A198E595B2F9C6155A7757
D028A28AD4F3828A28A0028A28A0028A28A0028A28A0028A28A0028A28A002B9
AF1BFF00C8161FFAF85FFD05ABA5AE6BC6FF00F20587FEBE17FF00416A00D9D2
3FE40B63FF005EF1FF00E822AE553D23FE40B63FF5EF1FFE822AE5001591E29B
F6D2FC2DA95E236D78EDDB61F462303F535AF5CD7C4085A7F02EAA8B9C8883F0
7B2B063FCAA2A36A0DA3A70518CF134E32D9C95FEF3C1F44D2A4D6B59B3D3222
435C481091D97AB1FC0026BD9B5DD764D0741874E99926D56391440D2F0AC919
0C267C745DA0671DF205701E04D3EC5F59D36E6E11D8EE7CE09273B580C01CE7
38E95D2EB722DCFC46B386E24F3ADE37B5846F1FC2C5DC93FF00025507F0AF3E
9270A775BBD0FB7CD671C4E3234E4AF18272F9A76DFEED0D1D27C2579ADCC353
F105CDCCA24C1114AECA597B0D80811AF3D393EE39152EBDE1CB1D1ACDE4D235
5BED2EF2452B1430CCD22CA48E9E5927F318C75ADED7B5C7D3E68ACE011C73CC
A584F3B6238D7A13EE7DAB16DF5CD034A95EE5EE26D4B5061F3DC797FA2E7000
FA57538412B7E27CFD3AF8CAAD55D797A452D2DE6B64BD7E48F21D7F45B8D16E
6386E83F9EEBBA4DE727279FEB5927918AF46F15DD5A789B505B936EF12AA05C
17E4919E78F6AE5EFB49B3B7B196540E19572096279AE0A94ACDB8EC7DBE0B1C
E54A0AB2B4DEFEA773E0ED59E5D3A02CC4B6CC364E790706BD2ACE51246BD791
5E31E10DC96D1827AA923F9D7AF69049B75C926BD986B4A2DF647E598C518636
B421B294ADF7B3C93E2EFF00C8E30FFD78C7FF00A1BD7A7F82941F0568F903FE
3D53B7B57987C5DFF91C61FF00AF18FF00F437AF50F057FC893A3FFD7AA7F2AE
1A3FC799F519A7FC89B0DFD7465FD4745D3356B7305FD8C13A1E9BD0647B83D4
1F715E15E37F0B9F0A6B691C123B5A4E0C96EE4FCCB83CAE7D471CFB8AFA12BC
CBE3218BFB334B071E6F9EFB7D76EDE7F5C5562E9C5D372EA8E6E1BC6D6A78C8
D1BDE32BDD7CAF73AAF036B926BFE14B5BA9DB75CA66198FAB2F19FC460FE35A
9AAEB5A76876BF69D4AEE3B78CF0BB8F2C7D001C93F4AE1FE0FB15F0DEA2CE40
8C5D9393DBE45CFF004AE0EE6FA4F1D78DA3FB6DE0B6B59642A8CEC02C31004F
19E01207E6697D61C6947AB668B26857CC2BC5BE5A70D5DBCF5B2FEBA1E88FF1
7BC3CB2945B6D41D41C6F112807F36CD755A1F8934AF1140D2E9B74B2EDFBF19
1B5D3EAA79AE67FE113F87FF0063FB3EEB1CE31E6FDB06FF00AE7775AF358263
E0BF1D836578B716F04CAA6556044B0B6320E38CE0FE6293AD529B4E766BC8D2
9E5981C74271C229C671575CDB33D5BE277FC8837FFEF47FFA1AD72DF067FD66
B1F48FFF0066AEA3E2690DF0FEF987426223FEFB5AE5FE0CFF00ACD63E91FF00
ECD4E7FEF31F4FF31613FE49FADFE2FF00E44EE35DF19E8DE1CBC4B5D4669525
74F3142C4CC31923A8FA557D57E20787F4886179AE1E59268C48B0C29B9C2900
8C8E02F07B915E7DF183FE467B3FFAF41FFA11AB1E0CF86F16B7A6C7AB6B334E
239F98618DB0597A0663D79EC076C5275AABA8E1043A79565F4F054F19899349
EE9757D96875163F15FC3979388A5FB55A64E03CF18DBF9A938AEDA29639E249
627592371B95D4E411EA0D791F8D3E1A5B695A54DAA68F2CC63806E9A095B77C
BDCA9EBC75C1AB1F0875D99A5BAD0E672D12A79F003FC3CE187D3907F3AA856A
91A9ECEA7532C5E5783AB8378CC049DA3BA7FD7F9995F17FFE46FB5FFAF04FFD
192575B63E3AD17C37E13D16DEEA4925B9FB0C44C30286651B475C9007E75C97
C5FF00F91BED7FEBC13FF46495A9E0EF86961A968706A7ABC93BBDCA6F8A28DF
6844FE1C9EA4E3F0AC539FB69286E7A75618479561E58B6D45745BB6755A1FC4
7D035CBB5B4479AD6E1CE112E502873E8082467DABAEAF9CFC63E1EFF845FC44
F650CCEF09512C0E7EF007D7DC11D6BDEFC3F7926A3E1DD36F26FF00593DB472
37D4A826BA2856949B84F7478D9CE5B87C3D3A789C2B6E13EE739A2F8AFC1BA8
6BD1A69B6F12EA57248128B3D8CDC1272D8F415ADAC78AECB47B9FB3BC724D22
E0BED65554C82402CC40DC40271E9CF15E2DF0F3FE47AD23FDF6FF00D16D5EAB
E24F0A5DEA5792CB6C239A19DC4AD13CC622B204F2F39DAC194AE32A4763D738
ACE8D59CE9B925ADCEACC72EC26171B1A5393E571BEAFADDAB5F4D2C751A7EA1
06A7669756C58A312A432E19581C1523B104106AD56768BA749A6D8B24F22C97
134AF3CCC830BB98E4803D07007D2B46BB237B6A7CCD650551A86DD028A28A66
6145145001451450014514500145145001451450015CD78DFF00E40B0FFD7C2F
FE82D5D2D735E37FF902C3FF005F0BFF00A0B5006CE91FF205B1FF00AF78FF00
F411572A9E91FF00205B1FFAF78FFF00411572800AAF7D6C9796335B48331CA8
5187B118AB1484646281A6D3BA3C034B373E1ED6E7D36560B756736636ECD8E7
38F42307F1AE87C61A8D9EA0F69A941732ACAF108AEB11FCD06D6DC8E3D76B03
C0EA0D6EF8F7C20FABECD42C709A8C230A7A7983D09F5F4AF3737A2657B0D437
DA5C03B5C118CFF866BCE9C5D34E0F6E87DF60EB52CC1C7151F8E3F12EBE6EDD
BAAECCEFBC53E25D26FBC35259DEBA36A020F9244745915F00E76EECA82472B9
CF6C5736DA7345E1DB6F10E9EC65D324C2DCC04E5AD5F386C13D533F88C8FAD6
39D06CD93F76D22FA10D9ADAD0F598FC3763A9E953DA4B79637D01291838CCB8
DA413FC208C73DB152E5294AF3348E1E187A2A1856E4EF769F54F7B76EEBB5BC
C881046474358DADDC6FF2EC63E5DC82DEC3B7F8FE14DFED41696715AC6C27B9
0A17E5E403FD69FA669D2CB379D2FCD3487249ED5508BACF957CC9C762E9E5B4
DD6A8FDEFB2BBBEFE88E93C356C536A8E81702BD574A52B6E80F5C5723E1ED27
62E48E7FFAF5DCDB44238C62BD59592B23F388734A4E72DD9E31F177FE47187F
EBC63FFD0DEBD43C15FF00224E8FFF005EA9FCAB8AF88DE11D7B5DF12C577A65
87DA205B548CBF9D1AE18339230CC0F715C87FC2B5F167FD01BFF2621FFE2EBC
AE69D3AB2928B67DEBA584C765B468CF111838EBAB5F95D1EDFAA788749D1616
96FEFE1876FF00016CB1F60A3926BC33C61E269BC5DAEA490C4E204FDCDAC3D5
8E4F5C7F798E38F6157EC7E15F896E2402782DECD73CB4932B1FC9735E8DE14F
87BA6F86E45BB95CDE6A007133AE1533FDD5CF1F5EBF4AA97B6AFEEB5646541E
5993DEAC6A7B5A9D2DB7E174BEF6FB173C2DE1D6D1BC1B1E992102E258D9A623
B3BF51F8703F0AF0BD1F494BFD7A0D26FAE7EC3E648617919376C719C02323B8
C75EF5F4CD79D78DBE1B1D6AEE4D53499123BB9399A0938594F1C83FC27F0C1F
6EF788A0DC63CAAF6E872E4B9BA856AAABCB95D4D79BB3D7FCFD34EC66FF00C2
965FFA0F9FFC031FFC5D5687E13D95CDD5C59C1E298DEE20C09625B505933EA3
7D67FD87E25DBC3F620354F2C0DA02CAADC7FBC0FF005ADDF04FC39D4EC35687
57D5A736CF19DCB045265DCFFB6C38C7A8E7358C6109349537F89E9D5C5E2A85
2954AB8D8B7F654545DFF0FEBB9D17C4B5D9F0F6F5339DA6219FF81AD731F067
FD66B1F48FFF0066AED7C75A5DE6B3E11BBB1B083CEB990A154DC1738704F248
1D0573FF000CBC35AC787E4D48EA9646DC4C13CB3E6A3EEC673F749ADE717F58
8BB696FF0033C9C362292C92B52725CCE5B5D5FECF4DCE63E3073E27B31FF4E9
FF00B31AF43F00EAF6DAAF846C56165F36D6258268C7546518E9E840C8AF3DF8
BFFF00233D9FFD7A0FFD08D534F027886DF4DD3F5AD065965FB4DB248C2193CB
963DC0123A8DC33FFEAEF58A9CA15E4E2AE7A93C2D0C4E5387A756A283E8DED7
D7467A978E357B6D23C277CD3BAF993C4D0C3193CBB30C703DB3935E6BF08AD2
493C5735C283E5C16AC18FBB1000FD0FE559F1F81FC63AD5EA9BBB5B8DC7869E
F261851F89271EC057AFF84FC2F6FE15D27EC913F9B348DBE7988C6F6F61D80E
C2AE2A75AAA9B5648E5AD2C2E5997CF0D4EA29CEA6F6D97F4BE7A9E63F17FF00
E46FB5FF00AF04FF00D19257A97843FE44DD17FEBCA2FF00D04570FF00123C25
AEEBDE2382EF4CB037102DA2C6CDE746B860EE48C3303D08AEFF00C39693D878
674CB4B94F2E782D638E44C83B5828046471574A3255A4DA39732AF4A79561E9
C649C96EAEAEB4EA8F27F8BFFF002355A7FD7A0FFD09ABD47C21FF00226E8BFF
005E517FE822B88F88FE12D775EF105BDCE99606E214B608CFE746BF36E27186
606BBEF0E5A4F61E19D32D2E53CB9E0B58E391320ED60A01191C514A3255E4DA
16635E94F2AC3D38C9392DD5D5D6FBA3C2FE1E7FC8F5A47FBEDFFA2DABE87AF1
9F06F81BC49A578B34EBDBDD34C56F0B3191FCF8DB19461D0313D48AF66A3071
9460D495B51F1457A55B1509529292E5E8D3EAFB0514515D67CD051451400514
51400514514005145140051451400514514005735E37FF00902C3FF5F0BFFA0B
574B5CD78DFF00E40B0FFD7C2FFE82D401B3A47FC816C7FEBDE3FF00D0455CAA
7A47FC816C7FEBDE3FFD0455CA0028A28A008A588483A5727E21F0958EAEB9B8
B75761F75C70C3F115D8D31E2571C8A346ACF5454273A7253A6DA6BAAD19E257
9E037B673F65BB9E319E06EE9F962B3FFE111B97C79D71349EA09AF6F9B4C8A4
E4C6093ED550E830939D9FF8ED47D5E8763BDE799A5B95557F72BFDF6B9E5963
E16F2F1B6203B64F535D6693E1CF2D9495E7EB5D5C5A3431FF00CB31D7D2B422
B448C7000C7B56C9C62AD1479551D5AD3E7AB26DBEAF521B3B25863000E95740
C0C5000030052D43772D2B05145140C28A28A0028A28A0028A28A0028A28A00F
16F8BFFF00233D9FFD7A0FFD08D7A7F843FE44DD17FEBCA2FF00D0454FA8F87B
47D5A759B50D3ADEE6555DA1A44C903D2AF5BDBC3696D1DBDBC6B1C312844451
80A07402B085271A929F73D8C5E654EBE06961A29DE1BB25A28A2B73C70A28A2
800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2
800A28A2800AE6BC6FFF0020587FEBE17FF416AE96B9AF1BFF00C8161FFAF85F
FD05A802845E30FB0411D9FD837F908B1EFF003B1BB0319C6DA7FF00C279FF00
50DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8F
FF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D1
45001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF0
9E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437
FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF
00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347F
C279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF00
50DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8F
FF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D1
45001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF0
9E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437
FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF
00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347F
C279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF00
50DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8F
FF00D8D145001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D1
45001FF09E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF0
9E7FD437FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437
FF0023FF00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF
00F6347FC279FF0050DFFC8FFF00D8D145001FF09E7FD437FF0023FF00F63556
FF005C1E23B616A6D8DBF96E24DDE66ECF0463181EB451401FFFD9}
Stretch = True
end
object btnCerrar: TButton
Left = 322
Top = 214
Width = 97
Height = 27
Anchors = [akRight, akBottom]
Cancel = True
Caption = '&Cerrar'
Default = True
ModalResult = 1
TabOrder = 0
OnClick = btnCerrarClick
end
object pnldesc: TPanel
Left = 1
Top = 1
Width = 426
Height = 80
Align = alTop
TabOrder = 1
DesignSize = (
426
80)
object lblDescription: TLabel
Left = 15
Top = 5
Width = 411
Height = 68
Anchors = [akLeft, akTop, akRight]
AutoSize = False
Caption =
'Esta demo utiliza las Librer'#237'as GLibWMI.'#13#10'GLibWMI es una librer'#237 +
'a de componentes que utilizan la WMI de Windows (Windows Managem' +
'ent Information).'#13#10#13#10'Copyright '#169' Germ'#225'n Est'#233'vez (Neftal'#237').'#13#10
WordWrap = True
end
end
end
end
| 63.391254 | 107 | 0.835478 |
c3999081486c8c7f5ccf5d5b31193123868c30ac | 73,668 | pas | Pascal | Production7/Main.pas | kadavris/ok-sklad | f9cd84be7bf984104d9af93d83c0719f2d5668c5 | [
"MIT"
]
| 1 | 2016-04-04T18:11:56.000Z | 2016-04-04T18:11:56.000Z | Production7/Main.pas | kadavris/ok-sklad | f9cd84be7bf984104d9af93d83c0719f2d5668c5 | [
"MIT"
]
| null | null | null | Production7/Main.pas | kadavris/ok-sklad | f9cd84be7bf984104d9af93d83c0719f2d5668c5 | [
"MIT"
]
| 5 | 2016-02-15T02:08:05.000Z | 2021-04-05T08:57:58.000Z | {$I ok_sklad.inc}
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, Menus, ExtCtrls, ToolWin, DB, DBClient, strUtils, ActnList,
StdCtrls, Buttons, ImgList, AppEvnts,
prFun, prTypes, xLngDefs, debugTraceForm,
dxDBGrid6,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxButtonEdit,
ssBaseSkinForm, ssBevel, ssSpeedButton, ssBaseConst,
ssGradientPanel, ssMDIChild, ssLabel, ssBaseTypes, ssFormStorage, ssClientDataSet,
ssPanel, okClasses,
TB2Item, TB2Dock, TB2Toolbar, TBSkinPlus,
IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP, TB2ExtItems, OleCtrls, SHDocVw,
JvExStdCtrls, JvHtControls;
type
TfrmMain = class(TfrmBaseSkin)
aAbout: TAction;
aBackupDB: TAction;
aBufNext: TAction;
aBufPrior: TAction;
ActionList1: TActionList;
ActionList2: TActionList;
aDocs: TAction;
aExcelImport: TAction;
aExit: TAction;
aFinances: TAction;
aHelp: TAction;
aInternet: TAction;
aLang: TAction;
aNewDB: TAction;
aOptions: TAction;
aRefs: TAction;
aReports: TAction;
aRestoreDB: TAction;
aRunCC: TAction;
aService: TAction;
aUpdateStat: TAction;
aURL: TAction;
aWarehouse: TAction;
btnBufNext: TssSpeedButton;
btnBufPrior: TssSpeedButton;
btnDocs: TssSpeedButton;
btnFinances: TssSpeedButton;
btnInet: TssSpeedButton;
btnRefs: TssSpeedButton;
btnReports: TssSpeedButton;
btnService: TssSpeedButton;
btnWMat: TssSpeedButton;
bufMain: TokFunctionBuffer;
dckMain: TTBDock;
FormStorage: TssFormStorage;
ilMain: TImageList;
ilMainDis: TImageList;
MenuBar: TTBToolbar;
mnuDB: TTBSubmenuItem;
mnuDebug: TTBSubmenuItem;
mnuExcelImport: TTBItem;
mnuFile: TTBSubmenuItem;
mnuHelp: TTBSubmenuItem;
mnuLang: TTBSubmenuItem;
mnuService: TTBSubmenuItem;
panToolbar: TPanel;
pmNextBufferHistory: TTBPopupMenu;
pmPriorBufferHistory: TTBPopupMenu;
sbMain: TStatusBar;
ssBevel1: TssBevel;
TBItem10: TTBItem;
TBItem11: TTBItem;
TBItem12: TTBItem;
TBItem1: TTBItem;
TBItem2: TTBItem;
TBItem3: TTBItem;
TBItem48: TTBItem;
TBItem4: TTBItem;
TBItem5: TTBItem;
TBItem6: TTBItem;
TBItem7: TTBItem;
TBItem8: TTBItem;
TBItem9: TTBItem;
TBSeparatorItem1: TTBSeparatorItem;
TBSeparatorItem2: TTBSeparatorItem;
TBSeparatorItem3: TTBSeparatorItem;
TBSeparatorItem4: TTBSeparatorItem;
TBSeparatorItem5: TTBSeparatorItem;
TBSeparatorItem6: TTBSeparatorItem;
mnuSrvDbgLevel: TTBEditItem;
aTutorial: TAction;
panInfo: TPanel;
Bevel1: TBevel;
debugButton1: TButton;
debugButton2: TButton;
smEnt: TTBSubmenuItem;
miEnt0: TTBItem;
lblStatus: TJvHTLabel;
WebBrowser1: TWebBrowser;
lDate: TLabel;
edOnDate: TcxDateEdit;
imgToolbarBg: TImage;
procedure aAboutExecute(Sender: TObject);
procedure aBackupDBExecute(Sender: TObject);
procedure aBufNextExecute(Sender: TObject);
procedure aBufPriorExecute(Sender: TObject);
procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean);
procedure aDocsExecute(Sender: TObject);
procedure aExcelImportExecute(Sender: TObject);
procedure aExitExecute(Sender: TObject);
procedure aFileExecute(Sender: TObject);
procedure aFinancesExecute(Sender: TObject);
procedure aHelpExecute(Sender: TObject);
procedure aInternetExecute(Sender: TObject);
procedure aLangEngExecute(Sender: TObject);
procedure aLangExecute(Sender: TObject);
procedure aNewDBExecute(Sender: TObject);
procedure aOptionsExecute(Sender: TObject);
procedure aRefsExecute(Sender: TObject);
procedure aReportsExecute(Sender: TObject);
procedure aRestoreDBExecute(Sender: TObject);
procedure aRunCCExecute(Sender: TObject);
procedure aServExecute(Sender: TObject);
procedure aServiceExecute(Sender: TObject);
procedure aTutorialExecute(Sender: TObject);
procedure aUpdateStatExecute(Sender: TObject);
procedure aURLExecute(Sender: TObject);
procedure aViewExecute(Sender: TObject);
procedure aWarehouseExecute(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure bufMainChange(Sender: TObject);
procedure debugButton2Click(Sender: TObject);
procedure debugButton1Click(Sender: TObject);
procedure edOnDateChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure lblStatusHyperLinkClick(Sender: TObject; LinkName: String);
procedure miEntClick(Sender: TObject);
procedure mnuSrvDbgLevelAcceptText(Sender: TObject; var NewText: String; var Accept: Boolean);
procedure pmNextBufferHistoryPopup(Sender: TObject);
procedure pmPriorBufferHistoryPopup(Sender: TObject);
procedure sbMainDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
procedure TBItem9Click(Sender: TObject);
private
function CheckSingleMode: Boolean;
function IsFunEnabled(ARoot: Integer): Boolean;
function RefExists(AFrame: TClass): boolean;
procedure CreateRef(AFrame: TClass);
procedure mnuBufferHistoryClick(Sender: TObject);
procedure mnuLangXXXClick(Sender: TObject);
procedure RebuildLngMenu;
procedure SetCaptions;
procedure WMCallBack(var M: TMessage); message WM_CALLBACK;
procedure WMInputLangChangeRequest(var M: TMessage); message WM_INPUTLANGCHANGEREQUEST;
procedure WMLayoutChanged(var M: TMessage); message WM_LAYOUTCHANGED;
procedure WMOKExecLocate(var M: TMessage); message WM_OK_EXECLOCATE;
procedure WMSetText(var M: TMessage); message WM_SETTEXT;
procedure WMSizing(var M: TMessage); message WM_SIZING;
protected
function IsCCFormFound(AType: TCCViewType): boolean;
procedure SetActiveMDI(AForm: TForm);
procedure BuildBufferHistoryMenu(APrior: Boolean);
public
function AllDisabled: Boolean;
function GetEnabledView(AView: TCCViewType): TCCViewType;
procedure AddToBuffer(AViewType: TCCViewType; AFunID: Integer; const AFunName, AClassName: string; AGType, AID, ASubID: Integer);
procedure doAdvertizing(AURL: String = '');
procedure ExecLocate(const AViewType: TCCViewType; const AClass: string; ID: Integer; GType: Integer = 0);
procedure ExecRefresh(const AClass: string; ID: Integer; AParam: Integer = 0);
procedure LoadSkin; override;
procedure RefreshMultiEnts;
procedure RefreshStatusBar;
procedure ReloadRes;
procedure ResetActive(AActive: TCCViewType);
procedure ResetStyle;
procedure SetBtnStates;
end;
TokMain = class of TfrmMain;
var
frmMain: TfrmMain;
ShellHook: HHOOK;
FlastAdTime: TDateTime;
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses
Registry, ClientData, prConst, CCMain, fMeasures, Options, fBank,
fEqType, fMaterials, fAccountType, fUsers, fUserGroups, ShellAPI,
fUserMonitor, fRecycleBin, fCurrency, ssFun, ssRegUtils, ssBaseWizard, StartWiz,
ssCallbackConst, EditKAgent, EditWaybill, Login, ExImportWiz, Progress,
About, fLoadingData, fMessageDlg, xLngManager, fWaybillOut, fAccOut,
fOrders, BaseFrame, Udebug, Dateutils, FR_Class, Protection,
CommonConstants, WebReq;
var
DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = '';
{$R *.dfm}
//==============================================================================================
function ShellProcHook(Code: Integer; WParam: WPARAM; LParam: LPARAM): LRESULT; stdcall;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'ShellProcHook') else _udebug := nil;{$ENDIF}
if Code = HSHELL_LANGUAGE then begin
if Assigned(frmMainForm) then SendMessage(frmMainForm.Handle, WM_LAYOUTCHANGED, 0, Word(LParam));
if Assigned(frmLogin) then SendMessage(frmLogin.Handle, WM_LAYOUTCHANGED, 0, Word(LParam));
end;
Result := CallNextHookEx(ShellHook, Code, WParam, LParam);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.doAdvertizing(AURL: String = '');
var
s: String;
begin
if (trim(AURL) = '') and (MinutesBetween(now, FlastAdTime) < 5) then Exit;
if trim(AURL) = ''
then s := 'http://' + URL_KeyHost + '/dv.php?op=getad&hid=' + trim(CurrentHardwareID)
else s := AURL;
{$IF defined(DEBUG) or defined(FREE)}
panInfo.Visible := True;
{$ELSE}
if not panInfo.Visible then panInfo.Visible := not optHideInfoPane;
{$IFEND}
WebBrowser1.Navigate(s);
FlastAdTime := now;
end;
//==============================================================================================
function TfrmMain.IsCCFormFound(AType: TCCViewType): boolean;
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.IsCCFormFound') else _udebug := nil;{$ENDIF}
Result := False;
for i := 0 to Screen.FormCount - 1 do
if (Screen.Forms[i] is TfrmCCMain) and (TfrmCCMain(Screen.Forms[i]).ViewType = AType)
then begin
if Screen.Forms[i].WindowState = wsMinimized then Screen.Forms[i].WindowState := wsMaximized;
if Screen.Forms[i] <> ActiveMDIChild then begin
//with TfrmCCMain(Screen.Forms[i]) do
// if Assigned(FrameList) and Assigned(FrameList.FcurrFrame) then FrameList.FcurrFrame.DoActivate;
//Screen.Forms[i].BringToFront;
SendMessage(ClientHandle, WM_MDIACTIVATE, Screen.Forms[i].Handle, 0);
//SendMessage(Screen.Forms[i].Handle, WM_MDIACTIVATE, ActiveMDIChild.Handle, Screen.Forms[i].Handle);
//SendMessage(ActiveMDIChild.Handle, WM_MDIACTIVATE, ActiveMDIChild.Handle, Screen.Forms[i].Handle);
//SetActiveMDI(Screen.Forms[i]);
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
end;
Result := True;
Break;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.btnExitClick(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.btnExitClick') else _udebug := nil;{$ENDIF}
Close;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.SetCaptions;
var
i, days: Integer;
lblStatusDefault: string;
mi: TTbItem;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.SetCaptions') else _udebug := nil;{$ENDIF}
with LangMan do begin
lDate.Caption := GetRS('fmKAgent', 'Date');
mnuFile.Caption := GetRS('frmMain', 'File');
mnuHelp.Caption := GetRS('Common', 'Help');
aAbout.Caption := GetRS('frmAbout', 'Title');
aURL.Caption := GetRS('Common', 'URL');
mnuService.Caption := GetRS('frmMain', 'Tools');
mnuDB.Caption := GetRS('frmMain', 'DB');
aNewDB.Caption := GetRS('frmMain', 'NewDB');
aBufPrior.Hint := GetRS('Common', 'Backward');
aBufNext.Hint := GetRS('Common', 'Forward');
aDocs.Caption := GetRS('frmMain', 'Docs');
aWarehouse.Caption := GetRS('frmMain', 'WMat');
aReports.Caption := GetRS('frmMain', 'Reports');
aRefs.Caption := GetRS('frmMain', 'Refs');
aService.Caption := GetRS('frmMain', 'Service');
aFinances.Caption := GetRS('frmMain', 'Finances');
aExit.Caption := GetRS('frmMain', 'Exit');
aHelp.Caption := GetRS('Common', 'Help');
aTutorial.Caption := GetRS('Common', 'OnlineTutorial');
aLang.Caption := GetRS('frmMain', 'Lang');
aOptions.Caption := GetRS('frmMain', 'Options');
aExcelImport.Caption := GetRS('frmMain', 'ExcelImport');
aUpdateStat.Caption := GetRS('frmMain', 'UpdateStat');
aBackupDB.Caption := GetRS('frmMain', 'BackupDB');
aRestoreDB.Caption := GetRS('frmMain', 'RestoreDB');
aBackupDB.Enabled := SingleUserMode;
aRestoreDB.Enabled := SingleUserMode;
sdxPanelText := rs('Common', 'GroupPanelText');
lblStatusDefault := '';
//setFontStyle(lblStatus.Font);
{$IF defined(FREE) or defined(BETA)}
days := MaxFreeDays - DaysBetween(Now, EncodeDate(compiledYear, compiledMonth, compiledDay));
{$IFDEF FREE}
lblStatusDefault := GetRS('Common', 'FreeVerStatus');
aExcelImport.Enabled := False;
{$ENDIF}
{$IFDEF BETA}
if days < 0 then days := 0;
if days = 0 then lblStatusDefault := Format(GetRS('Common', 'DaysLeft'), [days]);
{$ENDIF}
{$IFEND}
if ((ActivationResponse <> nil) and (ActivationResponse.DataString = '')) or (servMsg.Values['Atype'] = '1')
then lblStatusDefault := rs('Common', 'ActPending');
if lblStatusDefault = ''
then lblStatus.Caption := GetRS('Common', 'URL')
else lblStatus.Caption := lblStatusDefault + ' ' + GetRS('Common', 'VisitPls');
lblStatus.Caption := lblStatus.Caption + ': <a href="' + OK_URL + '">' + OK_URL + '</a>';
end;
lblStatus.Left := menuBar.Left + menuBar.Width + 10;
cdsEnts.First;
smEnt.Clear;
if cdsEnts.RecordCount <= 1
then smEnt.Enabled := False
else for i := 1 to cdsEnts.RecordCount do begin
mi := TTBitem.Create(menuBar);
smEnt.Add(mi);
mi.Name := 'miEnt' + IntTostr(i);
mi.Tag := cdsEnts.FieldByName('kaid').AsInteger;
mi.OnClick := miEntClick;
mi.Caption := cdsEnts.FieldByName('name').AsString;
mi.Checked := (cdsEnts.FieldByName('def').AsInteger = 1);
mi.Enabled := not mi.Checked;
cdsEnts.Next;
end;
panTitleBar.Caption := OK_AppName;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.FormCreate(Sender: TObject);
var
ov: OleVariant;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.FormCreate') else _udebug := nil;{$ENDIF}
inherited;
setFontStyle(ToolbarFont);
frmMainForm := Self;
fLoading := TfmLoadingData.Create(nil);
//SetStyle(Self, IStyle);
RefreshStatusBar;
SetCaptions;
FormStorage.IniFileName := PrRegKey;
FormStorage.IniSection := Self.Name;
FormStorage.Active := True;
RebuildLngMenu;
edOnDate.Date := Date;
SetUserActivity(ClientData.dmData.SConnection, 0);
ClientData.dmData.MHandle := Self.Handle;
SetBtnStates;
setFontStyle(Self.Font);
setFontStyle(MenuBar.Font);
mnuSrvDbgLevel.Text := dmData.SConnection.AppServer.Command(cmdSetServerDebugLevel, -1, ov); // get current dlevel
{$IFNDEF FREE}
panInfo.Visible := not optHideInfoPane;
{$ENDIF}
{$IFNDEF DEBUG}
mnuDebug.Visible := (cmdLineDebugLevel > 0);
{$ENDIF}
{$IFNDEF DEBUG}
debugButton1.Visible := False;
debugButton2.Visible := False;
{$ENDIF}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.ReloadRes;
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.ReloadRes') else _udebug := nil;{$ENDIF}
//LangMan.ActiveLngDesc := LangName;
Self.SetCaptions;
for i := 0 to Self.MDIChildCount - 1 do TMDIChild(Self.MDIChildren[i]).SetCaptions;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.CreateRef(AFrame: TClass);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.CreateRef') else _udebug := nil;{$ENDIF}
if not RefExists(AFrame) then
with TfrmCommonRef.Create(Application, AFrame.ClassName) do
try
OnDate := Self.edOnDate.Date;
fFrameClass := AFrame;
Show;
except
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.edOnDateChange(Sender: TObject);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.edOnDateChange') else _udebug := nil;{$ENDIF}
for i := 0 to Self.MDIChildCount - 1 do TMDIChild(Self.MDIChildren[i]).OnDate := edOnDate.Date;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.FormDestroy(Sender: TObject);
var
s: String;
i, runsec, runcount: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.FormDestroy') else _udebug := nil;{$ENDIF}
fProgress.Free;
fLoading.Free;
SetUserActivity(ClientData.dmData.SConnection, 0);
WriteToRegInt(PrRegKey, 'ViewType', Ord(CurrentView));
WriteToRegInt(PrRegKey, 'CurrNode', CurrentNode);
// statistics
if ClientStartTime <> 0.0 then begin // not cancelled at login
if not ReadFromRegStr(prRegStatKey, regKeyLastVer, s) // 1st run maybe. initializing
then s := FullVersionNo;
i := SecondsBetween(now, ClientStartTime);
//this version run time. resetting if ver changed from last time.
if not ReadFromRegInt(prRegStatKey, regKeyRunTimeCurVer, runsec) or (s <> FullVersionNo) then runsec := 0;
runsec := runsec + i;
WriteToRegInt(prRegStatKey, regKeyRunTimeCurVer, runsec);
// total run time for all versions
if not ReadFromRegInt(prRegStatKey, regKeyRunTime, runsec) then runsec := 0;
runsec := runsec + i;
WriteToRegInt(prRegStatKey, regKeyRunTime, runsec);
WriteToRegStr(prRegStatKey, regKeyLastVer, FullVersionNo);
//sending usage statistics and other shit
ReadFromRegInt(prRegStatKey, regKeyRunCount, runcount);
WebQuickPost(URL_KeyHost, 'http://' + URL_KeyHost + '/dv.php',
'op=rep'#13#10'hid=' + trim(CurrentHardwareID) + #13#10'rc=' + IntToStr(runcount)
+ #13#10'si=' + encodeKey(CollectTechInfo(False) + getUsageStat)
+ #13#10'version=' + FullVersionNo, s, 5000);
{$IFDEF DEBUG}debugInstantLog('Main.Formdestroy: Sendinfo response code: ' + s);{$ENDIF}
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.ResetStyle;
(*var
i: integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
*)
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.ResetStyle') else _udebug := nil;{$ENDIF}
SetStyle(Self, IStyle);
for i := 0 to Self.MDIChildCount - 1 do
SendMessage(Self.MDIChildren[i].Handle, WM_RESETSTYLE, 0, 0);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.aRunCCExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aRunCCExecute') else _udebug := nil;{$ENDIF}
if not IsCCFormFound(vtAll) then
with TfrmCCMain.Create(Application) do
try
OnDate := Self.edOnDate.Date;
ViewType := vtAll;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aRunCC.Caption), 0);
Show;
except
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TfrmMain.RefExists(AFrame: TClass): boolean;
(*var
i: integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
*)
begin
//{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.RefExists') else _udebug := nil;{$ENDIF}
Result := False;
(*for i := 0 to MDIChildCount-1 do
if (MDIChildren[i] is TfrmCommonRef) and (TfrmCommonRef(MDIChildren[i]).fFrame.ClassName=AFrame.ClassName)
then begin
MDIChildren[i].BringToFront;
Result := True;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.aDocsExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aDocsExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtDocs);
Application.ProcessMessages;
if not IsCCFormFound(vtDocs) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
//Visible := False;
OnDate := Self.edOnDate.Date;
ViewType := vtDocs;
Self.Height := Self.Height-1;
Self.Height := Self.Height+1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aDocs.Caption), 0);
//Visible := True;
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aInternetExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aInternetExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtInternet);
Application.ProcessMessages;
if not IsCCFormFound(vtInternet) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
//Visible := False;
OnDate := Self.edOnDate.Date;
ViewType := vtInternet;
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aInternet.Caption), 0);
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aReportsExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aReportsExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtReports);
Application.ProcessMessages;
if not IsCCFormFound(vtReports) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
OnDate := Self.edOnDate.Date;
ViewType := vtReports;
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aRunCC.Caption), 0);
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aRefsExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aRefsExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtRefs);
Application.ProcessMessages;
if not IsCCFormFound(vtRefs) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
WindowState := wsMaximized;
OnDate := Self.edOnDate.Date;
ViewType := vtRefs;
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aRefs.Caption), 0);
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aServiceExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aServiceExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtService);
Application.ProcessMessages;
if not IsCCFormFound(vtService) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
WindowState := wsMaximized;
OnDate := Self.edOnDate.Date;
ViewType := vtService;
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aService.Caption), 0);
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aWarehouseExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aWarehouseExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtWMat);
Application.ProcessMessages;
if not IsCCFormFound(vtWMat) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
OnDate := Self.edOnDate.Date;
ViewType := vtWMat;
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aRunCC.Caption), 0);
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aFileExecute(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aFileExecute') else _udebug := nil;{$ENDIF}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.aExitExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aExitExecute') else _udebug := nil;{$ENDIF}
Close;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aServExecute(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aServExecute') else _udebug := nil;{$ENDIF}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.aHelpExecute(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
//{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aHelpExecute') else _udebug := nil;{$ENDIF}
ShowHelpTopic('');
//{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aViewExecute(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aViewExecute') else _udebug := nil;{$ENDIF}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.aOptionsExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aOptionsExecute') else _udebug := nil;{$ENDIF}
Application.ProcessMessages;
with TfrmOptions.Create(Application) do
try
ShowModal;
finally
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aLangExecute(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aLangExecute') else _udebug := nil;{$ENDIF}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.aLangEngExecute(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
(*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aLangEngExecute') else _udebug := nil;{$ENDIF}
langID := (Sender as TComponent).Tag;
langName := LangNames[LangID];
case langID of
lidRUS: mnuRus.Checked := True;
lidUKR: mnuUkr.Checked := True;
lidENG: mnuEng.Checked := True;
end;
with newDataSet do
try
ProviderName := 'pProfiles_UpdLang';
FetchParams;
Params.ParamByName('profid').AsInteger := ProfID;
Params.ParamByName('lang').AsInteger := (Sender as TComponent).Tag;
Execute;
finally
Free;
end;
WriteToRegStr(MainRegKey + '\', 'Lang', LangName);
ReloadRes;
panTitleButtons.Repaint;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
*)
end;
//==============================================================================================
procedure TfrmMain.FormShow(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.FormShow') else _udebug := nil;{$ENDIF}
inherited;
Self.Caption := OK_AppName;
if not EntParamsLoaded then begin
with TfrmStartWiz.Create(nil) do
try
WizType := wtStartSettings;
defaultConn := ClientData.dmData.SConnection;
ShowModal;
finally
Free;
end;
SetCaptions;
end;
doAdvertizing;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.WMCallBack(var M: TMessage);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.WMCallBack') else _udebug := nil;{$ENDIF}
for i := 0 to Self.MDIChildCount - 1 do
PostMessage(TMDIChild(Self.MDIChildren[i]).Handle, WM_CALLBACK, M.WParam, M.LParam);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.WMInputLangChangeRequest(var M: TMessage);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.WMInputLangChangeRequest') else _udebug := nil;{$ENDIF}
inherited;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.WMLayoutChanged(var M: TMessage);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.WMLayoutChanged') else _udebug := nil;{$ENDIF}
for i := 0 to Screen.FormCount - 1 do begin
//if (Screen.Forms[i] is TfrmCCMain) or (Screen.Forms[i] is TfrmEditKAgent) or
//(Screen.Forms[i] is TfrmEditWaybill) or (Screen.Forms[i] is TfrmLogin) or
{then}
if Screen.Forms[i] <> Self then
PostMessage(Screen.Forms[i].Handle, WM_LAYOUTCHANGED, M.WParam, M.LParam);
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.WMSizing(var M: TMessage);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.WMSizing') else _udebug := nil;{$ENDIF}
{for i := 0 to Screen.FormCount - 1 do
if (Screen.Forms[i] is TfrmCCMain) and (Screen.Forms[i].FormStyle <> fsNormal)
then PostMessage(Screen.Forms[i].Handle, WM_SIZING, M.WParam, M.LParam);
}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aExcelImportExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aExcelImportExecute') else _udebug := nil;{$ENDIF}
with TfrmExImportWiz.Create(nil) do
try
ShowModal;
finally
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.ExecRefresh(const AClass: string; ID: Integer; AParam: Integer = 0);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.ExecRefresh') else _udebug := nil;{$ENDIF}
if AClass = 'WH' then begin
for i := 0 to MDIChildCount - 1 do
if (MDIChildren[i] is TfrmCCMain) and (TfrmCCMain(MDIChildren[i]).ViewType = vtWMat)
then TfrmCCMain(MDIChildren[i]).RefreshWH;
end
else
for i := 0 to MDIChildCount - 1 do
if MDIChildren[i] is TfrmCCMain then TfrmCCMain(MDIChildren[i]).ExecRefresh(AClass, ID, AParam);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aAboutExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aAboutExecute') else _udebug := nil;{$ENDIF}
with TfrmAbout.Create(nil) do
try
ShowModal;
finally
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TfrmMain.IsFunEnabled(ARoot: Integer): Boolean;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
function IsChildEnabled(ADS: TDataSet; AID: Integer): Boolean;
var
BM: TBookmark;
begin
Result := False;
BM := ADS.GetBookmark;
try
ADS.First;
while not ADS.Eof do begin
if (ADS.FieldByName('id').AsInteger = AID) then begin
if not ADS.FieldByName('funid').IsNull and GetUserAccess(ADS.FieldByName('funid').AsInteger, uaView)
then begin
Result := True;
Exit;
end
end
else if (ADS.FieldByName('pid').AsInteger = AID)
then begin
Result := IsChildEnabled(ADS, ADS.FieldByName('id').AsInteger);
if Result then Exit;
end;
ADS.Next;
end;
finally
ADS.GotoBookmark(BM);
ADS.FreeBookmark(BM);
end;
end;
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.IsFunEnabled') else _udebug := nil;{$ENDIF}
Result := False;
with newDataSet do
try
ProviderName := 'pUserTreeView_GetEx';
Open;
while not Eof do begin
if FieldByName('gtype').AsInteger = ARoot
then Result := IsChildEnabled(Fields[0].DataSet, FieldByName('id').AsInteger);
Next;
end;
Close;
finally
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.SetBtnStates;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.SetBtnStates') else _udebug := nil;{$ENDIF}
aDocs.Enabled := IsFunEnabled(2);
aFinances.Enabled := IsFunEnabled(206) or IsFunEnabled(207);
aRefs.Enabled := IsFunEnabled(1);
aService.Enabled := IsFunEnabled(3);
aReports.Enabled := IsFunEnabled(5);
aWarehouse.Enabled := IsFunEnabled(4) or IsFunEnabled(150) or IsFunEnabled(250) or IsFunEnabled(251);
aOptions.Enabled := GetUserAccessByClass('TfrmOptions', uaView);
aExcelImport.Enabled := UserID = 0;
aRestoreDB.Enabled := UserID = 0;
aBackupDB.Enabled := UserID = 0;
aUpdateStat.Enabled := UserID = 0;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TfrmMain.GetEnabledView(AView: TCCViewType): TCCViewType;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
function GetEnView: TCCViewType;
begin
Result := vtDocs;
if aWarehouse.Enabled then Result := vtWMat
else if aFinances.Enabled then Result := vtFinances
else if aReports.Enabled then Result := vtReports
else if aRefs.Enabled then Result := vtRefs
else if aService.Enabled then Result := vtService
else if aInternet.Enabled then Result := vtInternet;
end;
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.GetEnabledView') else _udebug := nil;{$ENDIF}
Result := vtDocs;
case AView of
vtDocs: if aDocs.Enabled then Result := AView else Result := GetEnView;
vtWMat: if aWarehouse.Enabled then Result := AView else Result := GetEnView;
vtFinances: if aFinances.Enabled then Result := AView else Result := GetEnView;
vtReports: if aReports.Enabled then Result := AView else Result := GetEnView;
vtRefs: if aRefs.Enabled then Result := AView else Result := GetEnView;
vtService: if aService.Enabled then Result := AView else Result := GetEnView;
vtInternet: if aInternet.Enabled then Result := AView else Result := GetEnView;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TfrmMain.AllDisabled: Boolean;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.AllDisabled') else _udebug := nil;{$ENDIF}
Result := not aDocs.Enabled and not aRefs.Enabled and not aReports.Enabled
and not aWarehouse.Enabled and not aService.Enabled and not aFinances.Enabled;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aUpdateStatExecute(Sender: TObject);
var
cdsTemp: TssClientDataSet;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aUpdateStatExecute') else _udebug := nil;{$ENDIF}
if not CheckSingleMode then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
fProgress.Caption := rs('frmMain', 'UpdatingStat');
fProgress.Show;
cdsTemp := newDataSet;
with newDataSet do
try
cdsTemp.ProviderName := 'pIndices_List';
ProviderName := 'pSQL';
FetchMacros;
cdsTemp.Open;
fProgress.pbMain.Max := cdsTemp.RecordCount;
while not cdsTemp.Eof do begin
Macros.ParamByName('sql').AsString := 'set statistics index ' + cdsTemp.Fields[0].AsString;
Execute;
fProgress.pbMain.StepIt;
Application.ProcessMessages;
cdsTemp.Next;
end;
cdsTemp.Close;
finally
cdsTemp.Free;
Free;
fProgress.Hide;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aBackupDBExecute(Sender: TObject);
var
Res: Boolean;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aBackupDBExecute') else _udebug := nil;{$ENDIF}
if not CheckSingleMode then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
with TSaveDialog.Create(nil) do
try
DefaultExt := 'fbk';
Filter := 'Firebird Backup Files (*.fbk)|*.fbk';
if Execute then begin
fProgress.Caption := rs('frmMain', 'Backuping');
fProgress.DoTimer;
Application.ProcessMessages;
Res := (ClientData.dmData.SConnection.AppServer.db_Backup(FileName, ClientData.dmData.SConnection.DBID) = 0);
fProgress.Hide;
if Res
then ssMessageDlg(rs('Common', 'BackupSuccess'), ssmtInformation, [ssmbOk])
else ssMessageDlg(rs('Common', 'BackupError') + ' ' + lastServerError, ssmtError, [ssmbOk]);
end;
finally
if fProgress.Visible then fProgress.Hide;
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aRestoreDBExecute(Sender: TObject);
var
i, j: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aRestoreDBExecute') else _udebug := nil;{$ENDIF}
if (not CheckSingleMode) or (mrYes <> ssMessageDlg(rs('frmMain', 'RestoreWarning'), ssmtWarning, [ssmbYes, ssmbCancel]))
then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
with TOpenDialog.Create(nil) do
try
DefaultExt := 'fbk';
Filter := 'Firebird Backup Files (*.fbk)|*.fbk';
if Execute then begin
fProgress.Caption := rs('frmMain', 'Restoring');
fProgress.DoTimer;
Application.ProcessMessages;
if 0 = ClientData.dmData.SConnection.AppServer.db_Restore(FileName, ClientData.dmData.SConnection.DBID)
then begin
ClientData.dmData.SConnection.DBConnected := False;
ClientData.dmData.SConnection.DBConnected := True;
EntName := '';
InitProfile(ClientData.dmData.SConnection, UserID, ProfID, TreeID, ClientData.dmData.scMain);
frmMainForm.SetBtnStates;
BaseCurrName := GetBaseCurrName(ClientData.dmData.SConnection);
try
for i := 0 to MDIChildCount - 1 do
if MDIChildren[i] <> ActiveMDIChild
then MDIChildren[i].Close
else with TfrmCCMain(MDIChildren[i]) do begin
tlMain.Selected := tlMain.Items[0];
try
for j := 0 to FrameList.FramesCount - 1 do FrameList.Items[i].Free;
except
end;
FrameList.Clear;
NotChangeDetail := True;
ReloadRes;
if ViewType <> frmMainForm.GetEnabledView(ViewType)
then ViewType := frmMainForm.GetEnabledView(ViewType)
else RefreshTree(0);
panNoAccess.Visible := frmMainForm.AllDisabled;
NotChangeDetail := False;
tlMain.Selected := tlMain.Items[0];
panTitleButtons.Invalidate;
end;
except
raise;
end;
fProgress.Hide;
ssMessageDlg(rs('Common', 'RestoreSuccess'), ssmtInformation, [ssmbOk]);
end
else ssMessageDlg(rs('Common', 'RestoreError') + ' ' + lastServerError, ssmtError, [ssmbOk]);
end;
finally
if fProgress.Visible then fProgress.Hide;
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TfrmMain.CheckSingleMode: Boolean;
var
s: WideString;
o: OleVariant;
res: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.CheckSingleMode') else _udebug := nil;{$ENDIF}
Result := SingleUserMode;
if UserID <> 0
then ssMessageDlg(rs('Common', 'SModeOnly'), ssmtError, [ssmbOk])
else if not Result then begin
s := '1'; // non-empty string to set single user
res := ClientData.dmData.SConnection.AppServer.Command(cmdSetSingleUserMode, s, o);
SingleUserMode := (0 = res);
Result := SingleUserMode;
case res of
0: ;
cmdSetSingleUserMode_res_NotOwner: ssMessageDlg(rs('Common', 'SModeNotOwner'), ssmtError, [ssmbOk]);
cmdSetSingleUserMode_res_NotAlone: ssMessageDlg(rs('Common', 'SModeNotAlone'), ssmtError, [ssmbOk]);
end;
end;
RefreshStatusBar;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.Image1Click(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.Image1Click') else _udebug := nil;{$ENDIF}
aAbout.Execute;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.ExecLocate(const AViewType: TCCViewType; const AClass: string; ID: Integer; GType: Integer = 0);
var
i: Integer;
FActiveView: TfrmCCMain;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.ExecLocate') else _udebug := nil;{$ENDIF}
if not (ActiveMDIChild is TfrmCCMain) then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
FActiveView := TfrmCCMain(ActiveMDIChild);
if (FActiveView.ViewType <> AViewType) then begin
case AViewType of
vtDocs: aDocs.Execute;
vtWMat: aWarehouse.Execute;
vtRefs: aRefs.Execute;
vtReports: aReports.Execute;
vtService: aService.Execute;
vtFinances: aFinances.Execute;
vtInternet: aInternet.Execute;
end;
FActiveView := TfrmCCMain(ActiveMDIChild);
end;
FActiveView.ExecLocate(AClass, ID, GType);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.RebuildLngMenu;
var
i: Integer;
FItem: TTBItem;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.RebuildLngMenu') else _udebug := nil;{$ENDIF}
for i := 0 to LangMan.FilesCount - 1 do begin
FItem := TTBItem.Create(MenuBar);
FItem.GroupIndex := 10;
FItem.Caption := LangMan.Files[i].Desc + ' - ' + LangMan.Files[i].LangName;
FItem.OnClick := mnuLangXXXClick;
mnuLang.Insert(i, FItem);
if i = LangMan.ActiveLngIndex then FItem.Checked := True;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.mnuLangXXXClick(Sender: TObject);
var
i:integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.mnuLangXXXClick') else _udebug := nil;{$ENDIF}
(Sender as TTBItem).Checked := True;
switchLang(mnuLang.IndexOf(Sender as TTBItem));
ReloadRes;
panTitleButtons.Repaint;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aFinancesExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aFinancesExecute') else _udebug := nil;{$ENDIF}
ResetActive(vtFinances);
Application.ProcessMessages;
if not IsCCFormFound(vtFinances) then
with TfrmCCMain.Create(Application) do
try
FormStyle := fsMDIChild;
OnDate := Self.edOnDate.Date;
ViewType := vtFinances;
Self.Height := Self.Height - 1;
Self.Height := Self.Height + 1;
SendMessage(Handle, WM_SETCAPTIONEX, integer(@aFinances.Caption), 0);
Show;
except
Free;
raise;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.LoadSkin;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.LoadSkin') else _udebug := nil;{$ENDIF}
inherited;
dckMain.Color := clokMainBk;
MenuBar.Color := clokMainBk;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aURLExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aURLExecute') else _udebug := nil;{$ENDIF}
ShellExecute(Application.Handle, nil, PChar(OK_URL), nil, nil, SW_SHOWNORMAL);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.debugButton2Click(Sender: TObject);
begin
fprogress.Done;
{with TColorDialog.Create(nil) do
try
if Execute then begin
btnDocs.GrStartColor := Color;
btnRefs.GrStartColor := Color;
btnwmat.GrStartColor := Color;
btnFinances.GrStartColor := Color;
btnReports.GrStartColor := Color;
btnService.GrStartColor := Color;
end;
finally
Free;
end;
}
end;
//==============================================================================================
procedure TfrmMain.debugButton1Click(Sender: TObject);
begin
//fprogress.DoTimer(30);
{with TColorDialog.Create(nil) do
try
if Execute then begin
btnDocs.grendcolor := Color;
btnRefs.grendcolor := Color;
btnwmat.grendcolor := Color;
btnFinances.grendcolor := Color;
btnReports.grendcolor := Color;
btnService.grendcolor := Color;
end;
finally
Free;
end;
}
end;
//==============================================================================================
procedure TfrmMain.SetActiveMDI(AForm: TForm);
var
FActiveID, FID, i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.SetActiveMDI') else _udebug := nil;{$ENDIF}
FActiveID := -1;
FID := -1;
for i := 0 to MDIChildCount - 1 do
if MDIChildren[i] = ActiveMDIChild
then FActiveID := i
else if MDIChildren[i] = AForm
then FID := i;
if FID > FActiveID then begin
while AForm <> ActiveMDIChild do SendMessage(ClientHandle, WM_MDINEXT, 0, 0);
end
else begin
while AForm <> ActiveMDIChild do SendMessage(ClientHandle, WM_MDINEXT, 0, 1);
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.AddToBuffer(AViewType: TCCViewType; AFunID: Integer; const AFunName, AClassName: string; AGType, AID, ASubID: Integer);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.AddToBuffer') else _udebug := nil;{$ENDIF}
bufMain.Add(AViewType, AFunID, AFunName, AClassName, AGType, AID, ASubID);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aBufPriorExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aBufPriorExecute') else _udebug := nil;{$ENDIF}
bufMain.Prior;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aBufNextExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aBufNextExecute') else _udebug := nil;{$ENDIF}
bufMain.Next;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.ActionList1Update(Action: TBasicAction; var Handled: Boolean);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
//if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.ActionList1Update') else _udebug := nil;{$ENDIF}
aBufPrior.Enabled := not bufMain.BOF;
aBufNext.Enabled := not bufMain.EOF;
//{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.bufMainChange(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.bufMainChange') else _udebug := nil;{$ENDIF}
JumpFromBuffer := True;
with bufMain.Current do ExecLocate(ViewType, ClassName_, ID, GType);
JumpFromBuffer := False;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.pmPriorBufferHistoryPopup(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.pmPriorBufferHistoryPopup') else _udebug := nil;{$ENDIF}
BuildBufferHistoryMenu(True);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.BuildBufferHistoryMenu(APrior: Boolean);
var
FItem: TTBItem;
i: Integer;
FFromIndex, FToIndex: Integer;
FMenu: TTBPopupMenu;
function ViewName(AViewType: TCCViewType): string;
begin
case AViewType of
vtDocs: Result := aDocs.Caption;
vtRefs: Result := aRefs.Caption;
vtWMat: Result := aWarehouse.Caption;
vtReports: Result := aReports.Caption;
vtService: Result := aService.Caption;
vtFinances: Result := aFinances.Caption;
vtInternet: Result := aInternet.Caption;
end;
end;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.BuildBufferHistoryMenu') else _udebug := nil;{$ENDIF}
if APrior then begin
FMenu := pmPriorBufferHistory;
FFromIndex := 0;
FToIndex := bufMain.ItemIndex - 1;
end
else begin
FMenu := pmNextBufferHistory;
FFromIndex := bufMain.ItemIndex + 1;
FToIndex := bufMain.ItemsCount - 1;
end;
FMenu.Items.Clear;
for i := FToIndex downto FFromIndex do begin
FItem := TTBItem.Create(FMenu);
FItem.Caption := ViewName(bufMain.Items[i].ViewType) + ' - ' + bufMain.Items[i].FunName;
FItem.Tag := i;
FItem.OnClick := mnuBufferHistoryClick;
FMenu.Items.Insert(FToIndex - i, FItem);
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.mnuBufferHistoryClick(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.mnuBufferHistoryClick') else _udebug := nil;{$ENDIF}
bufMain.MoveTo(TComponent(Sender).Tag);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.pmNextBufferHistoryPopup(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.pmNextBufferHistoryPopup') else _udebug := nil;{$ENDIF}
BuildBufferHistoryMenu(False);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.ResetActive(AActive: TCCViewType);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.ResetActive') else _udebug := nil;{$ENDIF}
btnDocs.Active := (AActive = vtDocs);
btnWMat.Active := (AActive = vtWMat);
btnRefs.Active := (AActive = vtRefs);
btnFinances.Active := (AActive = vtFinances);
btnReports.Active := (AActive = vtReports);
btnService.Active := (AActive = vtService);
btnInet.Active := (AActive = vtInternet);
doAdvertizing;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.WMOKExecLocate(var M: TMessage);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.WMOKExecLocate') else _udebug := nil;{$ENDIF}
with PokLocateInfo(M.WParam)^ do ExecLocate(ViewType, ClassName, ID, GType);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.FormResize(Sender: TObject);
var
i, ii: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.FormResize') else _udebug := nil;{$ENDIF}
{for i := 0 to MDIChildCount - 1 do begin
for ii := 0 to MDIChildren[i].ControlCount - 1 do try
(MDIChildren[i].Controls[ii] as TWinControl).EnableAlign;
except
end;
MDIChildren[i].Realign;
end;
}
RefreshStatusBar;
sbMain.Panels[1].Width := sbMain.Width - sbMain.Panels[2].Width - sbMain.Panels[0].Width - 150;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.RefreshStatusBar;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.RefreshStatusBar') else _udebug := nil;{$ENDIF}
setFontStyle(sbMain.Font);
sbMain.Panels[0].Text := ' ' + UserName + '@' + ClientData.dmData.SConnection.Host;
sbMain.Panels[0].Width := 2 * sbMain.Canvas.TextWidth(sbMain.Panels[0].Text);
sbMain.Panels[1].Text := OK_Version + ' ' + ifThen(trim(EntName) = '', rs('Common', 'EmptyEnt'), EntName);
if SingleUserMode
then sbMain.Panels[3].Text := ' ' + rs('frmMain', 'SingleUserMode')
else sbMain.Panels[3].Text := '';
doAdvertizing;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.WMSetText(var M: TMessage);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.WMSetText') else _udebug := nil;{$ENDIF}
RefreshStatusBar;
{if Trim(EntName) = ''
then lTitle.Caption := rs('Common', 'EmptyEnt')
else lTitle.Caption := OK_AppName + ' ' + OK_Version + ' ' + EntName;
}
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.miEntClick(Sender: TObject);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.miEntClick') else _udebug := nil;{$ENDIF}
try // finally
Screen.Cursor := crSQLWait;
try
for i := 0 to smEnt.Count - 1 do begin
smEnt.Items[i].Enabled := True;
smEnt.Items[i].Checked := False;
end;
TTBItem(Sender).Checked := True;
TTBItem(Sender).Enabled := False;
MakeDefaultEnt(ClientData.dmData.SConnection, TTBItem(Sender).Tag);
ExecRefresh('TfmKAgent', 0);
finally
Screen.Cursor := crDefault;
end;
RefreshStatusBar;
if MultiEntsViewType = 1 then RefreshMultiEnts;
finally
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
end;
//==============================================================================================
procedure TfrmMain.sbMainDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect);
var
Flags: Longint;
R: TRect;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.sbMainDrawPanel') else _udebug := nil;{$ENDIF}
with sbMain.Canvas do begin
if (Panel.Index = 3) and SingleUserMode then begin
//Brush.Color := CL_OK_SINGLE_MODE;
Pen.Color := clWindowText;
//FillRect(Rect);
Flags := DT_EXPANDTABS or DT_LEFT;
Flags := DrawTextBiDiModeFlags(Flags);
R := Rect;
ClientData.dmData.Images.Draw(sbMain.Canvas, R.Left + 1, R.Top, 197);
R.Top := R.Top + 1; R.Left := R.Left + 18;
DrawText(Handle, PChar(Panel.Text), Length(Panel.Text), R, Flags);
end
else if (Panel.Index = 0) then begin
//Brush.Color := CL_OK_SINGLE_MODE;
Pen.Color := clWindowText;
//FillRect(Rect);
Flags := DT_EXPANDTABS or DT_LEFT;
Flags := DrawTextBiDiModeFlags(Flags);
R := Rect;
ClientData.dmData.Images.Draw(sbMain.Canvas, R.Left + 1, R.Top, 198);
R.Top := R.Top + 1; R.Left := R.Left + 18;
DrawText(Handle, PChar(Panel.Text), Length(Panel.Text), R, Flags);
end;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aNewDBExecute(Sender: TObject);
var
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.aNewDBExecute') else _udebug := nil;{$ENDIF}
with TfrmStartWiz.Create(nil) do
try // finally
ParentHandle := Self.Handle;
if (Sender as TComponent).Tag = 1
then WizType := wtCopyDB
else WizType := wtNewDBSimple;
NeedClose := False;
NeedReconnect := False;
defaultConn := ClientData.dmData.SConnection;
if (ShowModal = mrOk) and (mrYes = ssMessageDlg(rs('frmMain', 'ConnectDB'), ssmtConfirmation, [ssmbYes, ssmbNo]))
then begin
Application.ProcessMessages;
ClientData.dmData.SConnection.Close;
// new DB admin have no password by default
if 0 <> LoginCodeInterprete(prFun.Login(ClientData.dmData.SConnection, ltProduction, AdminLoginName, '', ClientData.dmData.SConnection.Host, FnewDBID, False))
then Exit;
Application.ProcessMessages;
EntName := '';
InitProfile(ClientData.dmData.SConnection, UserID, ProfID, TreeID, ClientData.dmData.scMain);
frmMainForm.SetBtnStates;
BaseCurrName := GetBaseCurrName(ClientData.dmData.SConnection);
with frmMainForm do begin
for i := 0 to MDIChildCount - 1
do if MDIChildren[i].Handle <> (ActiveMDIChild as TfrmCCMainClass).Handle
then MDIChildren[i].Close;
for i := 0 to (ActiveMDIChild as TfrmCCMainClass).FrameList.FramesCount - 1
do (ActiveMDIChild as TfrmCCMainClass).FrameList.Items[i].Free;
(ActiveMDIChild as TfrmCCMainClass).FrameList.Clear;
(ActiveMDIChild as TfrmCCMainClass).NotChangeDetail := True;
//FrameList.Free;
//FrameList := TssFrameList.Create(Self);
ReloadRes;
if (ActiveMDIChild as TfrmCCMainClass).ViewType <> frmMainForm.GetEnabledView((ActiveMDIChild as TfrmCCMainClass).ViewType)
then (ActiveMDIChild as TfrmCCMainClass).ViewType := frmMainForm.GetEnabledView((ActiveMDIChild as TfrmCCMainClass).ViewType)
else (ActiveMDIChild as TfrmCCMainClass).RefreshTree(0);
(ActiveMDIChild as TfrmCCMainClass).panNoAccess.Visible := frmMainForm.AllDisabled;
(ActiveMDIChild as TfrmCCMainClass).NotChangeDetail := False;
(ActiveMDIChild as TfrmCCMainClass).tlMain.Selected := (ActiveMDIChild as TfrmCCMainClass).tlMain.Items[0];
panTitleButtons.Invalidate;
end;
end;
frmMainForm.RefreshStatusBar;
finally
Free;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
end;
//==============================================================================================
procedure TfrmMain.RefreshMultiEnts;
var
i: Integer;
FFrame: TssBaseFrame;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.RefreshMultiEnts') else _udebug := nil;{$ENDIF}
FFrame := TfrmCCMain(Self.ActiveMDIChild).FrameList.FcurrFrame;
if FFrame is TfmWaybillOut
then FFrame.DoRefresh(0)
else RefreshFun('TfmWaybillOut', 0);
if FFrame is TfmAccOut
then FFrame.DoRefresh(0)
else RefreshFun('TfmAccOut', 0);
if (FFrame is TfmOrders) and (FFrame.Tag = -16)
then FFrame.DoRefresh(0)
else RefreshFun('TfmOrders', -16);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.TBItem9Click(Sender: TObject);
//{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
//if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.lblWWWClick') else _udebug := nil;{$ENDIF}
with TfmDebugTrace.Create(nil) do begin
Mode := (Sender as TTBItem).Tag;
ShowModal;
Free;
end;
//{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.mnuSrvDbgLevelAcceptText(Sender: TObject; var NewText: String; var Accept: Boolean);
var
s: OleVariant;
//{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
//if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmMain.mnuSrvDbgLevelAcceptText') else _udebug := nil;{$ENDIF}
try
NewText := trim(NewText);
Accept := (0 <= StrToInt(NewText));
if Accept then Accept := ClientData.dmData.SConnection.AppServer.Command(cmdSetServerDebugLevel, NewText, s); // server should accept that too ;)
except
Accept := False;
end;
//{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.aTutorialExecute(Sender: TObject);
var
err: Integer;
s: String;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'aTutorialExecute') else _udebug := nil;{$ENDIF}
s := URL_KeyHost + '/tutorial';
err := ShellExecute(Application.Handle, nil, PChar(s), nil, nil, SW_SHOWNORMAL);
if err < 33 then ssMessageDlg(s + crlf + GetSysError, ssmtError, [ssmbOk]);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TfrmMain.lblStatusHyperLinkClick(Sender: TObject; LinkName: String);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'lblStatusHyperLinkClick') else _udebug := nil;{$ENDIF}
ShellExecute(Application.Handle, nil, PChar(LinkName), nil, nil, SW_SHOWNORMAL);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
initialization
{$IFDEF UDEBUG}
Debugging := False;
DEBUG_unit_ID := debugRegisterUnit('Main', @Debugging, DEBUG_group_ID);
{$ENDIF}
FlastAdTime := IncMonth(now, -1); // force 1st time show
ShellHook := SetWindowsHookEx(WH_SHELL, @ShellProcHook, 0, GetCurrentThreadId);
//==============================================================================================
finalization
UnhookWindowsHookEx(ShellHook);
//{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF}
end.
| 36.415225 | 165 | 0.60493 |
c38959fa11aa51fc5aaa3a7dcee65dc3d8b3e9f7 | 653 | dpr | Pascal | Demo/D10_4/SVGIconImageListDemo.dpr | atkins126/SVGIconImageList | 368376ad41c74e70691785469e965a9b0dc77d97 | [
"Apache-2.0"
]
| 4 | 2021-05-06T17:36:32.000Z | 2022-01-17T21:33:25.000Z | Demo/D10_4/SVGIconImageListDemo.dpr | atkins126/SVGIconImageList | 368376ad41c74e70691785469e965a9b0dc77d97 | [
"Apache-2.0"
]
| null | null | null | Demo/D10_4/SVGIconImageListDemo.dpr | atkins126/SVGIconImageList | 368376ad41c74e70691785469e965a9b0dc77d97 | [
"Apache-2.0"
]
| 1 | 2021-04-12T19:31:49.000Z | 2021-04-12T19:31:49.000Z | program SVGIconImageListDemo;
uses
Vcl.Forms,
Vcl.Themes,
Vcl.Styles,
UMainNew in '..\Source\UMainNew.pas' {MainForm},
SVGIconImageListEditorUnit in '..\..\Packages\SVGIconImageListEditorUnit.pas' {SVGIconImageListEditor},
SVGIconImageList in '..\..\source\SVGIconImageList.pas',
UDataModule in '..\Source\UDataModule.pas' {ImageDataModule: TDataModule};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
//TStyleManager.TrySetStyle('Windows10');
Application.CreateForm(TImageDataModule, ImageDataModule);
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end.
| 29.681818 | 106 | 0.739663 |
c3bfc233ac1f9d6ace362ea70df0b51c8bfb4f0c | 2,561 | pas | Pascal | Lib/Pkg.Json.Utils.pas | TCardinal/Delphi-JsonToDelphiClass | 49b3b75cdcd8b4dcd12989df9b0b28c51c298057 | [
"MIT"
]
| 56 | 2019-12-20T20:02:01.000Z | 2022-03-29T04:20:25.000Z | Lib/Pkg.Json.Utils.pas | TCardinal/Delphi-JsonToDelphiClass | 49b3b75cdcd8b4dcd12989df9b0b28c51c298057 | [
"MIT"
]
| null | null | null | Lib/Pkg.Json.Utils.pas | TCardinal/Delphi-JsonToDelphiClass | 49b3b75cdcd8b4dcd12989df9b0b28c51c298057 | [
"MIT"
]
| 15 | 2019-12-20T20:06:00.000Z | 2022-02-07T10:58:34.000Z | unit Pkg.Json.Utils;
interface
uses
System.Classes,
{$IFDEF MSWINDOWS}
Winapi.ShellAPI, Winapi.Windows,
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
Posix.Stdlib,
{$ENDIF POSIX}
System.Json.Writers, System.Json.Readers, System.SysUtils;
type
TJsonStringWriter = class(TJsonTextWriter)
private
FStrinBuilder: TStringBuilder;
FStringWriter: TStringWriter;
public
constructor Create;
destructor Destroy; override;
function ToString: string; override;
end;
TJsonStringReader = class(TJsonTextReader)
private
FStrinReader: TStringReader;
public
constructor Create(const AJson: string);
destructor Destroy; override;
end;
procedure ShellExecute(aFileName: string);
function MinifyJson(AJson: string): string;
function PrettyPrint(AJson: string): string;
implementation
uses
System.Json.Types;
procedure ShellExecute(aFileName: string);
begin
{$IFDEF MSWINDOWS}
Winapi.ShellAPI.ShellExecute(0, 'OPEN', PChar(aFileName), '', '', SW_SHOWNORMAL);
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
_system(PAnsiChar('open ' + AnsiString(aFileName)));
{$ENDIF POSIX}
end;
function JsonReformat(const AJson: string; Indented: Boolean): string;
var
JsonWriter: TJsonStringWriter;
JsonReader: TJsonStringReader;
begin
JsonReader := TJsonStringReader.Create(AJson);
JsonWriter := TJsonStringWriter.Create;
if Indented then
JsonWriter.Formatting := TJsonFormatting.Indented;
try
JsonWriter.WriteToken(JsonReader);
Result := JsonWriter.ToString;
finally
JsonWriter.Free;
JsonReader.Free;
end;
end;
function MinifyJson(AJson: string): string;
begin
Result := JsonReformat(AJson, false);
end;
function PrettyPrint(AJson: string): string;
begin
Result := JsonReformat(AJson, True);
end;
{ TJsonStringWriter }
constructor TJsonStringWriter.Create;
begin
FStrinBuilder := TStringBuilder.Create;
FStringWriter := TStringWriter.Create(FStrinBuilder);
inherited Create(FStringWriter);
end;
destructor TJsonStringWriter.Destroy;
begin
FStringWriter.Free;
FStrinBuilder.Free;
inherited Destroy;
end;
function TJsonStringWriter.ToString: string;
begin
Result := FStrinBuilder.ToString;
end;
{ TJsonStringReader }
constructor TJsonStringReader.Create(const AJson: string);
begin
FStrinReader := TStringReader.Create(AJson);
inherited Create(FStrinReader);
end;
destructor TJsonStringReader.Destroy;
begin
FStrinReader.Free;
inherited Destroy;
end;
end.
| 21.341667 | 84 | 0.724717 |
c3cd99ab390da55da11c1c508a000308829d7e41 | 27,977 | pas | Pascal | npp/FetchResourceForm.pas | novakjf2000/FHIRServer | a47873825e94cd6cdfa1a077f02e0960098bbefa | [
"BSD-3-Clause"
]
| 1 | 2018-01-08T06:40:02.000Z | 2018-01-08T06:40:02.000Z | npp/FetchResourceForm.pas | novakjf2000/FHIRServer | a47873825e94cd6cdfa1a077f02e0960098bbefa | [
"BSD-3-Clause"
]
| null | null | null | npp/FetchResourceForm.pas | novakjf2000/FHIRServer | a47873825e94cd6cdfa1a077f02e0960098bbefa | [
"BSD-3-Clause"
]
| null | null | null | unit FetchResourceForm;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
// todo:
// look ahead on search parameters on past values by name
// better date entry
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VirtualTrees, Vcl.StdCtrls, Vcl.ExtCtrls, NppForms, FHIRClient,
FHIRResources, FHIRTypes, FHIRUtilities, FHIRBase, AdvObjects, AdvGenerics, Math, StringSupport,
EncodeSupport, clipbrd, parsemap, Generics.Collections, FHIRProfileUtilities,
Vcl.Samples.Spin, fhirpath;
const
MIN_COL_WIDTH = 260;
SEARCH_PANEL_HEIGHT = 26;
type
TFetchResourceFrm = class;
TSearchEntryPanel = class (TAdvObject)
private
form : TFetchResourceFrm;
definition : TFhirCapabilityStatementRestResourceSearchParam;
panel : TPanel;
lbl : TLabel;
edit, edit2 : TEdit;
prefix, modList : TComboBox;
procedure build;
procedure buildEdit(typeNote : String);
procedure buildNumberEdit(typeNote : String; dateQualifiers : boolean);
procedure buildQuantityEdit;
procedure readParamValue(s : String);
public
constructor create(form : TFetchResourceFrm; definition : TFhirCapabilityStatementRestResourceSearchParam);
destructor Destroy; override;
procedure AdjustPosition(top, left, width : integer);
procedure addToUrl(b : TStringBuilder);
procedure readFromURL(pm : TParseMap);
end;
TFetchResourceFrm = class(TNppForm)
Panel1: TPanel;
Panel2: TPanel;
pnlCriteria: TPanel;
Panel4: TPanel;
Splitter1: TSplitter;
Label1: TLabel;
cbxType: TComboBox;
btnCancel: TButton;
btnOpen: TButton;
vtMatches: TVirtualStringTree;
ScrollBox1: TScrollBox;
Panel3: TPanel;
btnSearchAll: TButton;
btnCopy: TButton;
btnPaste: TButton;
btnFirst: TButton;
btnPrev: TButton;
btnNext: TButton;
btnLast: TButton;
btnSearchPaged: TButton;
Label2: TLabel;
cbxSort: TComboBox;
Label3: TLabel;
edtPageCount: TSpinEdit;
cbSearchOrder: TCheckBox;
rbXml: TRadioButton;
rbJson: TRadioButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure cbxTypeChange(Sender: TObject);
procedure btnCopyClick(Sender: TObject);
procedure btnPasteClick(Sender: TObject);
procedure btnSearchAllClick(Sender: TObject);
procedure btnSearchPagedClick(Sender: TObject);
procedure vtMatchesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
procedure vtMatchesAddToSelection(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure vtMatchesRemoveFromSelection(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure vtMatchesDblClick(Sender: TObject);
private
{ Private declarations }
FClient : TFhirHTTPClient;
FCapabilityStatement : TFHIRCapabilityStatement;
FProfiles : TProfileManager;
FType : TFhirResourceType;
FSearchItems : TAdvList<TSearchEntryPanel>;
FColumns : TDictionary<String, String>;
FMatches : TAdvList<TFHIRResource>;
FLinks : TDictionary<String, String>;
FSelectedId: String;
FSelectedType: TFhirResourceType;
procedure SetClient(const Value: TFhirHTTPClient);
procedure SetCapabilityStatement(const Value: TFHIRCapabilityStatement);
// choosing type
procedure loadTypeCombo;
procedure changeSelectedType;
// search parameters
procedure ClearSearchItems;
procedure AddSearchAll;
procedure AddSearch(rr : TFhirCapabilityStatementRestResource);
procedure loadSortCombo;
function createSearchParam(name, definition : String; type_ : TFhirSearchParamTypeEnum) : TFhirCapabilityStatementRestResourceSearchParam;
procedure SetProfiles(const Value: TProfileManager);
procedure layoutSearchParameters;
function asURL : String;
procedure readURL(pm : TParseMap);
procedure fetchUrl(s : String);
// columns
procedure clearColumns;
function ignoreColumn(st : TFhirStructureDefinition; ed : TFhirElementDefinition) : boolean;
procedure AddColumn(name, path : String);
// search
procedure clearSearch;
procedure dosearch(url : String; all : boolean);
function GetCell(res : TFhirResource; path : String ) : String;
public
{ Public declarations }
property Client : TFhirHTTPClient read FClient write SetClient;
property Conformance : TFHIRCapabilityStatement read FCapabilityStatement write SetCapabilityStatement;
property Profiles : TProfileManager read FProfiles write SetProfiles;
property SelectedType : TFhirResourceType read FSelectedType write FSelectedType;
property SelectedId : String read FSelectedId write FSelectedId;
end;
var
FetchResourceFrm: TFetchResourceFrm;
implementation
{$R *.dfm}
function tail(s : String) : String;
begin
result := s.Substring(s.LastIndexOf('.')+1);
end;
function TFetchResourceFrm.ignoreColumn(st : TFhirStructureDefinition; ed : TFhirElementDefinition) : boolean;
var
edx : TFhirElementDefinition;
begin
if (ed.path.EndsWith('.meta')) then
result := true
else
begin
result := false;
for edx in st.snapshot.elementList do
if edx.path.StartsWith(ed.path+'.') then
result := false;
end;
end;
procedure TFetchResourceFrm.AddColumn(name, path: String);
var
col : TVirtualTreeColumn;
begin
if not FColumns.ContainsKey(name) then
begin
FColumns.Add(name, path);
col := vtMatches.Header.Columns.Add;
col.Text := name;
end;
end;
procedure TFetchResourceFrm.AddSearch(rr: TFhirCapabilityStatementRestResource);
function ignore(name : String) : boolean;
begin
result := StringArrayExistsInsensitive(['_sort', '_filter', '_count'], name);
end;
var
n : boolean;
sp : TFhirCapabilityStatementRestResourceSearchParam;
st : TFhirStructureDefinition;
ed : TFhirElementDefinition;
begin
n := false;
for sp in rr.searchParamList do
n := n or (sp.name = '_id');
if not n then
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_id', 'Resource id', SearchParamTypeToken)));
for sp in rr.searchParamList do
if not ignore(sp.name) then
FSearchItems.Add(TSearchEntryPanel.create(self, sp.Link));
loadSortCombo;
FormResize(nil);
ClearColumns;
AddColumn('id', 'id');
AddColumn('version', 'meta.versionId');
AddColumn('date', 'meta.lastUpdated');
AddColumn('profile', 'meta.profile');
AddColumn('security', 'meta.security');
if not Profiles.getProfileStructure(nil, 'http://hl7.org/fhir/StructureDefinition/'+CODES_TFHIRResourceTypesEnum[rr.type_], st) then
AddColumn('text', 'text.div')
else
try
for ed in st.snapshot.elementList do
if ed.path.Contains('.') and ed.isSummary and not ignoreColumn(st, ed) then
AddColumn(tail(ed.path), ed.path);
finally
st.Free;
end;
end;
procedure TFetchResourceFrm.AddSearchAll;
begin
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_id', 'Resource id', SearchParamTypeToken)));
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_text', 'Search by text content (narrative)', SearchParamTypeString)));
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_content', 'Search by text content (all elements)', SearchParamTypeString)));
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_lastUpdated', 'Search by date of last update', SearchParamTypeDate)));
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_profile', 'Search by Profile', SearchParamTypeToken)));
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_security', 'Search by security label', SearchParamTypeToken)));
FSearchItems.Add(TSearchEntryPanel.create(self, createSearchParam('_tag', 'Search by workflow tag', SearchParamTypeToken)));
FormResize(nil);
loadSortCombo;
ClearColumns;
AddColumn('type', '@type');
AddColumn('id', 'id');
AddColumn('version', 'meta.versionId');
AddColumn('date', 'meta.lastUpdated');
AddColumn('profile', 'meta.profile');
AddColumn('security', 'meta.security');
AddColumn('tag', 'meta.tag');
AddColumn('text', 'text.div');
end;
function TFetchResourceFrm.asURL: String;
var
b : TStringBuilder;
se : TSearchEntryPanel;
begin
b := TStringBuilder.Create;
try
for se in FSearchItems do
se.addToUrl(b);
if b.Length > 0 then
b.Append('&');
b.Append('_count=');
b.Append(edtPageCount.Value);
if cbxSort.Text <> '' then
begin
if cbSearchOrder.Checked then
b.Append('_sort:desc=')
else
b.Append('_sort=');
b.Append(cbxSort.Text);
end;
result := b.ToString;
finally
b.Free;
end;
end;
procedure TFetchResourceFrm.btnCopyClick(Sender: TObject);
begin
Clipboard.Open;
Clipboard.AsText := '?'+asURL;
Clipboard.Close;
end;
procedure TFetchResourceFrm.btnPasteClick(Sender: TObject);
var
pm : TParseMap;
s : String;
begin
Clipboard.Open;
s := Clipboard.AsText;
Clipboard.Close;
if (s.StartsWith(FClient.url)) and not s.Contains('?') then
fetchUrl(s.Substring(FClient.url.Length+1))
else
begin
if s.Contains('?') then
s := s.Substring(s.IndexOf('?')+1);
pm := TParseMap.create(s);
try
readURL(pm);
finally
pm.Free;
end;
end;
end;
procedure TFetchResourceFrm.btnSearchAllClick(Sender: TObject);
begin
doSearch(asURL, true);
end;
procedure TFetchResourceFrm.btnSearchPagedClick(Sender: TObject);
begin
doSearch(asURL, false);
end;
procedure TFetchResourceFrm.cbxTypeChange(Sender: TObject);
begin
changeSelectedType;
end;
procedure TFetchResourceFrm.changeSelectedType;
var
obj : TFHIRObject;
begin
ClearSearchItems;
clearColumns;
clearSearch;
obj := cbxType.Items.Objects[cbxType.ItemIndex] as TFHIRObject;
if obj is TFhirCapabilityStatement then
begin
FType := frtNull;
AddSearchAll
end
else
begin
FType := ResourceTypeByName(CODES_TFHIRResourceTypesEnum[(obj as TFhirCapabilityStatementRestResource).type_]);
AddSearch(obj as TFhirCapabilityStatementRestResource);
end;
btnCopy.Enabled := true;
btnPaste.Enabled := true;
end;
procedure TFetchResourceFrm.clearColumns;
begin
FColumns.Clear;
vtMatches.Header.Columns.Clear;
end;
procedure TFetchResourceFrm.clearSearch;
begin
FMatches.Clear;
vtMatches.RootNodeCount := 0;
vtMatches.Invalidate;
btnFirst.Enabled := false;
btnNext.Enabled := false;
btnPrev.Enabled := false;
btnLast.Enabled := false;
end;
procedure TFetchResourceFrm.ClearSearchItems;
begin
FSearchItems.Clear;
end;
function TFetchResourceFrm.createSearchParam(name, definition: String; type_: TFhirSearchParamTypeEnum): TFhirCapabilityStatementRestResourceSearchParam;
begin
result := TFhirCapabilityStatementRestResourceSearchParam.Create;
try
result.name := name;
result.definition := definition;
result.type_ := type_;
result.Link;
finally
result.Free;
end;
end;
procedure TFetchResourceFrm.dosearch(url: String; all : boolean);
var
bundle : TFHIRBundle;
entry : TFhirBundleEntry;
link : TFhirBundleLink;
begin
clearSearch;
bundle := FClient.search(FType, all, url+'&_summary=true');
try
for entry in bundle.entryList do
if ((entry.search = nil) or (entry.search.mode = SearchEntryModeMatch)) and (entry.resource <> nil) and ((entry.resource.ResourceType = FType) or (FType = frtNull)) then
FMatches.Add(entry.resource.Link);
for link in bundle.link_List do
if link.relation = 'first' then
begin
FLinks.Add('first', link.url);
btnFirst.Enabled := true;
end
else if link.relation = 'next' then
begin
FLinks.Add('next', link.url);
btnNext.Enabled := true;
end
else if link.relation = 'previous' then
begin
FLinks.Add('prev', link.url);
btnPrev.Enabled := true;
end
else if link.relation = 'last' then
begin
FLinks.Add('last', link.url);
btnLast.Enabled := true;
end;
vtMatches.RootNodeCount := FMatches.Count;
vtMatches.Invalidate;
finally
bundle.Free;
end;
end;
procedure TFetchResourceFrm.fetchUrl(s: String);
var
pm : TParseMap;
a : TArray<String>;
bundle : TFHIRBundle;
begin
pm := TParseMap.create('');
try
readURL(pm);
finally
pm.free;
end;
clearSearch;
clearColumns;
a := s.Split(['/']);
if (Length(a) >= 1) then
begin
cbxType.ItemIndex := cbxType.Items.IndexOf(a[0]);
changeSelectedType;
end;
if (Length(a) >= 2) and (cbxType.ItemIndex > -1) then
begin
FMatches.Add(FClient.readResource(ResourceTypeByName(cbxType.Text), a[1]));
btnFirst.Enabled := false;
btnNext.Enabled := false;
btnPrev.Enabled := false;
btnLast.Enabled := false;
vtMatches.RootNodeCount := FMatches.Count;
vtMatches.Invalidate;
end;
end;
procedure TFetchResourceFrm.FormCreate(Sender: TObject);
begin
FSearchItems := TAdvList<TSearchEntryPanel>.create;
FColumns := TDictionary<String, String>.create;
FMatches := TAdvList<TFHIRResource>.create;
FLinks := TDictionary<String, String>.create;
end;
procedure TFetchResourceFrm.FormDestroy(Sender: TObject);
begin
FClient.free;
FCapabilityStatement.free;
FSearchItems.Free;
FProfiles.Free;
FColumns.Free;
FMatches.Free;
FLinks.Free;
end;
function enough(v, i: Integer) : integer;
begin
if v mod i = 0 then
result := v div i
else
result := v div i + 1;
end;
procedure TFetchResourceFrm.FormResize(Sender: TObject);
begin
layoutSearchParameters;
end;
procedure TFetchResourceFrm.FormShow(Sender: TObject);
begin
loadTypeCombo;
end;
function TFetchResourceFrm.GetCell(res: TFhirResource; path: String): String;
var
query : TFHIRPathEngine;
begin
query := TFHIRPathEngine.create(nil);
try
result := query.evaluateToString(nil, res, path);
finally
query.free;
end;
end;
procedure TFetchResourceFrm.layoutSearchParameters;
var
maxCols, naturalRows, naturalCols, actualCols, actualRows, width, left, top, i, c : integer;
begin
if FSearchItems.Count > 0 then
begin
maxCols := (ScrollBox1.ClientWidth - 20 {vertical scrollbar}) div MIN_COL_WIDTH;
naturalRows := ScrollBox1.ClientHeight div SEARCH_PANEL_HEIGHT;
naturalCols := enough(FSearchItems.Count, naturalRows);
actualCols := min(maxCols, naturalCols);
actualRows := enough(FSearchItems.Count, actualCols);
width := (ScrollBox1.ClientWidth - 20 {vertical scrollbar}) div actualCols;
top := 0;
left := 0;
c := 0;
for i := 0 to FSearchItems.Count - 1 do
begin
FSearchItems[i].AdjustPosition(top, left, width);
inc(c);
inc(top, SEARCH_PANEL_HEIGHT);
if c = actualRows then
begin
c := 0;
left := left + width;
top := 0;
end;
end;
end;
end;
procedure TFetchResourceFrm.loadSortCombo;
var
se : TSearchEntryPanel;
begin
cbxSort.Items.Clear;
cbxSort.Items.Add('');
for se in FSearchItems do
cbxSort.Items.Add(se.definition.name);
end;
procedure TFetchResourceFrm.loadTypeCombo;
var
r : TFhirCapabilityStatementRest;
rr : TFhirCapabilityStatementRestResource;
int : TFhirCapabilityStatementRestResourceInteraction;
it : TFhirCapabilityStatementRestInteraction;
any, ok : boolean;
fmt : TFHIRCode;
begin
cbxType.Items.Clear;
any := false;
for r in FCapabilityStatement.restList do
if r.mode = RestfulCapabilityModeServer then
begin
for it in r.interactionList do
if it.code = SystemRestfulInteractionSearchSystem then
cbxType.Items.AddObject('All Types', FCapabilityStatement);
for rr in r.resourceList do
begin
ok := false;
for int in rr.interactionList do
if (int.code in [TypeRestfulInteractionRead, TypeRestfulInteractionSearchType]) then
ok := true;
if ok then
cbxType.Items.AddObject(CODES_TFHIRResourceTypesEnum[rr.type_], rr);
end;
end;
for fmt in FCapabilityStatement.formatList do
if fmt.value.ToLower.Contains('xml') then
rbXml.Enabled := true
else if fmt.value.ToLower.Contains('json') then
rbJson.Enabled := true;
if not rbJson.Enabled then
rbXml.Checked := true
else
rbJson.Checked := true;
end;
procedure TFetchResourceFrm.readURL(pm: TParseMap);
var
se : TSearchEntryPanel;
begin
for se in FSearchItems do
se.readFromURL(pm);
if pm.varExists('_sort') then
begin
cbxSort.itemindex := cbxSort.Items.IndexOf(pm.GetVar('_sort'));
cbSearchOrder.Checked := false;
end else if pm.varExists('_sort:asc') then
begin
cbxSort.itemindex := cbxSort.Items.IndexOf(pm.GetVar('_sort:asc'));
cbSearchOrder.Checked := false;
end else if pm.varExists('_sort:desc') then
begin
cbxSort.itemindex := cbxSort.Items.IndexOf(pm.GetVar('_sort:desc'));
cbSearchOrder.Checked := true;
end;
if (pm.VarExists('_count')) then
edtPageCount.Value := StrToIntDef(pm.GetVar('_count'), 20);
end;
procedure TFetchResourceFrm.SetClient(const Value: TFhirHTTPClient);
begin
FClient.Free;
FClient := Value;
end;
procedure TFetchResourceFrm.SetCapabilityStatement(const Value: TFhirCapabilityStatement);
begin
FCapabilityStatement.Free;
FCapabilityStatement := Value;
end;
procedure TFetchResourceFrm.SetProfiles(const Value: TProfileManager);
begin
FProfiles.Free;
FProfiles := Value;
end;
procedure TFetchResourceFrm.vtMatchesAddToSelection(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
res : TFhirResource;
begin
res := FMatches[node.Index];
SelectedType := res.ResourceType;
SelectedId := res.id;
btnOpen.Enabled := true;
end;
procedure TFetchResourceFrm.vtMatchesDblClick(Sender: TObject);
begin
if btnOpen.Enabled then
ModalResult := mrOK;
end;
procedure TFetchResourceFrm.vtMatchesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
var
res : TFhirResource;
path : String;
begin
res := FMatches[node.Index];
path := FColumns[vtMatches.Header.Columns[Column].Text];
CellText := getCell(res, path);
end;
procedure TFetchResourceFrm.vtMatchesRemoveFromSelection(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
btnOpen.Enabled := false;
end;
{ TSearchEntryPanel }
constructor TSearchEntryPanel.create(form: TFetchResourceFrm; definition: TFhirCapabilityStatementRestResourceSearchParam);
begin
inherited create;
self.form := form;
self.definition := definition;
build;
end;
destructor TSearchEntryPanel.destroy;
begin
lbl.Free;
modList.Free;
panel.Free;
definition.Free;
inherited;
end;
procedure TSearchEntryPanel.readFromURL(pm: TParseMap);
var
ok : boolean;
s : String;
begin
if pm.VarExists(definition.name) then
readParamValue(pm.GetVar(definition.name))
else
begin
ok := false;
if (modList <> nil) then
for s in modList.Items do
if pm.VarExists(definition.name+':'+s) then
begin
ok := true;
modList.ItemIndex := modlist.Items.IndexOf(s);
readParamValue(pm.GetVar(definition.name+':'+s));
end;
if not ok then
readParamValue('');
end;
end;
procedure TSearchEntryPanel.readParamValue(s: String);
var
i, c : integer;
a : TArray<String>;
begin
case definition.type_ of
SearchParamTypeString, SearchParamTypeToken, SearchParamTypeComposite, SearchParamTypeUri, SearchParamTypeReference:
edit.text := s;
SearchParamTypeNumber, SearchParamTypeDate, SearchParamTypeQuantity:
begin
c := -1;
for i := 0 to prefix.Items.Count - 1 do
if s.StartsWith(prefix.Items[i].Substring(0, 2)) then
c := i;
if (c = -1) then
edit.text := s
else
begin
prefix.ItemIndex := c;
edit.text := s.Substring(2);
end;
if (definition.type_ = SearchParamTypeQuantity) then
begin
s := edit.text;
if (s.Contains('|')) then
begin
a := s.Split(['|']);
edit.Text := a[0];
if (length(a) >= 2) then
edit2.Text := a[2];
end;
end;
end;
end;
end;
procedure TSearchEntryPanel.build;
var
hasMod : boolean;
modc : TFhirSearchModifierCodeEnum;
begin
panel := TPanel.Create(form);
panel.Parent := form.ScrollBox1;
// the correct values will be assigned elsewhere, and pushed into adjustposition
panel.Top := 0;
panel.Left := 0;
panel.Width := 200;
panel.Height := SEARCH_PANEL_HEIGHT;
panel.BevelOuter := bvNone;
panel.BevelInner := bvNone;
lbl := TLabel.Create(form);
lbl.Parent := panel;
lbl.Caption := definition.name+':';
lbl.ParentShowHint := false;
lbl.ShowHint := true;
lbl.Hint := definition.documentation;
lbl.Top := 3;
lbl.Left := 5;
lbl.Width := form.Canvas.TextWidth(lbl.Caption);
// todo: fetch the search parameter definitions?
// hasMod := false;
// for modc := low(TFhirSearchModifierCodeEnum) to high(TFhirSearchModifierCodeEnum) do
// if modc in definition.modifier then
hasMod := true;
case definition.type_ of
SearchParamTypeString: buildEdit('Text to search by');
SearchParamTypeToken: buildEdit('Code or text to search by');
SearchParamTypeComposite: buildEdit('Composite value to search by');
SearchParamTypeUri: buildEdit('URI to search by');
SearchParamTypeReference: buildEdit('ID to search by');
SearchParamTypeNumber: buildNumberEdit('Number to search by', false);
SearchParamTypeDate: buildNumberEdit('Date to search by (variable precision, in the format yyyy-mm-ddThh:mm:ss[TS], where TX is Z or +/-hh:mm)', true);
SearchParamTypeQuantity: buildQuantityEdit;
end;
if (hasMod) then
begin
modList := TComboBox.Create(form);
modList.parent := panel;
modList.Left := panel.Width - 55;
modList.Top := edit.Top;
modlist.Width := 50;
modlist.Style := csDropDownList;
modlist.Items.Add('');
for modc := low(TFhirSearchModifierCodeEnum) to high(TFhirSearchModifierCodeEnum) do
// todo - use search parameter definition if modc in definition.modifier then
modlist.Items.Add(':'+CODES_TFhirSearchModifierCodeEnum[modc]);
end;
end;
procedure TSearchEntryPanel.buildEdit(typeNote : String);
begin
edit := TEdit.Create(form);
edit.Parent := panel;
edit.Left := lbl.left + lbl.Width + 5;
edit.ParentShowHint := false;
edit.ShowHint := true;
edit.Hint := typeNote;
edit.Width := 100;
edit.Text := '';
end;
procedure TSearchEntryPanel.buildNumberEdit(typeNote: String; dateQualifiers : boolean);
begin
prefix := TComboBox.Create(form);
prefix.Parent := panel;
prefix.Left := lbl.left + lbl.Width + 5;
prefix.ParentShowHint := false;
prefix.ShowHint := true;
prefix.Hint := 'Criteria for this value';
prefix.Width := 40;
prefix.Style := csDropDownList;
SendMessage(prefix.Handle, CB_SETDROPPEDWIDTH, 200, 0);
prefix.items.Add('eq - equals');
prefix.items.Add('ne - not equals');
prefix.items.Add('gt - greater than');
prefix.items.Add('lt - less than');
prefix.items.Add('ge - greater or equal');
prefix.items.Add('le - less or equal');
if (dateQualifiers) then
begin
prefix.items.Add('sa - starts before');
prefix.items.Add('eb - ends after');
end;
prefix.items.Add('ap - Approximately');
prefix.ItemIndex := 0;
prefix.DropDownCount := prefix.Items.Count;
edit := TEdit.Create(form);
edit.Parent := panel;
edit.Left := prefix.left + prefix.Width + 5;
edit.ParentShowHint := false;
edit.ShowHint := true;
edit.Hint := typeNote;
edit.Width := 100;
edit.Text := '';
end;
procedure TSearchEntryPanel.buildQuantityEdit;
begin
prefix := TComboBox.Create(form);
prefix.Parent := panel;
prefix.Left := lbl.left + lbl.Width + 5;
prefix.ParentShowHint := false;
prefix.ShowHint := true;
prefix.Hint := 'Criteria for this value';
prefix.Width := 40;
prefix.Style := csDropDownList;
SendMessage(prefix.Handle, CB_SETDROPPEDWIDTH, 200, 0);
prefix.items.Add('eq - equals');
prefix.items.Add('ne - not equals');
prefix.items.Add('gt - greater than');
prefix.items.Add('lt - less than');
prefix.items.Add('ge - greater or equal');
prefix.items.Add('le - less or equal');
prefix.items.Add('sa - starts before');
prefix.items.Add('eb - ends after');
prefix.items.Add('ap - Approximately');
prefix.ItemIndex := 0;
prefix.DropDownCount := prefix.Items.Count;
edit := TEdit.Create(form);
edit.Parent := panel;
edit.Left := prefix.left + prefix.Width + 5;
edit.ParentShowHint := false;
edit.ShowHint := true;
edit.Hint := 'Value of the quantity';
edit.Width := 500;
edit.Text := '';
edit2 := TEdit.Create(form);
edit2.Parent := panel;
edit2.Left := edit.left + edit.Width + 5;
edit2.ParentShowHint := false;
edit2.ShowHint := true;
edit2.Hint := 'Unit of the quantity';
edit2.Width := 500;
edit2.Text := '';
end;
procedure TSearchEntryPanel.addToUrl(b: TStringBuilder);
begin
if edit.text <> '' then
begin
if b.Length > 0 then
b.Append('&');
b.Append(definition.name);
if (modList <> nil) and (modList.ItemIndex > 0) then
b.Append(':'+modList.Text);
b.Append('=');
if (prefix <> nil) and (prefix.itemIndex > 0) then
b.append(copy(prefix.text, 1, 2));
b.Append(EncodeMIME(edit.Text));
if (edit2 <> nil) and (edit2.Text <> '') then
b.Append('||'+EncodeMIME(edit2.Text));
end;
end;
procedure TSearchEntryPanel.AdjustPosition(top, left, width: integer);
var
rw, w : integer;
begin
panel.Top := top;
panel.Left := left;
panel.Width := width;
if modList <> nil then
begin
modList.Left := panel.Width - 55;
rw := modList.Left;
end
else
rw := panel.Width;
case definition.type_ of
SearchParamTypeString, SearchParamTypeToken, SearchParamTypeComposite, SearchParamTypeUri, SearchParamTypeReference: edit.Width := rw-5-edit.Left;
SearchParamTypeNumber, SearchParamTypeDate: edit.Width := rw-5-edit.Left;
SearchParamTypeQuantity:
begin
w := (rw - edit.Left - 5) div 2;
edit.Width := w;
edit2.left := edit.Left + edit.Width + 5;
edit2.Width := rw - edit2.left;
end;
end;
end;
end.
| 29.731137 | 175 | 0.708868 |
c39b228d5aea9143d13b032a2bd772fc728ab97b | 2,964 | dpr | Pascal | Source/Propagator/Enterprise/BoldPropagatorDll.dpr | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
]
| 121 | 2020-09-22T10:46:20.000Z | 2021-11-17T12:33:35.000Z | Source/Propagator/Enterprise/BoldPropagatorDll.dpr | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
]
| 8 | 2020-09-23T12:32:23.000Z | 2021-07-28T07:01:26.000Z | Source/Propagator/Enterprise/BoldPropagatorDll.dpr | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
]
| 42 | 2020-09-22T14:37:20.000Z | 2021-10-04T10:24:12.000Z | library BoldPropagatorDll;
uses
ComServ,
BoldSubscriptionHandler in 'Source\Propagator\Enterprise\BoldSubscriptionHandler.pas',
BoldAdvancedPropagator in 'Source\Propagator\Enterprise\BoldAdvancedPropagator.pas',
BoldClientHandler in 'Source\Propagator\Enterprise\BoldClientHandler.pas',
BoldClientNotifierHandler in 'Source\Propagator\Enterprise\BoldClientNotifierHandler.pas',
BoldClientQueue in 'Source\Propagator\Enterprise\BoldClientQueue.pas',
BoldEnqueuer in 'Source\Propagator\Enterprise\BoldEnqueuer.pas',
BoldIndexedList in 'Source\Propagator\Enterprise\BoldIndexedList.pas',
BoldIndexList in 'Source\Propagator\Enterprise\BoldIndexList.pas',
BoldListNodes in 'Source\Propagator\Enterprise\BoldListNodes.pas',
BoldOutputQueueHandler in 'Source\Propagator\Enterprise\BoldOutputQueueHandler.pas',
BoldPriorityListEnlister in 'Source\Propagator\Enterprise\BoldPriorityListEnlister.pas',
BoldPropagatorApplication in 'Source\Propagator\Enterprise\BoldPropagatorApplication.pas',
BoldPropagatorServer in 'Source\Propagator\Enterprise\BoldPropagatorServer.pas',
BoldPropagatorCleanup in 'Source\Propagator\Enterprise\BoldPropagatorCleanup.pas',
BoldPropagatorMainForm in 'Source\Propagator\Enterprise\BoldPropagatorMainForm.pas' {PropagatorMainForm},
BoldPropagatorSubscriptions in 'Source\Propagator\Enterprise\BoldPropagatorSubscriptions.pas',
BoldPropagatorUIManager in 'Source\Propagator\Enterprise\BoldPropagatorUIManager.pas',
BoldAbstractOutputQueueHandler in 'Source\Propagator\Enterprise\BoldAbstractOutputQueueHandler.pas',
BoldLockingSupportInterfaces_TLB in '..\Common\BoldLockingSupportInterfaces_TLB.pas',
BoldClientHandlerCOM in 'Source\Propagator\Enterprise\BoldClientHandlerCOM.pas',
BoldEnqueuerCOM in 'Source\Propagator\Enterprise\BoldEnqueuerCOM.pas',
BoldAdvancedPropagatorCOM in 'Source\Propagator\Enterprise\BoldAdvancedPropagatorCOM.pas',
BoldLockManagerCOM in 'Source\Propagator\Enterprise\BoldLockManagerCOM.pas',
BoldLockManager in 'Source\Propagator\Enterprise\BoldLockManager.pas',
BoldLockManagerAdmin in 'Source\Propagator\Enterprise\BoldLockManagerAdmin.pas',
BoldLockManagerAdminCOM in 'Source\Propagator\Enterprise\BoldLockManagerAdminCOM.pas',
BoldLockList in 'Source\Propagator\Enterprise\BoldLockList.pas',
BoldServerHandlesDataMod in 'Source\Propagator\Enterprise\BoldServerHandlesDataMod.pas' {dmServerHandles: TDataModule},
BoldLockManagerExportHandle in 'Source\Propagator\Enterprise\BoldLockManagerExportHandle.pas',
BoldLockManagerAdminExportHandle in 'Source\Propagator\Enterprise\BoldLockManagerAdminExportHandle.pas',
BoldClientHandlerExportHandle in 'Source\Propagator\Enterprise\BoldClientHandlerExportHandle.pas',
BoldEnqueuerExportHandle in 'Source\Propagator\Enterprise\BoldEnqueuerExportHandle.pas';
exports
DllGetClassObject,
_DllCanUnloadNow name 'DllCanUnloadNow',
DllRegisterServer,
DllUnregisterServer;
{$R *.RES}
begin
end.
| 61.75 | 121 | 0.852901 |
c3785bff4a0f96d2a248bc1c1efce739535c1110 | 282,881 | pas | Pascal | references/mORMot/SynMongoDB.pas | zekiguven/alcinoe | e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c | [
"Apache-2.0"
]
| 2 | 2020-02-17T18:42:30.000Z | 2020-11-14T04:57:48.000Z | references/mORMot/SynMongoDB.pas | zekiguven/alcinoe | e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c | [
"Apache-2.0"
]
| 2 | 2019-06-23T00:02:43.000Z | 2019-10-12T22:39:28.000Z | references/mORMot/SynMongoDB.pas | zekiguven/alcinoe | e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c | [
"Apache-2.0"
]
| null | null | null | /// MongoDB document-oriented database direct access classes
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynMongoDB;
{
This file is part of Synopse framework.
Synopse framework. Copyright (C) 2018 Arnaud Bouchez
Synopse Informatique - https://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
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 Synopse mORMot framework.
The Initial Developer of the Original Code is Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (C) 2018
the Initial Developer. All Rights Reserved.
Contributor(s):
- BBackSoon
- Sabbiolina
- Zed
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
Version 1.18
- first public release, corresponding to mORMot Framework 1.18
and feature request [0fee1d995c]
TODO:
- handle BULK commands support for MongoDB >=2.6 for faster writes
see http://blog.mongodb.org/post/84922794768
- GridFS support
}
interface
{$I Synopse.inc} // define HASINLINE USETYPEINFO CPU32 CPU64 SQLITE3_FASTCALL
uses
{$ifdef MSWINDOWS}
Windows,
{$else}
{$ifdef KYLIX3}
SynKylix,
LibC,
{$else}
SynFPCLinux,
{$endif}
{$endif}
Classes,
Variants, // this unit expects Variants to be available for storage
SysUtils,
SynCrtSock,
SynCrypto, // MD5 and SHA1 needed for OpenAuth()
SynCommons,
SynTable, // for TSynTableStatement
SynLog;
{ ************ BSON (Binary JSON) process }
type
/// binary representation of a 128-bit decimal, stored as 16 bytes
// - i.e. IEEE 754-2008 128-bit decimal floating point as used in the
// BSON Decimal128 format, and processed by the TDecimal128 object
TDecimal128Bits = record
case integer of
0: (lo, hi: QWord);
1: (b: array[0..15] of byte);
2: (c: array[0..3] of cardinal);
end;
/// points to a 128-bit decimal binary
PDecimal128Bits = ^TDecimal128Bits;
/// enough characters to contain any TDecimal128 text representation
TDecimal128Str = array[0..42] of AnsiChar;
/// some special 128-bit decimal values
// - see TDecimal128.SetSpecial to set the corresponding value
// - dsvError is returned by TDecimal128.FromText() on parsing error
// - dsvValue indicates that this is not a known "special" value, but some
// valid decimal number
TDecimal128SpecialValue = (
dsvError, dsvValue, dsvNan, dsvZero, dsvPosInf, dsvNegInf, dsvMin, dsvMax);
/// handles a 128-bit decimal value
// - i.e. IEEE 754-2008 128-bit decimal floating point as used in the
// BSON Decimal128 format, i.e. betDecimal128 TBSONElementType
// - the betFloat BSON format stores a 64-bit floating point value, which
// doesn't have exact decimals, so may suffer from rounding or approximation
// - for instance, if you work with Delphi currency values, you may store
// betDecimal128 values in MongoDB - the easiest way is to include it as a
// TBSONVariant instance, via the NumberDecimal() function
// - there is no mathematical operator/methods for Decimal128 Value Objects,
// as required by MongoDB specifications: any computation must be done
// explicitly on native language value representation (e.g. currency, TBCD or
// any BigNumber library) - use ToCurr/FromCurr or ToText/FromText to make
// the appropriate safe conversions
{$ifndef UNICODE}
TDecimal128 = object
{$else}
TDecimal128 = record
{$endif}
public
/// the raw binary storage
Bits: TDecimal128Bits;
/// fills with the Zero value
// - note: under IEEE 754, Zero can have sign and exponents, so is not Hi=Lo=0
// - is the same as Fill(dsvZero)
procedure SetZero;
/// fills with a special value
// - dsvError or dsvValue will set dsvNan binary content
procedure SetSpecial(special: TDecimal128SpecialValue);
/// checks if the value matches one of the known special values
// - will search for dsvNan, dsvZero, dsvPosInf, dsvNegInf, dsvMin, dsvMax
function IsSpecial: TDecimal128SpecialValue;
/// fills with a 32-bit signed value
procedure FromInt32(value: integer);
/// fills with a 32-bit unsigned value
procedure FromUInt32(value: cardinal);
{$ifdef HASINLINE}inline;{$endif}
/// fills with a 64-bit signed value
procedure FromInt64(value: Int64);
/// fills with a 64-bit unsigned value
procedure FromQWord(value: QWord);
{$ifdef HASINLINE}inline;{$endif}
/// fills with a fixed decimal value, as stored in currency
// - will store the content with explictly four decimals, as in currency
// - by design, this method is very fast and accurate
procedure FromCurr(const value: Currency);
/// fills from the text representation of a decimal value
// - returns dsvValue or one of the dsvNan, dsvZero, dsvPosInf, dsvNegInf
// special value indicator otherwise on succes
// - returns dsvError on parsing failure
function FromText(text: PUTF8Char; textlen: integer): TDecimal128SpecialValue; overload;
/// fills from the text representation of a decimal value
// - returns dsvValue or one of the dsvNan, dsvZero, dsvPosInf, dsvNegInf
// special value indicator otherwise on succes
// - returns dsvError on parsing failure
function FromText(const text: RawUTF8): TDecimal128SpecialValue; overload;
/// convert a variant into one Decimal128 value
// - will first check for a TBSONVariant containing a betDecimal128 (e.g.
// as retrieved via the ToVariant method)
// - will recognize currency and VariantToInt64() stored values
// - then will try to convert the variant from its string value, expecting
// a floating-point text content
// - returns TRUE if conversion was made, FALSE on any error
function FromVariant(const value: variant): boolean;
/// fills with a native floating-point value
// - note that it doesn't make much sense to use this method: you should
// rather use the native betFloat BSON format, with native double precision
// - this method is just a wrapper around ExtendedToString and ToText,
// so you should provide the expected precision, from the actual storage
// variable (you may specify e.g. SINGLE_PRECISION or EXTENDED_PRECISION if
// you don't use a double kind of value)
function FromFloat(const value: TSynExtended; precision: integer=0): boolean;
/// fast bit-per-bit value comparison
function Equals(const other: TDecimal128): boolean;
{$ifdef HASINLINE}inline;{$endif}
/// converts the value to its string representation
// - returns the number of AnsiChar written to Buffer
function ToText(out Buffer: TDecimal128Str): integer; overload;
/// converts this Decimal128 value to its string representation
function ToText: RawUTF8; overload;
/// converts this Decimal128 value to its string representation
procedure ToText(var result: RawUTF8); overload;
/// convert this Decimal128 value to its TBSONVariant custom variant value
function ToVariant: variant; overload;
/// convert this Decimal128 value to its TBSONVariant custom variant value
procedure ToVariant(out result: variant); overload;
/// converts this Decimal128 value to a floating-point value
// - by design, some information may be lost during conversion
// - note that it doesn't make much sense to use this method: you should
// rather use the native betFloat BSON format, with native double precision
function ToFloat: TSynExtended;
/// converts this Decimal128 value to a fixed decimal value
// - by design, some information may be lost during conversion, unless the
// value has been stored previously via the FromCurr() method - in this
// case, conversion is immediate and accurate
function ToCurr: currency; overload;
{$ifdef HASINLINE}inline;{$endif}
/// converts this Decimal128 value to a fixed decimal value
// - by design, some information may be lost during conversion, unless the
// value has been stored previously via the FromCurr() method - in this
// case, conversion is immediate and accurate
procedure ToCurr(out result: currency); overload;
/// converts this Decimal128 value to its string representation
procedure AddText(W: TTextWriter);
end;
/// points to a 128-bit decimal value
PDecimal128 = ^TDecimal128;
const
/// the textual representation of the TDecimal128 special values
DECIMAL128_SPECIAL_TEXT: array[TDecimal128SpecialValue] of RawUTF8 = (
// dsvError, dsvValue, dsvNan, dsvZero, dsvPosInf, dsvNegInf, dsvMin, dsvMax
'', '', 'NaN', '0', 'Infinity', '-Infinity',
'-9.999999999999999999999999999999999E+6144',
'9.999999999999999999999999999999999E+6144');
BSON_DECIMAL128_HI_NAN = $7c00000000000000;
BSON_DECIMAL128_HI_INT64POS = $3040000000000000; // 0 fixed decimals
BSON_DECIMAL128_HI_INT64NEG = $b040000000000000;
BSON_DECIMAL128_HI_CURRPOS = $3038000000000000; // 4 fixed decimals
BSON_DECIMAL128_HI_CURRNEG = $b038000000000000;
BSON_DECIMAL128_EXPONENT_MAX = 6111;
BSON_DECIMAL128_EXPONENT_MIN = -6176;
BSON_DECIMAL128_EXPONENT_BIAS = 6176;
BSON_DECIMAL128_MAX_DIGITS = 34;
/// ready-to-be displayed text of a TDecimal128SpecialValue
function ToText(spec: TDecimal128SpecialValue): PShortString; overload;
type
/// exception type used for BSON process
EBSONException = class(ESynException);
/// storage of a BSON binary document
// - a specific type is defined for consistency with this unit classes
// - binary content should follow the "int32 e_list #0" standard layout
TBSONDocument = RawByteString;
/// dynamic array of BSON binary document storage
TBSONDocumentDynArray = array of TBSONDocument;
/// element types for BSON internal representation
TBSONElementType = (
betEOF, betFloat, betString, betDoc, betArray, betBinary,
betDeprecatedUndefined, betObjectID, betBoolean, betDateTime,
betNull, betRegEx, betDeprecatedDbptr, betJS, betDeprecatedSymbol,
betJSScope, betInt32, betTimestamp, betInt64, betDecimal128);
/// points to an element type for BSON internal representation
PBSONElementType = ^TBSONElementType;
/// sub-types for betBinary element BSON internal representation
TBSONElementBinaryType = (
bbtGeneric, bbtFunction, bbtOldBinary, bbtOldUUID, bbtUUID, bbtMD5,
bbtUser = $80);
/// 24-bit storage, mapped as a 3 bytes buffer
// - as used fo TBSONObjectID.MachineID and TBSONObjectID.Counter
TBSON24 = record
b1,b2,b3: byte;
end;
/// points to 24-bit storage, mapped as a 3 bytes buffer
PBSON24 = ^TBSON24;
/// BSON ObjectID internal binary representation
// - in MongoDB, documents stored in a collection require a unique _id field
// that acts as a primary key: by default, it uses such a 12-byte ObjectID
// - by design, sorting by _id: ObjectID is roughly equivalent to sorting by
// creation time, so ease sharding and BTREE storage
// - match betObjectID TBSONElementType
{$A-}
{$ifndef UNICODE}
TBSONObjectID = object
{$else}
TBSONObjectID = record
{$endif}
/// big-endian 4-byte value representing the seconds since the Unix epoch
// - time is expressed in Coordinated Universal Time (UTC), not local time
UnixCreateTime: cardinal;
/// 3-byte machine identifier
// - ComputeNew will use a hash of ExeVersion.Host and ExeVersion.User
MachineID: TBSON24;
/// 2-byte process id
// - ComputeNew will derivate it from MainThreadID
ProcessID: word;
/// 3-byte counter, starting with a random value
// - used to avoid collision
Counter: TBSON24;
/// ObjectID content be filled with some unique values
// - this implementation is thread-safe
procedure ComputeNew;
/// convert an hexadecimal string value into one ObjectID
// - returns TRUE if conversion was made, FALSE on any error
function FromText(const Text: RawUTF8): boolean; overload;
/// convert an hexadecimal string value into one ObjectID
// - returns TRUE if conversion was made, FALSE on any error
function FromText(Text: PUTF8Char): boolean; overload;
/// convert a variant into one ObjectID
// - will first check for a TBSONVariant containing a betObjectID
// - then will try to convert the variant from its string value, expecting
// an hexadecimal text content
// - returns TRUE if conversion was made, FALSE on any error
function FromVariant(const value: variant): boolean;
/// convert this ObjectID to its hexadecimal string value
function ToText: RawUTF8; overload;
/// convert this ObjectID to its hexadecimal string value
procedure ToText(var result: RawUTF8); overload;
/// convert this ObjectID to its TBSONVariant custom variant value
function ToVariant: variant;
/// returns the timestamp portion of the ObjectId() object as a Delphi date
// - time is expressed in Coordinated Universal Time (UTC), not local time
// so you can compare it to NowUTC returned time
function CreateDateTime: TDateTime;
/// compare two Object IDs
function Equal(const Another: TBSONObjectID): boolean;
{$ifdef HASINLINE}inline;{$endif}
end;
/// points to a BSON ObjectID internal binary representation
PBSONObjectID = ^TBSONObjectID;
/// memory structure used for some special BSON storage as variant
// - betObjectID kind will store a TBSONObjectID
// - betBinary kind will store a BLOB content as RawByteString
// - betDoc and betArray kind will store a BSON document, in its original
// binary format as RawByteString (TBSONDocument)
// - betDeprecatedDbptr, betJSScope, betTimestamp and betRegEx will store the
// raw original BSON content as RawByteString
// - betJS and betDeprecatedSymbol will store the UTF-8 encoded string
// as a RawUTF8
// - betDeprecatedUndefined or betMinKey/betMaxKey do not contain any data
// - betDecimal128 will store the TDecimal128 16 bytes binary buffer
// - warning: VBlob/VText use should match BSON_ELEMENTVARIANTMANAGED constant
TBSONVariantData = packed record
/// the variant type
VType: TVarType;
/// the kind of element stored
case VKind: TBSONElementType of
betObjectID: (
{$HINTS OFF} // does not complain if Filler is declared but never used
VFiller: array[1..SizeOf(TVarData)-SizeOf(TVarType)-SizeOf(TBSONElementType)
-SizeOf(TBSONObjectID)] of byte;
{$HINTS ON}
VObjectID: TBSONObjectID
);
betBinary, betDoc, betArray, betRegEx, betDeprecatedDbptr, betTimestamp,
betJSScope, betDecimal128: (
/// store the raw binary content as a RawByteString (or TBSONDocument for
// betDoc/betArray, i.e. the "int32 e_list #0" standard layout)
// - you have to use RawByteString(VBlob) when accessing this field
// - e.g. for betRegEx, it will contain raw [cstring cstring] content
VBlob: pointer;
);
betJS, betDeprecatedSymbol: (
/// store here a RawUTF8 with the associated text
// - you have to use RawUF8(VText) when accessing this field
VText: pointer;
);
end;
{$A+}
/// custom variant type used to store some special BSON elements
// - internal layout will follow TBSONVariantData
// - handled kind of item are complex BSON types, like betObjectID, betBinary
// or betDoc/betArray
// - it will allow conversion to/from string (and to date for ObjectID)
TBSONVariant = class(TSynInvokeableVariantType)
protected
function GetNewDoc(const BSONDoc: TBSONDocument): variant;
public
/// customization of JSON conversion into TBSONVariant kind of variants
function TryJSONToVariant(var JSON: PUTF8Char; var Value: variant;
EndOfObject: PUTF8Char): boolean; override;
/// variant serialization will use modMongoStrict JSON-compatible mode
procedure ToJSON(W: TTextWriter; const Value: variant; Escape: TTextWriterKind); override;
/// handle type conversion
// - only types processed by now are string/OleStr/UnicodeString/date
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
/// handle type conversion
// - only types processed by now are string/OleStr/UnicodeString/date
procedure CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); override;
/// clear the instance
procedure Clear(var V: TVarData); override;
/// copy one instance
procedure Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean); override;
/// compare two variant values
// - handle comparison of any variant, including TBSONVariant, via a
// temporary JSON conversion, and case-sensitive comparison
// - it uses case-sensitive text (hexadecimal) comparison for betObjectID
procedure Compare(const Left, Right: TVarData;
var Relationship: TVarCompareResult); override;
/// convert a TBSONDocument binary content into a TBSONVariant of kind
// betDoc or betArray
// - see also all BSONVariant() overloaded functions, which also create
// a TBSONVariant betDoc instance
procedure FromBSONDocument(const BSONDoc: TBSONDocument; var result: variant;
Kind: TBSONElementType=betDoc);
/// convert a BLOB binary content into a TBSONVariant of kind betBinary
// - if Bin is '', will store a NULL variant
procedure FromBinary(const Bin: RawByteString; BinType: TBSONElementBinaryType;
var result: variant);
/// convert a JSON content into a TBSONVariant of kind betDoc or betArray
// - warning: the supplied JSON buffer will be modified in-place
// - will create a plain variant value if the JSON doesn't start with [ or {
procedure FromJSON(json: PUTF8Char; var result: variant);
/// returns TRUE if the supplied variant stores the supplied BSON kind of value
function IsOfKind(const V: variant; Kind: TBSONElementType): boolean;
/// retrieve a betBinary content stored in a TBSONVariant instance
// - returns TRUE if the supplied variant is a betBinary, and set the
// binary value into the supplied Blob variable
// - returns FALSE otherwise
function ToBlob(const V: Variant; var Blob: RawByteString): boolean;
/// convert a TBSONDocument binary content into a TBSONVariant of kind betDoc
// - is the default property, so that you can write:
// ! BSONVariantType[BSON(['BSON',_Arr(['awesome',5.05, 1986])])]
// - see also all BSONVariant() overloaded functions, which also create
// a TBSONVariant betDoc instance
property NewDoc[const BSONDoc: TBSONDocument]: variant read GetNewDoc; default;
end;
/// define how betDoc/betArray BSON elements will be converted as variants
// - by default a TBSONVariant custom type will be returned, containing the
// raw BSON binary content of the embedded document or array
// - asDocVariantPerValue or asDocVariantPerReference could be used to
// create a tree of TDocVariant custom kind of variant, able to access
// to its nested properties via late-binding (asDocVariantPerReference being
// also much faster in some cases - but less safe - than asDocVariantPerValue)
// - asDocVariantPerValue will set JSON_OPTIONS[false] settings:
// ! [dvoReturnNullForUnknownProperty]
// - asDocVariantPerReference will set JSON_OPTIONS[true]/JSON_OPTIONS_FAST
// settings:
// ! [dvoValueCopiedByReference,dvoReturnNullForUnknownProperty]
// - asDocVariantInternNamesPerValue and asDocVariantInternNamesPerReference
// will include dvoInternalNames to the TDocVariant.Options
TBSONDocArrayConversion = (
asBSONVariant, asDocVariantPerValue, asDocVariantPerReference,
asDocVariantInternNamesPerValue, asDocVariantInternNamesPerReference);
/// how TBSONElement.AddMongoJSON() method and AddMongoJSON() and
// VariantSaveMongoJSON() functions will render their JSON content
// - modMongoStrict and modNoMongo will follow the JSON RFC specifications
// - modMongoShell will use a syntax incompatible with JSON RFC, but more
// common to MongoDB daily use - as 'ObjectId()' or '{ field: /acme.*corp/i }'
// - modMongoStrict will use the MongoDB Extended JSON syntax
// - modNoMongo will serialize dates as ISO-8601 strings, ObjectID as hexadecimal
// string and other MongoDB special objects in WrBase64() format
// - see http://docs.mongodb.org/manual/reference/mongodb-extended-json
TMongoJSONMode = (modNoMongo, modMongoStrict, modMongoShell);
/// data structure used during BSON binary decoding of one BSON element
// - will be retrieved by FromVariant() or FromNext()
// - see http://bsonspec.org/#/specification
// - this structure has been optimized to map the BSON binary content,
// without any temporary memory allocation (the SAX way)
{$ifndef UNICODE}
TBSONElement = object
protected
{$else}
TBSONElement = record
private
{$endif}
/// used internally to set the TBSONElement content, once Kind has been set
procedure FromBSON(bson: PByte);
public
/// index of this element in the original sequence list
// - is correct only when the element has been reset before the parsing
// loop, e.g.:
// ! item.Index := -1; // so item.Index will count starting at 0
// ! while item.FromNext(elem.Document) do
// ! writeln(item.Index,' ',Item.Name,' ',Item.ValueBytes);
Index: integer;
/// the UTF-8 encoded name of this element
Name: PUTF8Char;
/// the name length (in chars) of this element
NameLen: integer;
/// the element type
Kind: TBSONElementType;
/// number of bytes in the BSON element
// - will include the trailing #0 for string element
ElementBytes: integer;
/// pointer to the BSON element value
// - is the raw value, without any parsing, e.g. points to a double value or
// a document: "int32 e_list #0" standard layout (same as TBSONDocument)
// - you may cast it for simple types:
// ! PDouble(Element)^ PBoolean(Element)^ PInteger(Element)^
// ! PInt64(Element)^ PBSONObjectID(Element)^ PDecimal128(Element)^
// - or use the nested Data variant record to access more complex content
// - warning: equals nil for betString/betJS after FromVariant()
Element: pointer;
/// depending on the Kind, will point to parsed complex sub-data
// - since variable records can't have properties, we nest this information
// within this main Data variable record
// - not all Kind are handled here, only any complex data
Data: record
case TBSONElementType of
betFloat, betBoolean, betInt32, betDateTime, betInt64: (
/// this variable is not to be used directly, but for some internal
// temporary storage, e.g. with FromVariant()
// - use P*(Element)^ typecast instead
InternalStorage: Int64;
);
betString, betJS: (
/// points to the #0 ending string
Text: PUTF8Char;
/// number of bytes in Text (excluding trailing #0)
TextLen: integer;
);
betDoc, betArray: (
/// points to a "e_list #0" standard layout
DocList: PByte;
);
betBinary: (
/// points to the binary content
Blob: pointer;
/// number of bytes in Blob
BlobLen: integer;
/// corresponding sub-type of this Blob
BlobSubType: TBSONElementBinaryType;
);
betRegEx: (
RegEx: PUTF8Char;
RegExLen: integer;
RegExOptions: PUTF8Char;
RegExOptionsLen: integer;
);
betJSScope: (
JavaScript: PUTF8Char;
JavaScriptLen: integer;
ScopeDocument: PByte;
);
betTimestamp: (
{ map InternalStorage: Int64 }
time_t: cardinal;
ordinal: cardinal;
);
end;
/// fill a BSON Element structure from a variant content and associated name
// - perform the reverse conversion as made with ToVariant()
// - since the result won't store any data but points to the original binary
// content, the supplied Name/Value instances should remain available as long as
// you will access to the result content
// - aName here is just for conveniency, and could be left void
// - supplied aTemp variable will be used for temporary storage, private to
// this initialized TBSONElement
procedure FromVariant(const aName: RawUTF8; const aValue: Variant;
var aTemp: RawByteString);
/// fill a BSON Element structure from a BSON document
// - will check the document length then set Kind := betDoc and Data.DocList
// - will return TRUE if the supplied doc has a valid length, FALSE otherwise
// - you can later on use DocItemToVariant, DocItemToRawUTF8 or
// DocItemToInteger methods
// - the supplied "doc" variable should remain available until you are done
// with this TBSONElement wrapper
function FromDocument(const doc: TBSONDocument): boolean;
/// fill a BSON Element structure from a BSON encoded binary buffer list
// - parse the next BSON element: BSON parameter should point to the
// "e_list" of the "int32 e_list #0" BSON document
// - will decode the supplied binary buffer into the BSON element structure,
// then it will let BSON point to the next element, and return TRUE
// - returns FALSE when you reached betEOF, so that you can use it in a loop,
// and retrieve all the content as consecutive events, without any memory
// allocation (the SAX way):
// ! var bson: PByte;
// ! item: TBSONElement;
// ! ...
// ! BSONParseLength(bson);
// ! while item.FromNext(bson) do
// ! writeln(item.Name);
// - will raise an EBSONException if BSON content is not correct
// - as an alternative, consider using TBSONIterator, which wrap both a
// PByte and a TBSONElement into one convenient item
function FromNext(var BSON: PByte): boolean;
/// search for a given name in a BSON encoded binary buffer list
// - BSON parameter should point to the first "e_list" item of the
// "int32 e_list #0" BSON document
// - returns false if the item was not found (with case-insensitive search)
// - otherwise returns TRUE and the matching element content has been
// decoded within this TBSONElement structure
function FromSearch(BSON: PByte; const aName: RawUTF8): boolean;
/// convert a BSON element, as retrieved by TBSONElement.FromNext(),
// into a variant
// - it will return either standard variant values, or TBSONVariant custom type
// for most complex kind of elements (see TBSONVariantData type definition)
// - note that betString types will be stored as RawUTF8 varString
// - by default, it will return TBSONVariant custom variants for documents or
// arrays - but if storeDocArrayAsDocVariant is set, it will return a
// TDocVariant custom kind of variant, able to access to its nested
// properties via late-binding
function ToVariant(DocArrayConversion: TBSONDocArrayConversion=asBSONVariant): variant; overload;
/// convert a BSON element, as retrieved by TBSONElement.FromNext(),
// into a variant
// - same as the other ToVariant() overloaded function, but avoiding a copy
// of the resulting variant
procedure ToVariant(var result: variant;
DocArrayConversion: TBSONDocArrayConversion=asBSONVariant); overload;
/// convert a BSON element into an UTF-8 string
// - any complex types (e.g. nested documents) will be converted via a
// variant
function ToRawUTF8: RawUTF8;
/// convert a BSON element into an integer value
// - will work only for betBoolean/betInt32/betInt64 types
// - any other kind of values will return the supplied default value
function ToInteger(const default: Int64=0): Int64;
/// search a variant property value within the BSON element as document
// - returns true if aName has been found as property in the BSON element,
// and fills aValue with the corresponding value
// - returns false if aName was not found, or if Kind is not betDoc or betArray
function DocItemToVariant(const aName: RawUTF8; var aValue: variant;
DocArrayConversion: TBSONDocArrayConversion=asBSONVariant): boolean;
/// search an UTF-8 property value within the BSON element as document
// - returns the value if aName has been found as property in the BSON element
// - returns '' if aName was not found, or if Kind is not betDoc or betArray
function DocItemToRawUTF8(const aName: RawUTF8): RawUTF8;
/// search an integer property value within the BSON element as document
// - returns the value if aName has been found as property in the BSON element
// - returns default if aName was not found, or if Kind is not betDoc or betArray
function DocItemToInteger(const aName: RawUTF8; const default: Int64=0): Int64;
/// convert a BSON element, as retrieved by TBSONElement.FromNext(), into
// its JSON representation
// - this method will use by default the MongoDB Extended JSON syntax for
// specific MongoDB objects but you may use modMongoShell if needed
// - will raise an EBSONException if element is not correct
procedure AddMongoJSON(W: TTextWriter; Mode: TMongoJSONMode=modMongoStrict); overload;
end;
PBSONElement = ^TBSONElement;
/// data structure used for iterating over a BSON binary buffer
// - is just a wrapper around a PByte value, to be used with a TBSONDocument
{$ifndef UNICODE}
TBSONIterator = object
protected
{$else}
TBSONIterator = record
private
{$endif}
fBson: PByte;
public
/// map the current item, after the Next method did return TRUE
// - map the global document, after Init() but before the first Next call
Item: TBSONElement;
/// initialize the iteration on the supplied BSON document
// - will check the document length and returns TRUE if it is correct
// - only accepted kind are betDoc and betArray (but not used later)
// - you can then use the Next method to iterate over the Item elements
// - after this call, the Item property map to the global BSON document
// (note that after any call to the Next method, Item will map the current
// iterated value, and not the global BSON document any more)
function Init(const doc: TBSONDocument; kind: TBSONElementType=betArray): boolean;
/// will iterate on the BSON document
// - returns TRUE if the item has been retrieved into the Item property
// - returns FALSE if we reached the end of the supplied BSON buffer
function Next: boolean;
{$ifdef HASINLINE}inline;{$endif}
end;
/// used to write the BSON context
TBSONWriter = class(TFileBufferWriter)
{ note: inlining methods generates 70% SLOWER code due to inefficient compiler :( }
protected
fDocumentCount: integer;
fDocument: array of record
Offset: cardinal;
Length: cardinal;
end;
fDocumentStack: integer;
fDocumentStackOffset: TCardinalDynArray;
fDocumentArray: integer;
procedure WriteCollectionName(Flags: integer; const CollectionName: RawUTF8);
public
/// rewind the Stream to the position when Create() was called
// - this will also reset the internal document offset table
procedure CancelAll; override;
/// write a boolean value
procedure BSONWrite(const name: RawUTF8; const value: boolean); overload;
/// write a floating point value
procedure BSONWrite(const name: RawUTF8; const value: Double); overload;
/// write a 32 bit integer value
procedure BSONWrite(const name: RawUTF8; const value: integer); overload;
/// write a 64 bit integer value
procedure BSONWrite(const name: RawUTF8; const value: Int64); overload;
/// write a string (UTF-8) value
procedure BSONWrite(const name: RawUTF8; const value: RawUTF8; isJavaScript: boolean=false); overload;
/// write a string (UTF-8) value from a memory buffer
procedure BSONWrite(const name: RawUTF8; value: PUTF8Char); overload;
/// write a string (UTF-8) value from a memory buffer
procedure BSONWriteString(const name: RawUTF8; value: PUTF8Char; valueLen: integer);
/// write a binary (BLOB) value
procedure BSONWrite(const name: RawUTF8; Data: pointer; DataLen: integer); overload;
/// write an ObjectID value
procedure BSONWrite(const name: RawUTF8; const value: TBSONObjectID); overload;
/// write a RegEx value
procedure BSONWriteRegEx(const name: RawUTF8; const RegEx,Options: RawByteString);
/// write a data/time value
procedure BSONWriteDateTime(const name: RawUTF8; const value: TDateTime);
/// write an element with no value
// - elemType can be either betNull, betMinKey or betMaxKey
procedure BSONWrite(const name: RawUTF8; elemtype: TBSONElementType); overload;
/// write an element with no value
procedure BSONWrite(const name: RawUTF8; const elem: TBSONElement); overload;
/// write a BSONVariant instance value
procedure BSONWrite(const name: RawUTF8; const bson: TBSONVariantData); overload;
/// write a DocVariant instance value
procedure BSONWrite(const name: RawUTF8; const doc: TDocVariantData); overload;
/// write a TDecimal128 value
procedure BSONWrite(const name: RawUTF8; const value: TDecimal128); overload;
/// write a variant value
// - handle simple types (numbers, strings...) and custom types (TDocVariant
// and TBSONVariant, trying a translation to JSON for other custom types)
procedure BSONWriteVariant(const name: RawUTF8; const value: variant); overload;
/// write an open array (const Args: array of const) argument
// - handle simple types (numbers, strings...) and custom types (TDocVariant)
procedure BSONWrite(const name: RawUTF8; const value: TVarRec); overload;
/// write a value from the supplied JSON content
// - is able to handle any kind of values, including nested documents or
// BSON extended syntax (if DoNotTryExtendedMongoSyntax=false)
// - this method is used recursively by BSONWriteDocFromJSON(), and should
// not be called directly
// - will return JSON=nil in case of unexpected error in the supplied JSON
procedure BSONWriteFromJSON(const name: RawUTF8; var JSON: PUTF8Char;
EndOfObject: PUTF8Char; DoNotTryExtendedMongoSyntax: boolean=false);
/// recursive writing of a BSON document or value from a TDocVariant
// object or array, used e.g. by BSON(const doc: TDocVariantData) function
// - caller should execute BSONAdjustDocumentsSize() on the resulting buffer
// - this method will call BSONDocumentBegin/BSONDocumentEnd internally
// - will raise an EBSONException if doc is not a valid TDocVariant or null
// or if the resulting binary content is bigger than BSON_MAXDOCUMENTSIZE
procedure BSONWriteDoc(const doc: TDocVariantData);
/// write an object specified as name/value pairs as a BSON document
// - data must be supplied two by two, as Name,Value pairs, e.g.
// ! aBSONWriter.BSONWriteObject(['name','John','year',1972]);
// - this method wil be faster than using a BSONWriteDoc(_ObjFast(...))
procedure BSONWriteObject(const NameValuePairs: array of const);
/// write a projection specified as fieldname:1 pairs as a BSON document
procedure BSONWriteProjection(const FieldNamesCSV: RawUTF8);
/// write an object as query parameter
// - will handle all SQL operators, including IN (), IS NULL or LIKE
// - see @http://docs.mongodb.org/manual/reference/operator/query
// - inverted should be TRUE e.g. for a NOT ... expression
// - returns TRUE on success, FALSE if the operator is not implemented yet
function BSONWriteQueryOperator(name: RawUTF8; inverted: boolean;
operator: TSynTableStatementOperator; const Value: variant): boolean;
/// write one array item, i.e. the ASCII index name as text
// - only one level of array should be used per TBSONWriter class
procedure BSONWriteArray(const kind: TBSONElementType); overload;
/// write an array specified as a list of items as a BSON document
// - data must be supplied as a list of values e.g.
// ! aBSONWriter.BSONWriteArray(['John',1972]);
// - this method wil be faster than using a BSONWriteDoc(_ArrFast(...))
procedure BSONWriteArray(const Items: array of const); overload;
/// write an array of integers as a BSON Document
procedure BSONWriteArrayOfInteger(const Integers: array of integer);
/// write an array of integers as a BSON Document
procedure BSONWriteArrayOfInt64(const Integers: array of Int64);
/// write some BSON document from a supplied (extended) JSON array or object
// - warning: the incoming JSON buffer will be modified in-place: so you
// should make a private copy before running this method (see e.g. TSynTempBuffer)
// - will handle only '{ ... }', '[ ... ]' or 'null' input, with the standard
// strict JSON format, or BSON-like extensions, e.g. unquoted field names:
// $ {id:10,doc:{name:"John",birthyear:1972}}
// - if DoNotTryExtendedMongoSyntax is default FALSE, then the MongoDB Shell
// syntax will also be recognized to create BSON custom types, like
// $ new Date() ObjectId() MinKey MaxKey /<jRegex>/<jOptions>
// see @http://docs.mongodb.org/manual/reference/mongodb-extended-json
// $ {id:new ObjectId(),doc:{name:"John",date:ISODate()}}
// $ {name:"John",field:/acme.*corp/i}
// - if DoNotTryExtendedMongoSyntax is TRUE, process may be slightly faster
// - will create the BSON binary without any temporary TDocVariant storage
function BSONWriteDocFromJSON(JSON: PUTF8Char; aEndOfObject: PUTF8Char;
out Kind: TBSONElementType; DoNotTryExtendedMongoSyntax: boolean=false): PUTF8Char;
/// to be called before a BSON document will be written
// - each BSONDocumentBegin should be followed by its nested BSONDocumentEnd
procedure BSONDocumentBegin; overload;
/// to be called before a BSON document will be written
// - each BSONDocumentBegin should be followed by its nested BSONDocumentEnd
// - you could create a new BSON object by specifying a name and its
// type, i.e. either betDoc or betArray
procedure BSONDocumentBegin(const name: RawUTF8; kind: TBSONElementType=betDoc); overload;
/// to be called before a BSON document will be written in an array
// - only one level of array should be used per TBSONWriter class
procedure BSONDocumentBeginInArray(const name: RawUTF8; kind: TBSONElementType=betDoc);
/// to be called when a BSON document has been written
// - it will store the current stream position into an internal array,
// which will be written when you call AdjustDocumentsSize()
// - you can optional specify how many nested documents should be closed,
// and/or if it should not write an ending betEof item
procedure BSONDocumentEnd(CloseNumber: integer=1; WriteEndingZero: boolean=true);
/// after all content has been written, call this method on the resulting
// memory buffer to store all document size as expected by the standard
procedure BSONAdjustDocumentsSize(BSON: PByteArray); virtual;
/// flush the content and return the whole binary encoded stream
// - call BSONAdjustDocumentsSize() to adjust all internal document sizes
// - expect the TBSONWriter instance to have been created as such:
// ! TBSONWriter.Create(TRawByteStringStream);
procedure ToBSONDocument(var result: TBSONDocument); virtual;
/// flush the content and return the whole document as a TBSONVariant
// - call ToBSONDocument() to adjust all internal document sizes
// - expect the TBSONWriter instance to have been created as such:
// ! TBSONWriter.Create(TRawByteStringStream);
procedure ToBSONVariant(var result: variant; Kind: TBSONElementType=betDoc);
end;
const
/// fake BSON element type which compares lower than all other possible values
// - element type sounds to be stored as shortint, so here $ff=-1<0=betEOF
betMinKey = TBSONElementType($ff);
/// fake BSON element type which compares higher than all other possible values
// - element type sounds to be stored as shortint, so here betInt64=$12<$7f
betMaxKey = TBSONElementType($7f);
/// kind of elements which will store a RawByteString/RawUTF8 content
// within its TBSONVariant kind
// - i.e. TBSONVariantData.VBlob/VText field is to be managed
BSON_ELEMENTVARIANTMANAGED =
[betBinary, betDoc, betArray, betRegEx, betDeprecatedDbptr, betTimestamp,
betJSScope, betJS, betDeprecatedSymbol, betDecimal128];
/// by definition, maximum MongoDB document size is 16 MB
BSON_MAXDOCUMENTSIZE = 16*1024*1024;
/// special JSON string content which will be used to store a betDeprecatedUndefined item
// - *[false] is for strict JSON, *[true] for MongoDB Extended JSON
BSON_JSON_UNDEFINED: array[boolean] of string[23] =
('{"$undefined":true}','undefined');
/// special JSON string content which will be used to store a betMinKey item
// - *[false] is for strict JSON, *[true] for MongoDB Extended JSON
BSON_JSON_MINKEY: array[boolean] of string[15] = ('{"$minKey":1}','MinKey');
/// special JSON string content which will be used to store a betMaxKey item
// - *[false] is for strict JSON, *[true] for MongoDB Extended JSON
BSON_JSON_MAXKEY: array[boolean] of string[15] = ('{"$maxKey":1}','MaxKey');
/// special JSON patterns which will be used to format a betObjectID item
// - *[false,*] is to be written before the hexadecimal ID, *[true,*] after
BSON_JSON_OBJECTID: array[boolean,TMongoJSONMode] of string[15] = (
('"','{"$oid":"','ObjectId("'),('"','"}','")'));
/// special JSON patterns which will be used to format a betBinary item
// - *[false,*] is for strict JSON, *[true,*] for MongoDB Extended JSON
BSON_JSON_BINARY: array[boolean,boolean] of string[15] = (
('{"$binary":"','","$type":"'),('BinData(',',"'));
/// special JSON string content which will be used to store a betDeprecatedDbptr
// - *[false,*] is for strict JSON, *[true,*] for MongoDB Extended JSON
// - (not used by now for this deprecated content)
BSON_JSON_DBREF: array[boolean,0..2] of string[15] = (
('{"$ref":"','","$id":"','"}'),('DBRef("','","','")'));
/// special JSON string content which will be used to store a betRegEx
BSON_JSON_REGEX: array[0..2] of string[15] =
('{"$regex":"','","$options":"','"}');
/// special JSON patterns which will be used to format a betDateTime item
// - *[*,false] is to be written before the date value, *[*,true] after
BSON_JSON_DATE: array[TMongoJSONMode,boolean] of string[15] = (
('"','"'),('{"$date":"','"}'),('ISODate("','")'));
/// special JSON patterns which will be used to format a betDecimal128 item
// - *[false,*] is to be written before the decimal value, *[true,*] after
BSON_JSON_DECIMAL: array[boolean,TMongoJSONMode] of string[23] = (
('"','{"$numberDecimal":"','NumberDecimal("'),('"','"}','")'));
var
/// global TCustomVariantType used to register BSON variant types
// - if you use this unit, both TDocVariant and TBSONVariant custom types
// will be registered, since they are needed for any MongoDB / BSON process
BSONVariantType: TBSONVariant;
/// ready-to-be displayed text of a TBSONElementType value
function ToText(kind: TBSONElementType): PShortString; overload;
/// create a TBSONVariant custom variant type containing a BSON Object ID
// - will be filled with some unique values, ready to create a new document key
// - will store a BSON element of betObjectID kind
function ObjectID: variant; overload;
/// create a TBSONVariant Object ID custom variant type from a supplied text
// - will raise an EBSONException if the supplied text is not valid hexadecimal
// - will set a BSON element of betObjectID kind
function ObjectID(const Hexa: RaWUTF8): variant; overload;
/// convert a TBSONVariant Object ID custom variant into a TBSONObjectID
// - raise an exception if the supplied variant is not a TBSONVariant Object ID
function BSONObjectID(const aObjectID: variant): TBSONObjectID;
/// create a TBSONVariant JavaScript custom variant type from a supplied code
// - will set a BSON element of betJS kind
function JavaScript(const JS: RawUTF8): variant; overload;
/// create a TBSONVariant JavaScript and associated scope custom variant type
// from a supplied code and document
// - will set a BSON element of betJSScope kind
function JavaScript(const JS: RawUTF8; const Scope: TBSONDocument): variant; overload;
/// create a TBSONVariant Decimal128 from some text corresponding to
// a floating-point number
// - will store internally a TDecimal128 storage
function NumberDecimal(const Value: RawUTF8): variant; overload;
/// create a TBSONVariant Decimal128 from a currency fixed decimal
// - will store internally a TDecimal128 storage, with explictly 4 decimals
// - if you want to store some floating-point value, use plain BSON double format
function NumberDecimal(const Value: currency): variant; overload;
/// store some object content into BSON encoded binary
// - object will be initialized with data supplied two by two, as Name,Value
// pairs, e.g.:
// ! aBson := BSON(['name','John','year',1972]);
// - you can define nested arrays or objects as TDocVariant, e.g:
// ! aBSON := BSON(['bsonDat',_Arr(['awesome',5.05, 1986])]);
// - or you can specify nested arrays or objects with '['..']' or '{'..'}':
// ! aBSON := BSON(['BSON','[','awesome',5.05,1986,']'])
// ! u := BSONToJSON(BSON(['doc','{','name','John','year',1982,'}','id',123]));
// ! assert(u='{"doc":{"name":"John","year":1982},"id":123}');
// ! u := BSONToJSON(BSON(['doc','{','name','John','abc','[','a','b','c',']','}','id',123]));
// ! assert(u='{"doc":{"name":"John","abc":["a","b","c"]},"id":123}');
// - will create the BSON binary without any temporary TDocVariant storage
function BSON(const NameValuePairs: array of const): TBSONDocument; overload;
/// create a fields selector BSON document from a field names list
// - can be used via a TBSONVariant instance for the projection parameter of
// a TMongoRequestQuery, e.g.:
// ! BSONToJSON(BSONFieldSelector(['a','b','c']))='{"a":1,"b":1,"c":1}'
function BSONFieldSelector(const FieldNames: array of RawUTF8): TBSONDocument; overload;
/// create a fields selector BSON document from a CSV field names list
// - can be used via a TBSONVariant instance for the projection parameter of
// a TMongoRequestQuery, e.g.:
// ! BSONToJSON(BSONFieldSelector('a,b,c'))='{"a":1,"b":1,"c":1}'
function BSONFieldSelector(const FieldNamesCSV: RawUTF8): TBSONDocument; overload;
/// store some object content, supplied as (extended) JSON, into BSON encoded binary
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, e.g. unquoted field names:
// ! BSON('{id:10,doc:{name:"John",birthyear:1972}}');
// - MongoDB Shell syntax will also be recognized to create TBSONVariant, like
// ! new Date() ObjectId() MinKey MaxKey /<jRegex>/<jOptions>
// see @http://docs.mongodb.org/manual/reference/mongodb-extended-json
// ! BSON('{id:new ObjectId(),doc:{name:"John",date:ISODate()}}');
// ! BSON('{name:"John",field:/acme.*corp/i}');
// - will create the BSON binary without any temporary TDocVariant storage, by
// calling JSONBufferToBSONDocument() on a temporary copy of the supplied JSON
function BSON(const JSON: RawUTF8; kind: PBSONElementType=nil): TBSONDocument; overload;
{$ifdef HASINLINE}inline;{$endif}
/// store some object content, supplied as (extended) JSON and parameters,
// into BSON encoded binary
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, e.g. unquoted field names
// - MongoDB Shell syntax will also be recognized to create TBSONVariant, like
// ! new Date() ObjectId() MinKey MaxKey /<jRegex>/<jOptions>
// see @http://docs.mongodb.org/manual/reference/mongodb-extended-json
// - typical use could be:
// ! BSON('{%:{$in:[?,?]}}',['type'],['food','snack']);
// ! BSON('{type:{$in:?}}',[],[_Arr(['food','snack'])]);
// ! BSON('{%:[?,?,?]}',['BSON'],['awesome',5.05,1986])
// ! BSON('{%:?}',['BSON'],[_Arr(['awesome',5.05,1986])])
// ! BSON('{name:?,field:/%/i}',['acme.*corp'],['John']);
// ! BSON('{id:new ObjectId(),doc:{name:?,date:ISODate(?)}}',[],['John',NowUTC]);
// - will create the BSON binary without any temporary TDocVariant storage,
// by calling JSONBufferToBSONDocument() on the generated JSON content
// - since all content will be transformed into JSON internally, use this
// method only if the supplied parameters are simple types, and identified
// explicitely via BSON-like extensions: any complex value (e.g. a TDateTime
// or a BSONVariant binary) won't be handled as expected - use the overloaded
// BSON() with explicit BSONVariant() name/value pairs instead
function BSON(const Format: RawUTF8; const Args,Params: array of const;
kind: PBSONElementType=nil): TBSONDocument; overload;
/// store some TDocVariant custom variant content into BSON encoded binary
// - will write either a BSON object or array, depending of the internal
// layout of this TDocVariantData instance (i.e. Kind property value)
// - if supplied variant is not a TDocVariant, raise an EBSONException
function BSON(const doc: TDocVariantData): TBSONDocument; overload;
/// store an array of integer into BSON encoded binary
// - object will be initialized with data supplied e.g. as a TIntegerDynArray
function BSONFromIntegers(const Integers: array of integer): TBSONDocument;
/// store an array of 64 bit integer into BSON encoded binary
// - object will be initialized with data supplied e.g. as a TIntegerDynArray
function BSONFromInt64s(const Integers: array of Int64): TBSONDocument;
/// store some object content, supplied as (extended) JSON into BSON binary
// - warning: the supplied JSON buffer will be modified in-place, if necessary:
// so you should create a temporary copy before calling this function, or call
// BSON(const JSON: RawUTF8) function instead
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, e.g. unquoted field names
// - if DoNotTryExtendedMongoSyntax is FALSE, then MongoDB Shell syntax will
// also be recognized to create BSON custom values, like
// ! new Date() ObjectId() MinKey MaxKey /<jRegex>/<jOptions>
// see @http://docs.mongodb.org/manual/reference/mongodb-extended-json
// ! BSON('{id:new ObjectId(),doc:{name:"John",date:ISODate()}}');
// ! BSON('{name:"John",field:/acme.*corp/i}');
// - will create the BSON binary without any temporary TDocVariant storage
// - will return the kind of BSON document created, i.e. either betDoc or betArray
function JSONBufferToBSONDocument(JSON: PUTF8Char; var doc: TBSONDocument;
DoNotTryExtendedMongoSyntax: boolean=false): TBSONElementType;
/// store one JSON array into an array of BSON binary
// - since BSON documents are limited to 16 MB by design, this function
// will allow to process huge data content, as soon as it is provided as array
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, e.g. unquoted field names
// - if DoNotTryExtendedMongoSyntax is FALSE, then MongoDB Shell syntax will
// be recognized to create BSON custom values - but it will be slightly slower
function JSONBufferToBSONArray(JSON: PUTF8Char; out docs: TBSONDocumentDynArray;
DoNotTryExtendedMongoSyntax: boolean=false): boolean;
/// store some object content into a TBSONVariant betDoc type instance
// - object will be initialized with data supplied two by two, as Name,Value
// pairs, as expected by the corresponding overloaded BSON() function
function BSONVariant(const NameValuePairs: array of const): variant; overload;
/// create a fields selector BSON document from a field names list
// - can be used for the projection parameter of a TMongoRequestQuery, e.g.:
// ! VariantToJSON(BSONVariantFieldSelector(['a','b','c']))='{"a":1,"b":1,"c":1}'
function BSONVariantFieldSelector(const FieldNames: array of RawUTF8): variant; overload;
/// create a fields selector BSON document from a CSV field names list
// - can be used for the projection parameter of a TMongoRequestQuery, e.g.:
// ! VariantToJSON(BSONVariantFieldSelector('a,b,c'))='{"a":1,"b":1,"c":1}'
function BSONVariantFieldSelector(const FieldNamesCSV: RawUTF8): variant; overload;
{$ifdef HASINLINE}inline;{$endif}
/// store some object content, supplied as (extended) JSON, into a TBSONVariant
// betDoc type instance
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, as with the overloaded BSON() function
function BSONVariant(const JSON: RawUTF8): variant; overload;
{$ifdef HASINLINE}inline;{$endif}
/// store some object content, supplied as (extended) JSON, into a TBSONVariant
// betDoc type instance
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, as with the overloaded BSON() function
// - warning: this overloaded method will mofify the supplied JSON buffer
// in-place: you can use the overloaded BSONVariant(const JSON: RawUTF8) function
// instead if you do not want to modify the input buffer content
procedure BSONVariant(JSON: PUTF8Char; var result: variant); overload;
/// store some object content, supplied as (extended) JSON and parameters,
// into a TBSONVariant betDoc type instance
// - in addition to the JSON RFC specification strict mode, this method will
// handle some BSON-like extensions, as with the overloaded BSON() function
function BSONVariant(const Format: RawUTF8; const Args,Params: array of const): variant; overload;
/// convert a TDocVariant variant into a TBSONVariant betDoc type instance
function BSONVariant(doc: TDocVariantData): variant; overload;
{$ifdef HASINLINE}inline;{$endif}
/// store an array of integer into a TBSONVariant betArray type instance
// - object will be initialized with data supplied e.g. as a TIntegerDynArray
function BSONVariantFromIntegers(const Integers: array of integer): variant;
/// store an array of 64 bit integer into a TBSONVariant betArray type instance
// - object will be initialized with data supplied e.g. as a TIntegerDynArray
function BSONVariantFromInt64s(const Integers: array of Int64): variant;
/// parse the header of a BSON encoded binary buffer, and return its length
// - BSON should point to a "int32 e_list #0" BSON document (like TBSONDocument)
// - if ExpectedBSONLen is set, this function will check that the supplied
// BSON content "int32" length matches the supplied value, and raise an
// EBSONException if this comparison fails
// - as an alternative, consider using TBSONIterator, which wrap both a PByte
// and a TBSONElement into one convenient item
function BSONParseLength(var BSON: PByte; ExpectedBSONLen: integer=0): integer;
/// parse the next element in supplied BSON encoded binary buffer list
// - BSON should point to the "e_list" of the "int32 e_list #0" BSON document
// - will decode the supplied binary buffer as a variant, then it will let BSON
// point to the next element, and return TRUE
// - returns FALSE when you reached betEOF, so that you can use it in a loop:
// ! var bson: PByte;
// ! name: RaWUTF8;
// ! value: variant;
// ! ...
// ! BSONParseLength(bson);
// ! while BSONParseNextElement(bson,name,value) do
// ! writeln(name,':',value);
// - by default, it will return TBSONVariant custom variants for documents or
// arrays - but if storeDocArrayAsDocVariant is set, it will return a
// TDocVariant custom kind of variant, able to access to its nested
// properties via late-binding
// - if you want to parse a BSON list as fast as possible, you should better use
// TBSONElement.FromNext() which avoid any memory allocation (the SAX way) - in
// fact, this function is just a wrapper around TBSONElement.FromNext + ToVariant
// - as an alternative, consider using TBSONIterator, which wrap both a PByte
// and a TBSONElement into one convenient item
function BSONParseNextElement(var BSON: PByte; var name: RawUTF8; var element: variant;
DocArrayConversion: TBSONDocArrayConversion=asBSONVariant): boolean;
/// search for a property by number in a a supplied BSON encoded binary buffer
// - BSON should point to a "int32 e_list #0" BSON document (like TBSONDocument)
// - returns FALSE if the list has too few elements (starting at index 0)
// - otherwise, returns TRUE then let item point to the corresponding element
function BSONPerIndexElement(BSON: PByte; index: integer; var item: TBSONElement): boolean;
/// convert a BSON document into a TDocVariant variant instance
// - BSON should point to a "int32 e_list #0" BSON document
// - if ExpectedBSONLen is set, this function will check that the supplied
// BSON content "int32" length matches the supplied value
// - by definition, asBSONVariant is not allowed as Option value
procedure BSONToDoc(BSON: PByte; var Result: Variant; ExpectedBSONLen: integer=0;
Option: TBSONDocArrayConversion=asDocVariantPerReference);
/// convert a TBSONDocument into a TDocVariant variant instance
// - BSON should be valid BSON document (length will be checked against expected
// "int32 e_list #0" binary layout)
// - by definition, asBSONVariant is not allowed as Option value
function BSONDocumentToDoc(const BSON: TBSONDocument;
Option: TBSONDocArrayConversion=asDocVariantPerReference): variant;
{$ifdef HASINLINE}inline;{$endif}
/// convert a BSON document into its JSON representation
// - BSON should point to a "int32 e_list #0" BSON document
// - Kind should be either betDoc or betArray
// - if ExpectedBSONLen is set, this function will check that the supplied
// BSON content "int32" length matches the supplied value
// - this function will use by default the MongoDB Extended JSON syntax for
// specific MongoDB objects but you may use modMongoShell if needed
function BSONToJSON(BSON: PByte; Kind: TBSONElementType;
ExpectedBSONLen: integer=0; Mode: TMongoJSONMode=modMongoStrict): RawUTF8;
/// convert a TBSONDocument into its JSON representation
// - BSON should be valid BSON document (length will be checked against expected
// "int32 e_list #0" binary layout)
// - this function will use by default the MongoDB Extended JSON syntax for
// specific MongoDB objects but you may use modMongoShell if needed
function BSONDocumentToJSON(const BSON: TBSONDocument;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8;
{$ifdef HASINLINE}inline;{$endif}
/// convert a BSON list of elements into its JSON representation
// - BSON should point to the "e_list" of the "int32 e_list #0" BSON document,
// i.e. the item data as expected by TBSONElement.FromNext()
// - this function will use by default the MongoDB Extended JSON syntax for
// specific MongoDB objects but you may use modMongoShell if needed
procedure BSONListToJSON(BSONList: PByte; Kind: TBSONElementType; W: TTextWriter;
Mode: TMongoJSONMode=modMongoStrict);
/// convert any kind of BSON/JSON element, encoded as variant, into JSON
// - this function will use by default the MongoDB Extended JSON syntax for
// specific MongoDB objects but you may use modMongoShell if needed
procedure AddMongoJSON(const Value: variant; W: TTextWriter;
Mode: TMongoJSONMode=modMongoStrict); overload;
/// convert any kind of BSON/JSON element, encoded as variant, into JSON
// - in addition to default modMongoStrict as rendered by VariantSaveJSON(),
// this function can render the supplied variant with the Mongo Shell syntax
// or even raw JSON content
function VariantSaveMongoJSON(const Value: variant; Mode: TMongoJSONMode): RawUTF8;
{ ************ MongoDB Client }
const
/// MongoDB server default IP port
MONGODB_DEFAULTPORT = 27017;
type
/// exception type used for MongoDB process
EMongoException = class(ESynException);
/// the available MongoDB driver Request Opcodes
// - opReply: database reply to a client request - ResponseTo shall be set
// - opMsg: generic msg command followed by a string (deprecated)
// - opUpdate: update document
// - opInsert: insert new document
// - opQuery: query a collection
// - opGetMore: get more data from a previous query
// - opDelete: delete documents
// - opKillCursors: notify database client is done with a cursor
TMongoOperation = (
opReply, opMsg, opUpdate, opInsert, opQuery, opGetMore, opDelete, opKillCursors);
/// define how an opUpdate operation will behave
// - if mufUpsert is set, the database will insert the supplied object into
// the collection if no matching document is found
// - if mufMultiUpdate is set, the database will update all matching objects
// in the collection; otherwise (by default) only updates first matching doc
TMongoUpdateFlag =
(mufUpsert, mufMultiUpdate);
/// define how a TMongoRequestUpdate message will behave
TMongoUpdateFlags = set of TMongoUpdateFlag;
/// define how an opInsert operation will behave
// - if mifContinueOnError is set, the database will not stop processing a
// bulk insert if one fails (e.g. due to duplicate IDs); this makes bulk
// insert behave similarly to a series of single inserts, except lastError
// will be set if any insert fails, not just the last one - if multiple
// errors occur, only the most recent will be reported by getLastError
TMongoInsertFlag =
(mifContinueOnError);
/// define how a TMongoRequestInsert message will behave
TMongoInsertFlags = set of TMongoInsertFlag;
/// define how an opDelete operation will behave
// - if mdfSingleRemove is set, the database will remove only the first
// matching document in the collection. Otherwise (by default) all matching
// documents will be removed
TMongoDeleteFlag =
(mdfSingleRemove);
/// define how a TMongoRequestDelete message will behave
TMongoDeleteFlags = set of TMongoDeleteFlag;
/// define how an opQuery operation will behave
// - if mqfTailableCursor is set, cursor is not closed when the last data
// is retrieved
// - if mqfSlaveOk is set, it will allow query of replica slave; normally
// this returns an error except for namespace "local"
// - mqfOplogReplay is internal replication use only - driver should not set
// - if mqfNoCursorTimeout is set, the server normally does not times out
// idle cursors after an inactivity period (10 minutes) to prevent
// excess memory use
// - if mqfAwaitData is to use with TailableCursor. If we are at the end
// of the data, block for a while rather than returning no data. After a
// timeout period, we do return as normal
// - if mqfExhaust is set, stream the data down full blast in multiple "more"
// packages, on the assumption that the client will fully read all data queried
// - if mqfPartial is set, it will get partial results from a mongos if
// some shards are down (instead of throwing an error)
TMongoQueryFlag =
(mqfTailableCursor=1, mqfSlaveOk, mqfOplogReplay, mqfNoCursorTimeout,
mqfAwaitData, mqfExhaust, mqfPartial);
/// define how a TMongoRequestQuery message will behave
TMongoQueryFlags = set of TMongoQueryFlag;
/// abstract class used to create MongoDB Wire Protocol client messages
// - see http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol
// - this class is not tight to the connection class itself (which is one
// known limitation of TMongoWire for instance)
TMongoRequest = class(TBSONWriter)
protected
fRequestID: integer;
fResponseTo: integer;
fRequestOpCode: TMongoOperation;
fDatabaseName,
fCollectionName,
fFullCollectionName: RawUTF8;
fBSONDocument: TBSONDocument;
public
/// write a standard Message Header for MongoDB client
// - opCode is the type of the message
// - requestID is a client or database-generated identifier that uniquely
// identifies this message: in case of opQuery or opGetMore messages, it will
// be sent in the responseTo field from the database
// - responseTo is the requestID taken from previous opQuery or opGetMore
constructor Create(const FullCollectionName: RawUTF8;
opCode: TMongoOperation; requestID, responseTo: Integer); reintroduce;
/// append a query parameter as a BSON document
// - param can be a TDocVariant, e.g. created with:
// ! _JsonFast('{name:"John",age:{$gt:21}}');
// ! _JsonFastFmt('{name:?,age:{$gt:?}}',[],['John',21]);
// ! _JsonFastFmt('{name:?,field:/%/i}',['acme.*corp'],['John']);
// - param can be a TBSONVariant containing a TBSONDocument raw binary block
// created e.g. from:
// ! BSONVariant(['BSON',_Arr(['awesome',5.05, 1986])])
// ! BSONVariantType[BSON(['BSON',_Arr(['awesome',5.05, 1986])])]
// - if param is null, it will append a void document
// - if param is a string, it will be converted as expected by most
// database commands, e.g.
// ! TMongoRequestQuery.Create('admin.$cmd','buildinfo',[],1)
// will query { buildinfo: 1 } to the admin.$cmd collection, i.e.
// $ admin.$cmd.findOne( { buildinfo: 1 } )
procedure BSONWriteParam(const paramDoc: variant);
/// flush the content and return the whole binary encoded stream
// - expect the TBSONWriter instance to have been created with reintroduced
// Create() specific constructors inheriting from this TMongoRequest class
// - this overridden version will adjust the size in the message header
procedure ToBSONDocument(var result: TBSONDocument); override;
/// write the main parameters of the request as JSON
procedure ToJSON(W: TTextWriter; Mode: TMongoJSONMode); overload; virtual;
/// write the main parameters of the request as JSON
function ToJSON(Mode: TMongoJSONMode): RawUTF8; overload;
/// identify the message, after call to any reintroduced Create() constructor
property MongoRequestID: integer read fRequestID;
/// the associated full collection name, e.g. 'db.test'
property FullCollectionName: RawUTF8 read fFullCollectionName;
/// the associated full collection name, e.g. 'db'
property DatabaseName: RawUTF8 read fDatabaseName;
/// the associated full collection name, e.g. 'test'
property CollectionName: RawUTF8 read fCollectionName;
/// the message operation code
// - should be either opUpdate, opInsert, opQuery, opGetMore, opDelete
// or opKillCursors, depending on the TMongoRequest* class instantiated
property MongoRequestOpCode: TMongoOperation read fRequestOpCode;
end;
/// a MongoDB client abstract ancestor which is able to create a BULK
// command message for MongoDB >= 2.6 instead of older dedicated Wire messages
TMongoRequestWritable = class(TMongoRequest)
protected
public
end;
/// a MongoDB client message to update a document in a collection
TMongoRequestUpdate = class(TMongoRequestWritable)
protected
fSelector, fUpdate: TVarData;
public
/// initialize a MongoDB client message to update a document in a collection
// - FullCollectionName is e.g. 'dbname.collectionname'
// - how the update will be processed can be customized via Flags
// - Selector is the BSON document query to select the document, supplied as
// TDocVariant - i.e. created via _JsonFast() or _JsonFastFmt() - or as
// TBSONVariant - i.e. created via BSONVariant() - or null if all documents
// are to be updated
// - Update is the BSON document specification of the update to perform,
// supplied as TDocVariant or TBSONVariant
// - there is no response to an opUpdate message
constructor Create(const FullCollectionName: RawUTF8;
const Selector, Update: variant; Flags: TMongoUpdateFlags=[]); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJSON(W: TTextWriter; Mode: TMongoJSONMode); override;
end;
/// a MongoDB client message to insert one or more documents in a collection
TMongoRequestInsert = class(TMongoRequestWritable)
public
/// initialize a MongoDB client message to insert one or more documents in
// a collection, supplied as variants
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Documents is an array of TDocVariant or TBSONVariant - i.e. created via
// _JsonFast() _JsonFastFmt() or BSONVariant()
// - there is no response to an opInsert message
constructor Create(const FullCollectionName: RawUTF8;
const Documents: array of variant; Flags: TMongoInsertFlags=[]); reintroduce; overload;
/// initialize a MongoDB client message to insert one or more documents in
// a collection, supplied as raw BSON binary
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Documents is the low-level concatenation of BSON documents, created
// e.g. with a TBSONWriter stream
// - there is no response to an opInsert message
constructor Create(const FullCollectionName: RawUTF8;
const Documents: TBSONDocument; Flags: TMongoInsertFlags=[]); reintroduce; overload;
/// initialize a MongoDB client message to insert one or more documents in
// a collection, supplied as JSON objects
// - FullCollectionName is e.g. 'dbname.collectionname'
// - JSONDocuments is an array of JSON objects
// - there is no response to an opInsert message
constructor Create(const FullCollectionName: RawUTF8;
const JSONDocuments: array of PUTF8Char; Flags: TMongoInsertFlags=[]); reintroduce; overload;
end;
/// a MongoDB client message to delete one or more documents in a collection
TMongoRequestDelete = class(TMongoRequestWritable)
protected
fQuery: TVarData;
public
/// initialize a MongoDB client message to delete one or more documents in
// a collection
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Selector is the BSON document query to select the document, supplied as
// TDocVariant - i.e. created via _JsonFast() or _JsonFastFmt() - or as
// TBSONVariant - i.e. created via BSONVariant() - or null if all documents
// are to be deleted
// - warning: CreateDelete('db.coll',null) can be expensive so you should
// better drop the whole collection
// - there is no response to an opDelete message
constructor Create(const FullCollectionName: RawUTF8;
const Selector: variant; Flags: TMongoDeleteFlags=[]); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJSON(W: TTextWriter; Mode: TMongoJSONMode); override;
end;
/// a MongoDB client message to query one or more documents in a collection
TMongoRequestQuery = class(TMongoRequest)
protected
fNumberToReturn,fNumberToSkip: integer;
fQuery, fReturnFieldsSelector: TVarData;
public
/// initialize a MongoDB client message to query one or more documents in
// a collection from a specified Cursor identifier
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Query is the BSON document query to select the document, supplied as
// TDocVariant - i.e. created via _JsonFast() or _JsonFastFmt() - or null
// if all documents are to be retrieved - for instance:
// ! _JsonFast('{name:"John",age:{$gt:21}}');
// ! _JsonFastFmt('{name:?,age:{$gt:?}}',[],['John',21]);
// ! _JsonFastFmt('{name:?,field:/%/i}',['acme.*corp'],['John']);
// - if Query is a string, it will be converted as expected by most
// database commands, e.g.
// $ TMongoRequestQuery.Create('admin.$cmd','buildinfo',[],1)
// will query { buildinfo: 1 } to the admin.$cmd collection, i.e.
// $ admin.$cmd.findOne( { buildinfo: 1 } )
// - Query can also be a TBSONVariant, e.g. created with:
// ! BSONVariant('{name:?,age:{$gt:?}}',[],['John',21])
// - ReturnFieldsSelector is an optional selector (set to null if not
// applicable) as a BSON document that limits the fields in the returned
// documents, supplied as TDocVariant or TBSONVariant - e.g. created via:
// ! BSONVariantFieldSelector('a,b,c');
// ! BSONVariantFieldSelector(['a','b','c']);
// ! BSONVariant('{a:1,b:1,c:1}');
// ! _JsonFast('{a:1,b:1,c:1}');
// - if ReturnFieldsSelector is a string, it will be converted into
// $ { ReturnFieldsSelector: 1 }
constructor Create(const FullCollectionName: RawUTF8;
const Query, ReturnFieldsSelector: variant; NumberToReturn: integer;
NumberToSkip: Integer=0; Flags: TMongoQueryFlags=[]); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJSON(W: TTextWriter; Mode: TMongoJSONMode); override;
/// retrieve the NumberToReturn parameter as set to the constructor
property NumberToReturn: integer read fNumberToReturn;
/// retrieve the NumberToSkip parameter as set to the constructor
property NumberToSkip: integer read fNumberToSkip;
end;
/// a MongoDB client message to continue the query of one or more documents
// in a collection, after a TMongoRequestQuery message
TMongoRequestGetMore = class(TMongoRequest)
public
/// initialize a MongoDB client message to continue the query of one or more
// documents in a collection, after a opQuery / TMongoRequestQuery message
// - FullCollectionName is e.g. 'dbname.collectionname'
// - you can specify the number of documents to return (e.g. from previous
// opQuery response)
// - CursorID should have been retrieved within an opReply message from the
// database
constructor Create(const FullCollectionName: RawUTF8;
NumberToReturn: integer; CursorID: Int64); reintroduce;
end;
/// a MongoDB client message to close one or more active cursors
TMongoRequestKillCursor = class(TMongoRequest)
protected
fCursors: TInt64DynArray;
public
/// initialize a MongoDB client message to close one or more active cursors
// in the database
// - it is mandatory to ensure that database resources are reclaimed by
// the client at the end of the query
// - if a cursor is read until exhausted (read until opQuery or opGetMore
// returns zero for the CursorId), there is no need to kill the cursor
// - there is no response to an opKillCursor message
constructor Create(const FullCollectionName: RawUTF8;
const CursorIDs: array of Int64); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJSON(W: TTextWriter; Mode: TMongoJSONMode); override;
end;
/// used to store the binary raw data a database response to a
// TMongoRequestQuery / TMongoRequestGetMore client message
TMongoReply = RawByteString;
/// define an opReply message execution content
// - mrfCursorNotFound will be set when getMore is called but the cursor id
// is not valid at the server; returned with zero results
// - mrfQueryFailure is set when the query failed - results consist of one
// document containing an "$err" field describing the failure
// - mrfShardConfigStale should not be used by client, just by Mongos
// - mrfAwaitCapable is set when the server supports the AwaitData Query
// option (always set since Mongod version 1.6)
TMongoReplyCursorFlag = (
mrfCursorNotFound, mrfQueryFailure, mrfShardConfigStale,
mrfAwaitCapable);
/// define a TMongoReplyCursor message execution content
TMongoReplyCursorFlags = set of TMongoReplyCursorFlag;
/// internal low-level binary structure mapping the TMongoReply header
// - used e.g. by TMongoReplyCursor and TMongoConnection.GetReply()
TMongoReplyHeader = packed record
/// total message length, including the header
MessageLength: integer;
/// identifier of this message
RequestID: integer;
/// retrieve the RequestID from the original request
ResponseTo: integer;
/// low-level code of the message
OpCode: integer;
/// response flags
ResponseFlags: integer;
/// cursor identifier if the client may need to perform further opGetMore
CursorID: Int64;
/// where in the cursor this reply is starting
StartingFrom: integer;
/// number of documents in the reply
NumberReturned: integer;
end;
/// points to an low-level binary structure mapping the TMongoReply header
// - so that you can write e.g.
// ! PMongoReplyHeader(aMongoReply)^.RequestID
PMongoReplyHeader = ^TMongoReplyHeader;
/// map a MongoDB server reply message as sent by the database
// - in response to TMongoRequestQuery / TMongoRequestGetMore messages
// - you can use the record's methods to retrieve information about a given
// response, and navigate within all nested documents
// - several TMongoReplyCursor instances may map the same TMongoReply content
// - you can safely copy one TMongoReplyCursor instance to another
{$ifndef UNICODE}
TMongoReplyCursor = object
protected
{$else}
TMongoReplyCursor = record
private
{$endif}
fReply: TMongoReply;
fRequestID: integer;
fResponseTo: integer;
fResponseFlags: TMongoReplyCursorFlags;
fCursorID: Int64;
fStartingFrom: integer;
fNumberReturned: integer;
fDocuments: TPointerDynArray;
fCurrentPosition: integer;
fFirstDocument,
fCurrentDocument: PAnsiChar;
fLatestDocIndex: integer;
fLatestDocValue: variant;
procedure ComputeDocumentsList;
function GetOneDocument(index: integer): variant;
public
/// initialize the cursor with a supplied binary reply from the server
// - will raise an EMongoException if the content is not valid
// - will populate all record fields with the supplied data
procedure Init(const ReplyMessage: TMongoReply);
/// retrieve the next document in the list, as a TDocVariant instance
// - return TRUE if the supplied document has been retrieved
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! doc: variant;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(doc) do
// ! writeln('Name: ',doc.Name,' FirstName: ',doc.FirstName);
function Next(out doc: variant; option: TBSONDocArrayConversion=asDocVariantPerReference): boolean; overload;
/// retrieve the next document in the list, as BSON content
// - return TRUE if the supplied document has been retrieved - then doc
// points to a "int32 e_list #0" BSON document
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - this method is almost immediate, since the BSON raw binary is returned
// directly without any conversion
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! doc: PByte;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(doc) do
// ! writeln(BSONToJSON(doc,0,modMongoShell)); // fast display
function Next(out doc: PByte): boolean; overload;
/// retrieve the next document in the list, as a BSON binary document
// - return TRUE if the supplied document has been retrieved - then doc
// points to a "int32 e_list #0" BSON document
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - this method is slightly slower than the one returning a PByte, since
// it will allocate a memory buffer to store the TBSONDocument binary
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! doc: TBSONDocument;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(doc) do
// ! writeln(BSONToJSON(doc,0,modMongoShell)); // fast display
function Next(out BSON: TBSONDocument): boolean; overload;
/// retrieve the next document in the list, as JSON content
// - return TRUE if the supplied document has been retrieved
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! json: RawUTF8;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(json,modMongoShell) do
// ! writeln(json); // fast display
function Next(out JSON: RawUTF8; Mode: TMongoJSONMode=modMongoStrict): boolean; overload;
/// let Next() overloaded methods point to the first document of this message
procedure Rewind;
/// retrieve a given document as a TDocVariant instance
// - this method won't use any cache (like Document[..] property), since
// it should be used with a local variant on stack as cache:
// ! var Reply: TMongoReply;
// ! doc: variant;
// ! i: integer;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! for i := 0 to Reply.DocumentCount-1 do begin
// ! GmrfQueryFailureetDocument(i,doc);
// ! writeln('Name: ',doc.Name,' FirstName: ',doc.FirstName);
// ! end;
procedure GetDocument(index: integer; var result: variant);
/// return all documents content as a JSON array, or one JSON object
// if there is only one document in this reply
// - this method is very optimized and will convert the BSON binary content
// directly into JSON
procedure FetchAllToJSON(W: TTextWriter; Mode: TMongoJSONMode=modMongoStrict;
WithHeader: boolean=false; MaxSize: Cardinal=0);
/// return all documents content as a JSON array, or one JSON object
// if there is only one document in this reply
// - this method is very optimized and will convert the BSON binary content
// directly into JSON
function ToJSON(Mode: TMongoJSONMode=modMongoStrict; WithHeader: boolean=false;
MaxSize: Cardinal=0): RawUTF8;
/// append all documents content to a dynamic array of TDocVariant
// - return the new size of the Dest[] array
function AppendAllToDocVariantDynArray(var Dest: TVariantDynArray): integer;
/// append all documents content to a TDocVariant array instance
// - if the supplied instance if not already a TDocVariant of kind dvArray,
// a new void instance will be created
// - return the new size of the Dest array
function AppendAllToDocVariant(var Dest: TDocVariantData): integer;
/// append all documents content to a BSON binary stream
// - Dest.Tag will be used to count the current item number in the resulting
// BSON array
procedure AppendAllToBSON(Dest: TBSONWriter);
/// retrieve the context execution of this message
property ResponseFlags: TMongoReplyCursorFlags read fResponseFlags;
/// identifier of this message
property RequestID: integer read fRequestID;
/// retrieve the RequestID from the original request
property ResponseTo: integer read fResponseTo;
/// access to the low-level binary reply message
property Reply: TMongoReply read fReply;
/// cursor identifier if the client may need to perform further
// TMongoRequestGetMore messages
// - in the event that the result set of the query fits into one OP_REPLY
// message, CursorID will be 0
property CursorID: Int64 read fCursorID;
/// where in the cursor this reply is starting
property StartingFrom: integer read fStartingFrom;
/// number of documents in the reply
property DocumentCount: Integer read fNumberReturned;
/// points to the first document binary
// - i.e. just after the Reply header
property FirstDocument: PAnsiChar read fFirstDocument;
/// direct access to the low-level BSON binary content of each document
property DocumentBSON: TPointerDynArray read fDocuments;
/// retrieve a given document as a TDocVariant instance
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! i: integer;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! for i := 0 to Reply.DocumentCount-1 do
// ! writeln('Name: ',Reply.Document[i].Name,' FirstName: ',Reply.Document[i].FirstName);
// - note that there is an internal cache for the latest retrieved document
// by this property, so that you can call Reply.Document[i] several times
// without any noticeable speed penalty
property Document[index: integer]: variant read GetOneDocument;
/// the current position of the Next() call, starting at 0
property Position: integer read fCurrentPosition;
end;
/// event callback signature for iterative process of TMongoConnection
TOnMongoConnectionReply = procedure(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque) of object;
{$M+}
TMongoClient = class;
TMongoDatabase = class;
TMongoCollection = class;
/// one TCP/IP connection to a MongoDB server
// - all access will be protected by a mutex (critical section): it is thread
// safe but you may use one TMongoClient per thread or a connection pool, for
// better performance
TMongoConnection = class
protected
fLock: TRTLCriticalSection;
fLocked: cardinal;
fClient: TMongoClient;
fSocket: TCrtSocket;
fServerAddress: RawUTF8;
fServerPort: integer;
procedure Lock;
procedure UnLock;
function Send(Request: TMongoRequest): boolean;
function GetOpened: boolean;
function GetLocked: boolean;
// will call TMongoReplyCursor.FetchAllToJSON(TTextWriter(Opaque))
procedure ReplyJSONStrict(Request: TMongoRequest; const Reply: TMongoReplyCursor; var Opaque);
procedure ReplyJSONExtended(Request: TMongoRequest; const Reply: TMongoReplyCursor; var Opaque);
procedure ReplyJSONNoMongo(Request: TMongoRequest; const Reply: TMongoReplyCursor; var Opaque);
// will call TMongoReplyCursor.AppendAllToDocVariantDynArray(TVariantDynArray(Opaque))
procedure ReplyDocVariant(Request: TMongoRequest; const Reply: TMongoReplyCursor; var Opaque);
// will call TMongoReplyCursor.AppendAllToBSON(TBSONWrite(Opaque))
procedure ReplyBSON(Request: TMongoRequest; const Reply: TMongoReplyCursor; var Opaque);
public
/// initialize the connection to the corresponding MongoDB server
// - the server address is either a host name, or an IP address
// - if no server address is specified, will try to connect to localhost
// - this won't create the connection, until Open method is executed
constructor Create(const aClient: TMongoClient; const aServerAddress: RawByteString;
aServerPort: integer=MONGODB_DEFAULTPORT); reintroduce;
/// release the connection, including the socket
destructor Destroy; override;
/// connect to the MongoDB server
// - will raise an EMongoException on error
procedure Open;
/// disconnect from MongoDB server
// - will raise an EMongoException on error
procedure Close;
/// low-level method to send a request to the server
// - if Request is not either TMongoRequestQuery or TMongoRequestGetMore,
// will raise an EMongoException
// - then will return the reply message as sent back by the database,
// ready to be accessed using a TMongoReplyCursor wrapper
procedure GetReply(Request: TMongoRequest; out result: TMongoReply);
/// low-level method to send a request to the server, and return a cursor
// - if Request is not either TMongoRequestQuery or TMongoRequestGetMore,
// will raise an EMongoException
// - then will parse and return a cursor to the reply message as sent back
// by the database, with logging if necessary
// - raise an EMongoException if mrfQueryFailure flag is set in the reply
procedure GetCursor(Request: TMongoRequest; var Result: TMongoReplyCursor);
/// low-level method to send a query to the server, calling a callback event
// on each reply
// - is used by GetDocumentsAndFree, GetBSONAndFree and GetJSONAndFree
// methods to receive the whole document (you should better call those)
// - the supplied Query instance will be released when not needed any more
procedure GetRepliesAndFree(Query: TMongoRequestQuery;
OnEachReply: TOnMongoConnectionReply; var Opaque);
/// send a query to the server, returning a TDocVariant instance containing
// all the incoming data
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
// - if Query.NumberToReturn<>1, it will return either null or a dvArray
// kind of TDocVariant containing all returned items
// - if Query.NumberToReturn=1, then it will return either null or a
// single TDocVariant instance
function GetDocumentsAndFree(Query: TMongoRequestQuery): variant; overload;
/// send a query to the server, returning a TDocVariant instance containing
// all the incoming data
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
// - if Query.NumberToReturn<>1, it will return either null or a dvArray
// kind of TDocVariant containing all returned items
// - if Query.NumberToReturn=1, then it will return either null or a
// single TDocVariant instance
procedure GetDocumentsAndFree(Query: TMongoRequestQuery; var result: variant); overload;
/// send a query to the server, returning a dynamic array of TDocVariant
// instance containing all the incoming data
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
procedure GetDocumentsAndFree(Query: TMongoRequestQuery; var result: TVariantDynArray); overload;
/// send a query to the server, returning a TBSONDocument instance containing
// all the incoming data, as raw binary BSON document containing an array
// of the returned items
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
function GetBSONAndFree(Query: TMongoRequestQuery): TBSONDocument;
/// send a query to the server, returning all the incoming data as JSON
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - this method is very optimized and will convert the BSON binary content
// directly into JSON, in either modMongoStrict or modMongoShell layout
// (modNoMongo will do the same as modMongoStrict)
// - if Query.NumberToReturn<>1, it will return either 'null' or a '[..]'
// JSON array with all the incoming documents retrieved from the server
// - if Query.NumberToReturn=1, it will return either 'null' or a single
// '{...}' JSON object
// - the supplied Query instance will be released when not needed any more
function GetJSONAndFree(Query: TMongoRequestQuery; Mode: TMongoJSONMode): RawUTF8;
/// send a message to the MongoDB server
// - will apply Client.WriteConcern policy, and run an EMongoException
// in case of any error
// - the supplied Request instance will be released when not needed any more
// - by default, it will follow Client.WriteConcern pattern - but you can
// set NoAcknowledge = TRUE to avoid calling the getLastError command
// - will return the getLastError reply (if retrieved from server)
function SendAndFree(Request: TMongoRequest; NoAcknowledge: boolean=false): variant;
/// run a database command, supplied as a TDocVariant, TBSONVariant or a
// string, and return the a TDocVariant instance
// - see http://docs.mongodb.org/manual/reference/command for a list
// of all available commands
// - for instance:
// ! RunCommand('test',_ObjFast(['dbStats',1,'scale',1024],stats);
// ! RunCommand('test',BSONVariant(['dbStats',1,'scale',1024],stats);
// ! RunCommand('admin','buildinfo',fServerBuildInfo);
// - the message will be returned by the server as a single TDocVariant
// instance (since the associated TMongoRequestQuery.NumberToSkip=1)
// - in case of any error, the error message is returned as text
// - in case of success, this method will return ''
function RunCommand(const aDatabaseName: RawUTF8;
const command: variant; var returnedValue: variant): RawUTF8; overload;
/// run a database command, supplied as a TDocVariant, TBSONVariant or a
// string, and return the raw BSON document array of received items
// - this overloaded method can be used on huge content to avoid the slower
// conversion to an array of TDocVariant instances
// - in case of success, this method will return TRUE, or FALSE on error
function RunCommand(const aDatabaseName: RawUTF8;
const command: variant; var returnedValue: TBSONDocument): boolean; overload;
/// return TRUE if the Open method has successfully been called
property Opened: boolean read GetOpened;
/// access to the corresponding MongoDB server
property Client: TMongoClient read fClient;
/// direct access to the low-level TCP/IP communication socket
property Socket: TCrtSocket read fSocket;
/// is TRUE when the connection is busy
property Locked: boolean read GetLocked;
published
/// read-only access to the supplied server address
// - the server address is either a host name, or an IP address
property ServerAddress: RawUTF8 read fServerAddress;
/// read-only access to the supplied server port
// - the server Port is MONGODB_DEFAULTPORT (27017) by default
property ServerPort: integer read fServerPort;
end;
/// array of TCP connection to a MongoDB Replica Set
// - first item [0] is the Primary member
// - other items [1..] are the Secondary members
TMongoConnectionDynArray = array of TMongoConnection;
/// define Read Preference Modes to a MongoDB replica set
// - Important: All read preference modes except rpPrimary may return stale
// data because secondaries replicate operations from the primary with some
// delay - ensure that your application can tolerate stale data if you choose
// to use a non-primary mode
// - rpPrimary: Default mode - all operations read from the current replica
// set primary
// - rpPrimaryPreferred: in most situations, operations read from the primary
// but if it is unavailable, operations read from secondary members.
// - rpPsecondary: all operations read from the secondary members
// of the replica set
// - rpPsecondaryPreferred: in most situations, operations read from
// secondary members but if no secondary members are available, operations
// read from the primary
TMongoClientReplicaSetReadPreference = (
rpPrimary, rpPrimaryPreferred, rpSecondary, rpSecondaryPreferred);
/// define Write Concern property of a MongoDB connection
// - Write concern describes the guarantee that MongoDB provides when
// reporting on the success of a write operation. The strength of the write
// concerns determine the level of guarantee. When inserts, updates and
// deletes have a weak write concern, write operations return quickly. In
// some failure cases, write operations issued with weak write concerns may
// not persist. With stronger write concerns, clients wait after sending a
// write operation for MongoDB to confirm the write operations. MongoDB
// provides different levels of write concern to better address the specific
// needs of applications. Clients may adjust write concern to ensure that
// the most important operations persist successfully to an entire
// MongoDB deployment. For other less critical operations, clients can
// adjust the write concern to ensure faster performance rather than
// ensure persistence to the entire deployment.
// - wcAcknowledged is the default safe mode: the mongod confirms the
// receipt of the write operation. Acknowledged write concern allows clients
// to catch network, duplicate key, and other errors.
// - with wcJournaled, the mongod acknowledges the write operation only
// after committing the data to the journal. This write concern ensures that
// MongoDB can recover the data following a shutdown or power interruption.
// - wcReplicaAcknowledged will guarantee that the write operation propagates
// to at least one member of a replica set
// - with wcUnacknowledged, MongoDB does not acknowledge the receipt of
// write operation. Unacknowledged is similar to errors ignored; however,
// drivers attempt to receive and handle network errors when possible. The
// driver's ability to detect network errors depends on the system's
// networking configuration.
// - with wcErrorsIgnored, MongoDB does not acknowledge write operations.
// With this level of write concern, the client cannot detect failed write
// operations. These errors include connection errors and mongod exceptions
// such as duplicate key exceptions for unique indexes. Although the errors
// ignored write concern provides fast performance, this performance gain
// comes at the cost of significant risks for data persistence and durability.
// WARNING: Do not use wcErrorsIgnored write concern in normal operation.
TMongoClientWriteConcern = (
wcAcknowledged, wcJournaled, wcReplicaAcknowledged,
wcUnacknowledged, wcErrorsIgnored);
/// remote access to a MongoDB server
// - a single server can have several active connections, if some secondary
// hosts were defined
TMongoClient = class
protected
fConnectionString: RawUTF8;
fDatabases: TRawUTF8ListHashed;
fConnections: TMongoConnectionDynArray;
fReadPreference: TMongoClientReplicaSetReadPreference;
fWriteConcern: TMongoClientWriteConcern;
fConnectionTimeOut: Cardinal;
fConnectionTLS: boolean;
fGracefulReconnect: record
Enabled, ForcedDBCR: boolean;
User, Database: RawUTF8;
EncryptedDigest: RawByteString;
end;
fLog: TSynLog;
fLogRequestEvent: TSynLogInfo;
fLogReplyEvent: TSynLogInfo;
fLogReplyEventMaxSize: cardinal;
fServerBuildInfo: variant;
fServerBuildInfoNumber: cardinal;
fLatestReadConnectionIndex: integer;
procedure AfterOpen; virtual;
function GetOneReadConnection: TMongoConnection;
function GetBytesReceived: Int64;
function GetBytesSent: Int64;
function GetBytesTransmitted: Int64;
procedure Auth(const DatabaseName,UserName,Digest: RawUTF8; ForceMongoDBCR: boolean);
function ReOpen: boolean;
public
/// prepare a connection to a MongoDB server or Replica Set
// - this constructor won't create the connection until the Open method
// is called
// - you can specify multiple hosts, as CSV values, if necessary
// - depending on the platform, you may request for a TLS secured connection
constructor Create(const Host: RawUTF8; Port: Integer=MONGODB_DEFAULTPORT;
aTLS: boolean=false; const SecondaryHostCSV: RawUTF8=''; const SecondaryPortCSV: RawUTF8=''); overload;
/// connect to a database on a remote MongoDB primary server
// - this method won't use authentication, and will return the corresponding
// MongoDB database instance
// - this method is an alias to the Database[] property
function Open(const DatabaseName: RawUTF8): TMongoDatabase;
/// secure connection to a database on a remote MongoDB server
// - this method will use authentication and will return the corresponding
// MongoDB database instance, with a dedicated secured connection
// - will use MONGODB-CR for MongoDB engines up to 2.6 (or if ForceMongoDBCR
// is TRUE), and SCRAM-SHA-1 since MongoDB 3.x
// - see http://docs.mongodb.org/manual/administration/security-access-control
function OpenAuth(const DatabaseName,UserName,PassWord: RawUTF8;
ForceMongoDBCR: boolean=false): TMongoDatabase;
/// close the connection and release all associated TMongoDatabase,
// TMongoCollection and TMongoConnection instances
destructor Destroy; override;
/// define an optional logging instance to be used
// - you can also specify the event types to be used for requests or
// replay: by default, a verbose log with sllSQL and sllDB will be set
// - e.g. mORMotMongoDB.pas will call Client.SetLog(SQLite3Log) for you
procedure SetLog(LogClass: TSynLogClass;
RequestEvent: TSynLogInfo=sllSQL; ReplyEvent: TSynLogInfo=sllDB;
ReplyEventMaxSize: cardinal=1024);
/// retrieve extended server version and build information, as text
// - will create a string from ServerBuildInfo object, e.g. as
// $ 'MongoDB 3.2.0 mozjs mmapv1,wiredTiger'
function ServerBuildInfoText: RawUTF8;
/// retrieve the server version and build information
// - return the content as a TDocVariant document, e.g.
// ! ServerBuildInfo.version = '2.4.9'
// ! ServerBuildInfo.versionArray = [2,4,9,0]
// - this property is cached, so request is sent only once
// - you may rather use ServerBuildInfoNumber to check for available
// features at runtime, for easy comparison of the server version
property ServerBuildInfo: variant read fServerBuildInfo;
/// access to a given MongoDB database
// - try to open it via a non-authenticated connection it if not already:
// will raise an exception on error, or will return an instance
// - will return an existing instance if has already been opened
property Database[const DatabaseName: RawUTF8]: TMongoDatabase read Open; default;
/// low-level access to the TCP/IP connections of this MongoDB replica set
// - first item [0] is the Primary member
// - other items [1..] are the Secondary members
property Connections: TMongoConnectionDynArray read fConnections;
/// define the logging instance to be used for LogRequestEvent/LogReplyEvent
// - you may also call the SetLog() method to set all options at once
property Log: TSynLog read fLog write fLog;
published
/// the connection definition used to connect to this MongoDB server
property ConnectionString: RawUTF8 read fConnectionString;
/// retrieve the server version and build information
// - return the content as a TDocVariant document, e.g.
// ! 2040900 for MongoDB 2.4.9, or 2060000 for MongoDB 2.6, or
// ! 3000300 for MongoDB 3.0.3
// - this property is cached, so can be used to check for available
// features at runtime, without any performance penalty
property ServerBuildInfoNumber: cardinal read fServerBuildInfoNumber;
/// define Read Preference mode to a MongoDB replica set
// - see http://docs.mongodb.org/manual/core/read-preference
// - default is rpPrimary, i.e. reading from the main primary instance
// - Important: All read preference modes except rpPrimary may return stale
// data because secondaries replicate operations from the primary with some
// delay - ensure that your application can tolerate stale data if you choose
// to use a non-primary mode
property ReadPreference: TMongoClientReplicaSetReadPreference
read fReadPreference write fReadPreference;
/// define Write Concern mode to a MongoDB replica set
// - see http://docs.mongodb.org/manual/core/write-concern
// - default is wcAcknowledged, i.e. to acknowledge all write operations
property WriteConcern: TMongoClientWriteConcern
read fWriteConcern write fWriteConcern;
/// the connection time out, in milli seconds
// - default value is 30000, i.e. 30 seconds
property ConnectionTimeOut: Cardinal read fConnectionTimeOut write fConnectionTimeOut;
/// if the socket connection is secured over TLS
property ConnectionTLS: boolean read fConnectionTLS;
/// allow automatic reconnection (with authentication, if applying), if the
// socket is closed (e.g. was dropped from the server)
property GracefulReconnect: boolean
read fGracefulReconnect.Enabled write fGracefulReconnect.Enabled;
/// how may bytes this client did received, among all its connections
property BytesReceived: Int64 read GetBytesReceived;
/// how may bytes this client did received, among all its connections
property BytesSent: Int64 read GetBytesSent;
/// how may bytes this client did transmit, adding both input and output
property BytesTransmitted: Int64 read GetBytesTransmitted;
/// if set to something else than default sllNone, will log each request
// with the corresponding logging event kind
// - will use the Log property for the destination log
// - you may also call the SetLog() method to set all options at once
property LogRequestEvent: TSynLogInfo read fLogRequestEvent write fLogRequestEvent;
/// if set to something else than default sllNone, will log each reply
// with the corresponding logging event kind
// - WARNING: logging all incoming data may be very verbose, e.g. when
// retrieving a document list - use it with care, not on production, but
// only for debugging purposes - or set LogReplyEventMaxSize to a low value
// - will use the Log property for the destination log
// - you may also call the SetLog() method to set all options at once
property LogReplyEvent: TSynLogInfo read fLogReplyEvent write fLogReplyEvent;
/// defines how many characters a LogReplyEvent entry may append in the log
// - is set by default to 1024, which sounds somewhat good for debugging
property LogReplyEventMaxSize: cardinal
read fLogReplyEventMaxSize write fLogReplyEventMaxSize;
end;
/// remote access to a MongoDB database
TMongoDatabase = class
protected
fClient: TMongoClient;
fName: RawUTF8;
fCollections: TRawUTF8ListHashed;
function GetCollection(const Name: RawUTF8): TMongoCollection;
function GetCollectionOrCreate(const Name: RawUTF8): TMongoCollection;
function GetCollectionOrNil(const Name: RawUTF8): TMongoCollection;
public
/// initialize a reference to a given MongoDB Database
// - you should not use this constructor directly, but rather use the
// TMongoClient.Database[] property
// - it will connect to the Client's primary host, then retrieve all
// collection names of this database
constructor Create(aClient: TMongoClient; const aDatabaseName: RawUTF8);
/// release all associated TMongoCollection instances
destructor Destroy; override;
/// run a database command, supplied as a TDocVariant, TBSONVariant or a
// string, and return a TDocVariant instance
// - this is the preferred method to issue database commands, as it provides
// a consistent interface between the MongoDB shell and this driver
// - see http://docs.mongodb.org/manual/reference/command for a list
// of all available commands
// - for instance:
// ! RunCommand(_ObjFast(['dbStats',1,'scale',1024],stats);
// ! RunCommand(BSONVariant(['dbStats',1,'scale',1024],stats);
// ! RunCommand('dbStats',stats);
// ! RunCommand('hostInfo',host);
// - the message will be returned by the server as a TDocVariant instance
// (since the associated TMongoRequestQuery.NumberToSkip=1)
// - in case of any error, the error message is returned as text
// - in case of success, this method will return ''
function RunCommand(const command: variant;
var returnedValue: variant): RawUTF8; overload;
/// run a database command, supplied as a TDocVariant, TBSONVariant or a
// string, and return the raw BSON document array of received items
// - this overloaded method can be used on huge content to avoid the slower
// conversion to an array of TDocVariant instances
// - in case of success, this method will return TRUE, or FALSE on error
function RunCommand(const command: variant;
var returnedValue: TBSONDocument): boolean; overload;
/// create the user in the database to which the user will belong
// - you could specify the roles to use, for this database or others:
// ! reportingDB.CreateUser('reportsUser','12345678',BSONVariant(
// ! '[{ role: "readWrite", db: "reporting" }, { role: "read", db: "products" }]'));
// - returns '' on sucess, an error message otherwise
function CreateUser(const UserName,Password: RawUTF8;
const roles: variant): RawUTF8;
/// create the user with a read or read/write role on the current database
// - returns '' on sucess, an error message otherwise
function CreateUserForThisDatabase(const UserName,Password: RawUTF8;
allowWrite: Boolean=true): RawUTF8;
/// deletes the supplied user on the current database
// - returns '' on sucess, an error message otherwise
function DropUser(const UserName: RawUTF8): RawUTF8;
/// access to a given MongoDB collection
// - raise an EMongoDatabaseException if the collection name does not exist
property Collection[const Name: RawUTF8]: TMongoCollection
read GetCollection; default;
/// access to a given MongoDB collection
// - if the collection name does not exist, it will return nil
property CollectionOrNil[const Name: RawUTF8]: TMongoCollection
read GetCollectionOrNil;
/// access to a given MongoDB collection
// - if the collection name does not exist, it will add use the name to
// create a TMongoCollection instance and register it to the internal list
property CollectionOrCreate[const Name: RawUTF8]: TMongoCollection
read GetCollectionOrCreate;
published
/// the database name
property Name: RawUTF8 read fName;
/// the associated MongoDB client instance
property Client: TMongoClient read fClient;
end;
/// remote access to a MongoDB collection
TMongoCollection = class
protected
fDatabase: TMongoDatabase;
fName: RawUTF8;
fFullCollectionName: RawUTF8;
function AggregateCallFromJSON(const pipelineJSON: RawUTF8; var reply,res: variant): boolean; overload;
function AggregateCallFromVariant(const pipelineArray: variant; var reply,res: variant): boolean; overload;
public
/// initialize a reference to a given MongoDB Collection
// - you should not use this constructor directly, but rather use
// TMongoClient.Database[].Collection[] property
constructor Create(aDatabase: TMongoDatabase; const aCollectionName: RawUTF8);
/// select documents in a collection and returns a dvArray TDocVariant
// instance containing the selected documents
// - Criteria can be null (to retrieve all documents) or a TDocVariant /
// TBSONVariant query selector:
// ! FindDoc(BSONVariant('{name:"John",age:{$gt:21}}'),null);
// ! FindDoc(BSONVariant('{name:?,age:{$gt:?}}',[],['John',21]),null);
// see http://docs.mongodb.org/manual/reference/operator for reference
// - Projection can be null (to retrieve all fields) or a CSV string to set
// field names to retrieve, or a TDocVariant or TBSONVariant - e.g.:
// ! FindDoc(BSONVariant(['name','John']),null);
// ! FindDoc(BSONVariant(['name','John']),'_id,name');
// ! FindDoc(BSONVariant(['name','John']),BSONVariantFieldSelector('name,_id'));
// - NumberToReturn can be left to its default maxInt value to return all
// matching documents, or specify a limit (e.g. 1 for one document - in this
// case, the returned instance won't be a dvArray kind of TDocVariant, but
// either null or the single returned document)
// - if the query does not have any matching record, it will return null
function FindDoc(const Criteria, Projection: Variant;
NumberToReturn: integer=1; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]): variant; overload;
/// select documents in a collection and returns a dvArray TDocVariant
// instance containing the selected documents
// - Criteria can specify the query selector as (extended) JSON and
// parameters:
// ! FindDoc('{name:"John",age:{$gt:21}}',[]);
// ! FindDoc('{name:?,age:{$gt:?}}',['John',21]);
// see http://docs.mongodb.org/manual/reference/operator for reference
// - this overloaded method will use a null Projection, i.e. will retrieve
// all fields
// - NumberToReturn can be left to its default maxInt value to return all
// matching documents, or specify a limit (e.g. 1 for one document - in this
// case, the returned instance won't be a dvArray kind of TDocVariant, but
// either null or the single returned document)
// - if the query does not have any matching record, it will return null
function FindDoc(Criteria: PUTF8Char; const Params: array of const;
NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]): variant; overload;
/// find an existing document in a collection, by its _id field
// - _id will identify the unique document to be retrieved
// - returns null, or a TDocVariant instance
function FindOne(const _id: TBSONObjectID): variant; overload;
/// find an existing document in a collection, by its _id field
// - _id will identify the unique document to be retrieved
// - returns null, or a TDocVariant instance
function FindOne(const _id: variant): variant; overload;
/// find an existing document in a collection, by a custom Criteria value
// - Criteria object, specified as name/value pairs, will identify the
// unique document to be retrieved
// - returns the found TDocVariant instance
// - if the Criteria has no match, return either null or a new object with
// default values as NameValuePairs if ReturnNewObjectIfNotFound is true
function FindOne(const NameValuePairs: array of const;
ReturnNewObjectIfNotFound: boolean=false): variant; overload;
/// returns a dynamic array of TDocVariant instance containing
// all documents of a collection
// - Projection can be null (to retrieve all fields) or a CSV string to set
// field names to retrieve, or a TDocVariant or TBSONVariant with
// projection operators
procedure FindDocs(var result: TVariantDynArray; const Projection: variant;
NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]); overload;
/// select documents in a collection and returns a dynamic array of
// TDocVariant instance containing the selected documents
// - you can e.g. fill a res: TVariantDynArray with the following query:
// ! FindDocs('{name:?,age:{$gt:?}}',['John',21],res,null);
// - Projection can be null (to retrieve all fields) or a CSV string to set
// field names to retrieve, or a TDocVariant or TBSONVariant with
// projection operators
procedure FindDocs(Criteria: PUTF8Char; const Params: array of const;
var result: TVariantDynArray; const Projection: variant;
NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]); overload;
/// select documents in a collection and returns a dynamic array of
// TDocVariant instance containing the selected documents
// - could be used to fill a VCL grid using a TDocVariantArrayDataSet
// as defined in SynVirtualDataSet.pas:
// ! ds1.DataSet := ToDataSet(self,FindDocs('{name:?,age:{$gt:?}}',['John',21],null));
// - Projection can be null (to retrieve all fields) or a CSV string to set
// field names to retrieve, or a TDocVariant or TBSONVariant with
// projection operators
function FindDocs(Criteria: PUTF8Char; const Params: array of const;
const Projection: variant; NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]): TVariantDynArray; overload;
/// select documents in a collection and returns a JSON array of documents
// containing the selected documents
// - Criteria can be null (to retrieve all documents) or a TDocVariant /
// TBSONVariant query selector:
// ! FindJSON(BSONVariant('{name:"John",age:{$gt:21}}'),null);
// ! FindJSON(BSONVariant('{name:?,age:{$gt:?}}',[],['John',21]),null);
// see http://docs.mongodb.org/manual/reference/operator for reference
// - Projection can be null (to retrieve all fields) or a CSV string to set
// the field names to retrieve, or a TDocVariant or TBSONVariant - e.g.:
// ! FindJSON(BSONVariant(['name','John']),null);
// ! FindJSON(BSONVariant(['name','John']),'_id');
// ! FindJSON(BSONVariant(['name','John']),BSONVariantFieldSelector('name,_id'));
// - NumberToReturn can be left to its default maxInt value to return all
// matching documents as a '[..]' JSON array, or specify a limit (e.g. 1
// for one document - in this case, the returned instance won't be a '[..]'
// JSON array, but either 'null' or a single '{..}' JSON object)
// - this method is very optimized and will convert the BSON binary content
// directly into JSON, in either modMongoStrict or modMongoShell layout
// (modNoMongo will do the same as modMongoStrict)
function FindJSON(const Criteria, Projection: Variant;
NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]; Mode: TMongoJSONMode=modMongoStrict): RawUTF8; overload;
/// select documents in a collection and returns a JSON array of documents
// containing the selected documents
// - Criteria can specify the query selector as (extended) JSON and
// parameters:
// ! FindJSON('{name:"John",age:{$gt:21}}',[]);
// ! FindJSON('{name:?,age:{$gt:?}}',['John',21]);
// see http://docs.mongodb.org/manual/reference/operator for reference
// - this overloaded method will use a null Projection, i.e. will retrieve
// all fields
// - NumberToReturn can be left to its default maxInt value to return all
// matching documents as a '[..]' JSON array, or specify a limit (e.g. 1
// for one document - in this case, the returned instance won't be a '[..]'
// JSON array, but either 'null' or a single '{..}' JSON object)
function FindJSON(Criteria: PUTF8Char; const Params: array of const;
NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]; Mode: TMongoJSONMode=modMongoStrict): RawUTF8; overload;
/// select documents in a collection and returns a JSON array of documents
// containing the selected documents
// - Criteria and Projection can specify the query selector as (extended)
// JSON and parameters
function FindJSON(Criteria: PUTF8Char; const CriteriaParams: array of const;
const Projection: variant; NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]; Mode: TMongoJSONMode=modMongoStrict): RawUTF8; overload;
/// select documents in a collection and returns a TBSONDocument instance
// containing the selected documents as a raw binary BSON array document
// - Criteria can be null (to retrieve all documents) or a TDocVariant /
// TBSONVariant query selector:
// ! FindBSON(BSONVariant('{name:"John",age:{$gt:21}}'),null);
// ! FindBSON(BSONVariant('{name:?,age:{$gt:?}}',[],['John',21]),null);
// - Projection can be null (to retrieve all fields) or a CSV string to set
// the field names to retrieve, or a TDocVariant or TBSONVariant - e.g.:
// ! FindBSON(BSONVariant(['name','John']),null);
// ! FindBSON(BSONVariant(['name','John']),'_id');
// ! FindBSON(BSONVariant(['name','John']),BSONVariantFieldSelector('name,_id'));
// - NumberToReturn can be left to its default maxInt value to return all
// matching documents, or specify a limit (e.g. 1 for one document)
function FindBSON(const Criteria, Projection: Variant;
NumberToReturn: integer=maxInt; NumberToSkip: Integer=0;
Flags: TMongoQueryFlags=[]): TBSONDocument;
/// insert one document, supplied as (extended) JSON and parameters,
// in the collection
// - supplied JSON could be either strict or in MongoDB Shell syntax:
// ! products.insert('{ _id: ?, item: ?, qty: ? }',[1,'card',15]);
// ! // here _id is forced on the client side
// ! products.insert('{ item: ?, qty: ? }',[1,'card',15]);
// ! // here the _id will be created on the client side as an ObjectID
// - you can retrieve the client-side computed ObjectID, as such:
// ! var oid: TBSONObjectID;
// ! ...
// ! products.insert('{ item: ?, qty: ? }',['card',15],@oid);
// ! writeln(oid.ToText);
procedure Insert(const Document: RawUTF8; const Params: array of const;
CreatedObjectID: PBSONObjectID=nil); overload;
/// insert one or more documents in the collection
// - Documents is an array of TDocVariant (i.e. created via _JsonFast()
// or _JsonFastFmt()) - or of TBSONVariant (created via BSONVariant())
// - by default, it will follow Client.WriteConcern pattern - but you can
// set NoAcknowledge = TRUE to avoid calling the getLastError command and
// increase the execution speed, at the expense of a unsafe process
procedure Insert(const Documents: array of variant; Flags: TMongoInsertFlags=[];
NoAcknowledge: boolean=false); overload;
/// insert one or more documents in the collection
// - Documents is the low-level concatenation of BSON documents, created
// e.g. with a TBSONWriter stream
// - by default, it will follow Client.WriteConcern pattern - but you can
// set NoAcknowledge = TRUE to avoid calling the getLastError command and
// increase the execution speed, at the expense of a unsafe process
procedure Insert(const Documents: TBSONDocument;
Flags: TMongoInsertFlags=[]; NoAcknowledge: boolean=false); overload;
/// insert one or more documents in the collection
// - JSONDocuments is an array of JSON objects
// - by default, it will follow Client.WriteConcern pattern - but you can
// set NoAcknowledge = TRUE to avoid calling the getLastError command and
// increase the execution speed, at the expense of a unsafe process
procedure InsertJSON(const JSONDocuments: array of PUTF8Char;
Flags: TMongoInsertFlags=[]; NoAcknowledge: boolean=false);
/// updates an existing document or inserts a new document, depending on
// its document parameter
// - this document should be a TDocVariant (i.e. created via _JsonFast()
// or _JsonFastFmt()) since we need to check for the _id field, other types
// will be converted to a TDocVariant instance (via its JSON representation)
// so it is pointless to use BSONVariant() here
// - if the document does not contain an _id field, then the Save() method
// performs an insert; during the operation, the client will add to the
// Document variant the _id field and assign it a unique ObjectId - you can
// optionally retrieve it with the CreatedObjectID pointer - and the method
// returns FALSE
// - if the document contains an _id field, then the save() method performs
// an upsert, querying the collection on the _id field: if a document does
// not exist with the specified _id value, the save() method performs an
// insert; if a document exists with the specified _id value, the save()
// method performs an update that replaces ALL fields in the existing
// document with the fields from the document - and the method returns TRUE
function Save(var Document: variant; CreatedObjectID: PBSONObjectID=nil): boolean; overload;
/// updates an existing document or inserts a new document, depending on
// its document parameter, supplied as (extended) JSON and parameters
// - supplied JSON could be either strict or in MongoDB Shell syntax:
// - will perform either an insert or an update, depending of the
// presence of the _id field, as overloaded Save(const Document: variant)
procedure Save(const Document: RawUTF8; const Params: array of const;
CreatedObjectID: PBSONObjectID=nil); overload;
/// modifies an existing document or several documents in a collection
// - the method can modify specific fields of existing document or documents
// or replace an existing document entirely, depending on the update parameter
// - Query and Update parameters should be TDocVariant (i.e. created via
// _JsonFast() or _JsonFastFmt()) or TBSONVariant (created via BSONVariant())
// - Query is the selection criteria for the update; use the same query
// selectors as used in the Find() method
// - if Update contains a plain document, it will replace any existing data
// - if Update contains update operators (like $set), it will update the
// corresponding fields in the document
procedure Update(const Query, Update: variant; Flags: TMongoUpdateFlags=[]); overload;
/// modifies an existing document or several documents in a collection
// - the method can modify specific fields of existing document or documents
// or replace an existing document entirely, depending on the update parameter
// - since all content will be transformed into JSON internally, use this
// method only if the supplied parameters are simple types: any complex value
// (e.g. a TDateTime or a BSONVariant binary) won't be handled as expected -
// use the overloaded Update() with explicit BSONVariant() values instead
// - Query and Update parameters can be specified as JSON objects with
// parameters
// - Query is the selection criteria for the update; use the same query
// selectors as used in the Find() method
// - if Update contains a plain document, it will replace any existing data:
// ! people.update('{name:?}',['Andy'],'{name:?,age:? }',['Andy',25],[mufUpsert]);
// Warning: to avoid inserting the same document more than once, only use
// mufUpsert if the query field is uniquely indexed
// - if Update contains update operators (like $set), it will update the
// corresponding fields in the document:
// ! book.insert('{_id:?,item:?,stock:?}',[11,'Divine Comedy',2]);
// ! book.update('{item:?},['Divine Comedy'],'{$set:{price:?},$inc:{stock:?}},[18,5]);
// ! // the updated document is now:
// ! { "_id" : 11, "item" : "Divine Comedy", "price" : 18, "stock" : 7 }
procedure Update(Query: PUTF8Char; const QueryParams: array of const;
const Update: RawUTF8; const UpdateParams: array of const;
Flags: TMongoUpdateFlags=[]); overload;
/// modifies some fields of an existing document in a collection
// - by default, Update() or Save() will replace the whole document
// - this method will expect the identifier to be supplied as a variant -
// may be via the ObjectID() function
// - and will replace the specified fields, i.e. it will execute a $set:
// with the supplied UpdatedFields value
procedure UpdateOne(const _id, UpdatedFields: variant);
/// delete an existing document or several documents in a collection
// - Query parameter should be TDocVariant (i.e. created via _JsonFast() or
// _JsonFastFmt()) or TBSONVariant (created via BSONVariant())
// - Query is the selection criteria for the deletion; use the same query
// selectors as used in the Find() method
// - to limit the deletion to just one document, set Flags to [mdfSingleRemove]
// - to delete all documents matching the deletion criteria, leave it to []
procedure Remove(const Query: variant; Flags: TMongoDeleteFlags=[]); overload;
/// delete an existing document in a collection, by its _id field
// - _id will identify the unique document to be deleted
procedure RemoveOne(const _id: TBSONObjectID); overload;
/// delete an existing document in a collection, by its _id field
// - _id will identify the unique document to be deleted
procedure RemoveOne(const _id: variant); overload;
/// delete an existing document or several documents in a collection
// - Query parameter can be specified as JSON objects with parameters
// - Query is the selection criteria for the deletion; use the same query
// selectors as used in the Find() method
// - to limit the deletion to just one document, set Flags to [mdfSingleRemove]
// - to delete all documents matching the deletion criteria, leave it to []
procedure RemoveFmt(Query: PUTF8Char; const QueryParams: array of const;
Flags: TMongoDeleteFlags=[]);
/// creates an index on the specified field(s) if the index does
// not already exist
// - Keys and Options parameters should be TDocVariant (e.g. created via
// _JsonFast() or _JsonFastFmt()) - and not TBSONVariant values
// - for ascending/descending indexes, Keys is a document that contains pairs
// with the name of the field or fields to index and order of the index:
// value of 1 specifies ascending and of -1 specifies descending
// - options is a non-mandatory document that controls the creation
// of the index -
// - you can write e.g.
// ! book.EnsureIndex(_JsonFast('{ orderDate: 1 }'),null)
// ! book.EnsureIndex(_ObjFast(['orderDate',1]),null)
procedure EnsureIndex(const Keys, Options: variant); overload;
/// creates an index on the specified field(s) if the index does
// not already exist
// - Keys are the correspondiong field names
// - you can write e.g. to create an ascending index on a given field:
// ! book.EnsureIndex(['orderDate']);
procedure EnsureIndex(const Keys: array of RawUTF8; Ascending: boolean=true;
Unique: boolean=false); overload;
/// drops the entire collection from the database
// - once dropped, this TMongoCollection instance will be freed: never
// use this instance again after success (i.e. returned '')
// - in case of error, a textual message will be returned as result
// - once dropped, this collection will be removed from the parent
// Database.Collection[] internal list
// - Warning: this method obtains a write lock on the affected database
// and will block other operations until it has completed
function Drop: RawUTF8;
/// calculate the number of documents in the collection
// - be aware that this method may be somewhat slow for huge collections,
// since a full scan of an index is to be performed: if your purpose is
// to ensure that a collection contains items, use rather IsEmpty method
function Count: Int64;
/// calculate the number of documents in the collection that match
// a specific query
// - Criteria can specify the query selector as a BSONVariant/TDocVariant
function FindCount(const Query: variant): Int64; overload;
/// calculate the number of documents in the collection that match
// a specific query
// - Criteria can specify the query selector as (extended) JSON and
// parameters:
// ! FindCount('{name:?,age:{$gt:?}}',[],['John',21]);
// ! FindCount('{ ord_dt: { $gt: new Date(?) } }',[],[trunc(Now)-7]);
// - optional MaxNumberToReturn can specify a limit for the search (e.g. if
// you do not want an exact count, but only check for a specific limit)
// - optional NumberToSkip can specify the number of matching documents
// to skip before counting
function FindCount(Criteria: PUTF8Char; const Args,Params: array of const;
MaxNumberToReturn: integer=0; NumberToSkip: Integer=0): Int64; overload;
/// returns TRUE if the collection has no document, FALSE otherwise
// - is much faster than Count, especially for huge collections
function IsEmpty: boolean;
/// calculate aggregate values using the MongoDB aggregation framework
// and return the result as a TDocVariant instance
// - the Aggregation Framework was designed to be more efficient than the
// alternative map-reduce pattern, and is available since MongoDB 2.2 -
// see http://docs.mongodb.org/manual/reference/command/aggregate
// - you should specify the aggregation pipeline as a list of JSON object
// operators (without the [..]) - for reference of all available phases,
// see http://docs.mongodb.org/manual/core/aggregation-pipeline
// - if the server sent back no {result:...} member, will return null
// - if the server sent back one item as {result:[{..}]}, will return
// this single item as a TDocVariant
// - if the server sent back several items as {result:[{..},{..}]}, will
// return a dvArray kind of TDocVariant
function AggregateDoc(Operators: PUTF8Char; const Params: array of const): variant; overload;
/// calculate JSON aggregate values using the MongoDB aggregation framework
// - the Aggregation Framework was designed to be more efficient than the
// alternative map-reduce pattern, and is available since MongoDB 2.2 -
// see http://docs.mongodb.org/manual/reference/command/aggregate
// - you should specify the aggregation pipeline as a list of JSON object
// operators (without the [..]) - for reference of all available phases,
// see http://docs.mongodb.org/manual/core/aggregation-pipeline
// - for instance, the following will return as JSON a collection sorted in
// descending order according by the age field and then in ascending order
// according to the value in the posts field
// ! AggregateJSON('{ $sort : { age : -1, posts: 1 } }',[])
function AggregateJSON(Operators: PUTF8Char; const Params: array of const;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8; overload;
/// calculate aggregate values using the MongoDB aggregation framework
// and return the result as a TDocVariant instance
// - overloaded method to specify the pipeline as a BSON raw document
// as detailed by http://docs.mongodb.org/manual/core/aggregation-pipeline
function AggregateDocFromVariant(const pipelineArray: variant): variant;
/// calculate JSON aggregate values using the MongoDB aggregation framework
// - overloaded method to specify the pipeline as a BSON raw document
// as detailed by http://docs.mongodb.org/manual/core/aggregation-pipeline
function AggregateJSONFromVariant(const pipelineArray: variant;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8; overload;
/// calculate aggregate values using the MongoDB aggregation framework
// and return the result as a TDocVariant instance
// - overloaded method to specify the pipeline as a JSON text object
// as detailed by http://docs.mongodb.org/manual/core/aggregation-pipeline
// - for instance, the following will return the maximum _id value of
// the collection:
// ! AggregateDoc('{$group:{_id:null,max:{$max:"$_id"}}}').max
function AggregateDocFromJson(const PipelineJSON: RawUTF8): variant;
/// calculate JSON aggregate values using the MongoDB aggregation framework
// - overloaded method to specify the pipeline as a JSON text object
// as detailed by http://docs.mongodb.org/manual/core/aggregation-pipeline
function AggregateJSONFromJson(const PipelineJSON: RawUTF8;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8; overload;
published
/// the collection name
property Name: RawUTF8 read fName;
/// the full collection name, e.g. 'dbname.collectionname'
property FullCollectionName: RawUTF8 read fFullCollectionName;
/// the associated MongoDB database instance
property Database: TMongoDatabase read fDatabase;
end;
/// exception type used for MongoDB process, once connected
EMongoConnectionException = class(EMongoException)
protected
fConnection: TMongoConnection;
public
/// initialize the Exception for a given request
constructor Create(const aMsg: string; aConnection: TMongoConnection); reintroduce; overload;
/// initialize the Exception for a given request
constructor CreateUTF8(const Format: RawUTF8; const Args: array of const;
aConnection: TMongoConnection); reintroduce;
published
/// the associated connection
property Connection: TMongoConnection read fConnection;
end;
EMongoDatabaseException = class(EMongoConnectionException)
protected
fDatabase: TMongoDatabase;
public
/// initialize the Exception for a given request
constructor Create(const aMsg: string; aDatabase: TMongoDatabase); reintroduce; overload;
/// initialize the Exception for a given request
constructor CreateUTF8(const Format: RawUTF8; const Args: array of const;
aDatabase: TMongoDatabase); reintroduce;
{$ifndef NOEXCEPTIONINTERCEPT}
/// used to customize the exception log to contain information about the Query
// - it will log the database parameters
function CustomLog(WR: TTextWriter; const Context: TSynLogExceptionContext): boolean; override;
{$endif}
published
/// the associated Database
property Database: TMongoDatabase read fDatabase;
end;
/// exception type used for MongoDB query process
EMongoRequestException = class(EMongoConnectionException)
protected
fRequest: TMongoRequest;
fError: TMongoReplyCursor;
fErrorDoc: variant;
function GetErrorDoc: variant;
public
/// initialize the Exception for a given request
constructor Create(const aMsg: string; aConnection: TMongoConnection;
aRequest: TMongoRequest=nil); reintroduce; overload;
/// initialize the Exception for a given request
constructor CreateUTF8(const Format: RawUTF8; const Args: array of const;
aConnection: TMongoConnection; aRequest: TMongoRequest); reintroduce;
/// initialize the Exception for a given request
constructor Create(const aMsg: string; aConnection: TMongoConnection;
aRequest: TMongoRequest; const aError: TMongoReplyCursor); reintroduce; overload;
/// initialize the Exception for a given request
constructor Create(const aMsg: string; aConnection: TMongoConnection;
aRequest: TMongoRequest; const aErrorDoc: TDocVariantData); reintroduce; overload;
{$ifndef NOEXCEPTIONINTERCEPT}
/// used to customize the exception log to contain information about the Query
// - it will log both the failing request and the returned error message
function CustomLog(WR: TTextWriter; const Context: TSynLogExceptionContext): boolean; override;
{$endif}
/// the associated error reply document
property ErrorReply: TMongoReplyCursor read fError;
published
/// the associated error reply document, as a TDocVariant instance
// - will return the first document available in ErrorReply, or the supplied
// aErrorDoc: TDocVariantData instance
property ErrorDoc: Variant read GetErrorDoc;
end;
/// exception type used for MongoDB query process after an Operating System
// error (e.g. in case of socket error)
EMongoRequestOSException = class(EMongoRequestException)
protected
fSystemLastError: cardinal;
public
/// initialize the Exception for a given request, including the last
// error message retrieved from the operating system
// - if such an exception is raised, you can use SystemLastError property
// to retrieve the corresponding Operating System error code
constructor Create(const aMsg: string; aConnection: TMongoConnection;
aRequest: TMongoRequest=nil); reintroduce;
/// contain the associated Operating System last error code
// - will specify e.g. the kind of communication/socket error
property SystemLastError: cardinal read fSystemLastError;
end;
{$M-}
/// ready-to-be displayed text of a TMongoOperation item
function ToText(op: TMongoOperation): PShortString; overload;
/// ready-to-be displayed text of a TMongoClientWriteConcern item
function ToText(wc: TMongoClientWriteConcern): PShortString; overload;
/// ready-to-be displayed text of a TMongoClientReplicaSetReadPreference item
function ToText(pref: TMongoClientReplicaSetReadPreference): PShortString; overload;
implementation
// used by TBSONElement.ToVariant() method and BSONToDoc() procedure
procedure BSONItemsToDocVariant(Kind: TBSONElementType; BSON: PByte;
var Doc: TDocVariantData; Option: TBSONDocArrayConversion);
const OPTIONS: array[TBSONDocArrayConversion] of TDocVariantOptions =
([],[dvoReturnNullForUnknownProperty],
[dvoReturnNullForUnknownProperty,dvoValueCopiedByReference],
[dvoReturnNullForUnknownProperty,dvoInternNames],
[dvoReturnNullForUnknownProperty,dvoValueCopiedByReference,dvoInternNames]);
var k: TDocVariantKind;
i,n,cap: integer;
intnames: TRawUTF8Interning;
items: array[0..63] of TBSONElement;
begin // very fast optimized code
if BSON=nil then
TVarData(Doc).VType := varNull else begin
intnames := nil;
case Kind of
betDoc: begin
k := dvObject;
if dvoInternNames in Doc.Options then
intnames := DocVariantType.InternNames;
end;
betArray:
k := dvArray;
else exit; // leave Doc=varEmpty
end;
Doc.Init(OPTIONS[Option],k);
cap := 0;
repeat // will handle up to 64 TBSONElement per loop (via items[])
n := 0;
while items[n].FromNext(BSON) do begin
inc(n);
if n=length(items) then
break; // avoid buffer overflow
end;
if n=0 then
break;
inc(cap,n); // pre-allocate Doc.Names[]/Values[]
if cap<512 then
Doc.Capacity := cap else
if Doc.Capacity<cap then
Doc.Capacity := cap+cap shr 3; // faster for huge arrays
for i := 0 to n-1 do begin
if Kind=betDoc then
if intnames<>nil then
intnames.Unique(Doc.Names[i+Doc.Count],items[i].Name,items[i].NameLen) else
SetString(Doc.Names[i+Doc.Count],PAnsiChar(items[i].Name),items[i].NameLen);
items[i].ToVariant(Doc.Values[i+Doc.Count],Option);
end;
Doc.SetCount(Doc.Count+n);
until (BSON=nil) or (BSON^=byte(betEOF));
end;
end;
{ TBSONElement }
var
/// size (in bytes) of a BSON element
// - equals -1 for varying elements
BSON_ELEMENTSIZE: array[TBSONElementType] of integer = (
//betEOF, betFloat, betString, betDoc, betArray, betBinary,
0, sizeof(Double), -1, -1, -1, -1,
//betDeprecatedUndefined, betObjectID, betBoolean, betDateTime,
0, sizeof(TBSONObjectID), 1, sizeof(Int64),
//betNull, betRegEx, betDeprecatedDbptr, betJS, betDeprecatedSymbol,
0, -1, -1, -1, -1,
//betJSScope, betInt32, betTimestamp, betInt64, betDecimal128
-1, sizeof(Integer), sizeof(Int64), SizeOf(Int64), Sizeof(TDecimal128));
/// types which do not have an exact equivalency to a standard variant
// type will be mapped as varUnknown - and will be changed into
// BSONVariantType.VarType
BSON_ELEMENTTYPES: array[TBSONElementType] of word = (
//betEOF, betFloat, betString, betDoc, betArray, betBinary,
varEmpty, varDouble, varString, varUnknown, varUnknown, varUnknown,
//betDeprecatedUndefined, betObjectID, betBoolean, betDateTime,
varEmpty, varUnknown, varBoolean, varDate,
//betNull, betRegEx, betDeprecatedDbptr, betJS, betDeprecatedSymbol,
varNull, varUnknown, varUnknown, varUnknown, varUnknown,
//betJSScope, betInt32, betTimestamp, betInt64, betDecimal128
varUnknown, varInteger, varUnknown, varInt64, varUnknown);
function TBSONElement.ToVariant(DocArrayConversion: TBSONDocArrayConversion): variant;
begin
ToVariant(Result,DocArrayConversion);
end;
procedure TBSONElement.ToVariant(var result: variant;
DocArrayConversion: TBSONDocArrayConversion);
var res: TVarData absolute result;
resBSON: TBSONVariantData absolute result;
begin
if res.VType and VTYPE_STATIC<>0 then
VarClear(result);
ZeroFill(@result); // set result.VType=varEmpty and result.VAny=nil
case Kind of
betFloat:
res.VDouble := PDouble(Element)^;
betString:
SetString(RawUTF8(res.VAny),Data.Text,Data.TextLen);
betJS, betDeprecatedSymbol:
SetString(RawUTF8(resBSON.VText),Data.Text,Data.TextLen);
betDoc, betArray:
if DocArrayConversion=asBSONVariant then
SetString(TBSONDocument(resBSON.VBlob),PAnsiChar(Element),ElementBytes) else begin
BSONItemsToDocVariant(Kind,Data.DocList,TDocVariantData(result),DocArrayConversion);
exit;
end;
betBinary, betRegEx, betDeprecatedDbptr, betJSScope, betTimestamp, betDecimal128:
SetString(RawByteString(resBSON.VBlob),PAnsiChar(Element),ElementBytes);
betObjectID:
resBSON.VObjectID := PBSONObjectID(Element)^;
betBoolean:
res.VBoolean := PBoolean(Element)^;
betDateTime:
res.VDate := UnixMSTimeToDateTime(PUnixMSTime(Element)^);
betInt32:
res.VInteger := PInteger(Element)^;
betInt64:
res.VInt64 := PInt64(Element)^;
// betNull, betDeprecatedUndefined, betMinKey or betMaxKey has no data
end;
res.VType := BSON_ELEMENTTYPES[Kind];
if res.VType=varUnknown then begin
resBSON.VType := BSONVariantType.VarType;
resBSON.VKind := Kind;
end;
end;
function TBSONElement.ToInteger(const default: Int64=0): Int64;
begin
case Kind of
betBoolean:
result := PByte(Element)^;
betFloat:
result := Trunc(PDouble(Element)^);
betInt32:
result := PInteger(Element)^;
betInt64:
result := PInt64(Element)^;
else
result := default;
end;
end;
function TBSONElement.ToRawUTF8: RawUTF8;
procedure ComplexType;
var V: variant;
wasString: boolean;
begin
ToVariant(V);
VariantToUTF8(V,result,wasString);
end;
begin
case Kind of
betFloat:
ExtendedToStr(PDouble(Element)^,DOUBLE_PRECISION,result);
betString:
SetString(result,Data.Text,Data.TextLen);
betInt32:
Int32ToUtf8(PInteger(Element)^,result);
betInt64:
Int64ToUtf8(PInt64(Element)^,result);
betDecimal128:
PDecimal128(Element)^.ToText(result);
else ComplexType;
end;
end;
function TBSONElement.DocItemToVariant(const aName: RawUTF8; var aValue: variant;
DocArrayConversion: TBSONDocArrayConversion): boolean;
var item: TBSONElement;
begin
if (Kind in [betDoc,betArray]) and item.FromSearch(Data.DocList,aName) then begin
item.ToVariant(aValue,DocArrayConversion);
result := true;
end else
result := false;
end;
function TBSONElement.DocItemToRawUTF8(const aName: RawUTF8): RawUTF8;
var item: TBSONElement;
begin
if (Kind in [betDoc,betArray]) and item.FromSearch(Data.DocList,aName) then
result := item.ToRawUTF8 else
result := '';
end;
function TBSONElement.DocItemToInteger(const aName: RawUTF8; const default: Int64): Int64;
var item: TBSONElement;
begin
if (Kind in [betDoc,betArray]) and item.FromSearch(Data.DocList,aName) then
result := item.ToInteger(default) else
result := default;
end;
procedure TBSONElement.AddMongoJSON(W: TTextWriter; Mode: TMongoJSONMode);
label bin,regex;
begin
case Kind of
betFloat:
W.AddDouble(PDouble(Element)^);
betString, betJS, betDeprecatedSymbol: begin
W.Add('"');
W.AddJSONEscape(Data.Text,Data.TextLen);
W.Add('"');
end;
betDoc, betArray:
BSONListToJSON(Data.DocList,Kind,W,Mode);
betObjectID: begin
W.AddShort(BSON_JSON_OBJECTID[false,Mode]);
W.AddBinToHex(Element,SizeOf(TBSONObjectID));
W.AddShort(BSON_JSON_OBJECTID[true,Mode]);
end;
betDeprecatedUndefined:
W.AddShort(BSON_JSON_UNDEFINED[Mode=modMongoShell]);
betBinary:
case Mode of
modNoMongo:
W.WrBase64(Data.Blob,Data.BlobLen,true);
modMongoStrict: begin
W.AddShort(BSON_JSON_BINARY[false,false]);
W.WrBase64(Data.Blob,Data.BlobLen,false);
W.AddShort(BSON_JSON_BINARY[false,true]);
W.AddBinToHex(@Data.BlobSubType,1);
W.AddShort('"}');
end;
modMongoShell: begin
W.AddShort(BSON_JSON_BINARY[true,false]);
W.AddBinToHex(@Data.BlobSubType,1);
W.AddShort(BSON_JSON_BINARY[true,true]);
W.WrBase64(Data.Blob,Data.BlobLen,false);
W.AddShort('")');
end;
end;
betRegEx:
case Mode of
modNoMongo:
bin:W.WrBase64(Element,ElementBytes,true);
modMongoStrict:
goto regex;
modMongoShell:
if (PosChar(Data.RegEx,'/')=nil) and
(PosChar(Data.RegExOptions,'/')=nil) then begin
W.Add('/');
W.AddNoJSONEscape(Data.RegEx,Data.RegExLen);
W.Add('/');
W.AddNoJSONEscape(Data.RegExOptions,Data.RegExOptionsLen);
end else begin
regex: W.AddShort(BSON_JSON_REGEX[0]);
W.AddJSONEscape(Data.RegEx,Data.RegExLen);
W.AddShort(BSON_JSON_REGEX[1]);
W.AddJSONEscape(Data.RegExOptions,Data.RegExOptionsLen);
W.AddShort(BSON_JSON_REGEX[2]);
end;
end;
betDeprecatedDbptr:
goto bin; // no specific JSON construct for this deprecated item
betJSScope:
goto bin; // no specific JSON construct for this item yet
betTimestamp:
goto bin; // internal content will always be written as raw binary
betBoolean:
W.Add(PBoolean(Element)^);
betDateTime: begin
W.AddShort(BSON_JSON_DATE[Mode,false]);
W.AddUnixMSTime(Element,false);
W.AddShort(BSON_JSON_DATE[Mode,true]);
end;
betNull:
W.AddShort('null');
betInt32:
W.Add(PInteger(Element)^);
betInt64:
W.Add(PInt64(Element)^);
betDecimal128: begin
W.AddShort(BSON_JSON_DECIMAL[false,Mode]);
PDecimal128(Element)^.AddText(W);
W.AddShort(BSON_JSON_DECIMAL[true,Mode]);
end;
else
if Kind=betMinKey then
W.AddShort(BSON_JSON_MINKEY[Mode=modMongoShell]) else
if Kind=betMaxKey then
W.AddShort(BSON_JSON_MAXKEY[Mode=modMongoShell]) else
raise EBSONException.CreateUTF8('TBSONElement.AddMongoJSON: unexpected type %',
[ord(Kind)]);
end;
end;
procedure TBSONElement.FromVariant(const aName: RawUTF8; const aValue: Variant;
var aTemp: RawByteString);
const ELEMKIND: array[varEmpty..varWord64] of TBSONElementType = (
betEOF, betNull, betInt32, betInt32, betFloat, betFloat, betFloat, betDateTime,
betString, betEOF, betEOF, betBoolean, betEof, betEOF, betEOF, betEOF,
betInt32, betInt32, betInt32, betInt64, betInt64, betInt64);
var aVarData: TVarData absolute aValue;
aBson: TBSONVariantData absolute aValue;
aDoc: TDocVariantData absolute aValue;
label str, st2;
begin
if aVarData.VType=varByRef or varVariant then begin
FromVariant(aName,PVariant(aVarData.VPointer)^,aTemp);
exit;
end;
FillCharFast(self,sizeof(self),0);
Name := pointer(aName);
NameLen := length(aName);
case aVarData.VType of
0..varDate,varBoolean..high(ELEMKIND): begin // simple types
Element := @Data.InternalStorage;
Kind := ELEMKIND[aVarData.VType];
case Kind of
betFloat:
PDouble(Element)^ := double(aValue);
betDateTime:
PUnixMSTime(Element)^ := DateTimeToUnixMSTime(aVarData.VDate);
betBoolean:
PBoolean(Element)^ := aVarData.VBoolean;
betInt32:
if not VariantToInteger(aValue,PInteger(Element)^) then
raise EBSONException.Create('TBSONElement.FromVariant(betInt32)');
betInt64:
if not VariantToInt64(aValue,PInt64(Element)^) then
raise EBSONException.Create('TBSONElement.FromVariant(betInt64)');
end;
ElementBytes := BSON_ELEMENTSIZE[Kind];
end;
varString:
if (aVarData.VAny<>nil) and
(PInteger(aVarData.VAny)^ and $ffffff=JSON_SQLDATE_MAGIC) and
Iso8601CheckAndDecode(PUTF8Char(aVarData.VAny)+3,Length(RawUTF8(aVarData.VAny))-3,
PDateTime(@Data.InternalStorage)^) then begin
// recognized TTextWriter.AddDateTime(woDateTimeWithMagic) ISO-8601 format
Element := @Data.InternalStorage;
Kind := betDateTime;
ElementBytes := BSON_ELEMENTSIZE[betDateTime];
end else begin
Kind := betString;
Data.Text := aVarData.VAny;
Data.TextLen := Length(RawUTF8(aVarData.VAny));
st2: ElementBytes := Data.TextLen+1;
if aVarData.VAny=nil then
Data.InternalStorage := 1 else
Element := nil; // special case handled by TBSONWriter.BSONWrite()
end;
{$ifdef HASVARUSTRING}
varUString: begin
RawUnicodeToUtf8(aVarData.VAny,length(UnicodeString(aVarData.VAny)),RawUTF8(aTemp));
goto str;
end;
{$endif}
varOleStr: begin
RawUnicodeToUtf8(aVarData.VAny,length(WideString(aVarData.VAny)),RawUTF8(aTemp));
str:Kind := betString;
Data.Text := pointer(aTemp);
Data.TextLen := Length(aTemp);
goto st2;
end;
else
if aVarData.VType=BSONVariantType.VarType then begin
Kind := aBson.VKind;
case Kind of
betObjectID: FromBSON(@aBson.VObjectID); // stored inlined
else FromBSON(aBson.VBlob); // complex type stored as a RawByteString
end;
if ElementBytes<0 then
raise EBSONException.CreateUTF8('TBSONElement.FromVariant(bson,%)',[ToText(Kind)^]);
end else
if aVarData.VType=DocVariantType.VarType then begin
with TBSONWriter.Create(TRawByteStringStream) do // inlined BSON()
try
BSONWriteDoc(aDoc);
ToBSONDocument(aTemp);
finally
Free;
end;
if dvoIsObject in aDoc.Options then
Kind := betDoc else
if dvoIsArray in aDoc.Options then
Kind := betArray else
raise EBSONException.CreateUTF8('TBSONElement.FromVariant(doc,%)',[ToText(aDoc.Kind)^]);
FromBSON(pointer(aTemp));
if ElementBytes<0 then
raise EBSONException.CreateUTF8('TBSONElement.FromVariant(docbson,%)',[ToText(Kind)^]);
end else
raise EBSONException.CreateUTF8('TBSONElement.FromVariant(VType=%)',[aVarData.VType]);
end;
end;
function TBSONElement.FromDocument(const doc: TBSONDocument): boolean;
var n: Integer;
begin
FillCharFast(self,sizeof(self),0);
n := length(doc);
if (n>=4) and (PInteger(doc)^=n) then begin
Kind := betDoc;
FromBSON(pointer(doc));
result := true;
end else
result := false;
end;
const
NULCHAR: AnsiChar = #0;
procedure TBSONElement.FromBSON(bson: PByte);
begin // see http://bsonspec.org/#/specification
Element := bson;
case Kind of // handle variable-size storage
betString, betJS, betDeprecatedSymbol: begin // "\x02" e_name string
ElementBytes := PInteger(bson)^+sizeof(integer); // int32 (byte*) "\x00"
Data.TextLen := PInteger(bson)^-1;
inc(bson,sizeof(integer));
Data.Text := pointer(bson);
end;
betDoc, betArray: begin // "\x03" e_name document
ElementBytes := PInteger(bson)^;
inc(bson,sizeof(integer)); // points to a "e_list #0"
Data.DocList := bson;
end;
betBinary: begin // "\x05" e_name int32 subtype (byte*)
ElementBytes := PInteger(bson)^+(sizeof(integer)+1);
Data.BlobLen := PInteger(bson)^;
inc(bson,sizeof(integer));
Data.BlobSubType := TBSONElementBinaryType(bson^);
inc(bson);
Data.Blob := bson;
end;
betRegEx: begin // "\x0B" e_name cstring cstring
Data.RegEx := Element;
Data.RegExLen := StrLen(Data.RegEx);
Data.RegExOptions := Data.RegEx+Data.RegExLen+1;
Data.RegExOptionsLen := StrLen(Data.RegExOptions);
ElementBytes := Data.RegExLen+Data.RegExOptionsLen+2;
end;
betJSScope: begin // "\x0F" e_name int32 string document
ElementBytes := PInteger(bson)^;
inc(bson,sizeof(integer));
Data.JavaScriptLen := PInteger(bson)^-1;
inc(bson,sizeof(integer));
Data.JavaScript := pointer(bson);
inc(bson,Data.JavaScriptLen+1);
Data.ScopeDocument := bson;
end;
else
if Kind>high(BSON_ELEMENTSIZE) then // e.g. betMinKey betMaxKey
ElementBytes := 0 else
ElementBytes := BSON_ELEMENTSIZE[Kind]; // fixed size storage
end;
end;
function TBSONElement.FromNext(var BSON: PByte): boolean;
begin
if BSON=nil then begin
result := false;
exit;
end;
Kind := TBSONElementType(BSON^);
case ord(Kind) of
ord(betEOF):
result := false;
ord(betFloat)..ord(betDecimal128),ord(betMinKey),ord(betMaxKey): begin
inc(BSON);
Name := PUTF8Char(BSON);
NameLen := StrLen(PUTF8Char(BSON));
inc(BSON,NameLen+1);
FromBSON(BSON);
if ElementBytes<0 then
raise EBSONException.CreateUTF8(
'TBSONElement.FromNext: unexpected size % for type %',[ElementBytes,ord(Kind)]);
inc(BSON,ElementBytes);
inc(Index);
result := true;
end;
else raise EBSONException.CreateUTF8('TBSONElement.FromNext: unexpected type %',
[ord(Kind)]);
end;
end;
function TBSONElement.FromSearch(BSON: PByte; const aName: RawUTF8): boolean;
begin
result := true;
while FromNext(BSON) do
if IdemPropNameU(aName,Name,NameLen) then
exit;
result := false;
end;
{ TBSONIterator }
function TBSONIterator.Init(const doc: TBSONDocument; kind: TBSONElementType): boolean;
var n: integer;
begin
FillCharFast(self,sizeof(self),0);
n := length(doc);
if (kind in [betDoc,betArray]) and (n>=4) and (PInteger(doc)^=n) then begin
Item.Kind := kind;
Item.FromBSON(pointer(doc));
fBson := Item.Data.DocList;
result := true;
end else
result := false;
end;
function TBSONIterator.Next: boolean;
begin
result := Item.FromNext(fBson);
end;
function BSONParseLength(var BSON: PByte; ExpectedBSONLen: integer=0): integer;
begin
if (BSON=nil) or
((ExpectedBSONLen<>0) and (PInteger(BSON)^<>ExpectedBSONLen)) then
raise EBSONException.Create('Incorrect supplied BSON document content');
result := PInteger(BSON)^;
inc(PInteger(BSON));
end;
function BSONParseNextElement(var BSON: PByte; var name: RawUTF8; var element: variant;
DocArrayConversion: TBSONDocArrayConversion=asBSONVariant): boolean;
var item: TBSONElement;
begin
result := item.FromNext(BSON);
if result then begin
SetString(name,PAnsiChar(item.Name),item.NameLen);
item.ToVariant(element,DocArrayConversion);
end;
end;
function BSONPerIndexElement(BSON: PByte; index: integer; var item: TBSONElement): boolean;
begin
result := true;
if (index>=0) and (BSON<>nil) and (BSONParseLength(BSON)<>0) then
while item.FromNext(BSON) do
if index=0 then
exit else
dec(index);
result := false;
end;
procedure BSONToDoc(BSON: PByte; var Result: Variant; ExpectedBSONLen: Integer;
Option: TBSONDocArrayConversion);
begin
if Option=asBSONVariant then
raise EBSONException.Create('BSONToDoc(option=asBSONVariant) is not allowed');
if TVarData(result).VType and VTYPE_STATIC<>0 then
VarClear(result);
BSONParseLength(BSON,ExpectedBSONLen);
BSONItemsToDocVariant(betDoc,BSON,TDocVariantData(Result),Option);
end;
function BSONDocumentToDoc(const BSON: TBSONDocument; Option: TBSONDocArrayConversion): variant;
begin
BSONToDoc(pointer(BSON),result,length(BSON));
end;
procedure BSONListToJSON(BSONList: PByte; Kind: TBSONElementType;
W: TTextWriter; Mode: TMongoJSONMode);
var item: TBSONElement;
begin
case Kind of
betDoc:
if BSONList^=byte(betEOF) then
W.Add('{','}') else begin
W.Add('{');
while item.FromNext(BSONList) do begin
if Mode=modMongoShell then begin
W.AddNoJSONEscape(item.Name,item.NameLen);
W.Add(':');
end else
W.AddFieldName(item.Name,item.NameLen);
item.AddMongoJSON(W,Mode);
W.Add(',');
end;
W.CancelLastComma;
W.Add('}');
end;
betArray: begin
W.Add('[');
while item.FromNext(BSONList) do begin
item.AddMongoJSON(W,Mode);
W.Add(',');
end;
W.CancelLastComma;
W.Add(']');
end;
else raise EBSONException.CreateUTF8('BSONListToJSON(Kind=%)',[ord(Kind)]);
end;
end;
function BSONDocumentToJSON(const BSON: TBSONDocument;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8;
begin
result := BSONToJSON(pointer(BSON),betDoc,length(BSON),Mode);
end;
function BSONToJSON(BSON: PByte; Kind: TBSONElementType; ExpectedBSONLen: integer;
Mode: TMongoJSONMode): RawUTF8;
var W: TTextWriter;
begin
BSONParseLength(BSON,ExpectedBSONLen);
W := TTextWriter.CreateOwnedStream;
try
BSONListToJSON(BSON,Kind,W,Mode);
W.SetText(result);
finally
W.Free;
end;
end;
procedure AddMongoJSON(const Value: variant; W: TTextWriter; Mode: TMongoJSONMode);
procedure AddCustom;
var item: TBSONElement;
temp: RawByteString;
begin
item.FromVariant('',Value,temp);
item.AddMongoJSON(W,Mode);
end;
begin
if TVarData(Value).VType<$10F then
W.AddVariant(Value,twJSONEscape) else
AddCustom;
end;
function VariantSaveMongoJSON(const Value: variant; Mode: TMongoJSONMode): RawUTF8;
var W: TTextWriter;
begin
W := TTextWriter.CreateOwnedStream;
try
AddMongoJSON(Value,W,Mode);
W.SetText(result);
finally
W.Free;
end;
end;
{ TBSONWriter }
procedure TBSONWriter.CancelAll;
begin
inherited;
fDocumentCount := 0;
end;
procedure TBSONWriter.WriteCollectionName(Flags: integer; const CollectionName: RawUTF8);
begin
Write4(Flags);
if CollectionName='' then
raise EBSONException.Create('Missing collection name');
Write(pointer(CollectionName),length(CollectionName)+1); // +1 for #0
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; elemtype: TBSONElementType);
begin
Write1(ord(elemtype));
if name='' then
write1(0) else // write only #0
{$ifdef HASINLINE}
Write(pointer(name),length(name)+1); // +1 for #0
{$else}
Write(pointer(name),PInteger(PtrInt(name)-sizeof(integer))^+1); // +1 for #0
{$endif}
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: integer);
begin
BSONWrite(name,betInt32);
Write4(value);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: Double);
begin
BSONWrite(name,betFloat);
Write8(value);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: boolean);
begin
BSONWrite(name,betBoolean);
Write1(ord(value));
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: Int64);
begin
if (value>=low(integer)) and (value<=high(integer)) then begin
BSONWrite(name,betInt32);
Write4(value);
end else begin
BSONWrite(name,betInt64);
Write8(value);
end;
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: TBSONObjectID);
begin
BSONWrite(name,betObjectID);
Write(@value,sizeof(value));
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: TDecimal128);
begin
BSONWrite(name,betDecimal128);
Write(@value,sizeof(value));
end;
procedure TBSONWriter.BSONWriteRegEx(const name: RawUTF8;
const RegEx,Options: RawByteString);
begin
BSONWrite(name,betRegEx); // cstring cstring
Write(pointer(RegEx),length(RegEx));
Write1(0);
Write(pointer(Options),length(Options));
Write1(0);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: RawUTF8;
isJavaScript: boolean=false);
const TYP: array[boolean] of TBSONElementType = (betString,betJS);
var L: integer;
begin
BSONWrite(name,TYP[isJavaScript]);
L := length(value)+1; // +1 for ending #0
Write4(L);
if L=1 then
Write1(0) else
Write(pointer(value),L);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; value: PUTF8Char);
var L: integer;
begin
BSONWrite(name,betString);
L := StrLen(Value)+1;
Write4(L);
if L=1 then
Write1(0) else
Write(value,L);
end;
procedure TBSONWriter.BSONWriteString(const name: RawUTF8; value: PUTF8Char; valueLen: integer);
begin
BSONWrite(name,betString);
inc(valueLen);
Write4(valueLen);
if valueLen=1 then
Write1(0) else
Write(value,valueLen);
end;
procedure TBSONWriter.BSONWriteDateTime(const name: RawUTF8; const value: TDateTime);
var UnixTime: TUnixMSTime;
begin
UnixTime := DateTimeToUnixMSTime(value);
BSONWrite(name,betDateTime);
Write8(UnixTime);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; Data: pointer; DataLen: integer);
begin
BSONWrite(name,betBinary);
Write4(DataLen);
Write1(ord(bbtGeneric));
Write(Data,DataLen);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const elem: TBSONElement);
begin
BSONWrite(name,elem.Kind);
if (elem.Element=nil) and // handle special case of TBSONElement.FromVariant()
(elem.Kind in [betString,betJS,betDeprecatedSymbol]) then begin
Write4(elem.Data.TextLen+1); // int32 (byte*) "\x00"
Write(elem.Data.Text,elem.Data.TextLen+1);
end else
Write(elem.Element,elem.ElementBytes);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const bson: TBSONVariantData);
begin
case bson.VKind of
betObjectID:
BSONWrite(name,bson.VObjectID);
else begin
BSONWrite(name,bson.VKind);
WriteBinary(RawByteString(bson.VBlob));
end;
end;
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const doc: TDocVariantData);
begin
if dvoIsObject in doc.Options then
BSONWrite(name,betDoc) else
if dvoIsArray in doc.Options then
BSONWrite(name,betArray) else
raise EBSONException.Create('Undefined nested document');
BSONWriteDoc(doc);
end;
procedure TBSONWriter.BSONWriteArray(const kind: TBSONElementType);
begin
BSONWrite(UInt32ToUtf8(fDocumentArray),kind);
inc(fDocumentArray);
if kind in [betDoc,betArray] then
BSONDocumentBegin;
end;
procedure TBSONWriter.BSONDocumentBegin;
begin
if fDocumentStack>=Length(fDocumentStackOffset) then
SetLength(fDocumentStackOffset,fDocumentStack+fDocumentStack shr 3+16);
fDocumentStackOffset[fDocumentStack] := TotalWritten;
inc(fDocumentStack);
Write4(0);
end;
procedure TBSONWriter.BSONDocumentBegin(const name: RawUTF8; kind: TBSONElementType);
begin
if not (kind in [betDoc,betArray]) then
raise EBSONException.Create('BSONDocumentBegin(?)');
BSONWrite(name,kind);
BSONDocumentBegin;
end;
procedure TBSONWriter.BSONDocumentBeginInArray(const name: RawUTF8; kind: TBSONElementType);
begin
if fDocumentArray>0 then
BSONDocumentEnd;
BSONWriteArray(kind);
BSONDocumentBegin(name);
end;
procedure TBSONWriter.BSONDocumentEnd(CloseNumber: integer; WriteEndingZero: boolean);
begin
while CloseNumber>0 do begin
if (CloseNumber>1) or WriteEndingZero then
Write1(0);
if fDocumentStack=0 then
raise EBSONException.CreateUTF8('Unexpected %.BSONDocumentEnd',[self]);
dec(fDocumentStack);
if fDocumentCount>=Length(fDocument) then
SetLength(fDocument,fDocumentCount+fDocumentCount shr 3+16);
with fDocument[fDocumentCount] do begin
Offset := fDocumentStackOffset[fDocumentStack];
Length := TotalWritten-Offset;
end;
inc(fDocumentCount);
dec(CloseNumber);
end;
end;
procedure TBSONWriter.BSONAdjustDocumentsSize(BSON: PByteArray);
var i: Integer;
begin
for i := 0 to fDocumentCount-1 do
with fDocument[i] do
PCardinal(@BSON[Offset])^ := Length;
end;
procedure TBSONWriter.ToBSONDocument(var result: TBSONDocument);
begin
Flush;
result := (Stream as TRawByteStringStream).DataString;
BSONAdjustDocumentsSize(pointer(result));
end;
procedure TBSONWriter.ToBSONVariant(var result: variant; Kind: TBSONElementType);
var doc: TBSONDocument;
begin
ToBSONDocument(doc);
BSONVariantType.FromBSONDocument(doc,result,Kind);
end;
procedure TBSONWriter.BSONWrite(const name: RawUTF8; const value: TVarRec);
var tmp: RawUTF8;
begin
case value.VType of
vtBoolean: BSONWrite(name,value.VBoolean);
vtInteger: BSONWrite(name,value.VInteger);
vtCurrency: BSONWrite(name,value.VCurrency^);
vtExtended: BSONWrite(name,value.VExtended^);
vtVariant: BSONWriteVariant(name,value.VVariant^);
vtInt64{$ifdef FPC},vtQWord{$endif}:
BSONWrite(name,value.VInt64^);
vtString, vtAnsiString, {$ifdef HASVARUSTRING}vtUnicodeString,{$endif}
vtPChar, vtChar, vtWideChar, vtWideString: begin
VarRecToUTF8(value,tmp);
BSONWrite(name,tmp);
end;
else raise EBSONException.CreateUtf8(
'%.BSONWrite(TVarRec.VType=%)',[self,value.VType]);
end;
end;
procedure TBSONWriter.BSONWriteVariant(const name: RawUTF8; const value: variant);
procedure WriteComplex;
var temp: RawUTF8;
JSON: PUTF8Char;
begin
with TVarData(value) do
case VType of
{$ifdef HASVARUSTRING}
varUString: begin
RawUnicodeToUtf8(VAny,length(UnicodeString(VAny)),temp);
BSONWrite(Name,temp);
end;
{$endif}
varOleStr: begin
RawUnicodeToUtf8(VAny,length(WideString(VAny)),temp);
BSONWrite(Name,temp);
end;
else begin
VariantSaveJSON(value,twJSONEscape,temp);
JSON := pointer(temp);
BSONWriteFromJSON(name,JSON,nil);
if JSON=nil then
raise EBSONException.CreateUTF8('%.BSONWriteVariant(VType=%)',[self,VType]);
end;
end;
end;
var dt: TDateTime;
begin
with TVarData(value) do begin
case VType of
varEmpty,
varNull: BSONWrite(Name,betNull);
varSmallint: BSONWrite(Name,VSmallInt);
{$ifndef DELPHI5OROLDER}
varShortInt: BSONWrite(Name,VShortInt);
varWord: BSONWrite(Name,VWord);
varLongWord: BSONWrite(Name,VLongWord);
{$endif}
varByte: BSONWrite(Name,VByte);
varBoolean: BSONWrite(Name,VBoolean);
varInteger: BSONWrite(Name,VInteger);
varWord64,
varInt64: BSONWrite(Name,VInt64);
varSingle: BSONWrite(Name,VSingle);
varDouble: BSONWrite(Name,VDouble);
varDate: BSONWriteDateTime(Name,VDate);
varCurrency: BSONWrite(Name,VCurrency);
varString:
if (VAny<>nil) and (PInteger(VAny)^ and $ffffff=JSON_SQLDATE_MAGIC) and
Iso8601CheckAndDecode(PUTF8Char(VAny)+3,Length(RawUTF8(VAny))-3,dt) then
// recognized TTextWriter.AddDateTime(woDateTimeWithMagic) ISO-8601 format
BSONWriteDateTime(Name,dt) else
BSONWrite(Name,RawUTF8(VAny)); // expect UTF-8 content
else
if VType=varByRef or varVariant then
BSONWriteVariant(name,PVariant(VPointer)^) else
if VType=BSONVariantType.VarType then
BSONWrite(name,TBSONVariantData(value)) else
if VType=DocVariantType.VarType then
BSONWrite(name,TDocVariantData(value)) else
WriteComplex;
end;
end;
end;
procedure TBSONWriter.BSONWriteDoc(const doc: TDocVariantData);
var Name: RawUTF8;
i: integer;
begin
BSONDocumentBegin;
if TVarData(doc).VType>varNull then // null,empty will write {}
if TVarData(doc).VType<>DocVariantType.VarType then
raise EBSONException.CreateUTF8('%.BSONWriteDoc(VType=%)',
[self,TVarData(doc).VType]) else
for i := 0 to doc.Count-1 do begin
if doc.Names<>nil then
Name := doc.Names[i] else
UInt32ToUtf8(i,Name);
BSONWriteVariant(Name,doc.Values[i]);
if TotalWritten>BSON_MAXDOCUMENTSIZE then
raise EBSONException.CreateUTF8('%.BSONWriteDoc(size=%>max %)',
[self,TotalWritten,BSON_MAXDOCUMENTSIZE]);
end;
BSONDocumentEnd;
end;
procedure TBSONWriter.BSONWriteProjection(const FieldNamesCSV: RawUTF8);
var FieldNames: TRawUTF8DynArray;
i: integer;
begin
CSVToRawUTF8DynArray(pointer(FieldNamesCSV),FieldNames);
BSONDocumentBegin;
for i := 0 to high(FieldNames) do
BSONWrite(FieldNames[i],1);
BSONDocumentEnd;
end;
function TBSONWriter.BSONWriteQueryOperator(name: RawUTF8; inverted: boolean;
operator: TSynTableStatementOperator; const Value: variant): boolean;
const
QUERY_OPS: array[opNotEqualTo..opIn] of RawUTF8 = (
'$ne','$lt','$lte','$gt','$gte','$in');
INVERT_OPS: array[opEqualTo..opGreaterThanOrEqualTo] of TSynTableStatementOperator = (
opNotEqualTo,opEqualTo, opGreaterThanOrEqualTo,opGreaterThan,
opLessThanOrEqualTo,opLessThan);
var wasString: boolean;
like: RawUTF8;
len: integer;
doInvert: boolean;
begin
result := false; // error on premature exit
case Operator of
// http://docs.mongodb.org/manual/faq/developers/#faq-developers-query-for-nulls
// {$type:10} would return only existing fields, but our ODM do not insert
// blobs by default -> do not use {$type:10} trick but plain {field:null}
opIsNull:
operator := opEqualTo; // here Value=null
opIsNotNull:
operator := opNotEqualTo; // here Value=null
end;
doInvert := false;
if inverted then
if operator<=high(INVERT_OPS) then
operator := INVERT_OPS[operator] else begin
doInvert := true;
BSONDocumentBegin(name);
name := '$not';
end;
case Operator of
opEqualTo:
BSONWriteVariant(name,Value);
opNotEqualTo..opIn: begin
BSONDocumentBegin(name);
BSONWriteVariant(QUERY_OPS[operator],Value);
BSONDocumentEnd;
end;
opLike: begin
VariantToUTF8(Value,like,wasString);
len := length(like);
if (len=0) or not wasString then
exit;
if like[1]='%' then
if len=1 then // LIKE '%' is invalid
exit else
if like[len]='%' then
if len=2 then
exit else // LIKE '%%' is invalid
like := copy(like,2,len-2) else // LIKE '%a%' -> /a/
like := copy(like,2,len-1)+'$' else // LIKE '%a' -> /a$/
if like[len]='%' then
like := '^'+copy(like,1,len-1) else // LIKE 'a%' -> /^a/
like := '^'+like+'$'; // LIKE 'a' -> /^a$/
BSONWriteRegEx(name,like,'i'); // /like/i for case-insensitivity
end;
opContains: begin // http://docs.mongodb.org/manual/reference/operator/query/in
BSONDocumentBegin(name);
if _Safe(Value)^.Kind=dvArray then
BSONWriteVariant(QUERY_OPS[opIn],Value) else begin
BSONWrite(QUERY_OPS[opIn],betArray);
BSONWriteArray([Value]);
end;
BSONDocumentEnd;
end;
else
exit; // unhandled operator
end;
if doInvert then
BSONDocumentEnd;
result := true;
end;
procedure TBSONWriter.BSONWriteObject(const NameValuePairs: array of const);
var Name: RawUTF8;
i: integer;
begin
BSONDocumentBegin;
for i := 0 to (length(NameValuePairs)shr 1)-1 do begin
VarRecToUTF8(NameValuePairs[i*2],Name);
BSONWrite(Name,NameValuePairs[i*2+1]);
end;
BSONDocumentEnd;
end;
procedure TBSONWriter.BSONWriteArray(const Items: array of const);
var i: integer;
begin
BSONDocumentBegin;
for i := 0 to high(Items) do
BSONWrite(UInt32ToUtf8(i),Items[i]);
BSONDocumentEnd;
end;
procedure TBSONWriter.BSONWriteArrayOfInteger(const Integers: array of integer);
var i: integer;
begin
BSONDocumentBegin;
for i := 0 to high(Integers) do
BSONWrite(UInt32ToUtf8(i),Integers[i]);
BSONDocumentEnd;
end;
procedure TBSONWriter.BSONWriteArrayOfInt64(const Integers: array of Int64);
var i: integer;
begin
BSONDocumentBegin;
for i := 0 to high(Integers) do
BSONWrite(UInt32ToUtf8(i),Integers[i]);
BSONDocumentEnd;
end;
procedure TBSONWriter.BSONWriteFromJSON(const name: RawUTF8; var JSON: PUTF8Char;
EndOfObject: PUTF8Char; DoNotTryExtendedMongoSyntax: boolean);
var tmp: variant;
blob: RawByteString;
wasString: boolean;
Value: PUTF8Char;
ValueLen: integer;
VDouble: double;
ValueDateTime: TDateTime absolute VDouble;
VInt64: Int64 absolute VDouble;
Kind: TBSONElementType;
label dbl;
begin
if JSON^ in [#1..' '] then repeat inc(JSON) until not(JSON^ in [#1..' ']);
if not DoNotTryExtendedMongoSyntax and
BSONVariantType.TryJSONToVariant(JSON,tmp,EndOfObject) then
// was betDateTime, betObjectID or betRegEx, from strict or extended JSON
BSONWriteVariant(name,tmp) else
// try from simple types
case JSON^ of
#0: begin
JSON := nil;
exit;
end;
'[': begin // nested array
BSONWrite(name,betArray);
JSON := BSONWriteDocFromJSON(JSON,EndOfObject,Kind,DoNotTryExtendedMongoSyntax);
end;
'{': begin // nested document
BSONWrite(name,betDoc);
JSON := BSONWriteDocFromJSON(JSON,EndOfObject,Kind,DoNotTryExtendedMongoSyntax);
end;
else begin // simple types
Value := GetJSONField(JSON,JSON,@wasString,EndOfObject,@ValueLen);
if JSON=nil then
JSON := @NULCHAR;
if (Value=nil) or not wasString then
if GetVariantFromNotStringJSON(Value,TVarData(tmp),true) then begin
BSONWriteVariant(name,tmp); // null,boolean,Int64,double
exit;
end;
// found no simple value -> check text value
if Base64MagicCheckAndDecode(Value,ValueLen,blob) then
// recognized '\uFFF0base64encodedbinary' pattern
BSONWrite(name,pointer(blob),length(blob)) else
if Iso8601CheckAndDecode(Value,ValueLen,ValueDateTime) then
// recognized TTextWriter.AddDateTime() pattern
BSONWriteDateTime(name,ValueDateTime) else
if (PInteger(Value)^ and $ffffff=JSON_SQLDATE_MAGIC) and
Iso8601CheckAndDecode(Value+3,ValueLen-3,ValueDateTime) then
// recognized TTextWriter.AddDateTime(woDateTimeWithMagic) pattern
BSONWriteDateTime(name,ValueDateTime) else
// will point to the in-place escaped JSON text
BSONWriteString(name,Value,ValueLen);
end;
end;
if TotalWritten>BSON_MAXDOCUMENTSIZE then
raise EBSONException.CreateUTF8('%.BSONWriteDoc(size=% > max=%)',
[self,TotalWritten,BSON_MAXDOCUMENTSIZE]);
end;
function TBSONWriter.BSONWriteDocFromJSON(JSON: PUTF8Char; aEndOfObject: PUTF8Char;
out Kind: TBSONElementType; DoNotTryExtendedMongoSyntax: boolean): PUTF8Char;
var ndx: cardinal;
EndOfObject: AnsiChar;
Name: RawUTF8;
begin
result := nil;
if JSON=nil then
exit;
if JSON^ in [#1..' '] then repeat inc(JSON) until not(JSON^ in [#1..' ']);
case JSON^ of
'[': begin
Kind := betArray;
BSONDocumentBegin;
repeat inc(JSON) until not(JSON^ in [#1..' ']);
ndx := 0;
if JSON^=']' then
inc(JSON) else
repeat
UInt32ToUtf8(ndx,Name);
BSONWriteFromJSON(Name,JSON,@EndOfObject,DoNotTryExtendedMongoSyntax);
if JSON=nil then
exit; // invalid content
inc(ndx);
until EndOfObject=']';
end;
'{': begin
Kind := betDoc;
BSONDocumentBegin;
repeat inc(JSON) until not(JSON^ in [#1..' ']);
if JSON^='}' then
inc(JSON) else
repeat
// see http://docs.mongodb.org/manual/reference/mongodb-extended-json
Name := GetJSONPropName(JSON); // BSON/JSON accepts "" as key name
BSONWriteFromJSON(Name,JSON,@EndOfObject,DoNotTryExtendedMongoSyntax);
if (JSON=nil) or (EndOfObject=#0) then
exit; // invalid content
until EndOfObject='}';
end;
'n','N':
if IdemPChar(JSON+1,'ULL') then begin // append null as {}
Kind := betDoc;
BSONDocumentBegin;
inc(JSON,4);
end else
exit;
else exit;
end;
BSONDocumentEnd;
if JSON^ in [#1..' '] then repeat inc(JSON) until not(JSON^ in [#1..' ']);
if aEndOfObject<>nil then
aEndOfObject^ := JSON^;
if JSON^<>#0 then
repeat inc(JSON) until not(JSON^ in [#1..' ']);
result := JSON; // indicates successfully parsed
end;
{ TBSONObjectID }
var
GlobalBSONObjectID: record
Section: TRTLCriticalSection;
Default: packed record
Counter: cardinal;
MachineID: TBSON24;
ProcessID: word;
end;
LastCreateTime: cardinal;
LastCounter: cardinal;
end;
procedure InitBSONObjectIDComputeNew;
begin
InitializeCriticalSection(GlobalBSONObjectID.Section);
with GlobalBSONObjectID.Default do begin
TAESPRNG.Main.FillRandom(@Counter,3);
with ExeVersion do
PCardinal(@MachineID)^ := crc32c(crc32c(0,pointer(Host),length(Host)),
pointer(User),length(User));
ProcessID := (ProcessID shl 8) xor TThreadID(MainThreadID);
end;
end;
procedure TBSONObjectID.ComputeNew;
var now, count: cardinal;
begin
with GlobalBSONObjectID do begin
EnterCriticalSection(Section);
now := UnixTimeUTC; // fast API call (no need of cache)
if now>LastCreateTime then begin
LastCreateTime := now;
count := Default.Counter; // reset
end else begin
count := LastCounter+1;
if count and $ffffff=Default.Counter then begin
count := Default.Counter; // collision -> cheat on timestamp
inc(LastCreateTime);
end;
end;
Counter.b1 := count shr 16; // stored as bigendian
Counter.b2 := count shr 8;
Counter.b3 := count;
LastCounter := count;
UnixCreateTime := bswap32(LastCreateTime);
MachineID := Default.MachineID;
ProcessID := Default.ProcessID;
LeaveCriticalSection(Section);
end;
end;
function TBSONObjectID.Equal(const Another: TBSONObjectID): boolean;
begin
result := (PIntegerArray(@Self)[2]=PIntegerArray(@Another)[2]) and
{$ifdef CPU64}
(PInt64(@Self)^=PInt64(@Another)^);
{$else}
(PIntegerArray(@Self)[1]=PIntegerArray(@Another)[1]) and
(PIntegerArray(@Self)[0]=PIntegerArray(@Another)[0]);
{$endif}
end;
function TBSONObjectID.CreateDateTime: TDateTime;
begin
result := UnixTimeToDateTime(bswap32(UnixCreateTime));
end;
function TBSONObjectID.ToText: RawUTF8;
begin
ToText(result);
end;
function TBSONObjectID.ToVariant: variant;
begin
if TVarData(result).VType and VTYPE_STATIC<>0 then
VarClear(result);
with TBSONVariantData(result) do begin
VType := BSONVariantType.VarType;
VKind := betObjectID;
VObjectID := self;
end;
end;
function TBSONObjectID.FromText(const Text: RawUTF8): boolean;
begin
if length(Text)=SizeOf(self)*2 then
result := SynCommons.HexToBin(Pointer(Text),@self,SizeOf(self)) else
result := false;
end;
function TBSONObjectID.FromText(Text: PUTF8Char): boolean;
begin
result := SynCommons.HexToBin(Pointer(Text),@self,SizeOf(self));
end;
function TBSONObjectID.FromVariant(const value: variant): boolean;
var txt: RawUTF8;
wasString: boolean;
bson: TBSONVariantData absolute value;
begin
if TVarData(value).VType=varByRef or varVariant then
result := FromVariant(PVariant(TVarData(value).VPointer)^) else
if (bson.VType=BSONVariantType.VarType) and (bson.VKind=betObjectID) then begin
self := bson.VObjectID;
result:= true;
end else begin
VariantToUTF8(value,txt,wasString);
result := wasString and FromText(txt);
end;
end;
procedure TBSONObjectID.ToText(var result: RawUTF8);
begin
SetString(result,nil,sizeof(self)*2);
SynCommons.BinToHex(@self,pointer(result),sizeof(self));
end;
{ TBSONVariant }
procedure TBSONVariant.ToJSON(W: TTextWriter; const Value: variant; Escape: TTextWriterKind);
var item: TBSONElement;
temp: RawByteString;
begin
item.FromVariant('',Value,temp);
item.AddMongoJSON(W,modMongoStrict);
end;
function TBSONVariant.GetNewDoc(const BSONDoc: TBSONDocument): variant;
begin
FromBSONDocument(BSONDoc,result);
end;
function TBSONVariant.IsOfKind(const V: variant;
Kind: TBSONElementType): boolean;
begin
with TBSONVariantData(V) do
if VType=varByRef or varVariant then
result := IsOfKind(PVariant(TVarData(V).VPointer)^,Kind) else
result := (self<>nil) and (VType=VarType) and (VKind=Kind);
end;
function TBSONVariant.ToBlob(const V: Variant; var Blob: RawByteString): boolean;
begin
with TVarData(V) do
if VType=varByRef or varVariant then begin
result := ToBlob(PVariant(VPointer)^,Blob);
exit;
end;
with TBSONVariantData(V) do begin
result := (VType=VarType) and (VKind=betBinary);
if result then
if (VBlob=nil) or
(PInteger(VBlob)^<>Length(RawByteString(VBlob))-(sizeof(integer)+1)) then
Blob := '' else
SetString(Blob,PAnsiChar(VBlob)+(sizeof(integer)+1),PInteger(VBlob)^);
end;
end;
procedure TBSONVariant.FromBinary(const Bin: RawByteString;
BinType: TBSONElementBinaryType; var result: variant);
var Len: integer;
begin // "\x05" e_name int32 subtype (byte*)
with TBSONVariantData(result) do begin
if VType and VTYPE_STATIC<>0 then
VarClear(result);
if Bin='' then begin
VType := varNull; // stores a NULL
exit;
end;
VType := VarType;
VKind := betBinary;
VBlob := nil; // avoid GPF here below
Len := length(Bin);
SetLength(RawByteString(VBlob),Len+(sizeof(integer)+1));
PInteger(VBlob)^ := Len;
PByteArray(VBlob)^[sizeof(integer)] := ord(BinType);
MoveFast(pointer(Bin)^,PByteArray(VBlob)^[sizeof(integer)+1],Len);
end;
end;
procedure TBSONVariant.FromBSONDocument(const BSONDoc: TBSONDocument;
var result: variant; Kind: TBSONElementType);
begin
with TBSONVariantData(result) do begin
if VType and VTYPE_STATIC<>0 then
VarClear(result);
VType := VarType;
VKind := Kind;
VBlob := nil; // avoid GPF here below
RawByteString(VBlob) := BSONDoc;
end;
end;
procedure TBSONVariant.FromJSON(json: PUTF8Char; var result: variant);
begin
if TVarData(result).VType and VTYPE_STATIC<>0 then
VarClear(result);
if json=nil then
exit;
if json^ in [#1..' '] then repeat inc(json) until not(json^ in [#1..' ']);
if json^ in ['{','['] then
with TBSONVariantData(result) do begin
VType := VarType;
VBlob := nil; // avoid GPF here below
VKind := JSONBufferToBSONDocument(json,TBSONDocument(VBlob));
end else
VariantLoadJSON(result,json);
end;
function TBSONVariant.TryJSONToVariant(var JSON: PUTF8Char;
var Value: variant; EndOfObject: PUTF8Char): boolean;
var bsonvalue: TBSONVariantData absolute Value;
varvalue: TVarData absolute Value;
// warning: code should NOT modify JSON buffer in-place, unless it returns true
procedure Return(kind: TBSONElementType; P: PUTF8Char; GotoEndOfObject: AnsiChar='}');
begin
if GotoEndOfObject<>#0 then
while P^<>GotoEndOfObject do
if P^=#0 then begin
if kind in [betRegEx,betDecimal128] then
RawByteString(bsonvalue.VBlob) := ''; // avoid memory leak
exit;
end else inc(P);
P := GotoNextNotSpace(P+1);
if EndOfObject<>nil then
EndOfObject^ := P^;
if P^<>#0 then
JSON := P+1 else
JSON := P;
case kind of
betObjectID, betRegEx, betDecimal128: begin // see TBSONWriter.BSONWrite()
bsonvalue.VType := VarType;
bsonvalue.VKind := kind;
end;
betDateTime:
varvalue.VType := varDate;
end;
result := true;
end;
procedure TryDate(P: PUTF8Char; GotoEndOfObject: AnsiChar);
var L: integer;
begin
P := GotoNextNotSpace(P);
if GotoEndOfObject=')' then
if (P^=')') then begin // new date() constructor
varvalue.VDate := NowUTC;
Return(betDateTime,P,#0);
exit;
end else
if P^ in ['0'..'9'] then begin
varvalue.VDate := GetNextItemDouble(P,')');
if (varvalue.VDate<>0) and (P<>nil) then begin
Return(betDateTime,P-1,#0);
exit;
end;
end;
if P^<>'"' then exit;
if PCardinal(P)^=JSON_SQLDATE_MAGIC_QUOTE then
inc(P,3); // ignore\uFFF1 code for DateTimeToSQL/TimeLogToSQL functions
L := 1; while P[L]<>'"' do if P[L]<=' ' then exit else inc(L);
Iso8601ToDateTimePUTF8CharVar(P+1,L,varvalue.VDate);
if varvalue.VDate<>0 then
Return(betDateTime,P+L+1,GotoEndOfObject);
end;
procedure TryObjectID(P: PUTF8Char; GotoEndOfObject: AnsiChar);
begin
P := GotoNextNotSpace(P);
if (GotoEndOfObject=')') and (P^=')') then begin // ObjectId() constructor
bsonvalue.VObjectID.ComputeNew;
Return(betObjectID,P,#0);
exit;
end;
if P^<>'"' then exit;
if bsonvalue.VObjectID.FromText(P+1) then
Return(betObjectID,P+25,GotoEndOfObject);
end;
procedure TryDecimal(P: PUTF8Char; GotoEndOfObject: AnsiChar);
var dec: TDecimal128;
L: integer;
begin
if P^<>'"' then exit;
inc(P);
L := 0;
while P[L]<>'"' do
if not(P[L] in ['0'..'9','e','E','+','-','.']) then exit else inc(L);
if dec.FromText(P,L)=dsvError then
exit;
bsonvalue.VBlob := nil; // avoid GPF
SetString(RawByteString(bsonvalue.VBlob),PAnsiChar(@dec),sizeof(TDecimal128));
Return(betDecimal128,P+L+1,GotoEndOfObject);
end;
var Reg,Opt: PUTF8Char;
RegLen,OptLen: Integer;
procedure ReturnRegEx(P: PUTF8Char; GotoEndOfObject: AnsiChar);
var buf: PAnsiChar;
begin
bsonvalue.VBlob := nil; // avoid GPF
SetString(RawByteString(bsonvalue.VBlob),nil,RegLen+OptLen+2);
buf := bsonvalue.VBlob;
MoveFast(Reg^,buf^,RegLen); inc(buf,RegLen); buf^ := #0; inc(buf);
MoveFast(Opt^,buf^,OptLen); inc(buf,OptLen); buf^ := #0;
Return(betRegEx,P,GotoEndOfObject);
end;
procedure TryRegExShell(P: PUTF8Char);
begin
RegLen := 0; while P[RegLen]<>'/' do if P[RegLen]<=' ' then exit else inc(RegLen);
Reg := P;
inc(P,RegLen);
if P^<>'/' then exit else inc(P);
OptLen := 0; while ord(P[OptLen]) in IsWord do inc(OptLen);
if P[OptLen]=#0 then exit;
Opt := P;
ReturnRegEx(Opt+OptLen-1,#0);
end;
procedure TryRegExStrict(P: PUTF8Char);
begin // warning: this won't escape double quotes...
P := GotoNextNotSpace(P);
if P^<>'"' then exit else inc(P);
RegLen := 0; while P[RegLen]<>'"' do if P[RegLen]<=' ' then exit else inc(RegLen);
Reg := P;
P := GotoNextNotSpace(Reg+RegLen+1);
if P^<>',' then Exit; // $regex:"acme*.corp",$options:"i"}
P := GotoNextNotSpace(P+1);
if P^='"' then inc(P);
if not CompareMem(P,@BSON_JSON_REGEX[1][4],8) then exit else inc(P,8);
if P^='"' then inc(P);
P := GotoNextNotSpace(P);
if P^<>':' then exit;
P := GotoNextNotSpace(P+1);
if P^<>'"' then exit else inc(P);
OptLen := 0; while P[OptLen]<>'"' do if P[OptLen]<=' ' then exit else inc(OptLen);
Opt := P;
ReturnRegEx(Opt+OptLen+1,'}');
end;
var P: PUTF8Char;
begin // here JSON does not start with " or 1..9 (obvious simple types)
// see http://docs.mongodb.org/manual/reference/mongodb-extended-json
result := false;
case NormToUpperAnsi7[JSON^] of
'{': begin // strict MongoDB objects e.g. {"$undefined":true} or {"$oid":".."}
P := JSON;
repeat inc(P) until not(P^ in [#1..' ']);
if P^<>'"' then exit;
repeat inc(P) until not(P^ in [#1..' ']);
if P[0]='$' then
case P[1] of
'u': if CompareMem(P+2,@BSON_JSON_UNDEFINED[false][5],10) then
Return(betDeprecatedUndefined,P+12);
'm': if CompareMem(P+2,@BSON_JSON_MINKEY[false][5],7) then
Return(betMinKey,P+9) else
if CompareMem(P+2,@BSON_JSON_MAXKEY[false][5],7) then
Return(betMaxKey,P+9);
'o': if CompareMem(P+2,@BSON_JSON_OBJECTID[false,modMongoStrict][5],4) then
TryObjectID(P+6,'}');
'd': if CompareMem(P+2,@BSON_JSON_DATE[modMongoStrict,false][5],5) then
TryDate(P+7,'}');
'r': if CompareMem(P+2,@BSON_JSON_REGEX[0][5],6) then
TryRegExStrict(P+8);
'n': if CompareMem(P+2,@BSON_JSON_DECIMAL[false,modMongoStrict][5],14) then
TryDecimal(P+16,'}');
end;
end;
// MongoDB Shell Mode extended syntax
'U': if StrCompIL(JSON+1,@BSON_JSON_UNDEFINED[true][2],8)=0 then
Return(betDeprecatedUndefined,JSON+8,#0);
'M': if StrCompIL(JSON+1,@BSON_JSON_MINKEY[true][2],5)=0 then
Return(betMinKey,JSON+5,#0) else
if StrCompIL(JSON+1,@BSON_JSON_MAXKEY[true][2],7)=0 then
Return(betMaxKey,JSON+5,#0);
'O': if StrCompIL(JSON+1,@BSON_JSON_OBJECTID[false,modMongoShell][2],8)=0 then
TryObjectID(JSON+9,')');
'N': if StrCompIL(JSON+1,'ew Date(',8)=0 then
TryDate(JSON+9,')') else
if StrCompIL(JSON+1,@BSON_JSON_DECIMAL[false,modMongoShell][2],13)=0 then
TryDecimal(JSON+14,')');
'I': if StrCompIL(JSON+1,@BSON_JSON_DATE[modMongoShell,false][2],7)=0 then
TryDate(JSON+8,')');
'/': TryRegExShell(JSON+1);
end;
end;
procedure TBSONVariant.Cast(var Dest: TVarData; const Source: TVarData);
begin
CastTo(Dest,Source,VarType);
end;
procedure TBSONVariant.CastTo(var Dest: TVarData;
const Source: TVarData; const AVarType: TVarType);
var tmp: RawUTF8;
wasString: boolean;
begin
if AVarType=VarType then begin
VariantToUTF8(Variant(Source),tmp,wasString);
if wasString then begin
if Dest.VType and VTYPE_STATIC<>0 then
VarClear(variant(Dest));
if TBSONVariantData(Dest).VObjectID.FromText(tmp) then begin
Dest.VType := VarType;
TBSONVariantData(Dest).VKind := betObjectID;
exit;
end;
variant(Dest) := BSONVariant(tmp); // convert from JSON text
exit;
end;
RaiseCastError;
end else begin
if Source.VType<>VarType then
RaiseCastError;
with TBSONVariantData(Source) do
if (VKind=betObjectID) and (AVarType in [varDate,varDouble]) then begin
Dest.VType := AVarType;
Dest.VDate := VObjectID.CreateDateTime;
exit;
end else begin
if VKind=betObjectID then
VObjectID.ToText(tmp) else
tmp := VariantSaveMongoJSON(variant(Source),modMongoShell);
RawUTF8ToVariant(tmp,Dest,AVarType); // convert to JSON text
end;
end;
end;
procedure TBSONVariant.Clear(var V: TVarData);
begin
if TBSONVariantData(V).VKind in BSON_ELEMENTVARIANTMANAGED then
RawByteString(TBSONVariantData(V).VBlob) := '';
ZeroFill(@V); // will set V.VType := varEmpty
end;
procedure TBSONVariant.Copy(var Dest: TVarData;
const Source: TVarData; const Indirect: Boolean);
begin
if Indirect then
SimplisticCopy(Dest,Source,true) else begin
if Dest.VType and VTYPE_STATIC<>0 then
VarClear(variant(Dest)); // Dest may be a complex type
Dest := Source;
with TBSONVariantData(Dest) do
if VKind in BSON_ELEMENTVARIANTMANAGED then begin
VBlob := nil; // avoid GPF
RawByteString(VBlob) := RawByteString(TBSONVariantData(Source).VBlob);
end;
end;
end;
procedure TBSONVariant.Compare(const Left, Right: TVarData;
var Relationship: TVarCompareResult);
var res: integer;
LeftU,RightU: RawUTF8;
begin
LeftU := VariantSaveMongoJSON(variant(Left),modMongoStrict);
RightU := VariantSaveMongoJSON(variant(Right),modMongoStrict);
if LeftU=RightU then
Relationship := crEqual else begin
res := StrComp(pointer(LeftU),pointer(RightU));
if res<0 then
Relationship := crLessThan else
if res>0 then
Relationship := crGreaterThan else
Relationship := crEqual;
end;
end;
{ main BSON* functions }
function ToText(kind: TBSONElementType): PShortString;
begin
result := GetEnumName(TypeInfo(TBSONElementType),ord(kind));
end;
function ToText(spec: TDecimal128SpecialValue): PShortString;
begin
result := GetEnumName(TypeInfo(TDecimal128SpecialValue),ord(spec));
end;
function ToText(op: TMongoOperation): PShortString;
begin
result := GetEnumName(TypeInfo(TMongoOperation),ord(op));
end;
function ToText(wc: TMongoClientWriteConcern): PShortString;
begin
result := GetEnumName(TypeInfo(TMongoClientWriteConcern),ord(wc));
end;
function ToText(pref: TMongoClientReplicaSetReadPreference): PShortString;
begin
result := GetEnumName(TypeInfo(TMongoClientReplicaSetReadPreference),ord(pref));
end;
function ObjectID: variant;
var ID: TBSONObjectID;
begin
ID.ComputeNew;
result := ID.ToVariant;
end;
function ObjectID(const Hexa: RaWUTF8): variant;
var ID: TBSONObjectID;
begin
if ID.FromText(Hexa) then
result := ID.ToVariant else
raise EBSONException.CreateUTF8('Invalid ObjectID("%")',[Hexa]);
end;
function BSONObjectID(const aObjectID: variant): TBSONObjectID;
begin
if not result.FromVariant(aObjectID) then
raise EBSONException.Create('BSONObjectID() over not ObjectID variant');
end;
function JavaScript(const JS: RawUTF8): variant;
begin
with TBSONVariantData(result) do begin
if VType and VTYPE_STATIC<>0 then
VarClear(result);
VType := BSONVariantType.VarType;
VKind := betJS;
VText := nil; // avoid GPF
RawUTF8(VText) := JS;
end;
end;
function JavaScript(const JS: RawUTF8; const Scope: TBSONDocument): variant;
var Len, JSLen: integer;
begin
with TBSONVariantData(result) do begin
if VType and VTYPE_STATIC<>0 then
VarClear(result);
VType := BSONVariantType.VarType;
VKind := betJSScope;
JSLen := Length(JS)+1; // string = int32 text#0
Len := SizeOf(integer)*2+JSLen+length(Scope); // int32 string document
VBlob := nil; // avoid GPF
SetLength(RawByteString(VBlob),Len);
PIntegerArray(VBlob)^[0] := Len; // length:int32
PIntegerArray(VBlob)^[1] := JSLen; // string:int32
MoveFast(pointer(JS)^,PAnsiChar(VBlob)[8],JSLen); // string:text#0
MoveFast(pointer(Scope)^,PAnsiChar(VBlob)[8+JSLen],Length(Scope)); // document
end;
end;
function NumberDecimal(const Value: RawUTF8): variant;
var dec: TDecimal128;
begin
if dec.FromText(Value)=dsvError then
raise EBSONException.CreateUTF8('Invalid NumberDecimal("%")',[Value]);
dec.ToVariant(result);
end;
function NumberDecimal(const Value: currency): variant;
var dec: TDecimal128;
begin
dec.FromCurr(Value);
dec.ToVariant(result);
end;
function BSON(const doc: TDocVariantData): TBSONDocument;
begin
if TVarData(doc).VType=varVariant or varByRef then begin
result := BSON(PDocVariantData(TVarData(doc).VPointer)^);
exit;
end;
if TVarData(doc).VType<>DocVariantType.VarType then
raise EBSONException.Create('doc is not a TDocVariant');
with TBSONWriter.Create(TRawByteStringStream) do
try
BSONWriteDoc(doc);
ToBSONDocument(result);
finally
Free;
end;
end;
function BSONFromIntegers(const Integers: array of integer): TBSONDocument;
begin
with TBSONWriter.Create(TRawByteStringStream) do
try
BSONWriteArrayOfInteger(Integers);
ToBSONDocument(result);
finally
Free;
end;
end;
function BSONFromInt64s(const Integers: array of Int64): TBSONDocument;
begin
with TBSONWriter.Create(TRawByteStringStream) do
try
BSONWriteArrayOfInt64(Integers);
ToBSONDocument(result);
finally
Free;
end;
end;
function BSON(const NameValuePairs: array of const): TBSONDocument;
var W: TBSONWriter;
name: RawUTF8;
a: Integer;
procedure WriteValue;
var ndx: cardinal;
begin
case VarRecAsChar(NameValuePairs[a]) of
ord('['): begin
W.BSONDocumentBegin(name,betArray);
ndx := 0;
repeat
inc(a);
if VarRecAsChar(NameValuePairs[a])=ord(']') then
break;
UInt32ToUtf8(ndx,name);
WriteValue;
inc(ndx);
until a=high(NameValuePairs);
W.BSONDocumentEnd;
end;
ord('{'): begin
W.BSONDocumentBegin(name,betDoc);
repeat
inc(a);
VarRecToUTF8(NameValuePairs[a],name);
if (a=high(NameValuePairs)) or (name='}') then
break;
inc(a);
WriteValue;
until a=high(NameValuePairs);
W.BSONDocumentEnd;
end else
W.BSONWrite(name,NameValuePairs[a]);
end;
end;
begin
W := TBSONWriter.Create(TRawByteStringStream);
try
W.BSONDocumentBegin;
a := 0;
while a<high(NameValuePairs) do begin
VarRecToUTF8(NameValuePairs[a],name);
inc(a);
WriteValue;
inc(a);
end;
W.BSONDocumentEnd;
W.ToBSONDocument(result);
finally
W.Free;
end;
end;
function BSONFieldSelector(const FieldNames: array of RawUTF8): TBSONDocument;
var i: integer;
W: TBSONWriter;
begin
W := TBSONWriter.Create(TRawByteStringStream,512);
try
W.BSONDocumentBegin;
for i := 0 to high(FieldNames) do
W.BSONWrite(FieldNames[i],1);
W.BSONDocumentEnd;
W.ToBSONDocument(result);
finally
W.Free;
end;
end;
function BSONFieldSelector(const FieldNamesCSV: RawUTF8): TBSONDocument;
var FieldNames: TRawUTF8DynArray;
begin
CSVToRawUTF8DynArray(pointer(FieldNamesCSV),FieldNames);
result := BSONFieldSelector(FieldNames);
end;
function JSONBufferToBSONDocument(JSON: PUTF8Char; var doc: TBSONDocument;
DoNotTryExtendedMongoSyntax: boolean): TBSONElementType;
var W: TBSONWriter;
begin
W := TBSONWriter.Create(TRawByteStringStream);
try
W.BSONWriteDocFromJSON(JSON,nil,result,DoNotTryExtendedMongoSyntax);
W.ToBSONDocument(doc);
finally
W.Free;
end;
end;
function JSONBufferToBSONArray(JSON: PUTF8Char; out docs: TBSONDocumentDynArray;
DoNotTryExtendedMongoSyntax: boolean): boolean;
var W: TBSONWriter;
doc: TBSONDocument;
EndOfObject: AnsiChar;
Kind: TBSONElementType;
n: integer;
begin
result := false;
if JSON=nil then
exit;
JSON := GotoNextNotSpace(JSON);
if JSON^<>'[' then
exit;
JSON := GotoNextNotSpace(JSON+1);
n := 0;
W := TBSONWriter.Create(TRawByteStringStream,16384);
try
repeat
JSON := W.BSONWriteDocFromJSON(JSON,@EndOfObject,Kind,DoNotTryExtendedMongoSyntax);
if JSON=nil then
exit;
W.ToBSONDocument(doc);
if n>=length(docs) then
SetLength(docs,n+64+length(docs) shr 3);
docs[n] := doc;
inc(n);
W.CancelAll;
until EndOfObject=']';
finally
W.Free;
end;
SetLength(docs,n);
result := true;
end;
function BSON(const Format: RawUTF8; const Args,Params: array of const;
kind: PBSONElementType): TBSONDocument;
var JSON: RawUTF8; // since we use FormatUTF8(), TSynTempBuffer is useless here
v: variant;
k: TBSONElementType;
begin
if (Format='?') and (high(Params)>=0) then begin
VarRecToVariant(Params[0],v);
if DocVariantType.IsOfType(v) then begin
result := BSON(TDocVariantData(v));
if kind<>nil then
if TDocVariantData(v).Kind=dvArray then
kind^ := betArray else
kind^ := betDoc;
exit;
end;
end;
JSON := FormatUTF8(Format,Args,Params,true);
UniqueRawUTF8(JSON); // ensure Format is untouched if Args=[]
k := JSONBufferToBSONDocument(pointer(JSON),result);
if kind<>nil then
kind^ := k;
end;
function BSON(const JSON: RawUTF8; kind: PBSONElementType): TBSONDocument;
var tmp: TSynTempBuffer;
k: TBSONElementType;
begin
tmp.Init(JSON);
try
k := JSONBufferToBSONDocument(tmp.buf,result);
if kind<>nil then
kind^ := k;
finally
tmp.Done;
end;
end;
function BSONVariant(const NameValuePairs: array of const): variant;
begin
BSONVariantType.FromBSONDocument(BSON(NameValuePairs),result,betDoc);
end;
function BSONVariant(const JSON: RawUTF8): variant;
var k: TBSONElementType;
b: RawByteString;
begin
b := BSON(JSON,@k);
BSONVariantType.FromBSONDocument(b,result,k);
end;
procedure BSONVariant(JSON: PUTF8Char; var result: variant);
var tmp: TBSONDocument;
begin
JSONBufferToBSONDocument(JSON,tmp);
BSONVariantType.FromBSONDocument(tmp,result);
end;
function BSONVariant(const Format: RawUTF8; const Args,Params: array of const): variant; overload;
var k: TBSONElementType;
b: RawByteString;
begin
b := BSON(Format,Args,Params,@k);
BSONVariantType.FromBSONDocument(b,result,k);
end;
function BSONVariant(doc: TDocVariantData): variant; overload;
var k: TBSONElementType;
begin
if doc.Kind=dvArray then
k := betArray else
k := betDoc;
BSONVariantType.FromBSONDocument(BSON(Doc),result,k);
end;
function BSONVariantFieldSelector(const FieldNames: array of RawUTF8): variant;
begin
BSONVariantType.FromBSONDocument(BSONFieldSelector(FieldNames),result);
end;
function BSONVariantFieldSelector(const FieldNamesCSV: RawUTF8): variant;
begin
BSONVariantType.FromBSONDocument(BSONFieldSelector(FieldNamesCSV),result);
end;
function BSONVariantFromIntegers(const Integers: array of integer): variant;
begin
BSONVariantType.FromBSONDocument(BSONFromIntegers(Integers),result,betArray);
end;
function BSONVariantFromInt64s(const Integers: array of Int64): variant;
begin
BSONVariantType.FromBSONDocument(BSONFromInt64s(Integers),result,betArray);
end;
{ ************ MongoDB client }
{ TMongoRequest }
const
WIRE_OPCODES: array[TMongoOperation] of integer = (
1, 1000, 2001, 2002, 2004, 2005, 2006, 2007);
CLIENT_OPCODES = [opUpdate,opInsert,opQuery,opGetMore,opDelete,opKillCursors];
var
GlobalRequestID: Integer;
constructor TMongoRequest.Create(const FullCollectionName: RawUTF8;
opCode: TMongoOperation; requestID, responseTo: Integer);
begin
if not (opCode in CLIENT_OPCODES) then
raise EMongoException.CreateUTF8('Unexpected %.Create(opCode=%)',[self,ToText(opCode)^]);
inherited Create(TRawByteStringStream);
fFullCollectionName := FullCollectionName;
Split(fFullCollectionName,'.',fDatabaseName,fCollectionName);
if requestID=0 then
fRequestID := InterlockedIncrement(GlobalRequestID) else
fRequestID := requestID;
fResponseTo := responseTo;
BSONDocumentBegin;
fRequestOpCode := opCode;
Write4(fRequestID);
Write4(fResponseTo);
Write4(WIRE_OPCODES[opCode]);
end;
procedure TMongoRequest.BSONWriteParam(const paramDoc: variant);
begin
if TVarData(paramDoc).VType=varByRef or varVariant then
BSONWriteParam(PVariant(TVarData(paramDoc).VPointer)^) else
if VarIsStr(paramDoc) then
BSONWriteProjection(VariantToUTF8(paramDoc)) else
if (TVarData(paramDoc).VType=BSONVariantType.VarType) and
(TBSONVariantData(paramDoc).VKind in [betDoc,betArray]) and
(TBSONVariantData(paramDoc).VBlob<>nil) then
WriteBinary(RawByteString(TBSONVariantData(paramDoc).VBlob)) else
BSONWriteDoc(TDocVariantData(paramDoc)); // for TDocVariant or null
end;
procedure TMongoRequest.ToBSONDocument(var result: TBSONDocument);
begin
if (fRequestID=0) or (fRequestOpCode=opReply) then
raise EMongoException.CreateUTF8('No previous proper %.Create() call',[self]);
if fBSONDocument='' then begin
BSONDocumentEnd(1,false);
inherited ToBSONDocument(fBSONDocument);
end;
result := fBSONDocument;
end;
procedure TMongoRequest.ToJSON(W: TTextWriter; Mode: TMongoJSONMode);
begin
if self=nil then begin
W.AddShort('null');
exit;
end;
W.Add('{');
W.AddShort('collection:"');
W.AddJSONEscape(pointer(fFullCollectionName));
W.AddShort('",opCode:');
W.AddTypedJSON(TypeInfo(TMongoOperation),fRequestOpCode);
W.AddShort(',requestID:');
W.AddU(fRequestID);
if fResponseTo<>0 then begin
W.AddShort(',responseTo:');
W.AddU(fResponseTo);
end;
W.Add('}');
end;
function TMongoRequest.ToJSON(Mode: TMongoJSONMode): RawUTF8;
var W: TTextWriter;
begin
W := TTextWriter.CreateOwnedStream;
try
ToJSON(W,Mode);
W.SetText(result);
finally
W.Free;
end;
end;
{ TMongoRequestUpdate }
constructor TMongoRequestUpdate.Create(const FullCollectionName: RawUTF8;
const Selector, Update: variant; Flags: TMongoUpdateFlags);
begin
inherited Create(FullCollectionName,opUpdate,0,0);
fSelector := TVarData(Selector);
fUpdate := TVarData(Update);
WriteCollectionName(0,FullCollectionName);
Write4(byte(Flags));
BSONWriteParam(Selector);
BSONWriteParam(Update);
end;
procedure TMongoRequestUpdate.ToJSON(W: TTextWriter; Mode: TMongoJSONMode);
begin
inherited;
W.CancelLastChar('}');
W.AddShort(',selector:');
AddMongoJSON(variant(fSelector),W,modMongoShell);
W.AddShort(',update:');
AddMongoJSON(variant(fUpdate),W,modMongoShell);
W.Add('}');
end;
{ TMongoRequestInsert }
constructor TMongoRequestInsert.Create(const FullCollectionName: RawUTF8;
const Documents: array of variant; Flags: TMongoInsertFlags=[]);
var i: integer;
begin
inherited Create(FullCollectionName,opInsert,0,0);
WriteCollectionName(byte(Flags),FullCollectionName);
for i := 0 to high(Documents) do
BSONWriteParam(Documents[i]);
end;
constructor TMongoRequestInsert.Create(const FullCollectionName: RawUTF8;
const Documents: TBSONDocument; Flags: TMongoInsertFlags=[]);
begin
inherited Create(FullCollectionName,opInsert,0,0);
WriteCollectionName(byte(Flags),FullCollectionName);
Write(pointer(Documents),Length(Documents));
end;
constructor TMongoRequestInsert.Create(const FullCollectionName: RawUTF8;
const JSONDocuments: array of PUTF8Char; Flags: TMongoInsertFlags=[]);
var i: integer;
kind: TBSONElementType;
begin
inherited Create(FullCollectionName,opInsert,0,0);
WriteCollectionName(byte(Flags),FullCollectionName);
for i := 0 to high(JSONDocuments) do
BSONWriteDocFromJSON(JSONDocuments[i],nil,kind);
end;
{ TMongoRequestDelete }
constructor TMongoRequestDelete.Create(const FullCollectionName: RawUTF8;
const Selector: variant; Flags: TMongoDeleteFlags=[]);
begin
inherited Create(FullCollectionName,opDelete,0,0);
fQuery := TVarData(Selector);
WriteCollectionName(byte(Flags),FullCollectionName);
Write4(byte(Flags));
BSONWriteParam(Selector);
end;
procedure TMongoRequestDelete.ToJSON(W: TTextWriter; Mode: TMongoJSONMode);
begin
inherited;
W.CancelLastChar('}');
W.AddShort(',query:');
AddMongoJSON(variant(fQuery),W,modMongoShell);
W.Add('}');
end;
{ TMongoRequestQuery }
constructor TMongoRequestQuery.Create(const FullCollectionName: RawUTF8;
const Query, ReturnFieldsSelector: variant; NumberToReturn: integer;
NumberToSkip: Integer=0; Flags: TMongoQueryFlags=[]);
begin
inherited Create(FullCollectionName,opQuery,0,0);
fNumberToReturn := NumberToReturn;
fNumberToSkip := NumberToSkip;
fQuery := TVarData(Query);
fReturnFieldsSelector := TVarData(ReturnFieldsSelector);
WriteCollectionName(byte(Flags),FullCollectionName);
Write4(NumberToSkip);
Write4(NumberToReturn);
BSONWriteParam(Query);
if TVarData(ReturnFieldsSelector).VType>varNull then
BSONWriteParam(ReturnFieldsSelector);
end;
procedure TMongoRequestQuery.ToJSON(W: TTextWriter; Mode: TMongoJSONMode);
begin
inherited;
W.CancelLastChar('}');
W.AddShort(',query:');
AddMongoJSON(variant(fQuery),W,modMongoShell);
if fReturnFieldsSelector.VType<>varNull then begin
W.AddShort(',projection:');
AddMongoJSON(variant(fReturnFieldsSelector),W,modMongoShell);
end;
if fNumberToReturn<maxInt then begin
W.AddShort(',numberToReturn:');
W.Add(fNumberToReturn);
end;
if fNumberToSkip>0 then begin
W.AddShort(',numberToSkip:');
W.AddU(fNumberToSkip);
end;
W.Add('}');
end;
{ TMongoRequestGetMore }
constructor TMongoRequestGetMore.Create(const FullCollectionName: RawUTF8;
NumberToReturn: integer; CursorID: Int64);
begin
inherited Create(FullCollectionName,opGetMore,0,0);
WriteCollectionName(0,FullCollectionName);
Write4(NumberToReturn);
Write8(CursorID);
end;
{ TMongoRequestKillCursor }
constructor TMongoRequestKillCursor.Create(const FullCollectionName: RawUTF8;
const CursorIDs: array of Int64);
var n: integer;
begin
if high(CursorIDs)<0 then
raise EMongoException.CreateUTF8('Invalid %.Create([]) call',[self]);
inherited Create(FullCollectionName,opKillCursors,0,0);
Write4(0); // reserved for future use
n := length(CursorIDs);
Write4(n);
SetLength(fCursors,n);
n := n*sizeof(Int64);
MoveFast(CursorIDs[0],fCursors[0],n);
Write(pointer(fCursors),n);
end;
procedure TMongoRequestKillCursor.ToJSON(W: TTextWriter; Mode: TMongoJSONMode);
var i: integer;
begin
inherited;
W.CancelLastChar('}');
W.AddShort(',cursorID:[');
for i := 0 to high(fCursors) do begin
W.Add(fCursors[i]);
W.Add(',');
end;
W.CancelLastComma;
W.Add(']','}');
end;
{ TMongoReplyCursor }
procedure TMongoReplyCursor.Init(const ReplyMessage: TMongoReply);
var Len: integer;
begin
Len := length(ReplyMessage);
with PMongoReplyHeader(ReplyMessage)^ do begin
if (Len<sizeof(TMongoReplyHeader)) or (MessageLength<>Len) or
(sizeof(TMongoReplyHeader)+NumberReturned*5>Len) then
raise EMongoException.CreateUTF8('TMongoReplyCursor.Init(len=%)',[len]);
if OpCode<>WIRE_OPCODES[opReply] then
raise EMongoException.CreateUTF8('TMongoReplyCursor.Init(OpCode=%)',[OpCode]);
fRequestID := RequestID;
fResponseTo := ResponseTo;
byte(fResponseFlags) := ResponseFlags;
fCursorID := CursorID;
fStartingFrom := StartingFrom;
fNumberReturned := NumberReturned;
end;
fReply := ReplyMessage;
fFirstDocument := PAnsiChar(pointer(fReply))+sizeof(TMongoReplyHeader);
Rewind;
fLatestDocIndex := -1;
end;
procedure TMongoReplyCursor.ComputeDocumentsList;
var i, Len: integer;
P: PAnsiChar;
begin
if fDocuments<>nil then
exit;
Len := length(fReply);
SetLength(fDocuments,DocumentCount);
P := fFirstDocument;
for i := 0 to DocumentCount-1 do begin
fDocuments[i] := P;
inc(P,PInteger(P)^); // fast "parsing" of all supplied documents
if P-pointer(fReply)>Len then
raise EMongoException.CreateUTF8('ComputeDocumentsList(Document[%])',[i]);
end;
if P-pointer(fReply)<>Len then
raise EMongoException.Create('ComputeDocumentsList(Documents)');
end;
function TMongoReplyCursor.GetOneDocument(index: integer): variant;
begin
if fLatestDocIndex<>index then begin // naive but efficient cache
GetDocument(index,fLatestDocValue);
fLatestDocIndex := index;
end;
result := fLatestDocValue;
end;
procedure TMongoReplyCursor.GetDocument(index: integer; var result: variant);
begin
if cardinal(index)>=cardinal(length(fDocuments)) then
raise EMongoException.CreateUTF8('TMongoReplyCursor.GetDocument(index %>=%)',
[index,length(fDocuments)]);
if fDocuments=nil then
ComputeDocumentsList;
BSONToDoc(fDocuments[index],result,0,asDocVariantPerReference);
end;
function TMongoReplyCursor.Next(out doc: variant;
option: TBSONDocArrayConversion=asDocVariantPerReference): boolean;
var b: PByte;
begin
if Next(b) then begin
BSONToDoc(b,doc,0,option);
result := true;
end else
result := false;
end;
function TMongoReplyCursor.Next(out doc: PByte): boolean;
begin
if fCurrentPosition<DocumentCount then begin
doc := PByte(fCurrentDocument);
inc(fCurrentDocument,PInteger(fCurrentDocument)^);
inc(fCurrentPosition);
result := true;
end else begin
doc := nil;
result := false;
end;
end;
function TMongoReplyCursor.Next(out BSON: TBSONDocument): boolean;
var b: PByte;
begin
if Next(b) then begin
SetString(BSON,PAnsiChar(b)+4,PInteger(b)^);
result := true;
end else
result := false;
end;
function TMongoReplyCursor.Next(out JSON: RawUTF8; Mode: TMongoJSONMode=modMongoStrict): boolean;
var b: PByte;
begin
if Next(b) then begin
JSON := BSONToJSON(b,betDoc,0,Mode);
result := true;
end else
result := false;
end;
procedure TMongoReplyCursor.Rewind;
begin
fCurrentPosition := 0;
fCurrentDocument := fFirstDocument;
end;
function TMongoReplyCursor.AppendAllToDocVariantDynArray(var Dest: TVariantDynArray): integer;
var b: PByte;
begin
result := length(Dest);
if (fReply='') or (DocumentCount<=0) then
exit; // nothing to append
SetLength(Dest,result+DocumentCount);
Rewind;
while Next(b) do begin
BSONToDoc(b,Dest[result],0,asDocVariantPerReference);
inc(result);
end;
if result<>length(Dest) then
raise EMongoException.Create('Invalid opReply Documents');
end;
procedure TMongoReplyCursor.AppendAllToBSON(Dest: TBSONWriter);
var name: RawUTF8;
i: integer;
P: PAnsiChar;
begin
P := FirstDocument;
for i := 1 to DocumentCount do begin
UInt32ToUtf8(Dest.Tag,name); // Dest.Tag = item number in array
Dest.Tag := Dest.Tag+1;
Dest.BSONWrite(name,betDoc);
Dest.Write(P,PInteger(P)^);
inc(P,PInteger(P)^);
end;
end;
function TMongoReplyCursor.AppendAllToDocVariant(var Dest: TDocVariantData): integer;
var item: variant;
begin
if TVarData(Dest).VType<>DocVariantType.VarType then
TDocVariant.New(Variant(Dest),JSON_OPTIONS_FAST);
result := Dest.Count;
if (fReply='') or (DocumentCount<=0) then
exit; // nothing to append
inc(result,DocumentCount);
Dest.Capacity := result;
Rewind;
while Next(item) do
Dest.AddItem(item);
if Dest.Count<>result then
raise EMongoException.Create('Invalid opReply Documents');
end;
procedure TMongoReplyCursor.FetchAllToJSON(W: TTextWriter; Mode: TMongoJSONMode;
WithHeader: boolean; MaxSize: Cardinal);
var b: PByte;
begin
if (fReply='') or (DocumentCount<=0) then begin
W.AddShort('null');
exit;
end;
if WithHeader and (Mode=modMongoShell) then
W.Add('{ReplyHeader:{ResponseFlags:%,RequestID:%,ResponseTo:%,CursorID:%,'+
'StartingFrom:%,NumberReturned:%,ReplyDocuments:[',
[byte(ResponseFlags),RequestID,ResponseTo,CursorID,StartingFrom,DocumentCount]);
Rewind;
while Next(b) do begin
inc(b,sizeof(integer)); // points to the "e_list" of "int32 e_list #0"
BSONListToJSON(b,betDoc,W,Mode);
W.Add(',');
if (MaxSize>0) and (W.TextLength>MaxSize) then begin
W.AddShort('...');
break;
end;
end;
W.CancelLastComma;
if WithHeader then
W.Add(']','}');
end;
function TMongoReplyCursor.ToJSON(Mode: TMongoJSONMode; WithHeader: boolean;
MaxSize: Cardinal): RawUTF8;
var W: TTextWriter;
begin
if (fReply='') or (DocumentCount<=0) then
result := 'null' else begin
W := TTextWriter.CreateOwnedStream;
try
FetchAllToJSON(W,Mode,WithHeader,MaxSize);
W.SetText(result);
finally
W.Free;
end;
end;
end;
{ TMongoConnection }
const
/// message big enough to retrieve the maximum MongoDB document size
MONGODB_MAXMESSAGESIZE = BSON_MAXDOCUMENTSIZE+sizeof(TMongoReplyHeader);
constructor TMongoConnection.Create(const aClient: TMongoClient;
const aServerAddress: RawByteString; aServerPort: integer);
begin
if aClient=nil then
raise EMongoException.CreateUTF8('%.Create(nil)',[self]);
fClient := aClient;
fServerAddress := trim(aServerAddress);
if fServerAddress='' then
fServerAddress := '127.0.0.1';
fServerPort := aServerPort;
InitializeCriticalSection(fLock);
end;
destructor TMongoConnection.Destroy;
begin
try
try
Close;
except
; // continue on socket error
end;
finally
DeleteCriticalSection(fLock);
inherited Destroy;
end;
end;
procedure TMongoConnection.Open;
begin
if self=nil then
raise EMongoException.Create('TMongoConnection(nil).Open');
if fSocket<>nil then
raise EMongoConnectionException.Create('Duplicate Open',self);
try
fSocket := TCrtSocket.Open(fServerAddress,UInt32ToUtf8(fServerPort),
cslTCP,Client.ConnectionTimeOut,Client.ConnectionTLS);
except
on E: Exception do
raise EMongoException.CreateUTF8(
'%.Open unable to connect to MongoDB server %: % [%]',
[self,Client.ConnectionString,E,E.Message]);
end;
fSocket.TCPNoDelay := ord(true); // we buffer all output data before sending
fSocket.KeepAlive := ord(true); // do not close the connection without notice
end;
function TMongoConnection.GetOpened: boolean;
begin
result := (self<>nil) and (fSocket<>nil);
end;
procedure TMongoConnection.Close;
begin
FreeAndNil(fSocket);
end;
procedure TMongoConnection.GetDocumentsAndFree(Query: TMongoRequestQuery;
var result: TVariantDynArray);
begin
result := nil;
GetRepliesAndFree(Query,ReplyDocVariant,result);
end;
procedure TMongoConnection.GetDocumentsAndFree(Query: TMongoRequestQuery;
var result: variant);
var ForceOneInstance: boolean;
docs: TVariantDynArray;
begin
ForceOneInstance := Query.NumberToReturn=1;
SetVariantNull(result);
GetRepliesAndFree(Query,ReplyDocVariant,docs);
if docs<>nil then
if ForceOneInstance then
result := docs[0] else
TDocVariantData(result).InitArrayFromVariants(docs,JSON_OPTIONS_FAST);
end;
function TMongoConnection.GetDocumentsAndFree(Query: TMongoRequestQuery): variant;
begin
GetDocumentsAndFree(Query,result);
end;
function TMongoConnection.GetBSONAndFree(Query: TMongoRequestQuery): TBSONDocument;
var W: TBSONWriter;
begin
W := TBSONWriter.Create(TRawByteStringStream);
try
W.BSONDocumentBegin;
GetRepliesAndFree(Query,ReplyBSON,W); // W.Tag = item number in array
W.BSONDocumentEnd;
W.ToBSONDocument(result);
finally
W.Free;
end;
end;
function TMongoConnection.GetJSONAndFree(Query: TMongoRequestQuery; Mode: TMongoJSONMode): RawUTF8;
var W: TTextWriter;
ReturnAsJSONArray: boolean;
begin
ReturnAsJSONArray := Query.NumberToReturn>1;
W := TTextWriter.CreateOwnedStream;
try
if ReturnAsJSONArray then
W.Add('[');
case Mode of
modNoMongo: GetRepliesAndFree(Query,ReplyJSONNoMongo,W);
modMongoStrict: GetRepliesAndFree(Query,ReplyJSONStrict,W);
modMongoShell: GetRepliesAndFree(Query,ReplyJSONExtended,W);
end;
W.CancelLastComma;
if ReturnAsJSONArray then
W.Add(']');
W.SetText(result);
if (result='') or (result='[]') or (result='{}') then
result := 'null';
finally
W.Free;
end;
end;
procedure TMongoConnection.GetRepliesAndFree(Query: TMongoRequestQuery;
OnEachReply: TOnMongoConnectionReply; var Opaque);
var main, more: TMongoReplyCursor;
getMore: TMongoRequestGetMore;
count: integer;
cursorID: Int64;
begin
try
if not Assigned(Query) then
raise EMongoRequestException.Create('Query=nil',self);
if not Assigned(OnEachReply) then
raise EMongoRequestException.Create('OnEachReply=nil',self,Query);
count := Query.NumberToReturn; // 0 means default return size
GetCursor(Query,main);
if main.DocumentCount>0 then begin
OnEachReply(Query,main,Opaque);
if count>0 then
dec(count,main.DocumentCount);
end;
cursorID := main.CursorID;
if cursorID<>0 then
if (Query.NumberToReturn=0) or ((Query.NumberToReturn>0)and(count>0)) then
repeat
getMore := TMongoRequestGetMore.Create(
Query.FullCollectionName,count,cursorID);
try
GetCursor(getMore,more);
if mrfCursorNotFound in more.ResponseFlags then
raise EMongoRequestException.Create('GetMore cursor not found',self,Query,more);
if more.DocumentCount>0 then begin
OnEachReply(Query,more,Opaque);
dec(count,more.DocumentCount);
end;
cursorID := more.CursorID;
finally
getMore.Free;
end;
until ((Query.NumberToReturn>0)and(count<=0)) or (cursorID=0);
if cursorID<>0 then // if cursor not exhausted: need to kill it
SendAndFree(TMongoRequestKillCursor.Create(Query.FullCollectionName,[cursorID]),true);
finally
Query.Free;
end;
end;
procedure TMongoConnection.ReplyDocVariant(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
begin
Reply.AppendAllToDocVariantDynArray(TVariantDynArray(Opaque));
end;
procedure TMongoConnection.ReplyJSONStrict(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
var W: TTextWriter absolute Opaque;
begin
Reply.FetchAllToJSON(W,modMongoStrict,false);
W.Add(',');
end;
procedure TMongoConnection.ReplyJSONExtended(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
var W: TTextWriter absolute Opaque;
begin
Reply.FetchAllToJSON(W,modMongoShell,false);
W.Add(',');
end;
procedure TMongoConnection.ReplyJSONNoMongo(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
var W: TTextWriter absolute Opaque;
begin
Reply.FetchAllToJSON(W,modNoMongo,false);
W.Add(',');
end;
procedure TMongoConnection.ReplyBSON(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
begin
Reply.AppendAllToBSON(TBSONWriter(Opaque));
end;
function TMongoConnection.Send(Request: TMongoRequest): boolean;
var doc: TBSONDocument;
begin
if not Opened and not Client.ReOpen then
raise EMongoRequestException.Create('Send: Missing Open',self,Request);
if Request=nil then
raise EMongoRequestException.Create('Send(nil)',self);
Request.ToBSONDocument(doc);
if (Client.LogRequestEvent<>sllNone) and (Client.Log<>nil) and
(Client.LogRequestEvent in Client.Log.Family.Level) then
Client.Log.Log(Client.fLogRequestEvent,Request.ToJSON(modMongoShell),Request);
result := fSocket.TrySndLow(pointer(doc),length(doc));
end;
function TMongoConnection.SendAndFree(Request: TMongoRequest; NoAcknowledge: boolean): variant;
var cmd: variant;
begin
SetVariantNull(result);
try
if self=nil then
raise EMongoRequestException.Create('Connection=nil',self,Request);
Lock;
try
if Send(Request) then begin
if NoAcknowledge or
(Client.WriteConcern in [wcErrorsIgnored,wcUnacknowledged]) then
exit;
case Client.WriteConcern of
wcAcknowledged: cmd := 'getLastError';
wcJournaled: cmd := BSONVariant(['getLastError',1,'j',true]);
wcReplicaAcknowledged: cmd := BSONVariant(['getLastError',1,'w',2]);
else raise EMongoRequestException.CreateUTF8(
'%.SendAndFree WriteConcern=%',[self,ord(Client.WriteConcern)],self,Request);
end;
RunCommand(Request.DatabaseName,cmd,result);
if not VarIsNull(result.err) then
raise EMongoRequestException.Create(
'SendAndFree',self,Request,TDocVariantData(result));
end else // socket error on sending
if Client.WriteConcern=wcErrorsIgnored then
exit else
raise EMongoRequestOSException.Create('SendAndFree',self,Request);
finally
UnLock;
end;
finally
Request.Free;
end;
end;
procedure TMongoConnection.GetCursor(Request: TMongoRequest; var Result: TMongoReplyCursor);
var reply: TMongoReply;
begin
GetReply(Request,reply);
Result.Init(reply);
if (Client.LogReplyEvent<>sllNone) and (Client.Log<>nil) and
(Client.LogReplyEvent in Client.Log.Family.Level) then
Client.Log.Log(Client.LogReplyEvent,
Result.ToJSON(modMongoShell,True,Client.LogReplyEventMaxSize),Request);
if mrfQueryFailure in Result.ResponseFlags then
raise EMongoRequestException.Create('Query failure',self,Request,Result);
end;
procedure TMongoConnection.GetReply(Request: TMongoRequest; out result: TMongoReply);
var Header: TMongoReplyHeader;
HeaderLen, DataLen: integer;
begin
if self=nil then
raise EMongoRequestException.Create('Connection=nil',self,Request);
FillCharFast(Header,sizeof(Header),0);
HeaderLen := SizeOf(Header);
try
Lock;
if Send(Request) then
while true do
if fSocket.TrySockRecv(@Header,HeaderLen) then begin
if (Header.MessageLength<SizeOf(Header)) or
(Header.MessageLength>MONGODB_MAXMESSAGESIZE) then
raise EMongoRequestException.CreateUTF8('%.GetReply: MessageLength=%',
[self,Header.MessageLength],self,Request);
SetLength(result,Header.MessageLength);
PMongoReplyHeader(result)^ := Header;
DataLen := Header.MessageLength-sizeof(Header);
if fSocket.TrySockRecv(@PByteArray(result)[sizeof(Header)],DataLen) then
if Header.ResponseTo=Request.MongoRequestID then // success
exit else
if Header.OpCode=ord(opMsg) then begin
if Client.Log<>nil then
Client.Log.Log(sllWarning,'Msg from MongoDB: %',
[BSONToJSON(@PByteArray(result)[sizeof(Header)],betDoc,DataLen,modMongoShell)],Request);
end else
raise EMongoRequestException.CreateUTF8(
'%.GetReply: ResponseTo=% Expected:% in current blocking mode',
[self,Header.ResponseTo,Request.MongoRequestID],self,Request);
end else
try
Close;
finally
raise EMongoRequestException.Create('Server did reset the connection: '+
'probably due to a bad formatted BSON request -> close socket',self,Request);
end;
// if we reached here, this is due to a socket error
raise EMongoRequestOSException.Create('GetReply',self,Request);
finally
UnLock;
end;
end;
function TMongoConnection.RunCommand(const aDatabaseName: RawUTF8;
const command: variant; var returnedValue: variant): RawUTF8;
begin
GetDocumentsAndFree(
TMongoRequestQuery.Create(aDatabaseName+'.$cmd',command,null,1),
returnedValue);
with _Safe(returnedValue)^ do
if GetValueOrDefault('ok',1)<>0 then
result := '' else
if not GetAsRawUTF8('errmsg',result) then
result := 'unspecified error';
end;
function TMongoConnection.RunCommand(const aDatabaseName: RawUTF8;
const command: variant; var returnedValue: TBSONDocument): boolean;
var item: TBSONElement;
begin
returnedValue := GetBSONAndFree(
TMongoRequestQuery.Create(aDatabaseName+'.$cmd',command,null,1));
result := true;
item.FromDocument(returnedValue);
if item.DocItemToInteger('ok',1)=0 then
result := false;
end;
procedure TMongoConnection.Lock;
begin
EnterCriticalSection(fLock);
inc(fLocked);
end;
procedure TMongoConnection.UnLock;
begin
dec(fLocked);
LeaveCriticalSection(fLock);
end;
function TMongoConnection.GetLocked: boolean;
begin
result := (self<>nil) and (fLocked>0);
end;
{ EMongoConnectionException }
constructor EMongoConnectionException.Create(const aMsg: string;
aConnection: TMongoConnection);
begin
inherited Create(aMsg);
fConnection := aConnection;
end;
constructor EMongoConnectionException.CreateUTF8(const Format: RawUTF8; const Args: array of const;
aConnection: TMongoConnection);
begin
inherited CreateUTF8(Format,Args);
fConnection := aConnection;
end;
{ EMongoRequestException }
constructor EMongoRequestException.Create(const aMsg: string;
aConnection: TMongoConnection; aRequest: TMongoRequest);
begin
inherited Create(aMsg,aConnection);
fRequest := aRequest;
end;
constructor EMongoRequestException.CreateUTF8(const Format: RawUTF8;
const Args: array of const; aConnection: TMongoConnection;
aRequest: TMongoRequest);
begin
inherited CreateUTF8(Format,Args,aConnection);
fRequest := aRequest;
end;
constructor EMongoRequestException.Create(const aMsg: string;
aConnection: TMongoConnection; aRequest: TMongoRequest;
const aError: TMongoReplyCursor);
begin
Create(aMsg,aConnection,aRequest);
fError := aError;
end;
constructor EMongoRequestException.Create(const aMsg: string;
aConnection: TMongoConnection; aRequest: TMongoRequest;
const aErrorDoc: TDocVariantData);
begin
Create(aMsg,aConnection,aRequest);
fErrorDoc := variant(aErrorDoc);
end;
{$ifndef NOEXCEPTIONINTERCEPT}
function EMongoRequestException.CustomLog(WR: TTextWriter;
const Context: TSynLogExceptionContext): boolean;
begin
inherited CustomLog(WR,Context);
if fRequest<>nil then begin
WR.AddInstanceName(fRequest,':');
fRequest.ToJSON(WR,modMongoShell);
end;
if fError.Reply<>'' then
fError.FetchAllToJSON(WR,modMongoShell,True);
result := false; // log stack trace
end;
{$endif}
function EMongoRequestException.GetErrorDoc: variant;
begin
if TVarData(fErrorDoc).VType=varEmpty then begin
if not fError.Next(fErrorDoc) then
SetVariantNull(fErrorDoc);
end;
result := fErrorDoc;
end;
{ EMongoRequestOSException }
constructor EMongoRequestOSException.Create(const aMsg: string;
aConnection: TMongoConnection; aRequest: TMongoRequest=nil);
begin
fSystemLastError := GetLastError;
CreateUTF8('%: % (%)',[aMsg,SysErrorMessage(fSystemLastError),fSystemLastError],
aConnection,aRequest);
end;
{ EMongoDatabaseException }
constructor EMongoDatabaseException.Create(const aMsg: string;
aDatabase: TMongoDatabase);
begin
inherited Create(aMsg,aDatabase.Client.Connections[0]);
fDatabase := aDatabase;
end;
constructor EMongoDatabaseException.CreateUTF8(const Format: RawUTF8;
const Args: array of const; aDatabase: TMongoDatabase);
begin
inherited CreateUTF8(Format,Args,aDatabase.Client.Connections[0]);
fDatabase := aDatabase;
end;
{$ifndef NOEXCEPTIONINTERCEPT}
function EMongoDatabaseException.CustomLog(WR: TTextWriter;
const Context: TSynLogExceptionContext): boolean;
begin
inherited CustomLog(WR,Context);
WR.AddJSONEscape(['Database',fDatabase.Name]);
result := false; // log stack trace
end;
{$endif}
{ TMongoClient }
constructor TMongoClient.Create(const Host: RawUTF8; Port: Integer;
aTLS: boolean; const SecondaryHostCSV, SecondaryPortCSV: RawUTF8);
const PROT: array[boolean] of string[1] = ('', 's');
var secHost: TRawUTF8DynArray;
secPort: TIntegerDynArray;
nHost, i: integer;
begin
fConnectionTimeOut := 30000;
fConnectionTLS := aTLS;
fLogReplyEventMaxSize := 1024;
fGracefulReconnect.Enabled := true;
FormatUTF8('mongodb%://%:%',[PROT[aTLS],Host,Port],fConnectionString);
CSVToRawUTF8DynArray(pointer(SecondaryHostCSV),secHost);
nHost := length(secHost);
SetLength(fConnections,nHost+1);
fConnections[0] := TMongoConnection.Create(self,Host,Port);
if nHost>0 then begin
CSVToIntegerDynArray(pointer(SecondaryPortCSV),secPort);
for i := 0 to nHost-1 do begin
if i>high(secPort) then
Port := MONGODB_DEFAULTPORT else
Port := secPort[i];
fConnections[i+1] := TMongoConnection.Create(self,secHost[i],Port);
fConnectionString := FormatUTF8('%,%:%',[fConnectionString,secHost[i],Port]);
end;
end;
fDatabases := TRawUTF8ListHashed.Create(true);
end;
destructor TMongoClient.Destroy;
var i: integer;
begin
for i := 0 to high(fConnections) do
FreeAndNil(fConnections[i]);
FreeAndNil(fDatabases);
inherited;
end;
procedure TMongoClient.SetLog(LogClass: TSynLogClass;
RequestEvent, ReplyEvent: TSynLogInfo; ReplyEventMaxSize: cardinal);
begin
fLog := LogClass.Add;
LogRequestEvent := RequestEvent;
LogReplyEvent := ReplyEvent;
LogReplyEventMaxSize := ReplyEventMaxSize;
end;
function TMongoClient.ServerBuildInfoText: RawUTF8;
begin
with _Safe(ServerBuildInfo)^ do
if Count=0 then
result := '' else begin
FormatUTF8('MongoDB % %',[U['version'],U['javascriptEngine']],result);
with A['storageEngines']^ do begin
// "storageEngines":["devnull","ephemeralForTest","mmapv1","wiredTiger"]
DeleteByValue('devnull');
DeleteByValue('ephemeralForTest');
if Count>0 then
result := result+' '+ToCSV;
end;
end;
end;
function TMongoClient.GetOneReadConnection: TMongoConnection;
function GetUnlockedSecondaryIndex: integer;
var retry: integer;
begin
if Length(fConnections)=1 then // no secondary? use primary
result := 0 else begin
for retry := 1 to 100 do begin // search for an inactive connection
result := fLatestReadConnectionIndex; // simple round-robin pattern
if result=high(fConnections) then
if ReadPreference=rpSecondary then
result := 1 else
result := 0 else
inc(result); // thread-safety is not an issue here
if (retry<=length(fConnections)) and not fConnections[result].Opened then
try
fConnections[result].Open;
except
on E: Exception do
continue;
end;
if fConnections[result].Opened then
if fConnections[result].Locked then
if retry mod length(fConnections)=0 then
SleepHiRes(2) else
continue else
break;
end;
if not fConnections[result].Opened then
result := 0; // safe fallback to primary member in worst case
fLatestReadConnectionIndex := result;
end;
end;
begin
case ReadPreference of
rpPrimaryPreferred:
if fConnections[0].Locked then
result := fConnections[GetUnlockedSecondaryIndex] else
result := fConnections[0];
rpSecondary, rpSecondaryPreferred:
result := fConnections[GetUnlockedSecondaryIndex];
else // rpPrimary:
result := fConnections[0];
end;
end;
function TMongoClient.Open(const DatabaseName: RawUTF8): TMongoDatabase;
begin
if self=nil then
result := nil else begin
result := TMongoDatabase(fDatabases.GetObjectByName(DatabaseName));
if result=nil then begin // not already opened -> try now from primary host
if not fConnections[0].Opened then begin
fConnections[0].Open;
AfterOpen;
end;
result := TMongoDatabase.Create(Self,DatabaseName);
fDatabases.AddObject(DatabaseName,result);
end;
end;
end;
function PasswordDigest(const UserName,Password: RawUTF8): RawUTF8;
begin
result := MD5(UserName+':mongo:'+PassWord);
end;
function TMongoClient.OpenAuth(const DatabaseName,UserName,PassWord: RawUTF8;
ForceMongoDBCR: boolean): TMongoDatabase;
var digest: RawByteString;
begin
if (self=nil) or (DatabaseName='') or (UserName='') or (PassWord='') then
raise EMongoException.CreateUTF8('Invalid %.OpenAuth("%") call',[self,DatabaseName]);
result := TMongoDatabase(fDatabases.GetObjectByName(DatabaseName));
if result=nil then // not already opened -> try now from primary host
try // note: authentication works on a single database per socket connection
if not fConnections[0].Opened then
try
fConnections[0].Open; // socket connection
AfterOpen; // need ServerBuildInfoNumber just below
digest := PasswordDigest(UserName,Password);
Auth(DatabaseName,UserName,digest,ForceMongoDBCR);
with fGracefulReconnect do
if Enabled and (EncryptedDigest='') then begin
ForcedDBCR := ForceMongoDBCR;
User := UserName;
Database := DatabaseName;
EncryptedDigest := CryptDataForCurrentUser(digest,Database,true);
end;
except
fConnections[0].Close;
raise;
end;
result := TMongoDatabase.Create(Self,DatabaseName);
fDatabases.AddObject(DatabaseName,result);
finally
FillZero(digest);
end;
end;
procedure TMongoClient.Auth(const DatabaseName,UserName,Digest: RawUTF8;
ForceMongoDBCR: boolean);
var res,bson: variant;
err,nonce,first,key,user,msg,rnonce: RawUTF8;
payload: RawByteString;
rnd: TAESBlock;
sha: TSHA1;
salted,client,stored,server: TSHA1Digest;
resp: TDocVariantData;
procedure CheckPayload;
var bin: PVariant;
begin
if err<>'' then
exit;
if _Safe(res)^.GetAsPVariant('payload',bin) and
BSONVariantType.ToBlob(bin^,payload) then
resp.InitCSV(pointer(payload),JSON_OPTIONS_FAST,'=',',') else
err := 'missing or invalid returned payload';
end;
begin // caller should have made fConnections[0].Open
if (self=nil) or (DatabaseName='') or (UserName='') or (Digest='') then
raise EMongoException.CreateUTF8('Invalid %.Auth("%") call',[self,DatabaseName]);
if ForceMongoDBCR or (ServerBuildInfoNumber<3000000) then begin
// MONGODB-CR
// http://docs.mongodb.org/meta-driver/latest/legacy/implement-authentication-in-driver
bson := BSONVariant(['getnonce',1]);
err := fConnections[0].RunCommand(DatabaseName,bson,res);
if (err='') and not _Safe(res)^.GetAsRawUTF8('nonce',nonce) then
err := 'missing returned nonce';
if err<>'' then
raise EMongoException.CreateUTF8('%.OpenAuthCR("%") step1: % - res=%',
[self,DatabaseName,err,res]);
key := MD5(nonce+UserName+Digest);
bson := BSONVariant(['authenticate',1,'user',UserName,'nonce',nonce,'key',key]);
err := fConnections[0].RunCommand(DatabaseName,bson,res);
if err<>'' then
raise EMongoException.CreateUTF8('%.OpenAuthCR("%") step2: % - res=%',
[self,DatabaseName,err,res]);
end else begin
// SCRAM-SHA-1
// https://tools.ietf.org/html/rfc5802#section-5
user := StringReplaceAll(StringReplaceAll(UserName,'=','=3D'),',','=2C');
TAESPRNG.Main.FillRandom(rnd);
nonce := BinToBase64(@rnd,sizeof(rnd));
FormatUTF8('n=%,r=%',[user,nonce],first);
BSONVariantType.FromBinary('n,,'+first,bbtGeneric,bson);
err := fConnections[0].RunCommand(DatabaseName,BSONVariant([
'saslStart',1,'mechanism','SCRAM-SHA-1','payload',bson,'autoAuthorize',1]),res);
CheckPayload;
if err='' then begin
rnonce := resp.U['r'];
if copy(rnonce,1,length(nonce))<>nonce then
err := 'returned invalid nonce';
end;
if err<>'' then
raise EMongoException.CreateUTF8('%.OpenAuthSCRAM("%") step1: % - res=%',
[self,DatabaseName,err,res]);
key := 'c=biws,r='+rnonce;
PBKDF2_HMAC_SHA1(Digest,Base64ToBin(resp.U['s']),UTF8ToInteger(resp.U['i']),salted);
HMAC_SHA1(salted,'Client Key',client);
sha.Full(@client,SizeOf(client),stored);
msg := first+','+RawUTF8(payload)+','+key;
HMAC_SHA1(stored,msg,stored);
XorMemory(@client,@stored,SizeOf(client));
HMAC_SHA1(salted,'Server Key',server);
HMAC_SHA1(server,msg,server);
msg := key+',p='+BinToBase64(@client,SizeOf(client));
BSONVariantType.FromBinary(msg,bbtGeneric,bson);
err := fConnections[0].RunCommand(DatabaseName,BSONVariant([
'saslContinue',1,'conversationId',res.conversationId,'payload',bson]),res);
resp.Clear;
CheckPayload;
if (err='') and (resp.U['v']<>BinToBase64(@server,SizeOf(server))) then
err := 'Server returned an invalid signature';
if err<>'' then
raise EMongoException.CreateUTF8('%.OpenAuthSCRAM("%") step2: % - res=%',
[self,DatabaseName,err,res]);
if not res.done then begin
// third empty challenge may be required
err := fConnections[0].RunCommand(DatabaseName,BSONVariant([
'saslContinue',1,'conversationId',res.conversationId,'payload','']),res);
if (err='') and not res.done then
err := 'SASL conversation failed to complete';
if err<>'' then
raise EMongoException.CreateUTF8('%.OpenAuthSCRAM("%") step3: % - res=%',
[self,DatabaseName,err,res]);
end;
end;
end;
procedure TMongoClient.AfterOpen;
begin
if VarIsEmptyOrNull(fServerBuildInfo) then begin
fConnections[0].RunCommand('admin','buildinfo',fServerBuildInfo);
with _Safe(fServerBuildInfo)^.A['versionArray']^ do
if Count=4 then
fServerBuildInfoNumber := // e.g. 2040900 for MongoDB 2.4.9
integer(Values[0])*1000000+integer(Values[1])*10000+
integer(Values[2])*100+integer(Values[3]);
end;
end;
function TMongoClient.ReOpen: boolean;
var digest: RawByteString;
begin
result := false;
with fGracefulReconnect do
if Enabled then
try
if fLog<>nil then
fLog.Enter(self,'ReOpen: graceful reconnect');
fConnections[0].Open;
if EncryptedDigest<>'' then
try
digest := CryptDataForCurrentUser(EncryptedDigest,Database,false);
Auth(Database,User,digest,ForcedDBCR);
finally
FillZero(digest);
end;
result := true;
except
fConnections[0].Close;
raise;
end;
end;
function TMongoClient.GetBytesReceived: Int64;
var i: integer;
begin
result := 0;
if self<>nil then
for i := 0 to high(fConnections) do
with fConnections[i] do
if fSocket<>nil then
inc(result,fSocket.BytesIn);
end;
function TMongoClient.GetBytesSent: Int64;
var i: integer;
begin
result := 0;
if self<>nil then
for i := 0 to high(fConnections) do
with fConnections[i] do
if fSocket<>nil then
inc(result,fSocket.BytesOut);
end;
function TMongoClient.GetBytesTransmitted: Int64;
var i: integer;
begin
result := 0;
if self<>nil then
for i := 0 to high(fConnections) do
with fConnections[i] do
if fSocket<>nil then
inc(result,fSocket.BytesIn+fSocket.BytesOut);
end;
{ TMongoDatabase }
constructor TMongoDatabase.Create(aClient: TMongoClient;
const aDatabaseName: RawUTF8);
var colls: TBSONIterator;
full,db,coll: RawUTF8;
resp,batch: variant;
ndx: Integer;
begin
fClient := aClient;
fName := aDatabaseName;
fCollections := TRawUTF8ListHashed.Create(true);
if fClient.ServerBuildInfoNumber<3000000 then begin
if colls.Init(Client.Connections[0].GetBSONAndFree(TMongoRequestQuery.Create(
aDatabaseName+'.system.namespaces',null,'name',maxInt))) then
// e.g. [ {name:"test.system.indexes"}, {name:"test.test"} ]
while colls.Next do begin
full := colls.item.DocItemToRawUTF8('name');
if full<>'' then begin
split(full,'.',db,coll);
if db<>aDatabaseName then
raise EMongoConnectionException.CreateUTF8(
'%.Create: invalid "%" collection name for DB "%"',
[self,full,aDatabaseName],Client.Connections[0]);
fCollections.AddObject(coll,TMongoCollection.Create(self,coll));
end;
end;
end else begin
RunCommand('listCollections',resp);
if _Safe(resp)^.GetValueByPath('cursor.firstBatch',batch) then
with _Safe(batch)^ do
for ndx := 0 to Count-1 do
if _Safe(Values[ndx]).GetAsRawUTF8('name',coll) then
fCollections.AddObject(coll,TMongoCollection.Create(self,coll));
end;
end;
destructor TMongoDatabase.Destroy;
begin
FreeAndNil(fCollections);
inherited;
end;
function TMongoDatabase.CreateUser(const UserName,Password: RawUTF8;
const roles: variant): RawUTF8;
var res: variant;
begin
result := RunCommand(BSONVariant(
['createUser',UserName,'pwd',PasswordDigest(UserName,Password),
'digestPassword',false,'roles',roles]),res);
end;
function TMongoDatabase.CreateUserForThisDatabase(const UserName,Password: RawUTF8;
allowWrite: Boolean): RawUTF8;
const RW: array[boolean] of RawUTF8 = ('read','readWrite');
begin
result := CreateUser(UserName,Password,
BSONVariant('[{role:?,db:?}]',[],[RW[allowWrite],Name]));
end;
function TMongoDatabase.DropUser(const UserName: RawUTF8): RawUTF8;
var res: variant;
begin
result := RunCommand(BSONVariant(['dropUser',UserName]),res);
end;
function TMongoDatabase.GetCollection(const Name: RawUTF8): TMongoCollection;
begin
result := GetCollectionOrNil(Name);
if result=nil then
raise EMongoDatabaseException.CreateUTF8('%.GetCollection("%")',[self,Name],self);
end;
function TMongoDatabase.GetCollectionOrCreate(const Name: RawUTF8): TMongoCollection;
begin
result := GetCollectionOrNil(Name);
if result=nil then
if self<>nil then begin
result := TMongoCollection.Create(self,Name);
fCollections.AddObject(Name,result);
end;
end;
function TMongoDatabase.GetCollectionOrNil(const Name: RawUTF8): TMongoCollection;
begin
if self=nil then
result := nil else
result := TMongoCollection(fCollections.GetObjectByName(Name));
end;
function TMongoDatabase.RunCommand(const command: variant;
var returnedValue: variant): RawUTF8;
begin
result := Client.Connections[0].RunCommand(Name,Command,returnedValue);
end;
function TMongoDatabase.RunCommand(const command: variant;
var returnedValue: TBSONDocument): boolean;
begin
result := Client.Connections[0].RunCommand(Name,Command,returnedValue);
end;
{ TMongoCollection }
constructor TMongoCollection.Create(aDatabase: TMongoDatabase;
const aCollectionName: RawUTF8);
begin
fDatabase := aDatabase;
fName := aCollectionName;
fFullCollectionName := fDatabase.Name+'.'+fName;
end;
function TMongoCollection.AggregateCallFromJson(const pipelineJSON: RawUTF8;
var reply,res: variant): boolean;
begin // see http://docs.mongodb.org/manual/reference/command/aggregate
if fDatabase.Client.ServerBuildInfoNumber<2020000 then
raise EMongoException.Create('Aggregation needs MongoDB 2.2 or later');
// db.runCommand({aggregate:"test",pipeline:[{$group:{_id:null,max:{$max:"$_id"}}}]})
Database.RunCommand(BSONVariant('{aggregate:"%",pipeline:[%]}',[Name,pipelineJSON],[]),reply);
// { "result" : [ { "_id" : null, "max" : 1250 } ], "ok" : 1 }
res := reply.result;
result := not VarIsNull(res);
end;
function TMongoCollection.AggregateDoc(Operators: PUTF8Char;
const Params: array of const): variant;
begin
result := AggregateDocFromJson(FormatUTF8(Operators,Params));
end;
function TMongoCollection.AggregateJSON(Operators: PUTF8Char;
const Params: array of const; Mode: TMongoJSONMode): RawUTF8;
begin
result := AggregateJSONFromJson(FormatUTF8(Operators,Params),Mode);
end;
function TMongoCollection.AggregateCallFromVariant(const pipelineArray: variant; var reply,res: variant): boolean;
begin // see http://docs.mongodb.org/manual/reference/command/aggregate
if fDatabase.Client.ServerBuildInfoNumber<2020000 then
raise EMongoException.Create('Aggregation needs MongoDB 2.2 or later');
// db.runCommand({aggregate:"test",pipeline:[{$group:{_id:null,max:{$max:"$_id"}}}]})
Database.RunCommand(BSONVariant(['aggregate',name,'pipeline',pipelineArray]),reply);
// { "result" : [ { "_id" : null, "max" : 1250 } ], "ok" : 1 }
res := reply.result;
result := not VarIsNull(res);
end;
function TMongoCollection.AggregateDocFromVariant(const pipelineArray: variant): variant;
var reply: variant;
begin
if AggregateCallFromVariant(pipelineArray,reply,result) then
TDocVariant.GetSingleOrDefault(result,result,result) else
SetVariantNull(result);
end;
function TMongoCollection.AggregateJSONFromVariant(const pipelineArray: variant;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8;
var reply,res: variant;
begin
if AggregateCallFromVariant(pipelineArray,reply,res) then
result := VariantSaveMongoJSON(res,Mode) else
result := '';
end;
function TMongoCollection.AggregateDocFromJson(const PipelineJSON: RawUTF8): variant;
var reply: variant;
begin
if AggregateCallFromJSON(PipelineJSON,reply,result) then
TDocVariant.GetSingleOrDefault(result,result,result) else
SetVariantNull(result);
end;
function TMongoCollection.AggregateJSONFromJson(const PipelineJSON: RawUTF8;
Mode: TMongoJSONMode=modMongoStrict): RawUTF8;
var reply,res: variant;
begin
if AggregateCallFromJson(PipelineJSON,reply,res) then
result := VariantSaveMongoJSON(res,Mode) else
result := '';
end;
function TMongoCollection.Drop: RawUTF8;
var res: Variant;
begin
if self=nil then begin
result := 'No collection';
exit;
end;
if Database.Client.Log<>nil then
Database.Client.Log.Enter('Drop %',[Name],self);
result := fDatabase.RunCommand(BSONVariant('{drop:?}',[],[Name]),res);
Database.Client.Log.Log(sllTrace,'Drop("%")->%',[Name,res],self);
if result='' then
Database.fCollections.Delete(fDatabase.fCollections.IndexOf(Name));
end;
procedure TMongoCollection.EnsureIndex(const Keys, Options: variant);
var doc,res: variant;
indexName: RawUTF8;
ndx,order: integer;
useCommand: Boolean;
begin
if (self=nil) or (Database=nil) then
exit;
if Database.Client.Log<>nil then
Database.Client.Log.Enter('EnsureIndex %',[Name],self);
if DocVariantData(Keys)^.Kind<>dvObject then
raise EMongoException.CreateUTF8('%[%].EnsureIndex(Keys?)',[self,FullCollectionName]);
useCommand := fDatabase.Client.ServerBuildInfoNumber>=2060000;
doc := _ObjFast(['key', Keys]);
if not useCommand then
doc.ns := FullCollectionName;
if DocVariantType.IsOfType(Options) then
with _Safe(Options)^ do
for ndx := 0 to Count-1 do
if Names[ndx]='name' then
indexName := VariantToUTF8(Values[ndx]) else
TDocVariantData(doc).AddValue(Names[ndx],Values[ndx]);
if indexName='' then begin
with _Safe(Keys)^ do
for ndx := 0 to Count-1 do begin
indexName := indexName+Names[ndx]+'_';
order := VariantToIntegerDef(Values[ndx],10);
if order=-1 then
indexName := indexName+'_' else
if order<>1 then
raise EMongoException.CreateUTF8('%[%].EnsureIndex() on order {%:%}',
[self,FullCollectionName,Names[ndx],Values[ndx]]);
end;
end;
if length(FullCollectionName)+length(indexName)>120 then
raise EMongoException.CreateUTF8(
'%[%].EnsureIndex() computed name > 128 chars: please set as option',
[self,FullCollectionName]);
doc.name := indexName;
if useCommand then
fDatabase.RunCommand(BSONVariant(
'{ createIndexes: ?, indexes: [?] }',[],[Name,doc]),res) else
fDatabase.GetCollectionOrCreate('system.indexes').Insert([doc]);
Database.Client.Log.Log(sllTrace,'EnsureIndex("%",%)->%',[Name,doc,res],self);
end;
procedure TMongoCollection.EnsureIndex(const Keys: array of RawUTF8;
Ascending, Unique: boolean);
const Order: array[boolean] of Integer = (-1,1);
var k,opt: variant;
A: integer;
begin
if high(Keys)<0 then
exit; // no column name
TDocVariant.New(k);
for A := 0 to high(Keys) do
TDocVariantData(k).AddValue(Keys[A],Order[Ascending]);
if Unique then
opt := _ObjFast(['unique',true]);
EnsureIndex(k,opt);
end;
function TMongoCollection.Count: Int64;
var res: variant;
begin
fDatabase.RunCommand(BSONVariant(['count',Name]),res);
result := _Safe(res)^.GetValueOrDefault('n',0);
end;
function TMongoCollection.FindCount(const Query: variant): Int64;
var res: variant;
begin
fDatabase.RunCommand(BSONVariant(['count',Name,'query',Query]),res);
result := _Safe(res)^.GetValueOrDefault('n',0);
end;
function TMongoCollection.FindCount(Criteria: PUTF8Char;
const Args,Params: array of const;
MaxNumberToReturn: integer=0; NumberToSkip: Integer=0): Int64;
var cmd: RawUTF8;
res: variant;
begin
FormatUTF8('{count:"%",query:%',[Name,FormatUTF8(Criteria,Args,Params,true)],cmd);
if MaxNumberToReturn>0 then
cmd := FormatUTF8('%,limit:%',[cmd,MaxNumberToReturn]);
if NumberToSkip>0 then
cmd := FormatUTF8('%,skip:%',[cmd,NumberToSkip]);
fDatabase.RunCommand(BSONVariant(cmd+'}'),res);
result := _Safe(res)^.GetValueOrDefault('n',0);
end;
function TMongoCollection.IsEmpty: boolean;
var res: variant;
begin // much faster than Count>0 for huge collections
res := FindDoc(BSONVariant('{$query:{}}'),BSONVariant(['_id',1]));
result := VarIsEmptyOrNull(res);
end;
function TMongoCollection.FindBSON(const Criteria, Projection: Variant;
NumberToReturn, NumberToSkip: Integer; Flags: TMongoQueryFlags): TBSONDocument;
begin
result := Database.Client.GetOneReadConnection.GetBSONAndFree(
TMongoRequestQuery.Create(fFullCollectionName,
Criteria,Projection,NumberToReturn,NumberToSkip,Flags));
end;
function TMongoCollection.FindDoc(const Criteria, Projection: Variant;
NumberToReturn, NumberToSkip: Integer; Flags: TMongoQueryFlags): variant;
begin
Database.Client.GetOneReadConnection.GetDocumentsAndFree(
TMongoRequestQuery.Create(fFullCollectionName,
Criteria,Projection,NumberToReturn,NumberToSkip,Flags),result);
end;
function TMongoCollection.FindDoc(Criteria: PUTF8Char;
const Params: array of const; NumberToReturn, NumberToSkip: Integer;
Flags: TMongoQueryFlags): variant;
begin
result := FindDoc(BSONVariant(Criteria,[],Params),null,
NumberToReturn,NumberToSkip,Flags);
end;
procedure TMongoCollection.FindDocs(Criteria: PUTF8Char;
const Params: array of const; var result: TVariantDynArray;
const Projection: variant; NumberToReturn, NumberToSkip: Integer;
Flags: TMongoQueryFlags);
begin
Database.Client.GetOneReadConnection.GetDocumentsAndFree(
TMongoRequestQuery.Create(fFullCollectionName,
BSONVariant(Criteria,[],Params),Projection,
NumberToReturn,NumberToSkip,Flags),result);
end;
function TMongoCollection.FindDocs(Criteria: PUTF8Char; const Params: array of const;
const Projection: variant; NumberToReturn,NumberToSkip: Integer;
Flags: TMongoQueryFlags): TVariantDynArray;
begin
FindDocs(Criteria,Params,result,Projection,NumberToReturn,NumberToSkip,Flags);
end;
function TMongoCollection.FindOne(const _id: TBSONObjectID): variant;
begin
result := FindOne(['_id',_id.ToVariant]);
end;
function TMongoCollection.FindOne(const _id: variant): variant;
begin
result := FindOne(['_id',_id]);
end;
function TMongoCollection.FindOne(const NameValuePairs: array of const;
ReturnNewObjectIfNotFound: boolean): variant;
begin
result := FindDoc(BSONVariant(NameValuePairs),null,1);
if ReturnNewObjectIfNotFound and VarIsEmptyOrNull(result) then
TDocVariantData(Result).InitObject(NameValuePairs,JSON_OPTIONS_FAST);
end;
procedure TMongoCollection.FindDocs(var result: TVariantDynArray;
const Projection: variant; NumberToReturn, NumberToSkip: Integer;
Flags: TMongoQueryFlags);
begin
Database.Client.GetOneReadConnection.GetDocumentsAndFree(
TMongoRequestQuery.Create(fFullCollectionName,null,Projection,
NumberToReturn,NumberToSkip,Flags),result);
end;
function TMongoCollection.FindJSON(const Criteria, Projection: Variant;
NumberToReturn, NumberToSkip: Integer; Flags: TMongoQueryFlags;
Mode: TMongoJSONMode): RawUTF8;
begin
result := Database.Client.GetOneReadConnection.GetJSONAndFree(
TMongoRequestQuery.Create(fFullCollectionName,
Criteria,Projection,NumberToReturn,NumberToSkip,Flags),Mode);
end;
function TMongoCollection.FindJSON(Criteria: PUTF8Char;
const Params: array of const; NumberToReturn, NumberToSkip: Integer;
Flags: TMongoQueryFlags; Mode: TMongoJSONMode): RawUTF8;
begin
result := FindJSON(BSONVariant(Criteria,[],Params),null,
NumberToReturn,NumberToSkip,Flags,Mode);
end;
function TMongoCollection.FindJSON(
Criteria: PUTF8Char; const CriteriaParams: array of const;
const Projection: variant; NumberToReturn, NumberToSkip: Integer;
Flags: TMongoQueryFlags; Mode: TMongoJSONMode): RawUTF8;
begin
result := FindJSON(BSONVariant(Criteria,[],CriteriaParams),
Projection,NumberToReturn,NumberToSkip,Flags,Mode);
end;
procedure TMongoCollection.Insert(const Documents: array of variant;
Flags: TMongoInsertFlags; NoAcknowledge: boolean);
begin
Database.Client.Connections[0].SendAndFree(TMongoRequestInsert.Create(
fFullCollectionName,Documents,Flags),NoAcknowledge);
end;
procedure TMongoCollection.Insert(const Documents: TBSONDocument;
Flags: TMongoInsertFlags=[]; NoAcknowledge: boolean=false);
begin
Database.Client.Connections[0].SendAndFree(TMongoRequestInsert.Create(
fFullCollectionName,Documents,Flags),NoAcknowledge);
end;
procedure TMongoCollection.InsertJSON(const JSONDocuments: array of PUTF8Char;
Flags: TMongoInsertFlags; NoAcknowledge: boolean);
begin
Database.Client.Connections[0].SendAndFree(TMongoRequestInsert.Create(
fFullCollectionName,JSONDocuments,Flags),NoAcknowledge);
end;
function EnsureDocumentHasID(var doc: TDocVariantData; var oid: variant;
CreatedObjectID: PBSONObjectID): boolean;
var ndx: integer;
begin // return TRUE if _id has been computed (i.e. save=insert)
ndx := doc.GetValueIndex('_id',3,true);
if ndx<0 then begin
oid := ObjectID;
doc.AddValue('_id',oid);
result := true;
end else
if TVarData(doc.Values[ndx]).VType<=varNull then begin
oid := ObjectID;
doc.Values[ndx] := oid;
result := true;
end else begin
oid := doc.Values[ndx];
result := false;
end;
if CreatedObjectID<>nil then
CreatedObjectID^.FromVariant(oid)
end;
procedure TMongoCollection.Insert(const Document: RawUTF8;
const Params: array of const; CreatedObjectID: PBSONObjectID);
var doc: variant;
oid: variant;
begin
_JsonFmt(Document,[],Params,JSON_OPTIONS_FAST,doc);
EnsureDocumentHasID(TDocVariantData(doc),oid,CreatedObjectID);
Insert([doc]);
end;
function TMongoCollection.Save(var Document: variant;
CreatedObjectID: PBSONObjectID): boolean;
var oid: variant;
begin
if not DocVariantType.IsOfType(Document) then
Document := _JsonFast(VariantSaveMongoJSON(Document,modMongoShell));
result := EnsureDocumentHasID(TDocVariantData(Document),oid,CreatedObjectID);
if result then
Insert([Document]) else
Update(BSONVariant(['_id',oid]),Document,[mufUpsert])
end;
procedure TMongoCollection.Save(const Document: RawUTF8;
const Params: array of const; CreatedObjectID: PBSONObjectID);
var doc: variant;
begin
_JsonFmt(Document,[],Params,JSON_OPTIONS_FAST,doc);
Save(doc,CreatedObjectID);
end;
procedure TMongoCollection.Update(Query: PUTF8Char;
const QueryParams: array of const; const Update: RawUTF8;
const UpdateParams: array of const; Flags: TMongoUpdateFlags);
var quer,upd: variant;
begin
quer := BSONVariant(Query,[],QueryParams);
upd := BSONVariant(Update,[],UpdateParams);
self.Update(quer,upd,Flags);
end;
procedure TMongoCollection.Update(const Query, Update: variant;
Flags: TMongoUpdateFlags);
begin
Database.Client.Connections[0].SendAndFree(TMongoRequestUpdate.Create(
fFullCollectionName,Query,Update,Flags),false);
end;
procedure TMongoCollection.UpdateOne(const _id, UpdatedFields: variant);
begin
Update(BSONVariant(['_id',_id]),BSONVariant(['$set',UpdatedFields]));
end;
procedure TMongoCollection.Remove(const Query: variant;
Flags: TMongoDeleteFlags);
begin
Database.Client.Connections[0].SendAndFree(TMongoRequestDelete.Create(
fFullCollectionName,Query,Flags),False);
end;
procedure TMongoCollection.RemoveOne(const _id: TBSONObjectID);
begin
Remove(BSONVariant(['_id',_id.ToVariant]),[mdfSingleRemove]);
end;
procedure TMongoCollection.RemoveOne(const _id: variant);
begin
Remove(BSONVariant(['_id',_id]),[mdfSingleRemove]);
end;
procedure TMongoCollection.RemoveFmt(Query: PUTF8Char;
const QueryParams: array of const; Flags: TMongoDeleteFlags);
begin
Remove(BSONVariant(Query,[],QueryParams),Flags);
end;
{ TDecimal128 }
// see https://github.com/mongodb/libbson/blob/master/src/bson/bson-decimal128.c
procedure TDecimal128.SetZero;
begin
Bits.lo := 0;
Bits.hi := BSON_DECIMAL128_HI_INT64POS;
end;
const
D128: array[TDecimal128SpecialValue] of TDecimal128Bits = (
// dsvError, dsvValue, dsvNan, dsvZero, dsvPosInf, dsvNegInf, dsvMin, dsvMax
(hi:BSON_DECIMAL128_HI_NAN), (hi:BSON_DECIMAL128_HI_NAN), (hi:BSON_DECIMAL128_HI_NAN),
(hi:BSON_DECIMAL128_HI_INT64POS), (hi:$7800000000000000),
(hi:QWord($f800000000000000)), (lo:$378d8e63ffffffff; hi:QWord($dfffed09bead87c0)),
(lo:$378d8e63ffffffff; hi:$5fffed09bead87c0) );
procedure TDecimal128.SetSpecial(special: TDecimal128SpecialValue);
begin
Bits := D128[special];
end;
function TDecimal128.IsSpecial: TDecimal128SpecialValue;
begin
for result := dsvNan to high(D128) do
if (D128[result].hi=Bits.hi) and (D128[result].lo=Bits.lo) then
exit;
result := dsvValue;
end;
procedure TDecimal128.FromInt32(value: integer);
begin
if value>=0 then begin
Bits.lo := value;
Bits.hi := BSON_DECIMAL128_HI_INT64POS;
end else begin
Bits.lo := -value;
Bits.hi := BSON_DECIMAL128_HI_INT64NEG;
end;
end;
procedure TDecimal128.FromUInt32(value: cardinal);
begin
Bits.lo := value;
Bits.hi := BSON_DECIMAL128_HI_INT64POS;
end;
procedure TDecimal128.FromInt64(value: Int64);
begin
if value>=0 then begin
Bits.lo := value;
Bits.hi := BSON_DECIMAL128_HI_INT64POS;
end else begin
Bits.lo := -value;
Bits.hi := BSON_DECIMAL128_HI_INT64NEG;
end;
end;
procedure TDecimal128.FromQWord(value: QWord);
begin
Bits.lo := value;
Bits.hi := BSON_DECIMAL128_HI_INT64POS;
end;
function TDecimal128.FromFloat(const value: TSynExtended; precision: integer): boolean;
var tmp: shortstring;
begin
if precision<=0 then
precision := DOUBLE_PRECISION;
tmp[0] := AnsiChar(ExtendedToString(tmp,value,precision));
result := true;
case ExtendedToStringNan(tmp) of
seNan: SetSpecial(dsvNan);
seInf: SetSpecial(dsvPosInf);
seNegInf: SetSpecial(dsvNegInf);
else result := FromText(@tmp[1],ord(tmp[0]))<>dsvError;
end;
end;
procedure TDecimal128.FromCurr(const value: Currency);
begin // force exactly 4 decimals
if value<0 then begin
Bits.lo := -PInt64(@value)^;
Bits.hi := BSON_DECIMAL128_HI_CURRNEG;
end else begin
Bits.lo := PInt64(@value)^;
Bits.hi := BSON_DECIMAL128_HI_CURRPOS;
end;
end;
function TDecimal128.Equals(const other: TDecimal128): boolean;
begin
result := (Bits.lo=other.Bits.lo) and (Bits.hi=other.Bits.hi);
end;
function div128bits9digits(var value: THash128Rec): cardinal;
var r64: QWord;
i: integer;
begin
r64 := 0;
for i := 0 to high(value.c) do begin
r64 := r64 shl 32; // adjust remainder to match value of next dividend
inc(r64,value.c[i]); // add the divided to _rem
if r64=0 then
continue;
value.c[i] := r64 div 1000000000;
dec(r64,QWord(value.c[i])*1000000000);
end;
result := r64;
end;
{$ifdef CPU32DELPHI}
function x86div10(value: cardinal): cardinal;
asm // use fast reciprocal division for Delphi (FPC knows this optimization)
mov edx, 3435973837
mul edx
shr edx, 3
mov eax, edx
end;
{$endif}
function TDecimal128.ToText(out Buffer: TDecimal128Str): integer;
var dest: PUTF8Char;
exp, sciexp, signdig, radixpos: integer;
combi, biasedexp, signmsb, leastdig, fastdiv: cardinal;
digbuffer: array[0..35] of byte;
dig: PByte;
_128: THash128Rec;
j, k: integer;
procedure append(digits: integer);
var i: integer;
begin
for i := 0 to digits-1 do begin
dest^ := AnsiChar(dig^+ord('0'));
inc(dig);
inc(dest);
end;
end;
begin
dest := @Buffer;
if Int64(Bits.hi)<0 then begin
dest^ := '-';
inc(dest);
end;
if (Bits.lo=0) and (Bits.hi=0) then begin
dest^ := '0';
result := 1;
exit;
end;
combi := (Bits.c[3] shr 26) and $1f;
if combi shr 3=3 then
case combi of
30: begin
result := AppendRawUTF8ToBuffer(dest,DECIMAL128_SPECIAL_TEXT[dsvPosInf])-@Buffer;
exit;
end;
31: begin
result := AppendRawUTF8ToBuffer(@Buffer,DECIMAL128_SPECIAL_TEXT[dsvNan])-@Buffer;
exit;
end;
else begin
biasedexp := (Bits.c[3] shr 15) and $3fff;
signmsb := ((Bits.c[3] shr 14) and 1)+8;
end;
end
else begin
biasedexp := (Bits.c[3] shr 17) and $3fff;
signmsb := (Bits.c[3] shr 14) and 7;
end;
exp := biasedexp-BSON_DECIMAL128_EXPONENT_BIAS;
_128.c[0] := (Bits.c[3] and $3fff)+((signmsb and $0f)shl 14);
_128.c[1] := Bits.c[2];
_128.c[2] := Bits.c[1];
_128.c[3] := Bits.c[0];
FillCharFast(digbuffer,sizeof(digbuffer),0);
dig := @digbuffer;
if ((_128.lo=0) and (_128.hi=0)) or (_128.c[0]>=1 shl 17) then
signdig := 1 // non-canonical or zero -> 0
else begin
for k := 3 downto 0 do begin
if (_128.lo=0) and (_128.hi=0) then
break;
leastdig := div128bits9digits(_128);
if leastdig=0 then
continue;
for j := 8 downto 0 do begin
fastdiv := leastdig;
{$ifdef CPU32DELPHI}
leastdig := x86div10(leastdig); // Delphi compiler is not efficient
{$else}
leastdig := leastdig div 10; // FPC will use reciprocal division
{$endif}
digbuffer[k*9+j] := fastdiv-leastdig*10;
if leastdig=0 then
break;
end;
end;
signdig := 36; // 4*9 = k*j loops above
while dig^=0 do begin
dec(signdig);
inc(dig);
end;
end;
sciexp := signdig-1+exp;
if (sciexp<-6) or (exp>0) then begin // scientific format
dest^ := AnsiChar(dig^+ord('0'));
inc(dig);
inc(dest);
dec(signdig);
if signdig<>0 then begin
dest^ := '.';
inc(dest);
append(signdig);
end;
if sciexp>0 then
PWord(dest)^ := ord('E')+ord('+')shl 8 else begin
PWord(dest)^ := ord('E')+ord('-')shl 8;
sciexp := -sciexp;
end;
dest := AppendUInt32ToBuffer(dest+2,sciexp)
end else begin
if exp>=0 then // regular format with no decimal place
append(signdig)
else begin
radixpos := signdig+exp;
if radixpos>0 then // non-zero digits before radix
append(radixpos)
else begin
dest^ := '0'; // leading zero before radix point
inc(dest);
end;
dest^ := '.'; // radix char
inc(dest);
while radixpos<0 do begin // leading zeros after radix
dest^ := '0';
inc(dest);
inc(radixpos);
end;
append(signdig-radixpos);
end;
end;
result := dest-@Buffer;
end;
function TDecimal128.ToText: RawUTF8;
var tmp: TDecimal128Str;
begin
SetString(result,PAnsiChar(@tmp),ToText(tmp));
end;
procedure TDecimal128.ToText(var result: RawUTF8);
var tmp: TDecimal128Str;
begin
SetString(result,PAnsiChar(@tmp),ToText(tmp));
end;
procedure TDecimal128.AddText(W: TTextWriter);
var tmp: TDecimal128Str;
begin
W.AddNoJSONEscape(@tmp,ToText(tmp));
end;
function TDecimal128.ToVariant: variant;
begin
ToVariant(result);
end;
procedure TDecimal128.ToVariant(out result: variant);
begin
with TBSONVariantData(result) do begin
VType := BSONVariantType.VarType;
VKind := betDecimal128;
VBlob := nil;
SetString(RawByteString(VBlob),PAnsiChar(@Bits),sizeof(TDecimal128));
end;
end;
function TDecimal128.ToFloat: TSynExtended;
var tmp: TDecimal128Str;
begin
tmp[ToText(tmp)] := #0; // makes ASCIIZ temporary text conversion
result := GetExtended(@tmp);
end;
function TDecimal128.ToCurr: currency;
begin
ToCurr(result);
end;
procedure TDecimal128.ToCurr(out result: currency);
var tmp: TDecimal128Str;
res64: Int64 absolute result;
begin
if Bits.hi=BSON_DECIMAL128_HI_CURRNEG then // fast direct conversion e.g. FromCurr
res64 := -Bits.lo else
if Bits.hi=BSON_DECIMAL128_HI_CURRPOS then
res64 := Bits.lo else begin
tmp[ToText(tmp)] := #0; // makes ASCIIZ temporary text conversion
res64 := StrToCurr64(@tmp);
end;
end;
function TDecimal128.FromText(text: PUTF8Char; textlen: integer): TDecimal128SpecialValue;
var P,PEnd: PUTF8Char;
c: AnsiChar;
flags: set of (negative, signed, radix, nonzero);
digits: array[0..BSON_DECIMAL128_MAX_DIGITS-1] of byte;
firstnon0, digread, digstored, digcount, radixpos,
digfirst, diglast, exp, signdig, i: integer;
signhi, signlo: QWord;
biasedexp: cardinal;
sign: THash128Rec;
begin
for result := dsvNan to dsvNegInf do
if IdemPropNameU(DECIMAL128_SPECIAL_TEXT[result],text,textlen) then begin
Bits := D128[result];
exit; // fast recognition of special text values (including '0')
end;
Bits := D128[dsvError];
result := dsvError;
if (textlen=0) or (text=nil) then
exit;
P := text;
PEnd := text+textlen;
flags := [];
if P^ in ['+','-'] then begin
include(flags,signed);
if P^='-' then
include(flags,negative);
inc(P);
end;
digcount := 0;
digread := 0;
digstored := 0;
radixpos := 0;
firstnon0 := 0;
exp := 0;
while P<PEnd do begin
c := P^;
case c of
'.':
if radix in flags then // duplicated '.'
exit else begin
include(flags,radix);
inc(P);
continue;
end;
'0'..'9':
if digstored<BSON_DECIMAL128_MAX_DIGITS then
if (c>'0') or (nonzero in flags) then begin
if not(nonzero in flags) then begin
firstnon0 := digread;
include(flags,nonzero);
end;
digits[digstored] := ord(c)-ord('0');
inc(digstored);
end;
'E','e': begin
inc(P);
if P>=PEnd then
exit;
exp := GetInteger(P,PEnd);
break;
end;
else exit;
end;
if nonzero in flags then
inc(digcount);
if radix in flags then
inc(radixpos);
inc(digread);
inc(P);
end;
if digread=0 then
exit;
digfirst := 0;
if digstored=0 then begin // value is zero
diglast := 0;
digits[0] := 0;
digcount := 1;
digstored := 1;
signdig := 0;
end else begin
diglast := digstored-1;
signdig := digcount;
// handle trailing zeros as non-significant
while text[firstnon0+signdig-1+ord(radix in flags)+ord(signed in flags)]='0' do
dec(signdig);
end;
if (exp<=radixpos) and (radixpos-exp>1 shl 14) then
exp := BSON_DECIMAL128_EXPONENT_MIN else
dec(exp,radixpos);
while exp>BSON_DECIMAL128_EXPONENT_MAX do begin
inc(diglast);
digits[diglast] := 0;
if diglast-digfirst>BSON_DECIMAL128_MAX_DIGITS then
if signdig=0 then begin // zero clamping is allowed
exp := BSON_DECIMAL128_EXPONENT_MAX;
break;
end else
exit; // overflow is not permitted
dec(exp);
end;
while (exp<BSON_DECIMAL128_EXPONENT_MIN) or (digstored<digcount) do begin
if diglast=0 then
if signdig=0 then begin // zero clamping
exp := BSON_DECIMAL128_EXPONENT_MIN;
break;
end else
exit; // overflow
if digstored<digcount then
if (text[digcount-1+ord(signed in flags)+ord(radix in flags)]<>'0') and
(signdig<>0) then
exit else // overflow
dec(digcount) else // adjust to non stored digits
if digits[diglast]<>0 then
exit else // inexact rounding
dec(diglast); // adjust to round
if exp<BSON_DECIMAL128_EXPONENT_MAX then
inc(exp) else
exit;
end;
if diglast-digfirst+1<signdig then
if text[firstnon0+diglast+ord(signed in flags)+ord(radix in flags)]<>'0' then
exit; // inexact rouding
signhi := 0;
signlo := 0;
if signdig<>0 then // if not zero
if diglast-digfirst<17 then
for i := digfirst to diglast do
{$ifdef CPU32DELPHI} // use "shl" under x86 to avoid slower "call _llmul"
inc(signlo,signlo+signlo shl 3+digits[i]) else begin
for i := digfirst to diglast-17 do
inc(signhi,signhi+signhi shl 3+digits[i]);
for i := diglast-16 to diglast do
inc(signlo,signlo+signlo shl 3+digits[i]);
{$else}
signlo := signlo*10+digits[i] else begin
for i := digfirst to diglast-17 do
signhi := signhi*10+digits[i];
for i := diglast-16 to diglast do
signlo := signlo*10+digits[i];
{$endif}
end;
if signhi=0 then begin
sign.L := signlo;
sign.H := 0;
end else begin
mul64x64(signhi,100000000000000000,sign);
inc(sign.L,signlo);
{$ifdef FPC}
if sign.L<signlo then
{$else} // manual QWord processs (for oldest Delphi compilers)
if (sign.c1<TQWordRec(signlo).H) or
((sign.c1=TQWordRec(signlo).H) and (sign.c0<TQWordRec(signlo).L)) then
{$endif}
inc(sign.H);
end;
biasedexp := exp+BSON_DECIMAL128_EXPONENT_BIAS;
if (sign.H shr 49)and 1<>0 then
Bits.hi := (3 shl 61) or (QWord(biasedexp and $3fff)shl 47) or
(sign.H and $7fffffffffff) else
Bits.hi := (QWord(biasedexp and $3fff)shl 49) or
(sign.H and $1ffffffffffff);
Bits.lo := sign.L;
if negative in flags then
Bits.c[3] := Bits.c[3] or $80000000;
result := dsvValue;
end;
function TDecimal128.FromText(const text: RawUTF8): TDecimal128SpecialValue;
begin
result := FromText(pointer(text),length(text));
end;
function TDecimal128.FromVariant(const value: variant): boolean;
var txt: RawUTF8;
wasString: boolean;
bson: TBSONVariantData absolute value;
v64: Int64;
begin
if bson.VType=varByRef or varVariant then begin
result := FromVariant(PVariant(TVarData(value).VPointer)^);
exit;
end;
if (bson.VType=BSONVariantType.VarType) and (bson.VKind=betDecimal128) then
Bits := PDecimal128(bson.VBlob)^.Bits else
if VariantToInt64(value,v64) then
FromInt64(v64) else
if bson.VType=varCurrency then
FromCurr(TVarData(value).VCurrency) else begin
VariantToUTF8(value,txt,wasString);
result := FromText(txt)<>dsvError;
exit;
end;
result := true;
end;
initialization
Assert(sizeof(TDecimal128)=16);
Assert(ord(betEof)=$00);
Assert(ord(betInt64)=$12);
Assert(ord(betDecimal128)=$13);
Assert(ord(bbtGeneric)=$00);
Assert(ord(bbtMD5)=$05);
Assert(ord(bbtUser)=$80);
Assert(sizeof(TBSONObjectID)=12);
Assert(sizeof(TBSONVariantData)=sizeof(variant));
Assert(sizeof(TMongoReplyHeader)=36);
// ensure TDocVariant and TBSONVariant custom types are registered
if DocVariantType=nil then
DocVariantType := SynRegisterCustomVariantType(TDocVariant) as TDocVariant;
BSONVariantType := SynRegisterCustomVariantType(TBSONVariant) as TBSONVariant;
InitBSONObjectIDComputeNew;
finalization
DeleteCriticalSection(GlobalBSONObjectID.Section);
end.
| 40.62631 | 115 | 0.695713 |
47cb935406ce012e52639b62202c88f79aa2736c | 35,688 | pas | Pascal | iscbase/database/dbc/ZDbcASA.pas | isyscore/isc-fpbase | ce2469c977eba901005982dc7f89fee2d0718f76 | [
"MIT"
]
| 3 | 2021-06-10T12:33:29.000Z | 2021-12-13T06:59:48.000Z | iscbase/database/dbc/ZDbcASA.pas | isyscore/isc-fpbase | ce2469c977eba901005982dc7f89fee2d0718f76 | [
"MIT"
]
| null | null | null | iscbase/database/dbc/ZDbcASA.pas | isyscore/isc-fpbase | ce2469c977eba901005982dc7f89fee2d0718f76 | [
"MIT"
]
| null | null | null | {*********************************************************}
{ }
{ Zeos Database Objects }
{ Sybase SQL Anywhere Connectivity Classes }
{ }
{ Originally written by Sergey Merkuriev }
{ }
{*********************************************************}
{@********************************************************}
{ Copyright (c) 1999-2020 Zeos Development Group }
{ }
{ License Agreement: }
{ }
{ This library is distributed in the hope that it will be }
{ useful, but WITHOUT ANY WARRANTY; without even the }
{ implied warranty of MERCHANTABILITY or FITNESS FOR }
{ A PARTICULAR PURPOSE. See the GNU Lesser General }
{ Public License for more details. }
{ }
{ The source code of the ZEOS Libraries and packages are }
{ distributed under the Library GNU General Public }
{ License (see the file COPYING / COPYING.ZEOS) }
{ with the following modification: }
{ As a special exception, the copyright holders of this }
{ library give you permission to link this library with }
{ independent modules to produce an executable, }
{ regardless of the license terms of these independent }
{ modules, and to copy and distribute the resulting }
{ executable under terms of your choice, provided that }
{ you also meet, for each linked independent module, }
{ the terms and conditions of the license of that module. }
{ An independent module is a module which is not derived }
{ from or based on this library. If you modify this }
{ library, you may extend this exception to your version }
{ of the library, but you are not obligated to do so. }
{ If you do not wish to do so, delete this exception }
{ statement from your version. }
{ }
{ }
{ The project web site is located on: }
{ https://zeoslib.sourceforge.io/ (FORUM) }
{ http://sourceforge.net/p/zeoslib/tickets/ (BUGTRACKER)}
{ svn://svn.code.sf.net/p/zeoslib/code-0/trunk (SVN) }
{ }
{ http://www.sourceforge.net/projects/zeoslib. }
{ }
{ }
{ Zeos Development Group. }
{********************************************************@}
unit ZDbcASA;
interface
{$I ZDbc.inc}
{$IFNDEF ZEOS_DISABLE_ASA}
uses
ZCompatibility, Classes, {$IFDEF MSEgui}mclasses,{$ENDIF}
SysUtils,
ZDbcIntfs, ZDbcConnection, ZPlainASADriver, ZTokenizer, ZDbcGenericResolver,
ZGenericSqlAnalyser, ZDbcLogging;
type
{** Implements a ASA Database Driver. }
TZASADriver = class(TZAbstractDriver)
public
constructor Create; override;
function Connect(const Url: TZURL): IZConnection; override;
function GetMajorVersion: Integer; override;
function GetMinorVersion: Integer; override;
function GetTokenizer: IZTokenizer; override;
function GetStatementAnalyser: IZStatementAnalyser; override;
end;
{** Represents a ASA specific connection interface. }
IZASAConnection = interface (IZConnection)
['{FAAAFCE0-F550-4098-96C6-580145813EBF}']
function GetDBHandle: PZASASQLCA;
function GetPlainDriver: TZASAPlainDriver;
function GetByteBufferAddress: PByteBuffer;
procedure HandleErrorOrWarning(LoggingCategory: TZLoggingCategory;
const Msg: SQLString; const Sender: IImmediatelyReleasable);
// procedure CreateNewDatabase(const SQL: String);
end;
{** Implements ASA Database Connection. }
{ TZASAConnection }
TZASAConnection = class(TZAbstractSingleTxnConnection, IZConnection,
IZASAConnection, IZTransaction)
private
FSQLCA: TZASASQLCA;
FHandle: PZASASQLCA;
FPlainDriver: TZASAPlainDriver;
FHostVersion: Integer;
FLastWarning: EZSQLWarning;
FClientLanguageCP: Word;
private
function DetermineASACharSet: String;
procedure DetermineHostVersion;
procedure DetermineClientLanguageCP;
procedure SetOption(Temporary: Integer; const LogMsg: String;
const Option, Value: RawByteString; LoggingCategory: TZLoggingCategory);
protected
procedure InternalClose; override;
/// <summary>Immediately execute a query and do nothing with the results.</summary>
/// <remarks>A new driver needs to implement one of the overloads.</remarks>
/// <param>"SQL" a raw encoded query to be executed.</param>
/// <param>"LoggingCategory" the LoggingCategory for the Logging listeners.</param>
procedure ExecuteImmediat(const SQL: RawByteString; LoggingCategory: TZLoggingCategory); override;
public
function GetDBHandle: PZASASQLCA;
function GetPlainDriver: TZASAPlainDriver;
procedure HandleErrorOrWarning(LoggingCategory: TZLoggingCategory;
const Msg: SQLString; const Sender: IImmediatelyReleasable);
public
procedure AfterConstruction; override;
public
/// <summary>Creates a <c>Statement</c> interface for sending SQL statements
/// to the database. SQL statements without parameters are normally
/// executed using Statement objects. If the same SQL statement
/// is executed many times, it is more efficient to use a
/// <c>PreparedStatement</c> object. Result sets created using the returned
/// <c>Statement</c> interface will by default have forward-only type and
/// read-only concurrency.</summary>
/// <param>Info a statement parameters.</param>
/// <returns>A new Statement interface</returns>
function CreateStatementWithParams(Info: TStrings): IZStatement;
/// <summary>Creates a <code>CallableStatement</code> object for calling
/// database stored procedures. The <code>CallableStatement</code> object
/// provides methods for setting up its IN and OUT parameters, and methods
/// for executing the call to a stored procedure. Note: This method is
/// optimized for handling stored procedure call statements. Some drivers
/// may send the call statement to the database when the method
/// <c>prepareCall</c> is done; others may wait until the
/// <c>CallableStatement</c> object is executed. This has no direct effect
/// on users; however, it does affect which method throws certain
/// EZSQLExceptions. Result sets created using the returned
/// IZCallableStatement will have forward-only type and read-only
/// concurrency, by default.</summary>
/// <param>"Name" a procedure or function name.</param>
/// <param>"Params" a statement parameters list.</param>
/// <returns> a new IZCallableStatement interface containing the
/// pre-compiled SQL statement </returns>
function PrepareCallWithParams(const Name: String; Params: TStrings):
IZCallableStatement;
/// <summary>Creates a <c>PreparedStatement</c> interface for sending
/// parameterized SQL statements to the database. A SQL statement with
/// or without IN parameters can be pre-compiled and stored in a
/// PreparedStatement object. This object can then be used to efficiently
/// execute this statement multiple times.
/// Note: This method is optimized for handling parametric SQL statements
/// that benefit from precompilation. If the driver supports
/// precompilation, the method <c>prepareStatement</c> will send the
/// statement to the database for precompilation. Some drivers may not
/// support precompilation. In this case, the statement may not be sent to
/// the database until the <c>PreparedStatement</c> is executed. This has
/// no direct effect on users; however, it does affect which method throws
/// certain SQLExceptions. Result sets created using the returned
/// PreparedStatement will have forward-only type and read-only
/// concurrency, by default.</summary>
/// <param>"SQL" a SQL statement that may contain one or more '?' IN
/// parameter placeholders.</param>
/// <param> Info a statement parameter list.</param>
/// <returns> a new PreparedStatement object containing the
/// optional pre-compiled statement</returns>
function PrepareStatementWithParams(const SQL: string; Info: TStrings):
IZPreparedStatement;
/// <summary>If the current transaction is saved the current savepoint get's
/// released. Otherwise makes all changes made since the previous commit/
/// rollback permanent and releases any database locks currently held by
/// the Connection. This method should be used only when auto-commit mode
/// has been disabled. See setAutoCommit.</summary>
procedure Commit;
/// <summary>If the current transaction is saved the current savepoint get's
/// rolled back. Otherwise drops all changes made since the previous
/// commit/rollback and releases any database locks currently held by this
/// Connection. This method should be used only when auto-commit has been
/// disabled. See setAutoCommit.</summary>
procedure Rollback;
/// <summary>Sets this connection's auto-commit mode. If a connection is in
/// auto-commit mode, then all its SQL statements will be executed and
/// committed as individual transactions. Otherwise, its SQL statements are
/// grouped into transactions that are terminated by a call to either the
/// method <c>commit</c> or the method <c>rollback</c>. By default, new
/// connections are in auto-commit mode. The commit occurs when the
/// statement completes or the next execute occurs, whichever comes first.
/// In the case of statements returning a ResultSet, the statement
/// completes when the last row of the ResultSet has been retrieved or the
/// ResultSet has been closed. In advanced cases, a single statement may
/// return multiple results as well as output parameter values. In these
/// cases the commit occurs when all results and output parameter values
/// have been retrieved. It is not recommented setting autoCommit to false
/// because a call to either the method <c>commit</c> or the method
/// <c>rollback</c> will restart the transaction. It's use full only if
/// repeately many opertions are done and no startTransaction is intended
/// to use. If you change mode to true the current Transaction and it's
/// nested SavePoints are committed then.</summary>
/// <param>"Value" true enables auto-commit; false disables auto-commit.</param>
procedure SetAutoCommit(Value: Boolean); override;
/// <summary>Attempts to change the transaction isolation level to the one
/// given. The constants defined in the interface <c>Connection</c> are the
/// possible transaction isolation levels. Note: This method cannot be
/// called while in the middle of a transaction.
/// <param>"value" one of the TRANSACTION_* isolation values with the
/// exception of TRANSACTION_NONE; some databases may not support other
/// values. See DatabaseInfo.SupportsTransactionIsolationLevel</param>
procedure SetTransactionIsolation(Level: TZTransactIsolationLevel); override;
/// <summary>Starts transaction support or saves the current transaction.
/// If the connection is closed, the connection will be opened.
/// If a transaction is underway a nested transaction or a savepoint will
/// be spawned. While the tranaction(s) is/are underway the AutoCommit
/// property is set to False. Ending up the transaction with a
/// commit/rollback the autocommit property will be restored if changing
/// the autocommit mode was triggered by a starttransaction call.</summary>
/// <returns>Returns the current txn-level. 1 means a expicit transaction
/// was started. 2 means the transaction was saved. 3 means the previous
/// savepoint got saved too and so on.</returns>
function StartTransaction: Integer;
procedure Open; override;
function GetWarnings: EZSQLWarning; override;
procedure ClearWarnings; override;
/// <summary>Returns the ServicerProvider for this connection.</summary>
/// <returns>the ServerProvider</returns>
function GetServerProvider: TZServerProvider; override;
/// <summary>Creates a generic tokenizer interface.</summary>
/// <returns>a created generic tokenizer object.</returns>
function GetTokenizer: IZTokenizer;
/// <summary>Creates a generic statement analyser object.</summary>
/// <returns>a created generic tokenizer object as interface.</returns>
function GetStatementAnalyser: IZStatementAnalyser;
function GetHostVersion: Integer; override;
end;
{** Implements a specialized cached resolver for ASA. }
TZASACachedResolver = class(TZGenerateSQLCachedResolver)
end;
var
{** The common driver manager object. }
ASADriver: IZDriver;
{$ENDIF ZEOS_DISABLE_ASA}
implementation
{$IFNDEF ZEOS_DISABLE_ASA}
uses
ZFastCode, ZDbcASAMetadata, ZDbcASAStatement, ZSybaseToken,
ZSybaseAnalyser, ZSysUtils, ZDbcProperties, ZEncoding, ZMessages
{$IFDEF WITH_UNITANSISTRINGS}, AnsiStrings{$ENDIF};
{ TZASADriver }
{**
Attempts to make a database connection to the given URL.
The driver should return "null" if it realizes it is the wrong kind
of driver to connect to the given URL. This will be common, as when
the JDBC driver manager is asked to connect to a given URL it passes
the URL to each loaded driver in turn.
<P>The driver should raise a SQLException if it is the right
driver to connect to the given URL, but has trouble connecting to
the database.
<P>The java.util.Properties argument can be used to passed arbitrary
string tag/value pairs as connection arguments.
Normally at least "user" and "password" properties should be
included in the Properties.
@param url the URL of the database to which to connect
@param info a list of arbitrary string tag/value pairs as
connection arguments. Normally at least a "user" and
"password" property should be included.
@return a <code>Connection</code> object that represents a
connection to the URL
}
function TZASADriver.Connect(const Url: TZURL): IZConnection;
begin
Result := TZASAConnection.Create(Url);
end;
{**
Constructs this object with default properties.
}
constructor TZASADriver.Create;
begin
inherited Create;
AddSupportedProtocol(AddPlainDriverToCache(TZASAPlainDriver.Create));
end;
{**
Gets the driver's major version number. Initially this should be 1.
@return this driver's major version number
}
function TZASADriver.GetMajorVersion: Integer;
begin
Result := 1;
end;
{**
Gets the driver's minor version number. Initially this should be 0.
@return this driver's minor version number
}
function TZASADriver.GetMinorVersion: Integer;
begin
Result := 0;
end;
{**
Gets a SQL syntax tokenizer.
@returns a SQL syntax tokenizer object.
}
function TZASADriver.GetTokenizer: IZTokenizer;
begin
Result := TZSybaseTokenizer.Create; { thread save! Allways return a new Tokenizer! }
end;
{**
Creates a statement analyser object.
@returns a statement analyser object.
}
function TZASADriver.GetStatementAnalyser: IZStatementAnalyser;
begin
Result := TZSybaseStatementAnalyser.Create; { thread save! Allways return a new Analyser! }
end;
const
ASATIL: array[TZTransactIsolationLevel] of RawByteString = ('1','0','1','2','3');
SQLDA_sqldaid: PAnsiChar = 'SQLDA ';
var
PInt64_SQLDA_sqldaid: PInt64 absolute SQLDA_sqldaid;
{ TZASAConnection }
{**
Releases a Connection's database and JDBC resources
immediately instead of waiting for
them to be automatically released.
<P><B>Note:</B> A Connection is automatically closed when it is
garbage collected. Certain fatal errors also result in a closed
Connection.
}
procedure TZASAConnection.InternalClose;
begin
if Closed or (not Assigned(PlainDriver))then
Exit;
FSavePoints.Clear;
try
if AutoCommit
then FPlainDriver.dbpp_commit(FHandle, 0)
else begin
AutoCommit := not FRestartTransaction;
FPlainDriver.dbpp_rollback(FHandle, 0);
end;
if FHandle.sqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(lcTransaction, 'Close transaction', IImmediatelyReleasable(FWeakImmediatRelPtr));
finally
FPlainDriver.db_string_disconnect(FHandle, nil);
if FHandle.sqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(lcDisconnect, 'Disconnect from database', IImmediatelyReleasable(FWeakImmediatRelPtr));
FHandle := nil;
if FPlainDriver.db_fini(@FSQLCA) = 0 then begin
DriverManager.LogError(lcConnect, URL.Protocol, 'Finalizing SQLCA',
0, 'Error closing SQLCA');
raise EZSQLException.CreateWithCode(0, 'Error closing SQLCA');
end;
if DriverManager.HasLoggingListener then
DriverManager.LogMessage(lcDisconnect, URL.Protocol,
'DISCONNECT FROM "'+URL.Database+'"');
end;
end;
procedure TZASAConnection.Commit;
var S: RawByteString;
begin
if Closed then
raise EZSQLException.Create(SConnectionIsNotOpened);
if AutoCommit then
raise EZSQLException.Create(SCannotUseCommit);
if FSavePoints.Count > 0 then begin
S := cReleaseSP+{$IFDEF UNICODE}UnicodeStringToAscii7{$ENDIF}(FSavePoints[FSavePoints.Count-1]);
ExecuteImmediat(S, lcTransaction);
FSavePoints.Delete(FSavePoints.Count-1);
end else begin
FPlainDriver.dbpp_commit(FHandle, 0);
if FHandle.SqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(lcTransaction, sCommitMsg, IImmediatelyReleasable(FWeakImmediatRelPtr))
else if DriverManager.HasLoggingListener then
DriverManager.LogMessage(lcTransaction, URL.Protocol, sCommitMsg);
//SetOption(1, nil, 'CHAINED', 'ON');
AutoCommit := True;
if FRestartTransaction then
StartTransaction;
end;
end;
function TZASAConnection.CreateStatementWithParams(Info: TStrings): IZStatement;
begin
if IsClosed then Open;
Result := TZASAStatement.Create(Self, Info);
end;
{**
Get database connection handle.
@return database handle
}
function TZASAConnection.GetDBHandle: PZASASQLCA;
begin
Result := FHandle;
end;
{**
Gets the host's full version number. Initially this should be 0.
The format of the version returned must be XYYYZZZ where
X = Major version
YYY = Minor version
ZZZ = Sub version
@return this server's full version number
}
function TZASAConnection.GetHostVersion: Integer;
begin
Result := FHostVersion;
end;
function TZASAConnection.GetPlainDriver: TZASAPlainDriver;
begin
Result := FPlainDriver;
end;
{**
Checks for possible sql errors or warings.
@param LogCategory a logging category.
@param Msg a logging message.
@param Sender the calling object to handle connection loss
}
procedure TZASAConnection.HandleErrorOrWarning(
LoggingCategory: TZLoggingCategory; const Msg: SQLString;
const Sender: IImmediatelyReleasable);
var err_len: Integer;
SQLState, FormatStr: String;
ErrCode: an_sql_code;
Error: EZSQLThrowable;
ExeptionClass: EZSQLThrowableClass;
P: PAnsiChar;
{$IFNDEF UNICODE}excCP: Word;{$ENDIF}
begin
ErrCode := FHandle.SqlCode;
if (ErrCode = SQLE_NOERROR) or //Nothing todo
(ErrCode = SQLE_NOTFOUND) then //no line found
Exit;
P := @FByteBuffer[0];
PByte(P)^ := 0;
{$IFNDEF UNICODE}
excCP := {$IFDEF WITH_DEFAULTSYSTEMCODEPAGE}DefaultSystemCodePage{$ELSE}
{$IFDEF LCL}zCP_UTF8{$ELSE}zOSCodePage{$ENDIF}{$ENDIF};
{$ENDIF}
P := FPlainDriver.sqlError_Message(FHandle, P, SizeOf(TByteBuffer)-1);
err_len := ZFastCode.StrLen(P);
{$IFDEF UNICODE}
SQLState := USASCII7ToUnicodeString(@FHandle.sqlState[0], 5);
FLogMessage := PRawToUnicode(P, err_Len, FClientLanguageCP);
{$ELSE}
SQLState := '';
ZSetString(PAnsiChar(@FHandle.sqlState[0]), 5, SQLState);
FLogMessage := '';
if excCP <> FClientLanguageCP
then PRawToRawConvert(P, err_len, FClientLanguageCP, excCP, FLogMessage)
else System.SetString(FLogMessage, P, err_Len);
{$ENDIF}
if DriverManager.HasLoggingListener then
LogError(LoggingCategory, ErrCode, Sender, Msg, FLogMessage);
if ErrCode > 0 //that's a Warning
then ExeptionClass := EZSQLWarning
else if (ErrCode = SQLE_CONNECTION_NOT_FOUND) or
(ErrCode = SQLE_CONNECTION_TERMINATED) or (ErrCode = SQLE_COMMUNICATIONS_ERROR)
then ExeptionClass := EZSQLConnectionLost
else ExeptionClass := EZSQLException;
if AddLogMsgToExceptionOrWarningMsg and (Msg <> '') then
if LoggingCategory in [lcExecute, lcPrepStmt, lcExecPrepStmt]
then FormatStr := SSQLError3
else FormatStr := SSQLError4
else FormatStr := SSQLError2;
if AddLogMsgToExceptionOrWarningMsg and (Msg <> '')
then FLogMessage := Format(FormatStr, [FLogMessage, ErrCode, Msg])
else FLogMessage := Format(FormatStr, [FLogMessage, ErrCode]);
Error := ExeptionClass.CreateWithCodeAndStatus(ErrCode, SQLState, FLogMessage);
FLogMessage := '';
if ErrCode > 0 then begin//that's a Warning
ClearWarnings;
if not RaiseWarnings then begin
FLastWarning := EZSQLWarning(Error);
Error := nil;
end;
end else if (ErrCode = SQLE_CONNECTION_NOT_FOUND) or (ErrCode = SQLE_CONNECTION_TERMINATED) or
(ErrCode = SQLE_COMMUNICATIONS_ERROR) then begin
if (Sender <> nil)
then Sender.ReleaseImmediat(Sender, EZSQLConnectionLost(Error))
else ReleaseImmediat(Self, EZSQLConnectionLost(Error));
end;
if Error <> nil then
raise Error;
end;
function TZASAConnection.GetServerProvider: TZServerProvider;
begin
Result := spASA;
end;
function TZASAConnection.GetStatementAnalyser: IZStatementAnalyser;
begin
Result := TZSybaseStatementAnalyser.Create;
end;
function TZASAConnection.GetTokenizer: IZTokenizer;
begin
Result := TZSybaseTokenizer.Create;
end;
{**
Opens a connection to database server with specified parameters.
}
procedure TZASAConnection.Open;
var
ConnectionString, Links: string;
{$IFDEF UNICODE}
RawTemp: RawByteString;
{$ENDIF UNICODE}
begin
if not Closed then
Exit;
FClientLanguageCP := ZOSCodePage; //init
FHandle := nil;
ConnectionString := '';
try
if FPlainDriver.db_init(@FSQLCA) = 0 then
begin
DriverManager.LogError(lcConnect, URL.Protocol, 'Inititalizing SQLCA',
0, 'Error initializing SQLCA');
raise EZSQLException.Create('Error initializing SQLCA');
end;
FHandle := @FSQLCA;
if HostName <> '' then
ConnectionString := ConnectionString + 'ENG="' + HostName + '"; ';
if User <> '' then
ConnectionString := ConnectionString + 'UID="' + User + '"; ';
if Password <> '' then
ConnectionString := ConnectionString + 'PWD="' + Password + '"; ';
if Database <> '' then
begin
if CompareText(ExtractFileExt(Database), '.db') = 0 then
ConnectionString := ConnectionString + 'DBF="' + Database + '"; '
else
ConnectionString := ConnectionString + 'DBN="' + Database + '"; ';
end;
Links := '';
if Info.Values[ConnProps_CommLinks] <> ''
then Links := 'CommLinks=' + Info.Values[ConnProps_CommLinks];
if Info.Values[ConnProps_Links] <> ''
then Links := 'LINKS=' + Info.Values[ConnProps_Links];
if (Links = '') and (Port <> 0)
then Links := 'LINKS=tcpip(PORT=' + ZFastCode.IntToStr(Port) + ')';
if Links <> ''
then ConnectionString := ConnectionString + Links + '; ';
{$IFDEF UNICODE}
RawTemp := ZUnicodeToRaw(ConnectionString, ZOSCodePage);
if FPlainDriver.db_string_connect(FHandle, Pointer(RawTemp)) <> 0 then
{$ELSE}
if FPlainDriver.db_string_connect(FHandle, Pointer(ConnectionString)) <> 0 then
{$ENDIF}
FLogMessage := Format(SConnect2AsUser, [URL.Database, URL.UserName]);
if FHandle.SqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(lcConnect, FLogMessage, IImmediatelyReleasable(FWeakImmediatRelPtr))
else if DriverManager.HasLoggingListener then
DriverManager.LogMessage(lcConnect, URL.Protocol, FLogMessage);
if (FClientCodePage <> '' ) then begin
FLogMessage := 'Set client characterset to: '+FClientCodePage;
{$IFDEF UNICODE}
RawTemp := ZUnicodeToRaw(FClientCodePage, ZOSCodePage);
Move(Pointer(RawTemp)^, FByteBuffer[0], Length(RawTemp)+1);
if (FPlainDriver.db_change_char_charset(FHandle, @FByteBuffer[0]) = 0 ) or
(FPlainDriver.db_change_nchar_charset(FHandle, @FByteBuffer[0]) = 0 ) then
{$ELSE}
if (FPlainDriver.db_change_char_charset(FHandle, Pointer(FClientCodePage)) = 0 ) or
(FPlainDriver.db_change_nchar_charset(FHandle, Pointer(FClientCodePage)) = 0 ) then
{$ENDIF}
HandleErrorOrWarning(lcConnect, FLogMessage, IImmediatelyReleasable(FWeakImmediatRelPtr))
else if DriverManager.HasLoggingListener then
DriverManager.LogMessage(lcOther, URL.Protocol, FLogMessage);
end;
inherited Open;
finally
if Closed and (FHandle <> nil) then begin
FPlainDriver.db_fini(FHandle);
FHandle := nil;
end;
end;
if FClientCodePage = '' then
CheckCharEncoding(DetermineASACharSet);
DetermineClientLanguageCP;
DetermineHostVersion;
if FHostVersion >= 17000000 then //chained is deprecated On is comparable with AutoCommit=off
SetOption(1, 'SET OPTION chained = "on"', 'chained', 'On', lcTransaction);
{ Sets an auto commit mode. }
AutoCommit := not AutoCommit;
SetAutoCommit(not AutoCommit);
end;
{**
Returns the first warning reported by calls on this Connection.
<P><B>Note:</B> Subsequent warnings will be chained to this
SQLWarning.
@return the first SQLWarning or null
}
function TZASAConnection.GetWarnings: EZSQLWarning;
begin
Result := FLastWarning;
end;
procedure TZASAConnection.AfterConstruction;
begin
FPlainDriver := PlainDriver.GetInstance as TZASAPlainDriver;
FMetadata := TZASADatabaseMetadata.Create(Self, URL);
inherited AfterConstruction;
end;
{**
Clears all warnings reported for this <code>Connection</code> object.
After a call to this method, the method <code>getWarnings</code>
returns null until a new warning is reported for this Connection.
}
procedure TZASAConnection.ClearWarnings;
begin
FreeAndNil(FLastWarning);
end;
function TZASAConnection.PrepareCallWithParams(const Name: String;
Params: TStrings): IZCallableStatement;
begin
if IsClosed then Open;
Result := TZASACallableStatement.Create(Self, Name, Params);
end;
function TZASAConnection.PrepareStatementWithParams(const SQL: string;
Info: TStrings): IZPreparedStatement;
begin
if IsClosed then Open;
Result := TZASAPreparedStatement.Create(Self, SQL, Info);
end;
procedure TZASAConnection.Rollback;
var S: RawByteString;
begin
if Closed then
raise EZSQLException.Create(SConnectionIsNotOpened);
if AutoCommit then
raise EZSQLException.Create(SCannotUseRollback);
if FSavePoints.Count > 0 then begin
S := cRollbackToSP+{$IFDEF UNICODE}UnicodeStringToAscii7{$ENDIF}(FSavePoints[FSavePoints.Count-1]);
ExecuteImmediat(S, lcTransaction);
FSavePoints.Delete(FSavePoints.Count-1);
end else begin
FPlainDriver.dbpp_rollback(FHandle, 0);
if FHandle.SqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(lcTransaction, sRollbackMsg, IImmediatelyReleasable(FWeakImmediatRelPtr))
else if DriverManager.HasLoggingListener then
DriverManager.LogMessage(lcTransaction, URL.Protocol, sRollbackMsg);
// SetOption(1, nil, 'CHAINED', 'ON');
AutoCommit := True;
if FRestartTransaction then
StartTransaction;
end;
end;
procedure TZASAConnection.SetAutoCommit(Value: Boolean);
begin
if Value <> AutoCommit then begin
FRestartTransaction := AutoCommit;
if Closed
then AutoCommit := Value
else if Value then begin
FSavePoints.Clear;
if FHostVersion >= 17000000
then SetOption(1, 'SET OPTION <USER>.AUTO_COMMIT = On', 'AUTO_COMMIT', 'On', lcTransaction)
else SetOption(1, 'SET OPTION <USER>.chained = Off', 'chained', 'Off', lcTransaction);
AutoCommit := True;
end else
StartTransaction;
end;
end;
procedure TZASAConnection.SetOption(Temporary: Integer; const LogMsg: String;
const Option, Value: RawByteString; LoggingCategory: TZLoggingCategory);
var
SQLDA: PASASQLDA;
Sz: Integer;
begin
if Assigned(FHandle) then
begin
Sz := SizeOf(TASASQLDA) - (32767 * SizeOf(TZASASQLVAR));
SQLDA := AllocMem(Sz);
try
PInt64(@SQLDA.sqldaid[0])^ := PInt64_SQLDA_sqldaid^;
SQLDA.sqldabc := Sz;
SQLDA.sqln := 1;
SQLDA.sqld := 1;
SQLDA.sqlVar[0].sqlType := DT_STRING;
SQLDA.sqlVar[0].sqlLen := Length(Value){$IFNDEF WITH_TBYTES_AS_RAWBYTESTRING}+1{$ENDIF};
SQLDA.sqlVar[0].sqlData := Pointer(Value);
FPlainDriver.dbpp_setoption(FHandle, Temporary, nil, Pointer(Option), SQLDA);
if FHandle.SqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(LoggingCategory, LogMsg, IImmediatelyReleasable(FWeakImmediatRelPtr))
else if DriverManager.HasLoggingListener then
DriverManager.LogMessage(LoggingCategory, URL.Protocol, LogMsg);
finally
FreeMem(SQLDA);
end;
end;
end;
procedure TZASAConnection.SetTransactionIsolation(
Level: TZTransactIsolationLevel);
begin
if (Level = tiNone) then
Level := tiReadUnCommitted;
if Level <> TransactIsolationLevel then begin
if not IsClosed then
SetOption(1, 'SET OPTION <USER>.ISOLATION_LEVEL = '+ZFastCode.IntToStr(Ord(Level)),
'ISOLATION_LEVEL', ASATIL[Level], lcTransaction);
TransactIsolationLevel := Level;
end;
end;
function TZASAConnection.StartTransaction: Integer;
var S: String;
begin
if Closed then
Open;
if AutoCommit then begin
if FHostVersion >= 17000000
then SetOption(1, 'SET OPTION <USER>.AUTO_COMMIT = Off', 'AUTO_COMMIT', 'Off', lcTransaction)
else SetOption(1, 'SET OPTION <USER>.chained = On', 'chained', 'On', lcTransaction);
AutoCommit := False;
Result := 1;
end else begin
S := '"SP'+ZFastCode.IntToStr(NativeUint(Self))+'_'+ZFastCode.IntToStr(FSavePoints.Count)+'"';
ExecuteImmediat(cSavePoint+{$IFDEF UNICODE}UnicodeStringToAscii7{$ENDIF}(S), lcTransaction);
Result := FSavePoints.Add(S) +2;
end;
end;
function TZASAConnection.DetermineASACharSet: String;
var
Stmt: IZStatement;
RS: IZResultSet;
begin
Stmt := CreateStatementWithParams(Info);
RS := Stmt.ExecuteQuery('SELECT DB_PROPERTY(''CharSet'')');
if RS.Next then
Result := RS.GetString(FirstDbcIndex)
else
Result := '';
RS := nil;
Stmt.Close;
Stmt := nil;
end;
procedure TZASAConnection.DetermineClientLanguageCP;
var
Stmt: IZStatement;
RS: IZResultSet;
S: String;
begin
Stmt := CreateStatementWithParams(Info);
RS := Stmt.ExecuteQuery('SELECT CONNECTION_PROPERTY(''Language'')');
if RS.Next
then S := RS.GetString(FirstDbcIndex)
else S := '';
RS := nil;
Stmt.Close;
Stmt := nil;
if S = 'arabic' then
FClientLanguageCP := zCP_WIN1256
else if S = 'czech' then
FClientLanguageCP := zCP_WIN1250
else if S = 'danish' then
FClientLanguageCP := zCP_WIN1252
else if S = 'dutch' then
FClientLanguageCP := zCP_WIN1252
else if (S = 'us_english') or (S = 'english') then
FClientLanguageCP := zCP_us_ascii
else if S = 'finnish' then
FClientLanguageCP := zCP_WIN1252
else if S = 'french' then
FClientLanguageCP := zCP_WIN1252
else if S = 'german' then
FClientLanguageCP := zCP_WIN1252
else if S = 'greek' then
FClientLanguageCP := zCP_WIN1253
else if S = 'hebrew' then
FClientLanguageCP := zCP_WIN1255
else if S = 'hungarian' then
FClientLanguageCP := zCP_WIN1250
else if S = 'italian' then
FClientLanguageCP := zCP_WIN1252
else if S = 'japanese' then
FClientLanguageCP := zCP_SHIFTJS
else if S = 'korean' then
FClientLanguageCP := zCP_EUCKR
else if S = 'lithuanian' then
FClientLanguageCP := zCP_WIN1257
else if (S = 'norwegian') or (s = 'norweg') then
FClientLanguageCP := zCP_WIN1252
else if S = 'polish' then
FClientLanguageCP := zCP_WIN1251
else if (S = 'portuguese') or (S = 'portugue') then
FClientLanguageCP := zCP_WIN1252
else if S = 'russian' then
FClientLanguageCP := zCP_WIN1251
else if (S = 'chinese') or (S = 'simpchin') then
FClientLanguageCP := zCP_GB2312
else if S = 'spanish' then
FClientLanguageCP := zCP_WIN1252
else if S = 'swedish' then
FClientLanguageCP := zCP_WIN1252
else if S = 'thai' then
FClientLanguageCP := zCP_WIN874
else if (S = 'tchinese') or (S = 'tradchin') then
FClientLanguageCP := zCP_Big5
else if S = 'turkish' then
FClientLanguageCP := zCP_WIN1254
else if S = 'ukrainian' then
FClientLanguageCP := zCP_WIN1251
else FClientLanguageCP := zOSCodePage;
end;
procedure TZASAConnection.DetermineHostVersion;
var
Stmt: IZStatement;
RS: IZResultSet;
P: PAnsiChar;
L: NativeUint;
Code, Major, Minior, Sub: Integer;
begin
Stmt := CreateStatementWithParams(Info);
RS := Stmt.ExecuteQuery('SELECT PROPERTY(''ProductVersion'')');
if RS.Next
then P := RS.GetPAnsiChar(FirstDbcIndex, L)
else P := nil;
if P <> nil then begin
Major := ValRawInt(P, Code);
Inc(P, Code);
Minior := ValRawInt(P, Code);
Inc(P, Code);
Sub := ValRawInt(P, Code);
FHostVersion := ZSysUtils.EncodeSQLVersioning(Major, Minior, Sub);
end;
RS := nil;
Stmt.Close;
Stmt := nil;
end;
procedure TZASAConnection.ExecuteImmediat(const SQL: RawByteString;
LoggingCategory: TZLoggingCategory);
var LogSQL: String;
begin
FPlainDriver.dbpp_execute_imm(FHandle, Pointer(SQL), 0);
if (FHandle.SqlCode <> SQLE_NOERROR) or DriverManager.HasLoggingListener then begin
{$IFDEF UNICODE}
LogSQL := ZRawToUnicode(SQL, ConSettings.ClientCodePage.CP);
{$ELSE}
LogSQL := SQL;
{$ENDIF}
end else LogSQL := '';
if FHandle.SqlCode <> SQLE_NOERROR then
HandleErrorOrWarning(LoggingCategory, LogSQL, IImmediatelyReleasable(FWeakImmediatRelPtr))
else if DriverManager.HasLoggingListener then
DriverManager.LogMessage(LoggingCategory, URL.Protocol, LogSQL);
end;
initialization
ASADriver := TZASADriver.Create;
DriverManager.RegisterDriver(ASADriver);
finalization
if Assigned(DriverManager) then
DriverManager.DeregisterDriver(ASADriver);
ASADriver := nil;
{$ENDIF ZEOS_DISABLE_ASA}
end.
| 39.56541 | 116 | 0.683563 |
c3a758ff79c55e0348be428972958bb2fe007f2e | 2,020 | pas | Pascal | Daten/Source/CShSrcRc/unt_CShTestData.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 11 | 2017-06-17T05:13:45.000Z | 2021-07-11T13:18:48.000Z | Daten/Source/CShSrcRc/unt_CShTestData.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 2 | 2019-03-05T12:52:40.000Z | 2021-12-03T12:34:26.000Z | Daten/Source/CShSrcRc/unt_CShTestData.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 6 | 2017-09-07T09:10:09.000Z | 2022-02-19T20:19:58.000Z | unit unt_CShTestData;
{$mode objfpc}{$H+}
{$modeswitch advancedrecords on}
interface
uses
Classes, SysUtils;
type { TResultType }
TResultType = record
eType,
Data,
Ref: string;
SubType: integer;
function ToString: string;
procedure SetAll(const aValue: array of variant; NoConvert: boolean=true);
overload;
procedure SetAll(const aValue: TStringArray); overload;
function ToCSV(delim: string): string;
// property All:array of Variant write SetAll
end;
TResultTypeArray = array of TResultType;
implementation
uses typInfo,CShScanner;
{$if FPC_FULLVERSION = 30200 }
{$WARN 6058 OFF}
{$ENDIF}
{ TResultType }
function TResultType.ToString: string;
begin
Result := format('(eType:%s;Data:%s;Ref:%s;SubType:%d)',
[QuotedStr(eType), QuotedStr(Data), QuotedStr(Ref), SubType]);
end;
procedure TResultType.SetAll(const aValue: array of variant;NoConvert:boolean=true);
begin
if length(aValue) = 4 then
begin
eType := GetEnumName(TypeInfo( TToken) ,aValue[0]);
Data := aValue[1];
if not NoConvert then
Data := Data.Replace('\\', '\'#1).Replace('\r', #13).Replace('\n', #10).Replace('\t', #9).Replace('\'#1, '\');
Ref := aValue[2];
SubType := aValue[3];
end;
end;
procedure TResultType.SetAll(const aValue: TStringArray);
begin
if (length(aValue) = 4) and TryStrToInt(aValue[3], SubType) then
begin
eType := aValue[0];
Data := aValue[1].Replace('\\', '\'#1).Replace('\r', #13).Replace('\n', #10).Replace('\t', #9).Replace('\'#1, '\');
Ref := aValue[2];
end
else
eType := 'NIO';
end;
function TResultType.ToCSV(delim: string): string;
begin
Result := ''.Join(delim, [eType, Data.Replace('\', '\\').Replace(
#9, '\t').Replace(#10, '\n').Replace(#13, '\r'), ref, IntToStr(SubType)]);
end;
end.
| 26.933333 | 124 | 0.581683 |
fcba326e77bb74ec2bfca500c3dd149a1f0421f1 | 1,758 | pas | Pascal | runtime/Work/Connor/Protobuf/Delphi/ProtocGenDelphi/Runtime/Internal/Work.Connor.Protobuf.Delphi.ProtocGenDelphi.Runtime.Internal.uProtobufDouble.pas | connor-work/protoc-gen-delphi | 0cc17fefa769b47c7d802ebb69e694160ff63d7a | [
"Apache-2.0"
]
| 1 | 2021-01-08T01:47:56.000Z | 2021-01-08T01:47:56.000Z | runtime/Work/Connor/Protobuf/Delphi/ProtocGenDelphi/Runtime/Internal/Work.Connor.Protobuf.Delphi.ProtocGenDelphi.Runtime.Internal.uProtobufDouble.pas | connor-work/protoc-gen-delphi | 0cc17fefa769b47c7d802ebb69e694160ff63d7a | [
"Apache-2.0"
]
| 54 | 2020-09-03T13:22:42.000Z | 2021-11-14T11:19:22.000Z | runtime/Work/Connor/Protobuf/Delphi/ProtocGenDelphi/Runtime/Internal/Work.Connor.Protobuf.Delphi.ProtocGenDelphi.Runtime.Internal.uProtobufDouble.pas | connor-work/protoc-gen-delphi | 0cc17fefa769b47c7d802ebb69e694160ff63d7a | [
"Apache-2.0"
]
| 3 | 2020-08-27T07:56:29.000Z | 2021-01-08T01:47:59.000Z | /// Copyright 2020 Connor Roehricht (connor.work)
/// Copyright 2020 Sotax AG
///
/// 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.
/// <summary>
/// Runtime-internal support for the protobuf type <c>double</c>.
/// </summary>
/// <remarks>
/// Generated code needs to reference this unit in order to operate on protobuf field values of this type.
/// </remarks>
unit Work.Connor.Protobuf.Delphi.ProtocGenDelphi.Runtime.Internal.uProtobufDouble;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
// Runtime-internal support for the protobuf binary wire format
Work.Connor.Protobuf.Delphi.ProtocGenDelphi.Runtime.Internal.uIProtobufWireCodec,
// RUNTIME-IMPL: Replace reference
// To provide the wire codec instance
Work.Connor.Protobuf.Delphi.ProtocGenDelphi.StubRuntime.uProtobufWireCodec;
var
/// <summary>
/// <i>Field codec</i> for <c>protoc-gen-delphi</c> that defines the encoding/decoding of
/// protobuf fields of type <c>double</c> from/to the protobuf binary wire format.
/// </summary>
gProtobufWireCodecDouble: IProtobufWireCodec<Double>;
implementation
initialization
begin
// RUNTIME-IMPL: Replace constructed class
gProtobufWireCodecDouble := TProtobufWireCodec<Double>.Create;
end;
end.
| 33.169811 | 106 | 0.744596 |
fc7c549a68e86d37c95ba2839e603ad50a8de888 | 4,400 | pas | Pascal | Lib/Classes/Common/ZXing.ResultPointImplementation.pas | grahamegrieve/ZXing.Delphi | fb5f9c82dc799c6d1bfe0efec9a68c7a6b22c990 | [
"Apache-2.0"
]
| 12 | 2018-06-30T13:48:57.000Z | 2022-02-27T22:42:05.000Z | Lib/Classes/Common/ZXing.ResultPointImplementation.pas | grahamegrieve/ZXing.Delphi | fb5f9c82dc799c6d1bfe0efec9a68c7a6b22c990 | [
"Apache-2.0"
]
| 1 | 2021-10-06T07:25:45.000Z | 2021-10-06T07:25:45.000Z | Lib/Classes/Common/ZXing.ResultPointImplementation.pas | grahamegrieve/ZXing.Delphi | fb5f9c82dc799c6d1bfe0efec9a68c7a6b22c990 | [
"Apache-2.0"
]
| 6 | 2018-06-30T11:57:45.000Z | 2021-10-05T19:04:38.000Z | unit ZXing.ResultPointImplementation;
{$IFDEF FPC}
{$mode delphi}{$H+}
{$ENDIF}
interface
uses
SysUtils,
ZXing.ResultPoint;
type
/// <summary>
/// Encapsulates a point of interest in an image containing a barcode. Typically, this
/// would be the location of a finder pattern or the corner of the barcode, for example.
/// this class is meant to be used only indirectly, via the IResultPoint reference-counted interface
// it implements. It is exposed in the interface section just to allow the declaration of its derived classes
/// </summary>
TResultPoint = class(TInterfacedObject,IResultPoint)
private type
TSingleArray = array [0 .. Pred(SizeOf(Single))] of Byte;
var
Fx, Fy: Single;
bytesX, bytesY: TSingleArray;
FToString: String;
protected
procedure SetX(const AValue: Single);
procedure SetY(const AValue: Single);
function GetX: Single;
function GetY: Single;
public
/// <summary>
/// Initializes a new instance of the <see cref="TResultPoint"/> class.
/// </summary>
constructor Create; overload;
/// <summary>
/// Initializes a new instance of the <see cref="TResultPoint"/> class.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
constructor Create(const pX, pY: Single); overload;
destructor Destroy; override;
/// <summary>
/// Determines whether the specified <see cref="System.TObject"/> is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="System.TObject"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.TObject"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
function Equals(other: TObject): Boolean; override;
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
function GetHashCode(): PtrInt; override;
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
function ToString(): String; override;
property x: Single read GetX write SetX;
property y: Single read GetY write SetY;
end;
// these are the helping functions that actually create a new instance.
// The actual constructor cannot be called outside of this unit
function NewResultPoint:IResultPoint; overload;
function NewResultPoint(const pX, pY: Single):IResultPoint; overload;
implementation
function NewResultPoint:IResultPoint;
begin
result := TResultPoint.Create;
end;
function NewResultPoint(const pX, pY: Single):IResultPoint;
begin
result := TResultPoint.Create(px,py);
end;
{ TResultPoint }
constructor TResultPoint.Create;
begin
inherited;
end;
constructor TResultPoint.Create(const pX, pY: Single);
begin
inherited Create;
Fx := pX;
Fy := pY;
bytesX := TSingleArray(pX);
bytesY := TSingleArray(pY);
end;
destructor TResultPoint.Destroy;
var
n: Single;
begin
n := 0;
bytesX := TSingleArray(n);
bytesY := TSingleArray(n);
inherited;
end;
procedure TResultPoint.SetX(const AValue: Single);
begin
if (AValue <> Fx) then
begin
Fx := AValue;
bytesX := TSingleArray(Fx);
end;
end;
procedure TResultPoint.SetY(const AValue: Single);
begin
if (AValue <> Fy) then
begin
Fy := AValue;
bytesY := TSingleArray(Fy);
end;
end;
function TResultPoint.GetX: Single;
begin
result := Fx;
end;
function TResultPoint.GetY: Single;
begin
result := Fy;
end;
function TResultPoint.Equals(other: TObject): Boolean;
var
otherPoint: TResultPoint;
begin
otherPoint := other as TResultPoint;
if (otherPoint = nil) then
Result := false
else
Result := ((otherPoint.x = Fx) and (otherPoint.y = Fy));
end;
function TResultPoint.GetHashCode: PtrInt;
begin
Result := 31 * ((bytesX[0] shl 24) + (bytesX[1] shl 16) + (bytesX[2] shl 8) +
bytesX[3]) + (bytesY[0] shl 24) + (bytesY[1] shl 16) + (bytesY[2] shl 8) +
bytesY[3];
end;
function TResultPoint.ToString: String;
begin
if (FToString = '') then
FToString := Format('(%g),(%g)', [Fx, Fy]);
Result := FToString;
end;
end.
| 25 | 117 | 0.674091 |
c315b4c4463d9b62587f3516d1dd16a7fc2a6b6a | 68,059 | pas | Pascal | vcl/XLSReadWrite6/SrcXLS/xpgParseDocPropsApp.pas | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
]
| null | null | null | vcl/XLSReadWrite6/SrcXLS/xpgParseDocPropsApp.pas | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
]
| null | null | null | vcl/XLSReadWrite6/SrcXLS/xpgParseDocPropsApp.pas | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
]
| null | null | null | unit xpgParseDocPropsApp;
// Copyright (c) 2010,2011 Axolot Data
// Web : http://www.axolot.com/xpg
// Mail: xpg@axolot.com
//
// X X PPP GGG
// X X P P G
// X PPP G GG
// X X P G G
// X X P GGG
//
// File generated with Axolot XPG, Xml Parser Generator.
// Version 0.00.90.
// File created on 2011-12-03 17:16:44
{$I AxCompilers.inc}
{$MINENUMSIZE 2}
{$BOOLEVAL OFF}
{$RANGECHECKS OFF}
interface
uses Classes, SysUtils, Contnrs, IniFiles, xpgPUtils, xpgPLists, xpgPXMLUtils,
XLSUtils5,
xpgPXML;
type TST_ArrayBaseType = (stabtVariant,stabtI1,stabtI2,stabtI4,stabtInt,stabtUi1,stabtUi2,stabtUi4,stabtUint,stabtR4,stabtR8,stabtDecimal,stabtBstr,stabtDate,stabtBool,stabtCy,stabtError);
const StrTST_ArrayBaseType: array[0..16] of AxUCString = ('variant','i1','i2','i4','int','ui1','ui2','ui4','uint','r4','r8','decimal','bstr','date','bool','cy','error');
type TST_VectorBaseType = (stvbtVariant,stvbtI1,stvbtI2,stvbtI4,stvbtI8,stvbtUi1,stvbtUi2,stvbtUi4,stvbtUi8,stvbtR4,stvbtR8,stvbtLpstr,stvbtLpwstr,stvbtBstr,stvbtDate,stvbtFiletime,stvbtBool,stvbtCy,stvbtError,stvbtClsid,stvbtCf);
const StrTST_VectorBaseType: array[0..20] of AxUCString = ('variant','i1','i2','i4','i8','ui1','ui2','ui4','ui8','r4','r8','lpstr','lpwstr','bstr','date','filetime','bool','cy','error','clsid','cf');
type TXPGDocBase = class(TObject)
protected
FErrors: TXpgPErrors;
public
property Errors: TXpgPErrors read FErrors;
end;
TXPGBase = class(TObject)
protected
FOwner: TXPGDocBase;
FElementCount: integer;
FAttributeCount: integer;
FAssigneds: TXpgAssigneds;
function CheckAssigned: integer; virtual;
function Assigned: boolean;
function HandleElement(AReader: TXpgReadXML): TXPGBase; virtual;
procedure AssignAttributes(AAttributes: TXpgXMLAttributeList); virtual;
procedure AfterTag; virtual;
class procedure AddEnums;
class function StrToEnum(AValue: AxUCString): integer;
class function StrToEnumDef(AValue: AxUCString; ADefault: integer): integer;
class function TryStrToEnum(AValue: AxUCString; AText: AxUCString; AEnumNames: array of AxUCString; APtrInt: PInteger): boolean;
public
function Available: boolean;
property ElementCount: integer read FElementCount write FElementCount;
property AttributeCount: integer read FAttributeCount write FAttributeCount;
property Assigneds: TXpgAssigneds read FAssigneds write FAssigneds;
end;
TXPGBaseObjectList = class(TObjectList)
protected
FOwner: TXPGDocBase;
FAssigned: boolean;
function GetItems(Index: integer): TXPGBase;
public
constructor Create(AOwner: TXPGDocBase);
property Items[Index: integer]: TXPGBase read GetItems;
end;
TXPGReader = class(TXpgReadXML)
protected
FCurrent: TXPGBase;
FStack: TObjectStack;
FErrors: TXpgPErrors;
public
constructor Create(AErrors: TXpgPErrors; ARoot: TXPGBase);
destructor Destroy; override;
procedure BeginTag; override;
procedure EndTag; override;
end;
TCT_Vector = class;
TCT_Array = class;
TCT_Empty = class(TXPGBase)
protected
function CheckAssigned: integer; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
end;
TCT_Null = class(TXPGBase)
protected
function CheckAssigned: integer; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
end;
TCT_Vstream = class(TXPGBase)
protected
FVersion: AxUCString;
FContent: integer;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
procedure WriteAttributes(AWriter: TXpgWriteXML);
procedure AssignAttributes(AAttributes: TXpgXMLAttributeList); override;
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property Version: AxUCString read FVersion write FVersion;
property Content: integer read FContent write FContent;
end;
TCT_Cf = class(TXPGBase)
protected
FFormat: AxUCString;
FContent: integer;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
procedure WriteAttributes(AWriter: TXpgWriteXML);
procedure AssignAttributes(AAttributes: TXpgXMLAttributeList); override;
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property Format: AxUCString read FFormat write FFormat;
property Content: integer read FContent write FContent;
end;
TCT_CfXpgList = class(TXPGBaseObjectList)
protected
function GetItems(Index: integer): TCT_Cf;
public
function Add: TCT_Cf;
function CheckAssigned: integer;
procedure Write(AWriter: TXpgWriteXML; AName: AxUCString);
property Items[Index: integer]: TCT_Cf read GetItems; default;
end;
TCT_Variant = class(TXPGBase)
protected
FVt_Variant: TCT_Variant;
FVt_Vector: TCT_Vector;
FVt_Array: TCT_Array;
FVt_Blob: longword;
FVt_Oblob: longword;
FVt_Empty: TCT_Empty;
FVt_Null: TCT_Null;
FVt_I1: longword;
FVt_I2: longword;
FVt_I4: longword;
FVt_I8: longword;
FVt_Int: longword;
FVt_Ui1: longword;
FVt_Ui2: longword;
FVt_Ui4: longword;
FVt_Ui8: longword;
FVt_Uint: longword;
FVt_R4: extended;
FVt_R8: extended;
FVt_Decimal: extended;
FVt_Lpstr: AxUCString;
FVt_Lpwstr: AxUCString;
FVt_Bstr: AxUCString;
FVt_Date: TDateTime;
FVt_Filetime: TDateTime;
FVt_Bool: boolean;
FVt_Cy: AxUCString;
FVt_Error: AxUCString;
FVt_Stream: longword;
FVt_Ostream: longword;
FVt_Storage: longword;
FVt_Ostorage: longword;
FVt_Vstream: TCT_Vstream;
FVt_Clsid: AxUCString;
FVt_Cf: TCT_Cf;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
function CreateTCT_Variant: TCT_Variant;
function CreateTCT_Vector: TCT_Vector;
function CreateTCT_Array: TCT_Array;
property Vt_Variant: TCT_Variant read FVt_Variant;
property Vt_Vector: TCT_Vector read FVt_Vector write FVt_Vector;
property Vt_Array: TCT_Array read FVt_Array write FVt_Array;
property Vt_Blob: longword read FVt_Blob write FVt_Blob;
property Vt_Oblob: longword read FVt_Oblob write FVt_Oblob;
property Vt_Empty: TCT_Empty read FVt_Empty;
property Vt_Null: TCT_Null read FVt_Null;
property Vt_I1: longword read FVt_I1 write FVt_I1;
property Vt_I2: longword read FVt_I2 write FVt_I2;
property Vt_I4: longword read FVt_I4 write FVt_I4;
property Vt_I8: longword read FVt_I8 write FVt_I8;
property Vt_Int: longword read FVt_Int write FVt_Int;
property Vt_Ui1: longword read FVt_Ui1 write FVt_Ui1;
property Vt_Ui2: longword read FVt_Ui2 write FVt_Ui2;
property Vt_Ui4: longword read FVt_Ui4 write FVt_Ui4;
property Vt_Ui8: longword read FVt_Ui8 write FVt_Ui8;
property Vt_Uint: longword read FVt_Uint write FVt_Uint;
property Vt_R4: extended read FVt_R4 write FVt_R4;
property Vt_R8: extended read FVt_R8 write FVt_R8;
property Vt_Decimal: extended read FVt_Decimal write FVt_Decimal;
property Vt_Lpstr: AxUCString read FVt_Lpstr write FVt_Lpstr;
property Vt_Lpwstr: AxUCString read FVt_Lpwstr write FVt_Lpwstr;
property Vt_Bstr: AxUCString read FVt_Bstr write FVt_Bstr;
property Vt_Date: TDateTime read FVt_Date write FVt_Date;
property Vt_Filetime: TDateTime read FVt_Filetime write FVt_Filetime;
property Vt_Bool: boolean read FVt_Bool write FVt_Bool;
property Vt_Cy: AxUCString read FVt_Cy write FVt_Cy;
property Vt_Error: AxUCString read FVt_Error write FVt_Error;
property Vt_Stream: longword read FVt_Stream write FVt_Stream;
property Vt_Ostream: longword read FVt_Ostream write FVt_Ostream;
property Vt_Storage: longword read FVt_Storage write FVt_Storage;
property Vt_Ostorage: longword read FVt_Ostorage write FVt_Ostorage;
property Vt_Vstream: TCT_Vstream read FVt_Vstream;
property Vt_Clsid: AxUCString read FVt_Clsid write FVt_Clsid;
property Vt_Cf: TCT_Cf read FVt_Cf;
end;
TCT_VariantXpgList = class(TXPGBaseObjectList)
protected
function GetItems(Index: integer): TCT_Variant;
public
function Add: TCT_Variant;
function CheckAssigned: integer;
procedure Write(AWriter: TXpgWriteXML; AName: AxUCString);
property Items[Index: integer]: TCT_Variant read GetItems; default;
end;
TCT_Array = class(TXPGBase)
protected
FLBounds: integer;
FUBounds: integer;
FBaseType: TST_ArrayBaseType;
FVt_VariantXpgList: TCT_VariantXpgList;
FVt_I1XpgList: TLongwordXpgList;
FVt_I2XpgList: TLongwordXpgList;
FVt_I4XpgList: TLongwordXpgList;
FVt_IntXpgList: TLongwordXpgList;
FVt_Ui1XpgList: TLongwordXpgList;
FVt_Ui2XpgList: TLongwordXpgList;
FVt_Ui4XpgList: TLongwordXpgList;
FVt_UintXpgList: TLongwordXpgList;
FVt_R4XpgList: TExtendedXpgList;
FVt_R8XpgList: TExtendedXpgList;
FVt_DecimalXpgList: TExtendedXpgList;
FVt_BstrXpgList: TStringXpgList;
FVt_DateXpgList: TTDateTimeXpgList;
FVt_BoolXpgList: TBooleanXpgList;
FVt_ErrorXpgList: TStringXpgList;
FVt_CyXpgList: TStringXpgList;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
procedure WriteAttributes(AWriter: TXpgWriteXML);
procedure AssignAttributes(AAttributes: TXpgXMLAttributeList); override;
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
function CreateTCT_VariantXpgList: TCT_VariantXpgList;
property LBounds: integer read FLBounds write FLBounds;
property UBounds: integer read FUBounds write FUBounds;
property BaseType: TST_ArrayBaseType read FBaseType write FBaseType;
property Vt_VariantXpgList: TCT_VariantXpgList read FVt_VariantXpgList;
property Vt_I1XpgList: TLongwordXpgList read FVt_I1XpgList;
property Vt_I2XpgList: TLongwordXpgList read FVt_I2XpgList;
property Vt_I4XpgList: TLongwordXpgList read FVt_I4XpgList;
property Vt_IntXpgList: TLongwordXpgList read FVt_IntXpgList;
property Vt_Ui1XpgList: TLongwordXpgList read FVt_Ui1XpgList;
property Vt_Ui2XpgList: TLongwordXpgList read FVt_Ui2XpgList;
property Vt_Ui4XpgList: TLongwordXpgList read FVt_Ui4XpgList;
property Vt_UintXpgList: TLongwordXpgList read FVt_UintXpgList;
property Vt_R4XpgList: TExtendedXpgList read FVt_R4XpgList;
property Vt_R8XpgList: TExtendedXpgList read FVt_R8XpgList;
property Vt_DecimalXpgList: TExtendedXpgList read FVt_DecimalXpgList;
property Vt_BstrXpgList: TStringXpgList read FVt_BstrXpgList;
property Vt_DateXpgList: TTDateTimeXpgList read FVt_DateXpgList;
property Vt_BoolXpgList: TBooleanXpgList read FVt_BoolXpgList;
property Vt_ErrorXpgList: TStringXpgList read FVt_ErrorXpgList;
property Vt_CyXpgList: TStringXpgList read FVt_CyXpgList;
end;
TCT_Vector = class(TXPGBase)
protected
FBaseType: TST_VectorBaseType;
FSize: integer;
FVt_VariantXpgList: TCT_VariantXpgList;
FVt_I1XpgList: TLongwordXpgList;
FVt_I2XpgList: TLongwordXpgList;
FVt_I4XpgList: TLongwordXpgList;
FVt_I8XpgList: TLongwordXpgList;
FVt_Ui1XpgList: TLongwordXpgList;
FVt_Ui2XpgList: TLongwordXpgList;
FVt_Ui4XpgList: TLongwordXpgList;
FVt_Ui8XpgList: TLongwordXpgList;
FVt_R4XpgList: TExtendedXpgList;
FVt_R8XpgList: TExtendedXpgList;
FVt_LpstrXpgList: TStringXpgList;
FVt_LpwstrXpgList: TStringXpgList;
FVt_BstrXpgList: TStringXpgList;
FVt_DateXpgList: TTDateTimeXpgList;
FVt_FiletimeXpgList: TTDateTimeXpgList;
FVt_BoolXpgList: TBooleanXpgList;
FVt_CyXpgList: TStringXpgList;
FVt_ErrorXpgList: TStringXpgList;
FVt_ClsidXpgList: TStringXpgList;
FVt_CfXpgList: TCT_CfXpgList;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
procedure WriteAttributes(AWriter: TXpgWriteXML);
procedure AssignAttributes(AAttributes: TXpgXMLAttributeList); override;
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
function CreateTCT_VariantXpgList: TCT_VariantXpgList;
property BaseType: TST_VectorBaseType read FBaseType write FBaseType;
property Size: integer read FSize write FSize;
property Vt_VariantXpgList: TCT_VariantXpgList read FVt_VariantXpgList;
property Vt_I1XpgList: TLongwordXpgList read FVt_I1XpgList;
property Vt_I2XpgList: TLongwordXpgList read FVt_I2XpgList;
property Vt_I4XpgList: TLongwordXpgList read FVt_I4XpgList;
property Vt_I8XpgList: TLongwordXpgList read FVt_I8XpgList;
property Vt_Ui1XpgList: TLongwordXpgList read FVt_Ui1XpgList;
property Vt_Ui2XpgList: TLongwordXpgList read FVt_Ui2XpgList;
property Vt_Ui4XpgList: TLongwordXpgList read FVt_Ui4XpgList;
property Vt_Ui8XpgList: TLongwordXpgList read FVt_Ui8XpgList;
property Vt_R4XpgList: TExtendedXpgList read FVt_R4XpgList;
property Vt_R8XpgList: TExtendedXpgList read FVt_R8XpgList;
property Vt_LpstrXpgList: TStringXpgList read FVt_LpstrXpgList;
property Vt_LpwstrXpgList: TStringXpgList read FVt_LpwstrXpgList;
property Vt_BstrXpgList: TStringXpgList read FVt_BstrXpgList;
property Vt_DateXpgList: TTDateTimeXpgList read FVt_DateXpgList;
property Vt_FiletimeXpgList: TTDateTimeXpgList read FVt_FiletimeXpgList;
property Vt_BoolXpgList: TBooleanXpgList read FVt_BoolXpgList;
property Vt_CyXpgList: TStringXpgList read FVt_CyXpgList;
property Vt_ErrorXpgList: TStringXpgList read FVt_ErrorXpgList;
property Vt_ClsidXpgList: TStringXpgList read FVt_ClsidXpgList;
property Vt_CfXpgList: TCT_CfXpgList read FVt_CfXpgList;
end;
TCT_VectorVariant = class(TXPGBase)
protected
FVt_Vector: TCT_Vector;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property Vt_Vector: TCT_Vector read FVt_Vector;
end;
TCT_VectorLpstr = class(TXPGBase)
protected
FVt_Vector: TCT_Vector;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property Vt_Vector: TCT_Vector read FVt_Vector;
end;
TCT_DigSigBlob = class(TXPGBase)
protected
FVt_Blob: longword;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property Vt_Blob: longword read FVt_Blob write FVt_Blob;
end;
TCT_Properties = class(TXPGBase)
protected
FTemplate: AxUCString;
FManager: AxUCString;
FCompany: AxUCString;
FPages: longword;
FWords: longword;
FCharacters: longword;
FPresentationFormat: AxUCString;
FLines: longword;
FParagraphs: longword;
FSlides: longword;
FNotes: longword;
FTotalTime: longword;
FHiddenSlides: longword;
FMMClips: longword;
FScaleCrop: boolean;
FHeadingPairs: TCT_VectorVariant;
FTitlesOfParts: TCT_VectorLpstr;
FLinksUpToDate: boolean;
FCharactersWithSpaces: longword;
FSharedDoc: boolean;
FHyperlinkBase: AxUCString;
FHLinks: TCT_VectorVariant;
FHyperlinksChanged: boolean;
FDigSig: TCT_DigSigBlob;
FApplication: AxUCString;
FAppVersion: AxUCString;
FDocSecurity: longword;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property Template: AxUCString read FTemplate write FTemplate;
property Manager: AxUCString read FManager write FManager;
property Company: AxUCString read FCompany write FCompany;
property Pages: longword read FPages write FPages;
property Words: longword read FWords write FWords;
property Characters: longword read FCharacters write FCharacters;
property PresentationFormat: AxUCString read FPresentationFormat write FPresentationFormat;
property Lines: longword read FLines write FLines;
property Paragraphs: longword read FParagraphs write FParagraphs;
property Slides: longword read FSlides write FSlides;
property Notes: longword read FNotes write FNotes;
property TotalTime: longword read FTotalTime write FTotalTime;
property HiddenSlides: longword read FHiddenSlides write FHiddenSlides;
property MMClips: longword read FMMClips write FMMClips;
property ScaleCrop: boolean read FScaleCrop write FScaleCrop;
property HeadingPairs: TCT_VectorVariant read FHeadingPairs;
property TitlesOfParts: TCT_VectorLpstr read FTitlesOfParts;
property LinksUpToDate: boolean read FLinksUpToDate write FLinksUpToDate;
property CharactersWithSpaces: longword read FCharactersWithSpaces write FCharactersWithSpaces;
property SharedDoc: boolean read FSharedDoc write FSharedDoc;
property HyperlinkBase: AxUCString read FHyperlinkBase write FHyperlinkBase;
property HLinks: TCT_VectorVariant read FHLinks;
property HyperlinksChanged: boolean read FHyperlinksChanged write FHyperlinksChanged;
property DigSig: TCT_DigSigBlob read FDigSig;
property Application: AxUCString read FApplication write FApplication;
property AppVersion: AxUCString read FAppVersion write FAppVersion;
property DocSecurity: longword read FDocSecurity write FDocSecurity;
end;
T__ROOT__ = class(TXPGBase)
protected
FRootAttributes: TStringXpgList;
FProperties: TCT_Properties;
function CheckAssigned: integer; override;
function HandleElement(AReader: TXpgReadXML): TXPGBase; override;
procedure Write(AWriter: TXpgWriteXML);
public
constructor Create(AOwner: TXPGDocBase);
destructor Destroy; override;
procedure Clear;
property RootAttributes: TStringXpgList read FRootAttributes;
property Properties: TCT_Properties read FProperties;
end;
TXPGDocDocPropsApp = class(TXPGDocBase)
protected
FRoot: T__ROOT__;
FReader: TXPGReader;
FWriter: TXpgWriteXML;
function GetProperties: TCT_Properties;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromFile(AFilename: AxUCString);
procedure LoadFromStream(AStream: TStream);
procedure SaveToFile(AFilename: AxUCString);
procedure SaveToStream(AStream: TStream);
property Root: T__ROOT__ read FRoot;
property Properties: TCT_Properties read GetProperties;
end;
implementation
{$ifdef DELPHI_5}
var FEnums: TStringList;
{$else}
var FEnums: THashedStringList;
{$endif}
{ TXPGBase }
function TXPGBase.CheckAssigned: integer;
begin
Result := 1;
end;
function TXPGBase.Assigned: boolean;
begin
Result := FAssigneds <> [];
end;
function TXPGBase.HandleElement(AReader: TXpgReadXML): TXPGBase;
begin
Result := Self;
end;
procedure TXPGBase.AssignAttributes(AAttributes: TXpgXMLAttributeList);
begin
end;
procedure TXPGBase.AfterTag;
begin
end;
class procedure TXPGBase.AddEnums;
begin
FEnums.AddObject('stabtVariant',TObject(0));
FEnums.AddObject('stabtI1',TObject(1));
FEnums.AddObject('stabtI2',TObject(2));
FEnums.AddObject('stabtI4',TObject(3));
FEnums.AddObject('stabtInt',TObject(4));
FEnums.AddObject('stabtUi1',TObject(5));
FEnums.AddObject('stabtUi2',TObject(6));
FEnums.AddObject('stabtUi4',TObject(7));
FEnums.AddObject('stabtUint',TObject(8));
FEnums.AddObject('stabtR4',TObject(9));
FEnums.AddObject('stabtR8',TObject(10));
FEnums.AddObject('stabtDecimal',TObject(11));
FEnums.AddObject('stabtBstr',TObject(12));
FEnums.AddObject('stabtDate',TObject(13));
FEnums.AddObject('stabtBool',TObject(14));
FEnums.AddObject('stabtCy',TObject(15));
FEnums.AddObject('stabtError',TObject(16));
FEnums.AddObject('stvbtVariant',TObject(0));
FEnums.AddObject('stvbtI1',TObject(1));
FEnums.AddObject('stvbtI2',TObject(2));
FEnums.AddObject('stvbtI4',TObject(3));
FEnums.AddObject('stvbtI8',TObject(4));
FEnums.AddObject('stvbtUi1',TObject(5));
FEnums.AddObject('stvbtUi2',TObject(6));
FEnums.AddObject('stvbtUi4',TObject(7));
FEnums.AddObject('stvbtUi8',TObject(8));
FEnums.AddObject('stvbtR4',TObject(9));
FEnums.AddObject('stvbtR8',TObject(10));
FEnums.AddObject('stvbtLpstr',TObject(11));
FEnums.AddObject('stvbtLpwstr',TObject(12));
FEnums.AddObject('stvbtBstr',TObject(13));
FEnums.AddObject('stvbtDate',TObject(14));
FEnums.AddObject('stvbtFiletime',TObject(15));
FEnums.AddObject('stvbtBool',TObject(16));
FEnums.AddObject('stvbtCy',TObject(17));
FEnums.AddObject('stvbtError',TObject(18));
FEnums.AddObject('stvbtClsid',TObject(19));
FEnums.AddObject('stvbtCf',TObject(20));
end;
class function TXPGBase.StrToEnum(AValue: AxUCString): integer;
var
i: integer;
begin
i := FEnums.IndexOf(AValue);
if i >= 0 then
Result := Integer(FEnums.Objects[i])
else
Result := 0;
end;
class function TXPGBase.StrToEnumDef(AValue: AxUCString; ADefault: integer): integer;
var
i: integer;
begin
i := FEnums.IndexOf(AValue);
if i >= 0 then
Result := Integer(FEnums.Objects[i])
else
Result := ADefault;
end;
class function TXPGBase.TryStrToEnum(AValue: AxUCString; AText: AxUCString; AEnumNames: array of AxUCString; APtrInt: PInteger): boolean;
var
i: integer;
begin
i := FEnums.IndexOf(AValue);
if i >= 0 then
begin
i := Integer(FEnums.Objects[i]);
Result := (i <= High(AEnumNames)) and (AText = AEnumNames[i]);
if Result then
APtrInt^ := i;
end
else
Result := False;
end;
function TXPGBase.Available: boolean;
begin
Result := xaRead in FAssigneds;
end;
{ TXPGBaseObjectList }
function TXPGBaseObjectList.GetItems(Index: integer): TXPGBase;
begin
Result := TXPGBase(inherited Items[Index]);
end;
constructor TXPGBaseObjectList.Create(AOwner: TXPGDocBase);
begin
inherited Create;
FOwner := AOwner;
end;
{ TXPGReader }
constructor TXPGReader.Create(AErrors: TXpgPErrors; ARoot: TXPGBase);
begin
inherited Create;
FErrors := AErrors;
FErrors.NoDuplicates := True;
FCurrent := ARoot;
FStack := TObjectStack.Create;
end;
destructor TXPGReader.Destroy;
begin
FStack.Free;
inherited Destroy;
end;
procedure TXPGReader.BeginTag;
begin
FStack.Push(FCurrent);
FCurrent := FCurrent.HandleElement(Self);
FCurrent.AssignAttributes(Attributes);
end;
procedure TXPGReader.EndTag;
begin
FCurrent := TXPGBase(FStack.Pop);
FCurrent.AfterTag;
end;
{ TCT_Empty }
function TCT_Empty.CheckAssigned: integer;
begin
FAssigneds := [];
Result := 0;
end;
procedure TCT_Empty.Write(AWriter: TXpgWriteXML);
begin
end;
constructor TCT_Empty.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 0;
FAttributeCount := 0;
end;
destructor TCT_Empty.Destroy;
begin
end;
procedure TCT_Empty.Clear;
begin
FAssigneds := [];
end;
{ TCT_Null }
function TCT_Null.CheckAssigned: integer;
begin
FAssigneds := [];
Result := 0;
end;
procedure TCT_Null.Write(AWriter: TXpgWriteXML);
begin
end;
constructor TCT_Null.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 0;
FAttributeCount := 0;
end;
destructor TCT_Null.Destroy;
begin
end;
procedure TCT_Null.Clear;
begin
FAssigneds := [];
end;
{ TCT_Vstream }
function TCT_Vstream.CheckAssigned: integer;
var
AttrsAssigned: integer;
begin
AttrsAssigned := 0;
FAssigneds := [];
if FVersion <> '' then
Inc(AttrsAssigned);
Result := 0;
Inc(Result,AttrsAssigned);
if AttrsAssigned > 0 then
FAssigneds := [xaAttributes];
if FContent <> 0 then
begin
FAssigneds := FAssigneds + [xaContent];
Inc(Result);
end;
end;
function TCT_Vstream.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_Vstream.Write(AWriter: TXpgWriteXML);
begin
end;
procedure TCT_Vstream.WriteAttributes(AWriter: TXpgWriteXML);
begin
if FVersion <> '' then
AWriter.AddAttribute('version',FVersion);
end;
procedure TCT_Vstream.AssignAttributes(AAttributes: TXpgXMLAttributeList);
begin
if AAttributes[0] = 'version' then
FVersion := AAttributes.Values[0]
else
FOwner.Errors.Error(xemUnknownAttribute,AAttributes[0]);
end;
constructor TCT_Vstream.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 0;
FAttributeCount := 1;
end;
destructor TCT_Vstream.Destroy;
begin
end;
procedure TCT_Vstream.Clear;
begin
FAssigneds := [];
FVersion := '';
end;
{ TCT_Cf }
function TCT_Cf.CheckAssigned: integer;
var
AttrsAssigned: integer;
begin
AttrsAssigned := 0;
FAssigneds := [];
if FFormat <> '' then
Inc(AttrsAssigned);
Result := 0;
Inc(Result,AttrsAssigned);
if AttrsAssigned > 0 then
FAssigneds := [xaAttributes];
if FContent <> 0 then
begin
FAssigneds := FAssigneds + [xaContent];
Inc(Result);
end;
end;
function TCT_Cf.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_Cf.Write(AWriter: TXpgWriteXML);
begin
end;
procedure TCT_Cf.WriteAttributes(AWriter: TXpgWriteXML);
begin
if FFormat <> '' then
AWriter.AddAttribute('format',FFormat);
end;
procedure TCT_Cf.AssignAttributes(AAttributes: TXpgXMLAttributeList);
begin
if AAttributes[0] = 'format' then
FFormat := AAttributes.Values[0]
else
FOwner.Errors.Error(xemUnknownAttribute,AAttributes[0]);
end;
constructor TCT_Cf.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 0;
FAttributeCount := 1;
end;
destructor TCT_Cf.Destroy;
begin
end;
procedure TCT_Cf.Clear;
begin
FAssigneds := [];
FFormat := '';
end;
{ TCT_CfXpgList }
function TCT_CfXpgList.GetItems(Index: integer): TCT_Cf;
begin
Result := TCT_Cf(inherited Items[Index]);
end;
function TCT_CfXpgList.Add: TCT_Cf;
begin
Result := TCT_Cf.Create(FOwner);
inherited Add(Result);
end;
function TCT_CfXpgList.CheckAssigned: integer;
var
i: integer;
begin
Result := 0;
for i := 0 to Count - 1 do
Inc(Result,Items[i].CheckAssigned);
FAssigned := Result > 0;
end;
procedure TCT_CfXpgList.Write(AWriter: TXpgWriteXML; AName: AxUCString);
var
i: integer;
begin
for i := 0 to Count - 1 do
begin
if xaAttributes in Items[i].FAssigneds then
GetItems(i).WriteAttributes(AWriter);
if xaContent in Items[i].FAssigneds then
AWriter.Text := XmlIntToStr(GetItems(i).Content);
if xaElements in Items[i].FAssigneds then
begin
AWriter.BeginTag(AName);
GetItems(i).Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag(AName);
end
end;
{ TCT_Variant }
function TCT_Variant.CheckAssigned: integer;
var
ElemsAssigned: integer;
begin
ElemsAssigned := 0;
FAssigneds := [];
if FVt_Variant <> Nil then
Inc(ElemsAssigned,FVt_Variant.CheckAssigned);
if FVt_Vector <> Nil then
Inc(ElemsAssigned,FVt_Vector.CheckAssigned);
if FVt_Array <> Nil then
Inc(ElemsAssigned,FVt_Array.CheckAssigned);
if FVt_Blob <> 0 then
Inc(ElemsAssigned);
if FVt_Oblob <> 0 then
Inc(ElemsAssigned);
Inc(ElemsAssigned,FVt_Empty.CheckAssigned);
Inc(ElemsAssigned,FVt_Null.CheckAssigned);
if FVt_I1 <> 0 then
Inc(ElemsAssigned);
if FVt_I2 <> 0 then
Inc(ElemsAssigned);
if FVt_I4 <> 0 then
Inc(ElemsAssigned);
if FVt_I8 <> 0 then
Inc(ElemsAssigned);
if FVt_Int <> 0 then
Inc(ElemsAssigned);
if FVt_Ui1 <> 0 then
Inc(ElemsAssigned);
if FVt_Ui2 <> 0 then
Inc(ElemsAssigned);
if FVt_Ui4 <> 0 then
Inc(ElemsAssigned);
if FVt_Ui8 <> 0 then
Inc(ElemsAssigned);
if FVt_Uint <> 0 then
Inc(ElemsAssigned);
if FVt_R4 <> 0 then
Inc(ElemsAssigned);
if FVt_R8 <> 0 then
Inc(ElemsAssigned);
if FVt_Decimal <> 0 then
Inc(ElemsAssigned);
if FVt_Lpstr <> '' then
Inc(ElemsAssigned);
if FVt_Lpwstr <> '' then
Inc(ElemsAssigned);
if FVt_Bstr <> '' then
Inc(ElemsAssigned);
if FVt_Date <> 0 then
Inc(ElemsAssigned);
if FVt_Filetime <> 0 then
Inc(ElemsAssigned);
if FVt_Bool <> False then
Inc(ElemsAssigned);
if FVt_Cy <> '' then
Inc(ElemsAssigned);
if FVt_Error <> '' then
Inc(ElemsAssigned);
if FVt_Stream <> 0 then
Inc(ElemsAssigned);
if FVt_Ostream <> 0 then
Inc(ElemsAssigned);
if FVt_Storage <> 0 then
Inc(ElemsAssigned);
if FVt_Ostorage <> 0 then
Inc(ElemsAssigned);
Inc(ElemsAssigned,FVt_Vstream.CheckAssigned);
if FVt_Clsid <> '' then
Inc(ElemsAssigned);
Inc(ElemsAssigned,FVt_Cf.CheckAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := [xaElements];
Inc(Result,ElemsAssigned);
end;
function TCT_Variant.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
case CalcHash_B(QName) of
$B5C7FF21: begin
if FVt_Variant = Nil then
FVt_Variant := TCT_Variant.Create(FOwner);
Result := FVt_Variant;
end;
$81B62115: begin
if FVt_Vector = Nil then
FVt_Vector := TCT_Vector.Create(FOwner);
Result := FVt_Vector;
end;
$B440F481: begin
if FVt_Array = Nil then
FVt_Array := TCT_Array.Create(FOwner);
Result := FVt_Array;
end;
$967441F3: FVt_Blob := XmlStrToIntDef(AReader.Text,0);
$98D69A10: FVt_Oblob := XmlStrToIntDef(AReader.Text,0);
$7F5EEFD7: Result := FVt_Empty;
$B853B495: Result := FVt_Null;
$38DDD3DA: FVt_I1 := XmlStrToIntDef(AReader.Text,0);
$38DDD3DB: FVt_I2 := XmlStrToIntDef(AReader.Text,0);
$38DDD3DD: FVt_I4 := XmlStrToIntDef(AReader.Text,0);
$38DDD3E1: FVt_I8 := XmlStrToIntDef(AReader.Text,0);
$0A8080CD: FVt_Int := XmlStrToIntDef(AReader.Text,0);
$B3221D13: FVt_Ui1 := XmlStrToIntDef(AReader.Text,0);
$B3221D14: FVt_Ui2 := XmlStrToIntDef(AReader.Text,0);
$B3221D16: FVt_Ui4 := XmlStrToIntDef(AReader.Text,0);
$B3221D1A: FVt_Ui8 := XmlStrToIntDef(AReader.Text,0);
$EF455F44: FVt_Uint := XmlStrToIntDef(AReader.Text,0);
$4B44F38E: FVt_R4 := XmlStrToFloatDef(AReader.Text,0);
$4B44F392: FVt_R8 := XmlStrToFloatDef(AReader.Text,0);
$0BBD54E9: FVt_Decimal := XmlStrToFloatDef(AReader.Text,0);
$1195B217: FVt_Lpstr := AReader.Text;
$2B7BCD18: FVt_Lpwstr := AReader.Text;
$77E8DE81: FVt_Bstr := AReader.Text;
$5CBC47B4: FVt_Date := XmlStrToDateTime(AReader.Text);
$3859BFE7: FVt_Filetime := XmlStrToDateTime(AReader.Text);
$DB822482: FVt_Bool := XmlStrToBoolDef(AReader.Text,False);
$81EE69AC: FVt_Cy := AReader.Text;
$705AE430: FVt_Error := AReader.Text;
$58E2571E: FVt_Stream := XmlStrToIntDef(AReader.Text,0);
$DD4415E3: FVt_Ostream := XmlStrToIntDef(AReader.Text,0);
$7788575F: FVt_Storage := XmlStrToIntDef(AReader.Text,0);
$CFAA81EA: FVt_Ostorage := XmlStrToIntDef(AReader.Text,0);
$8A564EC4: begin
Result := FVt_Vstream;
if AReader.HasText then
TCT_Vstream(Result).Content := XmlStrToIntDef(AReader.Text,0);
end;
$2E171597: FVt_Clsid := AReader.Text;
$81EE6999: begin
Result := FVt_Cf;
if AReader.HasText then
TCT_Cf(Result).Content := XmlStrToIntDef(AReader.Text,0);
end;
else
FOwner.Errors.Error(xemUnknownElement,QName);
end;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_Variant.Write(AWriter: TXpgWriteXML);
begin
if (FVt_Variant <> Nil) and FVt_Variant.Assigned then
if xaElements in FVt_Variant.FAssigneds then
begin
AWriter.BeginTag('vt:variant');
FVt_Variant.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('vt:variant');
if (FVt_Vector <> Nil) and FVt_Vector.Assigned then
begin
FVt_Vector.WriteAttributes(AWriter);
if xaElements in FVt_Vector.FAssigneds then
begin
AWriter.BeginTag('vt:vector');
FVt_Vector.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('vt:vector');
end;
if (FVt_Array <> Nil) and FVt_Array.Assigned then
begin
FVt_Array.WriteAttributes(AWriter);
if xaElements in FVt_Array.FAssigneds then
begin
AWriter.BeginTag('vt:array');
FVt_Array.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('vt:array');
end;
if FVt_Blob <> 0 then
AWriter.SimpleTextTag('vt:blob',XmlIntToStr(FVt_Blob));
if FVt_Oblob <> 0 then
AWriter.SimpleTextTag('vt:oblob',XmlIntToStr(FVt_Oblob));
if FVt_Empty.Assigned then
AWriter.SimpleTag('vt:empty');
if FVt_Null.Assigned then
AWriter.SimpleTag('vt:null');
if FVt_I1 <> 0 then
AWriter.SimpleTextTag('vt:i1',XmlIntToStr(FVt_I1));
if FVt_I2 <> 0 then
AWriter.SimpleTextTag('vt:i2',XmlIntToStr(FVt_I2));
if FVt_I4 <> 0 then
AWriter.SimpleTextTag('vt:i4',XmlIntToStr(FVt_I4));
if FVt_I8 <> 0 then
AWriter.SimpleTextTag('vt:i8',XmlIntToStr(FVt_I8));
if FVt_Int <> 0 then
AWriter.SimpleTextTag('vt:int',XmlIntToStr(FVt_Int));
if FVt_Ui1 <> 0 then
AWriter.SimpleTextTag('vt:ui1',XmlIntToStr(FVt_Ui1));
if FVt_Ui2 <> 0 then
AWriter.SimpleTextTag('vt:ui2',XmlIntToStr(FVt_Ui2));
if FVt_Ui4 <> 0 then
AWriter.SimpleTextTag('vt:ui4',XmlIntToStr(FVt_Ui4));
if FVt_Ui8 <> 0 then
AWriter.SimpleTextTag('vt:ui8',XmlIntToStr(FVt_Ui8));
if FVt_Uint <> 0 then
AWriter.SimpleTextTag('vt:uint',XmlIntToStr(FVt_Uint));
if FVt_R4 <> 0 then
AWriter.SimpleTextTag('vt:r4',XmlFloatToStr(FVt_R4));
if FVt_R8 <> 0 then
AWriter.SimpleTextTag('vt:r8',XmlFloatToStr(FVt_R8));
if FVt_Decimal <> 0 then
AWriter.SimpleTextTag('vt:decimal',XmlFloatToStr(FVt_Decimal));
if FVt_Lpstr <> '' then
AWriter.SimpleTextTag('vt:lpstr',FVt_Lpstr);
if FVt_Lpwstr <> '' then
AWriter.SimpleTextTag('vt:lpwstr',FVt_Lpwstr);
if FVt_Bstr <> '' then
AWriter.SimpleTextTag('vt:bstr',FVt_Bstr);
if FVt_Date <> 0 then
AWriter.SimpleTextTag('vt:date',XmlDateTimeToStr(FVt_Date));
if FVt_Filetime <> 0 then
AWriter.SimpleTextTag('vt:filetime',XmlDateTimeToStr(FVt_Filetime));
if FVt_Bool <> False then
AWriter.SimpleTextTag('vt:bool',XmlBoolToStr(FVt_Bool));
if FVt_Cy <> '' then
AWriter.SimpleTextTag('vt:cy',FVt_Cy);
if FVt_Error <> '' then
AWriter.SimpleTextTag('vt:error',FVt_Error);
if FVt_Stream <> 0 then
AWriter.SimpleTextTag('vt:stream',XmlIntToStr(FVt_Stream));
if FVt_Ostream <> 0 then
AWriter.SimpleTextTag('vt:ostream',XmlIntToStr(FVt_Ostream));
if FVt_Storage <> 0 then
AWriter.SimpleTextTag('vt:storage',XmlIntToStr(FVt_Storage));
if FVt_Ostorage <> 0 then
AWriter.SimpleTextTag('vt:ostorage',XmlIntToStr(FVt_Ostorage));
if FVt_Vstream.Assigned then
begin
AWriter.Text := XmlIntToStr(FVt_Vstream.Content);
FVt_Vstream.WriteAttributes(AWriter);
AWriter.SimpleTag('vt:vstream');
end;
if FVt_Clsid <> '' then
AWriter.SimpleTextTag('vt:clsid',FVt_Clsid);
if FVt_Cf.Assigned then
begin
AWriter.Text := XmlIntToStr(FVt_Cf.Content);
FVt_Cf.WriteAttributes(AWriter);
AWriter.SimpleTag('vt:cf');
end;
end;
constructor TCT_Variant.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 35;
FAttributeCount := 0;
FVt_Empty := TCT_Empty.Create(FOwner);
FVt_Null := TCT_Null.Create(FOwner);
FVt_Vstream := TCT_Vstream.Create(FOwner);
FVt_Cf := TCT_Cf.Create(FOwner);
end;
destructor TCT_Variant.Destroy;
begin
if FVt_Variant <> Nil then
FVt_Variant.Free;
if FVt_Vector <> Nil then
FVt_Vector.Free;
if FVt_Array <> Nil then
FVt_Array.Free;
FVt_Empty.Free;
FVt_Null.Free;
FVt_Vstream.Free;
FVt_Cf.Free;
end;
procedure TCT_Variant.Clear;
begin
FAssigneds := [];
if FVt_Variant <> Nil then
FVt_Variant.Clear;
if FVt_Vector <> Nil then
FVt_Vector.Clear;
if FVt_Array <> Nil then
FVt_Array.Clear;
FVt_Blob := 0;
FVt_Oblob := 0;
FVt_Empty.Clear;
FVt_Null.Clear;
FVt_I1 := 0;
FVt_I2 := 0;
FVt_I4 := 0;
FVt_I8 := 0;
FVt_Int := 0;
FVt_Ui1 := 0;
FVt_Ui2 := 0;
FVt_Ui4 := 0;
FVt_Ui8 := 0;
FVt_Uint := 0;
FVt_R4 := 0;
FVt_R8 := 0;
FVt_Decimal := 0;
FVt_Lpstr := '';
FVt_Lpwstr := '';
FVt_Bstr := '';
FVt_Date := 0;
FVt_Filetime := 0;
FVt_Bool := False;
FVt_Cy := '';
FVt_Error := '';
FVt_Stream := 0;
FVt_Ostream := 0;
FVt_Storage := 0;
FVt_Ostorage := 0;
FVt_Vstream.Clear;
FVt_Clsid := '';
FVt_Cf.Clear;
end;
function TCT_Variant.CreateTCT_Variant: TCT_Variant;
begin
Result := TCT_Variant.Create(FOwner);
end;
function TCT_Variant.CreateTCT_Vector: TCT_Vector;
begin
Result := TCT_Vector.Create(FOwner);
end;
function TCT_Variant.CreateTCT_Array: TCT_Array;
begin
Result := TCT_Array.Create(FOwner);
end;
{ TCT_VariantXpgList }
function TCT_VariantXpgList.GetItems(Index: integer): TCT_Variant;
begin
Result := TCT_Variant(inherited Items[Index]);
end;
function TCT_VariantXpgList.Add: TCT_Variant;
begin
Result := TCT_Variant.Create(FOwner);
inherited Add(Result);
end;
function TCT_VariantXpgList.CheckAssigned: integer;
var
i: integer;
begin
Result := 0;
for i := 0 to Count - 1 do
Inc(Result,Items[i].CheckAssigned);
FAssigned := Result > 0;
end;
procedure TCT_VariantXpgList.Write(AWriter: TXpgWriteXML; AName: AxUCString);
var
i: integer;
begin
for i := 0 to Count - 1 do
if xaElements in Items[i].FAssigneds then
begin
AWriter.BeginTag(AName);
GetItems(i).Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag(AName);
end;
{ TCT_Array }
function TCT_Array.CheckAssigned: integer;
var
ElemsAssigned: integer;
AttrsAssigned: integer;
begin
ElemsAssigned := 0;
AttrsAssigned := 0;
FAssigneds := [];
if FLBounds <> 0 then
Inc(AttrsAssigned);
if FUBounds <> 0 then
Inc(AttrsAssigned);
if Integer(FBaseType) <> XPG_UNKNOWN_ENUM then
Inc(AttrsAssigned);
if FVt_VariantXpgList <> Nil then
Inc(ElemsAssigned,FVt_VariantXpgList.CheckAssigned);
Inc(ElemsAssigned,FVt_I1XpgList.Count);
Inc(ElemsAssigned,FVt_I2XpgList.Count);
Inc(ElemsAssigned,FVt_I4XpgList.Count);
Inc(ElemsAssigned,FVt_IntXpgList.Count);
Inc(ElemsAssigned,FVt_Ui1XpgList.Count);
Inc(ElemsAssigned,FVt_Ui2XpgList.Count);
Inc(ElemsAssigned,FVt_Ui4XpgList.Count);
Inc(ElemsAssigned,FVt_UintXpgList.Count);
Inc(ElemsAssigned,FVt_R4XpgList.Count);
Inc(ElemsAssigned,FVt_R8XpgList.Count);
Inc(ElemsAssigned,FVt_DecimalXpgList.Count);
Inc(ElemsAssigned,FVt_BstrXpgList.Count);
Inc(ElemsAssigned,FVt_DateXpgList.Count);
Inc(ElemsAssigned,FVt_BoolXpgList.Count);
Inc(ElemsAssigned,FVt_ErrorXpgList.Count);
Inc(ElemsAssigned,FVt_CyXpgList.Count);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := FAssigneds + [xaElements];
if AttrsAssigned > 0 then
FAssigneds := FAssigneds + [xaAttributes];
Inc(Result,ElemsAssigned + AttrsAssigned);
end;
function TCT_Array.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
case CalcHash_A(QName) of
$00000419: begin
if FVt_VariantXpgList = Nil then
FVt_VariantXpgList := TCT_VariantXpgList.Create(FOwner);
Result := FVt_VariantXpgList.Add;
end;
$000001BE: FVt_I1XpgList.Add(AReader.Text);
$000001BF: FVt_I2XpgList.Add(AReader.Text);
$000001C1: FVt_I4XpgList.Add(AReader.Text);
$0000026F: FVt_IntXpgList.Add(AReader.Text);
$00000233: FVt_Ui1XpgList.Add(AReader.Text);
$00000234: FVt_Ui2XpgList.Add(AReader.Text);
$00000236: FVt_Ui4XpgList.Add(AReader.Text);
$000002E4: FVt_UintXpgList.Add(AReader.Text);
$000001CA: FVt_R4XpgList.Add(AReader.Text);
$000001CE: FVt_R8XpgList.Add(AReader.Text);
$000003F3: FVt_DecimalXpgList.Add(AReader.Text);
$000002DF: FVt_BstrXpgList.Add(AReader.Text);
$000002C2: FVt_DateXpgList.Add(AReader.Text);
$000002D0: FVt_BoolXpgList.Add(AReader.Text);
$0000034E: FVt_ErrorXpgList.Add(AReader.Text);
$00000200: FVt_CyXpgList.Add(AReader.Text);
else
FOwner.Errors.Error(xemUnknownElement,QName);
end;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_Array.Write(AWriter: TXpgWriteXML);
begin
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Write(AWriter,'vt:variant');
FVt_I1XpgList.WriteElements(AWriter,'vt:i1');
FVt_I2XpgList.WriteElements(AWriter,'vt:i2');
FVt_I4XpgList.WriteElements(AWriter,'vt:i4');
FVt_IntXpgList.WriteElements(AWriter,'vt:int');
FVt_Ui1XpgList.WriteElements(AWriter,'vt:ui1');
FVt_Ui2XpgList.WriteElements(AWriter,'vt:ui2');
FVt_Ui4XpgList.WriteElements(AWriter,'vt:ui4');
FVt_UintXpgList.WriteElements(AWriter,'vt:uint');
FVt_R4XpgList.WriteElements(AWriter,'vt:r4');
FVt_R8XpgList.WriteElements(AWriter,'vt:r8');
FVt_DecimalXpgList.WriteElements(AWriter,'vt:decimal');
FVt_BstrXpgList.WriteElements(AWriter,'vt:bstr');
FVt_DateXpgList.WriteElements(AWriter,'vt:date');
FVt_BoolXpgList.WriteElements(AWriter,'vt:bool');
FVt_ErrorXpgList.WriteElements(AWriter,'vt:error');
FVt_CyXpgList.WriteElements(AWriter,'vt:cy');
end;
procedure TCT_Array.WriteAttributes(AWriter: TXpgWriteXML);
begin
AWriter.AddAttribute('lBounds',XmlIntToStr(FLBounds));
AWriter.AddAttribute('uBounds',XmlIntToStr(FUBounds));
if Integer(FBaseType) <> XPG_UNKNOWN_ENUM then
AWriter.AddAttribute('baseType',StrTST_ArrayBaseType[Integer(FBaseType)]);
end;
procedure TCT_Array.AssignAttributes(AAttributes: TXpgXMLAttributeList);
var
i: integer;
S: AxUCString;
begin
for i := 0 to AAttributes.Count - 1 do
begin
S := AAttributes[i];
case CalcHash_A(S) of
$000002D7: FLBounds := XmlStrToIntDef(AAttributes.Values[i],0);
$000002E0: FUBounds := XmlStrToIntDef(AAttributes.Values[i],0);
$0000033D: FBaseType := TST_ArrayBaseType(StrToEnum('stabt' + AAttributes.Values[i]));
else
FOwner.Errors.Error(xemUnknownAttribute,S);
end;
end
end;
constructor TCT_Array.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 17;
FAttributeCount := 3;
FVt_I1XpgList := TLongwordXpgList.Create;
FVt_I2XpgList := TLongwordXpgList.Create;
FVt_I4XpgList := TLongwordXpgList.Create;
FVt_IntXpgList := TLongwordXpgList.Create;
FVt_Ui1XpgList := TLongwordXpgList.Create;
FVt_Ui2XpgList := TLongwordXpgList.Create;
FVt_Ui4XpgList := TLongwordXpgList.Create;
FVt_UintXpgList := TLongwordXpgList.Create;
FVt_R4XpgList := TExtendedXpgList.Create;
FVt_R8XpgList := TExtendedXpgList.Create;
FVt_DecimalXpgList := TExtendedXpgList.Create;
FVt_BstrXpgList := TStringXpgList.Create;
FVt_DateXpgList := TTDateTimeXpgList.Create;
FVt_BoolXpgList := TBooleanXpgList.Create;
FVt_ErrorXpgList := TStringXpgList.Create;
FVt_CyXpgList := TStringXpgList.Create;
FBaseType := TST_ArrayBaseType(XPG_UNKNOWN_ENUM);
end;
destructor TCT_Array.Destroy;
begin
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Free;
FVt_I1XpgList.Free;
FVt_I2XpgList.Free;
FVt_I4XpgList.Free;
FVt_IntXpgList.Free;
FVt_Ui1XpgList.Free;
FVt_Ui2XpgList.Free;
FVt_Ui4XpgList.Free;
FVt_UintXpgList.Free;
FVt_R4XpgList.Free;
FVt_R8XpgList.Free;
FVt_DecimalXpgList.Free;
FVt_BstrXpgList.Free;
FVt_DateXpgList.Free;
FVt_BoolXpgList.Free;
FVt_ErrorXpgList.Free;
FVt_CyXpgList.Free;
end;
procedure TCT_Array.Clear;
begin
FAssigneds := [];
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Clear;
FVt_I1XpgList.DelimitedText := '';
FVt_I2XpgList.DelimitedText := '';
FVt_I4XpgList.DelimitedText := '';
FVt_IntXpgList.DelimitedText := '';
FVt_Ui1XpgList.DelimitedText := '';
FVt_Ui2XpgList.DelimitedText := '';
FVt_Ui4XpgList.DelimitedText := '';
FVt_UintXpgList.DelimitedText := '';
FVt_R4XpgList.DelimitedText := '';
FVt_R8XpgList.DelimitedText := '';
FVt_DecimalXpgList.DelimitedText := '';
FVt_BstrXpgList.DelimitedText := '';
FVt_DateXpgList.DelimitedText := '';
FVt_BoolXpgList.DelimitedText := '';
FVt_ErrorXpgList.DelimitedText := '';
FVt_CyXpgList.DelimitedText := '';
FLBounds := 0;
FUBounds := 0;
FBaseType := TST_ArrayBaseType(XPG_UNKNOWN_ENUM);
end;
function TCT_Array.CreateTCT_VariantXpgList: TCT_VariantXpgList;
begin
Result := TCT_VariantXpgList.Create(FOwner);
end;
{ TCT_Vector }
function TCT_Vector.CheckAssigned: integer;
var
ElemsAssigned: integer;
AttrsAssigned: integer;
begin
ElemsAssigned := 0;
AttrsAssigned := 0;
FAssigneds := [];
if Integer(FBaseType) <> XPG_UNKNOWN_ENUM then
Inc(AttrsAssigned);
if FSize <> 0 then
Inc(AttrsAssigned);
if FVt_VariantXpgList <> Nil then
Inc(ElemsAssigned,FVt_VariantXpgList.CheckAssigned);
Inc(ElemsAssigned,FVt_I1XpgList.Count);
Inc(ElemsAssigned,FVt_I2XpgList.Count);
Inc(ElemsAssigned,FVt_I4XpgList.Count);
Inc(ElemsAssigned,FVt_I8XpgList.Count);
Inc(ElemsAssigned,FVt_Ui1XpgList.Count);
Inc(ElemsAssigned,FVt_Ui2XpgList.Count);
Inc(ElemsAssigned,FVt_Ui4XpgList.Count);
Inc(ElemsAssigned,FVt_Ui8XpgList.Count);
Inc(ElemsAssigned,FVt_R4XpgList.Count);
Inc(ElemsAssigned,FVt_R8XpgList.Count);
Inc(ElemsAssigned,FVt_LpstrXpgList.Count);
Inc(ElemsAssigned,FVt_LpwstrXpgList.Count);
Inc(ElemsAssigned,FVt_BstrXpgList.Count);
Inc(ElemsAssigned,FVt_DateXpgList.Count);
Inc(ElemsAssigned,FVt_FiletimeXpgList.Count);
Inc(ElemsAssigned,FVt_BoolXpgList.Count);
Inc(ElemsAssigned,FVt_CyXpgList.Count);
Inc(ElemsAssigned,FVt_ErrorXpgList.Count);
Inc(ElemsAssigned,FVt_ClsidXpgList.Count);
Inc(ElemsAssigned,FVt_CfXpgList.CheckAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := FAssigneds + [xaElements];
if AttrsAssigned > 0 then
FAssigneds := FAssigneds + [xaAttributes];
Inc(Result,ElemsAssigned + AttrsAssigned);
end;
function TCT_Vector.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
case CalcHash_A(QName) of
$00000419: begin
if FVt_VariantXpgList = Nil then
FVt_VariantXpgList := TCT_VariantXpgList.Create(FOwner);
Result := FVt_VariantXpgList.Add;
end;
$000001BE: FVt_I1XpgList.Add(AReader.Text);
$000001BF: FVt_I2XpgList.Add(AReader.Text);
$000001C1: FVt_I4XpgList.Add(AReader.Text);
$000001C5: FVt_I8XpgList.Add(AReader.Text);
$00000233: FVt_Ui1XpgList.Add(AReader.Text);
$00000234: FVt_Ui2XpgList.Add(AReader.Text);
$00000236: FVt_Ui4XpgList.Add(AReader.Text);
$0000023A: FVt_Ui8XpgList.Add(AReader.Text);
$000001CA: FVt_R4XpgList.Add(AReader.Text);
$000001CE: FVt_R8XpgList.Add(AReader.Text);
$00000359: FVt_LpstrXpgList.Add(AReader.Text);
$000003D0: FVt_LpwstrXpgList.Add(AReader.Text);
$000002DF: FVt_BstrXpgList.Add(AReader.Text);
$000002C2: FVt_DateXpgList.Add(AReader.Text);
$00000473: FVt_FiletimeXpgList.Add(AReader.Text);
$000002D0: FVt_BoolXpgList.Add(AReader.Text);
$00000200: FVt_CyXpgList.Add(AReader.Text);
$0000034E: FVt_ErrorXpgList.Add(AReader.Text);
$00000333: FVt_ClsidXpgList.Add(AReader.Text);
$000001ED: begin
Result := FVt_CfXpgList.Add;
if AReader.HasText then
TCT_Cf(Result).Content := XmlStrToIntDef(AReader.Text,0);
end;
else
FOwner.Errors.Error(xemUnknownElement,QName);
end;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_Vector.Write(AWriter: TXpgWriteXML);
begin
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Write(AWriter,'vt:variant');
FVt_I1XpgList.WriteElements(AWriter,'vt:i1');
FVt_I2XpgList.WriteElements(AWriter,'vt:i2');
FVt_I4XpgList.WriteElements(AWriter,'vt:i4');
FVt_I8XpgList.WriteElements(AWriter,'vt:i8');
FVt_Ui1XpgList.WriteElements(AWriter,'vt:ui1');
FVt_Ui2XpgList.WriteElements(AWriter,'vt:ui2');
FVt_Ui4XpgList.WriteElements(AWriter,'vt:ui4');
FVt_Ui8XpgList.WriteElements(AWriter,'vt:ui8');
FVt_R4XpgList.WriteElements(AWriter,'vt:r4');
FVt_R8XpgList.WriteElements(AWriter,'vt:r8');
FVt_LpstrXpgList.WriteElements(AWriter,'vt:lpstr');
FVt_LpwstrXpgList.WriteElements(AWriter,'vt:lpwstr');
FVt_BstrXpgList.WriteElements(AWriter,'vt:bstr');
FVt_DateXpgList.WriteElements(AWriter,'vt:date');
FVt_FiletimeXpgList.WriteElements(AWriter,'vt:filetime');
FVt_BoolXpgList.WriteElements(AWriter,'vt:bool');
FVt_CyXpgList.WriteElements(AWriter,'vt:cy');
FVt_ErrorXpgList.WriteElements(AWriter,'vt:error');
FVt_ClsidXpgList.WriteElements(AWriter,'vt:clsid');
FVt_CfXpgList.Write(AWriter,'vt:cf');
end;
procedure TCT_Vector.WriteAttributes(AWriter: TXpgWriteXML);
begin
if Integer(FBaseType) <> XPG_UNKNOWN_ENUM then
AWriter.AddAttribute('baseType',StrTST_VectorBaseType[Integer(FBaseType)]);
AWriter.AddAttribute('size',XmlIntToStr(FSize));
end;
procedure TCT_Vector.AssignAttributes(AAttributes: TXpgXMLAttributeList);
var
i: integer;
S: AxUCString;
begin
for i := 0 to AAttributes.Count - 1 do
begin
S := AAttributes[i];
case CalcHash_A(S) of
$0000033D: FBaseType := TST_VectorBaseType(StrToEnum('stvbt' + AAttributes.Values[i]));
$000001BB: FSize := XmlStrToIntDef(AAttributes.Values[i],0);
else
FOwner.Errors.Error(xemUnknownAttribute,S);
end;
end
end;
constructor TCT_Vector.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 21;
FAttributeCount := 2;
FVt_I1XpgList := TLongwordXpgList.Create;
FVt_I2XpgList := TLongwordXpgList.Create;
FVt_I4XpgList := TLongwordXpgList.Create;
FVt_I8XpgList := TLongwordXpgList.Create;
FVt_Ui1XpgList := TLongwordXpgList.Create;
FVt_Ui2XpgList := TLongwordXpgList.Create;
FVt_Ui4XpgList := TLongwordXpgList.Create;
FVt_Ui8XpgList := TLongwordXpgList.Create;
FVt_R4XpgList := TExtendedXpgList.Create;
FVt_R8XpgList := TExtendedXpgList.Create;
FVt_LpstrXpgList := TStringXpgList.Create;
FVt_LpwstrXpgList := TStringXpgList.Create;
FVt_BstrXpgList := TStringXpgList.Create;
FVt_DateXpgList := TTDateTimeXpgList.Create;
FVt_FiletimeXpgList := TTDateTimeXpgList.Create;
FVt_BoolXpgList := TBooleanXpgList.Create;
FVt_CyXpgList := TStringXpgList.Create;
FVt_ErrorXpgList := TStringXpgList.Create;
FVt_ClsidXpgList := TStringXpgList.Create;
FVt_CfXpgList := TCT_CfXpgList.Create(FOwner);
FBaseType := TST_VectorBaseType(XPG_UNKNOWN_ENUM);
end;
destructor TCT_Vector.Destroy;
begin
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Free;
FVt_I1XpgList.Free;
FVt_I2XpgList.Free;
FVt_I4XpgList.Free;
FVt_I8XpgList.Free;
FVt_Ui1XpgList.Free;
FVt_Ui2XpgList.Free;
FVt_Ui4XpgList.Free;
FVt_Ui8XpgList.Free;
FVt_R4XpgList.Free;
FVt_R8XpgList.Free;
FVt_LpstrXpgList.Free;
FVt_LpwstrXpgList.Free;
FVt_BstrXpgList.Free;
FVt_DateXpgList.Free;
FVt_FiletimeXpgList.Free;
FVt_BoolXpgList.Free;
FVt_CyXpgList.Free;
FVt_ErrorXpgList.Free;
FVt_ClsidXpgList.Free;
FVt_CfXpgList.Free;
end;
procedure TCT_Vector.Clear;
begin
FAssigneds := [];
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Clear;
FVt_I1XpgList.DelimitedText := '';
FVt_I2XpgList.DelimitedText := '';
FVt_I4XpgList.DelimitedText := '';
FVt_I8XpgList.DelimitedText := '';
FVt_Ui1XpgList.DelimitedText := '';
FVt_Ui2XpgList.DelimitedText := '';
FVt_Ui4XpgList.DelimitedText := '';
FVt_Ui8XpgList.DelimitedText := '';
FVt_R4XpgList.DelimitedText := '';
FVt_R8XpgList.DelimitedText := '';
FVt_LpstrXpgList.DelimitedText := '';
FVt_LpwstrXpgList.DelimitedText := '';
FVt_BstrXpgList.DelimitedText := '';
FVt_DateXpgList.DelimitedText := '';
FVt_FiletimeXpgList.DelimitedText := '';
FVt_BoolXpgList.DelimitedText := '';
FVt_CyXpgList.DelimitedText := '';
FVt_ErrorXpgList.DelimitedText := '';
FVt_ClsidXpgList.DelimitedText := '';
FVt_CfXpgList.Clear;
FBaseType := TST_VectorBaseType(XPG_UNKNOWN_ENUM);
FSize := 0;
end;
function TCT_Vector.CreateTCT_VariantXpgList: TCT_VariantXpgList;
begin
if FVt_VariantXpgList <> Nil then
FVt_VariantXpgList.Free;
Result := TCT_VariantXpgList.Create(FOwner);
FVt_VariantXpgList := Result;
end;
{ TCT_VectorVariant }
function TCT_VectorVariant.CheckAssigned: integer;
var
ElemsAssigned: integer;
begin
ElemsAssigned := 0;
FAssigneds := [];
Inc(ElemsAssigned,FVt_Vector.CheckAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := [xaElements];
Inc(Result,ElemsAssigned);
end;
function TCT_VectorVariant.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
if QName = 'vt:vector' then
Result := FVt_Vector
else
FOwner.Errors.Error(xemUnknownElement,QName);
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_VectorVariant.Write(AWriter: TXpgWriteXML);
begin
if FVt_Vector.Assigned then
begin
FVt_Vector.WriteAttributes(AWriter);
if xaElements in FVt_Vector.FAssigneds then
begin
AWriter.BeginTag('vt:vector');
FVt_Vector.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('vt:vector');
end;
end;
constructor TCT_VectorVariant.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 1;
FAttributeCount := 0;
FVt_Vector := TCT_Vector.Create(FOwner);
end;
destructor TCT_VectorVariant.Destroy;
begin
FVt_Vector.Free;
end;
procedure TCT_VectorVariant.Clear;
begin
FAssigneds := [];
FVt_Vector.Clear;
end;
{ TCT_VectorLpstr }
function TCT_VectorLpstr.CheckAssigned: integer;
var
ElemsAssigned: integer;
begin
ElemsAssigned := 0;
FAssigneds := [];
Inc(ElemsAssigned,FVt_Vector.CheckAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := [xaElements];
Inc(Result,ElemsAssigned);
end;
function TCT_VectorLpstr.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
if QName = 'vt:vector' then
Result := FVt_Vector
else
FOwner.Errors.Error(xemUnknownElement,QName);
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_VectorLpstr.Write(AWriter: TXpgWriteXML);
begin
if FVt_Vector.Assigned then
begin
FVt_Vector.WriteAttributes(AWriter);
if xaElements in FVt_Vector.FAssigneds then
begin
AWriter.BeginTag('vt:vector');
FVt_Vector.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('vt:vector');
end;
end;
constructor TCT_VectorLpstr.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 1;
FAttributeCount := 0;
FVt_Vector := TCT_Vector.Create(FOwner);
end;
destructor TCT_VectorLpstr.Destroy;
begin
FVt_Vector.Free;
end;
procedure TCT_VectorLpstr.Clear;
begin
FAssigneds := [];
FVt_Vector.Clear;
end;
{ TCT_DigSigBlob }
function TCT_DigSigBlob.CheckAssigned: integer;
var
ElemsAssigned: integer;
begin
ElemsAssigned := 0;
FAssigneds := [];
if FVt_Blob <> 0 then
Inc(ElemsAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := [xaElements];
Inc(Result,ElemsAssigned);
end;
function TCT_DigSigBlob.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
if QName = 'vt:blob' then
FVt_Blob := XmlStrToIntDef(AReader.Text,0)
else
FOwner.Errors.Error(xemUnknownElement,QName);
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_DigSigBlob.Write(AWriter: TXpgWriteXML);
begin
if FVt_Blob <> 0 then
AWriter.SimpleTextTag('vt:blob',XmlIntToStr(FVt_Blob));
end;
constructor TCT_DigSigBlob.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 1;
FAttributeCount := 0;
end;
destructor TCT_DigSigBlob.Destroy;
begin
end;
procedure TCT_DigSigBlob.Clear;
begin
FAssigneds := [];
FVt_Blob := 0;
end;
{ TCT_Properties }
function TCT_Properties.CheckAssigned: integer;
var
ElemsAssigned: integer;
begin
ElemsAssigned := 0;
FAssigneds := [];
if FTemplate <> '' then
Inc(ElemsAssigned);
if FManager <> '' then
Inc(ElemsAssigned);
if FCompany <> '' then
Inc(ElemsAssigned);
if FPages <> 0 then
Inc(ElemsAssigned);
if FWords <> 0 then
Inc(ElemsAssigned);
if FCharacters <> 0 then
Inc(ElemsAssigned);
if FPresentationFormat <> '' then
Inc(ElemsAssigned);
if FLines <> 0 then
Inc(ElemsAssigned);
if FParagraphs <> 0 then
Inc(ElemsAssigned);
if FSlides <> 0 then
Inc(ElemsAssigned);
if FNotes <> 0 then
Inc(ElemsAssigned);
if FTotalTime <> 0 then
Inc(ElemsAssigned);
if FHiddenSlides <> 0 then
Inc(ElemsAssigned);
if FMMClips <> 0 then
Inc(ElemsAssigned);
if FScaleCrop <> False then
Inc(ElemsAssigned);
Inc(ElemsAssigned,FHeadingPairs.CheckAssigned);
Inc(ElemsAssigned,FTitlesOfParts.CheckAssigned);
if FLinksUpToDate <> False then
Inc(ElemsAssigned);
if FCharactersWithSpaces <> 0 then
Inc(ElemsAssigned);
if FSharedDoc <> False then
Inc(ElemsAssigned);
if FHyperlinkBase <> '' then
Inc(ElemsAssigned);
Inc(ElemsAssigned,FHLinks.CheckAssigned);
if FHyperlinksChanged <> False then
Inc(ElemsAssigned);
Inc(ElemsAssigned,FDigSig.CheckAssigned);
if FApplication <> '' then
Inc(ElemsAssigned);
if FAppVersion <> '' then
Inc(ElemsAssigned);
if FDocSecurity <> 0 then
Inc(ElemsAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := [xaElements];
Inc(Result,ElemsAssigned);
end;
function TCT_Properties.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
QName: AxUCString;
begin
Result := Self;
QName := AReader.QName;
case CalcHash_A(QName) of
$0000033C: FTemplate := AReader.Text;
$000002BB: FManager := AReader.Text;
$000002D7: FCompany := AReader.Text;
$000001F0: FPages := XmlStrToIntDef(AReader.Text,0);
$0000020F: FWords := XmlStrToIntDef(AReader.Text,0);
$00000400: FCharacters := XmlStrToIntDef(AReader.Text,0);
$00000765: FPresentationFormat := AReader.Text;
$000001FB: FLines := XmlStrToIntDef(AReader.Text,0);
$00000409: FParagraphs := XmlStrToIntDef(AReader.Text,0);
$00000264: FSlides := XmlStrToIntDef(AReader.Text,0);
$00000209: FNotes := XmlStrToIntDef(AReader.Text,0);
$00000393: FTotalTime := XmlStrToIntDef(AReader.Text,0);
$000004B0: FHiddenSlides := XmlStrToIntDef(AReader.Text,0);
$00000295: FMMClips := XmlStrToIntDef(AReader.Text,0);
$0000037C: FScaleCrop := XmlStrToBoolDef(AReader.Text,False);
$000004AF: Result := FHeadingPairs;
$00000534: Result := FTitlesOfParts;
$00000507: FLinksUpToDate := XmlStrToBoolDef(AReader.Text,False);
$000007FB: FCharactersWithSpaces := XmlStrToIntDef(AReader.Text,0);
$0000036D: FSharedDoc := XmlStrToBoolDef(AReader.Text,False);
$00000531: FHyperlinkBase := AReader.Text;
$00000249: Result := FHLinks;
$000006D3: FHyperlinksChanged := XmlStrToBoolDef(AReader.Text,False);
$00000237: Result := FDigSig;
$00000474: FApplication := AReader.Text;
$00000407: FAppVersion := AReader.Text;
$0000046E: FDocSecurity := XmlStrToIntDef(AReader.Text,0);
else
FOwner.Errors.Error(xemUnknownElement,QName);
end;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure TCT_Properties.Write(AWriter: TXpgWriteXML);
begin
if FTemplate <> '' then
AWriter.SimpleTextTag('Template',FTemplate);
if FManager <> '' then
AWriter.SimpleTextTag('Manager',FManager);
if FCompany <> '' then
AWriter.SimpleTextTag('Company',FCompany);
if FPages <> 0 then
AWriter.SimpleTextTag('Pages',XmlIntToStr(FPages));
if FWords <> 0 then
AWriter.SimpleTextTag('Words',XmlIntToStr(FWords));
if FCharacters <> 0 then
AWriter.SimpleTextTag('Characters',XmlIntToStr(FCharacters));
if FPresentationFormat <> '' then
AWriter.SimpleTextTag('PresentationFormat',FPresentationFormat);
if FLines <> 0 then
AWriter.SimpleTextTag('Lines',XmlIntToStr(FLines));
if FParagraphs <> 0 then
AWriter.SimpleTextTag('Paragraphs',XmlIntToStr(FParagraphs));
if FSlides <> 0 then
AWriter.SimpleTextTag('Slides',XmlIntToStr(FSlides));
if FNotes <> 0 then
AWriter.SimpleTextTag('Notes',XmlIntToStr(FNotes));
if FTotalTime <> 0 then
AWriter.SimpleTextTag('TotalTime',XmlIntToStr(FTotalTime));
if FHiddenSlides <> 0 then
AWriter.SimpleTextTag('HiddenSlides',XmlIntToStr(FHiddenSlides));
if FMMClips <> 0 then
AWriter.SimpleTextTag('MMClips',XmlIntToStr(FMMClips));
if FScaleCrop <> False then
AWriter.SimpleTextTag('ScaleCrop',XmlBoolToStr(FScaleCrop));
if FHeadingPairs.Assigned then
if xaElements in FHeadingPairs.FAssigneds then
begin
AWriter.BeginTag('HeadingPairs');
FHeadingPairs.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('HeadingPairs');
if FTitlesOfParts.Assigned then
if xaElements in FTitlesOfParts.FAssigneds then
begin
AWriter.BeginTag('TitlesOfParts');
FTitlesOfParts.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('TitlesOfParts');
if FLinksUpToDate <> False then
AWriter.SimpleTextTag('LinksUpToDate',XmlBoolToStr(FLinksUpToDate));
if FCharactersWithSpaces <> 0 then
AWriter.SimpleTextTag('CharactersWithSpaces',XmlIntToStr(FCharactersWithSpaces));
if FSharedDoc <> False then
AWriter.SimpleTextTag('SharedDoc',XmlBoolToStr(FSharedDoc));
if FHyperlinkBase <> '' then
AWriter.SimpleTextTag('HyperlinkBase',FHyperlinkBase);
if FHLinks.Assigned then
if xaElements in FHLinks.FAssigneds then
begin
AWriter.BeginTag('HLinks');
FHLinks.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('HLinks');
if FHyperlinksChanged <> False then
AWriter.SimpleTextTag('HyperlinksChanged',XmlBoolToStr(FHyperlinksChanged));
if FDigSig.Assigned then
if xaElements in FDigSig.FAssigneds then
begin
AWriter.BeginTag('DigSig');
FDigSig.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('DigSig');
if FApplication <> '' then
AWriter.SimpleTextTag('Application',FApplication);
if FAppVersion <> '' then
AWriter.SimpleTextTag('AppVersion',FAppVersion);
if FDocSecurity <> 0 then
AWriter.SimpleTextTag('DocSecurity',XmlIntToStr(FDocSecurity));
end;
constructor TCT_Properties.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FElementCount := 27;
FAttributeCount := 0;
FHeadingPairs := TCT_VectorVariant.Create(FOwner);
FTitlesOfParts := TCT_VectorLpstr.Create(FOwner);
FHLinks := TCT_VectorVariant.Create(FOwner);
FDigSig := TCT_DigSigBlob.Create(FOwner);
end;
destructor TCT_Properties.Destroy;
begin
FHeadingPairs.Free;
FTitlesOfParts.Free;
FHLinks.Free;
FDigSig.Free;
end;
procedure TCT_Properties.Clear;
begin
FAssigneds := [];
FTemplate := '';
FManager := '';
FCompany := '';
FPages := 0;
FWords := 0;
FCharacters := 0;
FPresentationFormat := '';
FLines := 0;
FParagraphs := 0;
FSlides := 0;
FNotes := 0;
FTotalTime := 0;
FHiddenSlides := 0;
FMMClips := 0;
FScaleCrop := False;
FHeadingPairs.Clear;
FTitlesOfParts.Clear;
FLinksUpToDate := False;
FCharactersWithSpaces := 0;
FSharedDoc := False;
FHyperlinkBase := '';
FHLinks.Clear;
FHyperlinksChanged := False;
FDigSig.Clear;
FApplication := '';
FAppVersion := '';
FDocSecurity := 0;
end;
{ T__ROOT__ }
function T__ROOT__.CheckAssigned: integer;
var
ElemsAssigned: integer;
begin
ElemsAssigned := 0;
FAssigneds := [];
Inc(ElemsAssigned,FProperties.CheckAssigned);
Result := 0;
if ElemsAssigned > 0 then
FAssigneds := [xaElements];
Inc(Result,ElemsAssigned);
end;
function T__ROOT__.HandleElement(AReader: TXpgReadXML): TXPGBase;
var
i: integer;
QName: AxUCString;
begin
for i := 0 to AReader.Attributes.Count - 1 do
FRootAttributes.Add(AReader.Attributes.AsXmlText2(i));
Result := Self;
QName := AReader.QName;
case CalcHash_B(QName) of
$DF9CD057: Result := FProperties;
else
FOwner.Errors.Error(xemUnknownElement,QName);
end;
if Result <> Self then
Result.FAssigneds := [xaRead];
end;
procedure T__ROOT__.Write(AWriter: TXpgWriteXML);
begin
AWriter.Attributes := FRootAttributes.Text;
if FProperties.Assigned then
if xaElements in FProperties.FAssigneds then
begin
AWriter.BeginTag('Properties');
FProperties.Write(AWriter);
AWriter.EndTag;
end
else
AWriter.SimpleTag('Properties');
end;
constructor T__ROOT__.Create(AOwner: TXPGDocBase);
begin
FOwner := AOwner;
FRootAttributes := TStringXpgList.Create;
FElementCount := 36;
FAttributeCount := 0;
FProperties := TCT_Properties.Create(FOwner);
end;
destructor T__ROOT__.Destroy;
begin
FRootAttributes.Free;
FProperties.Free;
end;
procedure T__ROOT__.Clear;
begin
FRootAttributes.Clear;
FAssigneds := [];
FProperties.Clear;
end;
{ TTXPGDocDocPropsApp }
function TXPGDocDocPropsApp.GetProperties: TCT_Properties;
begin
Result := FRoot.Properties;
end;
constructor TXPGDocDocPropsApp.Create;
begin
FRoot := T__ROOT__.Create(Self);
FErrors := TXpgPErrors.Create;
FReader := TXPGReader.Create(FErrors,FRoot);
FWriter := TXpgWriteXML.Create;
end;
destructor TXPGDocDocPropsApp.Destroy;
begin
FRoot.Free;
FReader.Free;
FWriter.Free;
FErrors.Free;
inherited Destroy;
end;
procedure TXPGDocDocPropsApp.LoadFromFile(AFilename: AxUCString);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(AFilename,fmOpenRead);
try
FReader.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TXPGDocDocPropsApp.LoadFromStream(AStream: TStream);
begin
FReader.LoadFromStream(AStream);
end;
procedure TXPGDocDocPropsApp.SaveToFile(AFilename: AxUCString);
begin
FWriter.SaveToFile(AFilename);
FRoot.CheckAssigned;
FRoot.Write(FWriter);
end;
procedure TXPGDocDocPropsApp.SaveToStream(AStream: TStream);
begin
FWriter.SaveToStream(AStream);
FRoot.CheckAssigned;
FRoot.Write(FWriter);
end;
initialization
{$ifdef DELPHI_5}
FEnums := TStringList.Create;
{$else}
FEnums := THashedStringList.Create;
{$endif}
TXPGBase.AddEnums;
finalization
FEnums.Free;
end.
| 29.616623 | 231 | 0.728133 |
f15405a64089e670efe558994e7328f52cc58184 | 3,616 | pas | Pascal | windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/APIExamples/FastMM/FastMMLeakGroupFrame.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/APIExamples/FastMM/FastMMLeakGroupFrame.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/APIExamples/FastMM/FastMMLeakGroupFrame.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | unit FastMMLeakGroupFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, JclStackTraceViewerAPI, FastMMParser;
type
TfrmLeakGroup = class(TFrame, IJclStackTraceViewerPreparableStackFrame, IJclStackTraceViewerStackSelection)
pnlTop: TPanel;
Label1: TLabel;
Label2: TLabel;
lbLeakCount: TLabel;
lbLeakSize: TLabel;
private
FLeakGroupData: TFastMMLeakGroup;
FStackFrame: TCustomFrame;
function GetSelected: IJclLocationInfo;
function GetPreparableLocationInfoListCount: Integer;
function GetPreparableLocationInfoList(AIndex: Integer): IJclPreparedLocationInfoList;
procedure UpdateViews;
procedure SetLeakGroupData(const Value: TFastMMLeakGroup);
{ Private-Deklarationen }
public
{ Public-Deklarationen }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property LeakGroupData: TFastMMLeakGroup write SetLeakGroupData;
end;
implementation
{$R *.dfm}
{ TfrmLeakGroup }
constructor TfrmLeakGroup.Create(AOwner: TComponent);
var
StackFrameClass: TCustomFrameClass;
begin
inherited Create(AOwner);
FLeakGroupData := nil;
if Assigned(StackTraceViewerStackServices) then
begin
StackFrameClass := StackTraceViewerStackServices.GetDefaultFrameClass(dfStack);
if Assigned(StackFrameClass) then
begin
FStackFrame := StackFrameClass.Create(Self);
FStackFrame.Parent := Self;
FStackFrame.Align := alClient;
end;
end;
end;
destructor TfrmLeakGroup.Destroy;
begin
FStackFrame.Free;
inherited Destroy;
end;
function TfrmLeakGroup.GetPreparableLocationInfoList(AIndex: Integer): IJclPreparedLocationInfoList;
begin
Result := FLeakGroupData[0].Stack;
end;
function TfrmLeakGroup.GetPreparableLocationInfoListCount: Integer;
var
Dummy: IJclPreparedLocationInfoList;
begin
if Assigned(FLeakGroupData) and (FLeakGroupData.Count > 0) and
(FLeakGroupData[0].Stack.QueryInterface(IJclPreparedLocationInfoList, Dummy) = S_OK) then
Result := 1
else
Result := 0;
end;
function TfrmLeakGroup.GetSelected: IJclLocationInfo;
var
StackTraceViewerStackSelection: IJclStackTraceViewerStackSelection;
begin
if FStackFrame.Visible and
(FStackFrame.GetInterface(IJclStackTraceViewerStackSelection, StackTraceViewerStackSelection)) and
Assigned(StackTraceViewerStackSelection.Selected) then
Result := StackTraceViewerStackSelection.Selected
else
Result := nil;
end;
procedure TfrmLeakGroup.SetLeakGroupData(const Value: TFastMMLeakGroup);
var
StackTraceViewerStackFrame: IJclStackTraceViewerStackFrame;
begin
FLeakGroupData := Value;
pnlTop.Visible := Assigned(FLeakGroupData);
if Assigned(FLeakGroupData) then
begin
lbLeakCount.Caption := IntToStr(FLeakGroupData.Count);
lbLeakSize.Caption := IntToStr(FLeakGroupData.LeakSize);
end;
if Assigned(FStackFrame) then
begin
FStackFrame.Visible := Assigned(FLeakGroupData) and (FLeakGroupData.Count > 0) and (FLeakGroupData[0].Stack.Count > 0);
if FStackFrame.Visible and (FStackFrame.GetInterface(IJclStackTraceViewerStackFrame, StackTraceViewerStackFrame)) then
StackTraceViewerStackFrame.SetStackList(FLeakGroupData[0].Stack);
end;
end;
procedure TfrmLeakGroup.UpdateViews;
var
StackTraceViewerPreparableStackFrame: IJclStackTraceViewerPreparableStackFrame;
begin
if FStackFrame.Visible and
(FStackFrame.GetInterface(IJclStackTraceViewerPreparableStackFrame, StackTraceViewerPreparableStackFrame)) then
StackTraceViewerPreparableStackFrame.UpdateViews;
end;
end.
| 30.386555 | 123 | 0.793971 |
fcf55a8b0972e01eb9437a892587d186eb53b29b | 10,505 | pas | Pascal | dependencies/Indy10/Protocols/IdTunnelCommon.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | dependencies/Indy10/Protocols/IdTunnelCommon.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | dependencies/Indy10/Protocols/IdTunnelCommon.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | {
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.0 11/13/2002 08:03:48 AM JPMugaas
}
unit IdTunnelCommon;
{*
Indy Tunnel components module
Copyright (C) 1999, 2000, 2001 Gregor Ibic (gregor.ibic@intelicom.si)
Intelicom d.o.o., www.intelicom.si
This component is published under same license like Indy package.
This package is a TCP Tunnel implementation written
by Gregor Ibic (gregor.ibic@intelicom.si).
This notice may not be removed or altered from any source
distribution.
// MAJOR CHANGES
05-January-20001
GI: Major code reorganization and polishing
31-May-2000
GI TunnelHeaders eliminated. Some other code jugling.
29-May-2000
GI Components split in several files to be more compliant
with Indy coding standards.
It consists of:
- IdTunnelHeaders
- IdTunnelCommon
- IdTunnelMaster
- IdTunnelSlave
24-May-2000
GI: Turbo translation mode finished (01:24). It works!
Will draw icons in the morning.
23-May-2000
GI: Turbo translation mode to Indy standard started by
Gregor Ibic (hehe) (now is 23:15)
*}
interface
{$i IdCompilerDefines.inc}
uses
SysUtils, Classes, SyncObjs,
IdException,
IdHashCRC,
IdStack,
IdCoder, IdResourceStrings,
IdTCPServer;
const
BUFFERLEN = $4000;
// Statistics constants
NumberOfConnectionsType = 1;
NumberOfPacketsType = 2;
CompressionRatioType = 3;
CompressedBytesType = 4;
BytesReadType = 5;
BytesWriteType = 6;
NumberOfClientsType = 7;
NumberOfSlavesType = 8;
NumberOfServicesType = 9;
// Message types
tmError = 0;
tmData = 1;
tmDisconnect = 2;
tmConnect = 3;
tmCustom = 99;
type
TIdStatisticsOperation = (soIncrease,
soDecrease
);
TIdHeader = record
CRC16: Word;
MsgType: Word;
MsgLen: Word;
UserId: Word;
Port: Word;
IpAddr: TIdInAddr;
end;
TReceiver = class(TObject)
private
fiPrenosLen: LongInt;
fiMsgLen: LongInt;
fsData: String;
fbNewMessage: Boolean;
fCRCFailed: Boolean;
Locker: TCriticalSection;
CRC16Calculator: TIdHashCRC16;
function FNewMessage: Boolean;
procedure SetData(const Value: string);
public
pBuffer: PChar;
HeaderLen: Integer;
Header: TIdHeader;
MsgLen: Word;
TypeDetected: Boolean;
Msg: PChar;
property Data: String read fsData write SetData;
property NewMessage: Boolean read FNewMessage;
property CRCFailed: Boolean read fCRCFailed;
procedure ShiftData;
constructor Create;
destructor Destroy; override;
end;
TSender = class(TObject)
public
Header: TIdHeader;
DataLen: Word;
HeaderLen: Integer;
pMsg: PChar;
Locker: TCriticalSection;
CRC16Calculator: TIdHashCRC16;
public
Msg: String;
procedure PrepareMsg(var Header: TIdHeader;
buffer: PChar; buflen: Integer);
constructor Create;
destructor Destroy; override;
end;
//
// END Communication classes
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Logging class
//
TLogger = class(TObject)
private
OnlyOneThread: TCriticalSection; // Some locking code
fLogFile: TextFile; // Debug Log File
fbActive: Boolean;
public
property Active: Boolean read fbActive Default False;
procedure LogEvent(Msg: String);
constructor Create(LogFileName: String);
destructor Destroy; override;
end;
//
// Logging class
///////////////////////////////////////////////////////////////////////////////
TSendMsgEvent = procedure(Thread: TIdPeerThread; var CustomMsg: String) of object;
TSendTrnEvent = procedure(Thread: TIdPeerThread; var Header: TIdHeader; var CustomMsg: String) of object;
TSendTrnEventC = procedure(var Header: TIdHeader; var CustomMsg: String) of object;
TTunnelEventC = procedure(Receiver: TReceiver) of object;
TSendMsgEventC = procedure(var CustomMsg: String) of object;
// TTunnelEvent = procedure(Thread: TSlaveThread) of object;
EIdTunnelException = class(EIdException);
EIdTunnelTransformErrorBeforeSend = class(EIdTunnelException);
EIdTunnelTransformError = class(EIdTunnelException);
EIdTunnelConnectToMasterFailed = class(EIdTunnelException);
EIdTunnelDontAllowConnections = class(EIdTunnelException);
EIdTunnelCRCFailed = class(EIdTunnelException);
EIdTunnelMessageTypeRecognitionError = class(EIdTunnelException);
EIdTunnelMessageHandlingFailed = class(EIdTunnelException);
EIdTunnelInterpretationOfMessageFailed = class(EIdTunnelException);
EIdTunnelCustomMessageInterpretationFailure = class(EIdTunnelException);
implementation
///////////////////////////////////////////////////////////////////////////////
// Communication classes
//
constructor TSender.Create;
begin
inherited;
Locker := TCriticalSection.Create;
CRC16Calculator := TIdHashCRC16.Create;
HeaderLen := SizeOf(TIdHeader);
GetMem(pMsg, BUFFERLEN);
end;
destructor TSender.Destroy;
begin
FreeMem(pMsg, BUFFERLEN);
Locker.Free;
CRC16Calculator.Free;
inherited;
end;
procedure TSender.PrepareMsg(var Header: TIdHeader;
buffer: PChar; buflen: Integer);
begin
Locker.Enter;
try
//Header.MsgType := mType;
Header.CRC16 := CRC16Calculator.HashValue(buffer^);
Header.MsgLen := Headerlen + bufLen;
//Header.UserId := mUser;
//Header.Port := Port;
//Header.IpAddr := IPAddr;
Move(Header, pMsg^, Headerlen);
Move(buffer^, (pMsg + Headerlen)^, bufLen);
SetLength(Msg, Header.MsgLen);
SetString(Msg, pMsg, Header.MsgLen);
finally
Locker.Leave;
end;
end;
constructor TReceiver.Create;
begin
inherited;
Locker := TCriticalSection.Create;
CRC16Calculator := TIdHashCRC16.Create;
fiPrenosLen := 0;
fsData := ''; {Do not Localize}
fiMsgLen := 0;
HeaderLen := SizeOf(TIdHeader);
GetMem(pBuffer, BUFFERLEN);
GetMem(Msg, BUFFERLEN);
end;
destructor TReceiver.Destroy;
begin
FreeMem(pBuffer, BUFFERLEN);
FreeMem(Msg, BUFFERLEN);
Locker.Free;
CRC16Calculator.Free;
inherited;
end;
function TReceiver.FNewMessage: Boolean;
begin
Result := fbNewMessage;
end;
procedure TReceiver.SetData(const Value: string);
var
CRC16: Word;
begin
Locker.Enter;
try
try
fsData := Value;
fiMsgLen := Length(fsData);
if fiMsgLen > 0 then begin
Move(fsData[1], (pBuffer + fiPrenosLen)^, fiMsgLen);
fiPrenosLen := fiPrenosLen + fiMsgLen;
if (fiPrenosLen >= HeaderLen) then begin
// copy the header
Move(pBuffer^, Header, HeaderLen);
TypeDetected := True;
// do we have enough data for the entire message
if Header.MsgLen <= fiPrenosLen then begin
MsgLen := Header.MsgLen - HeaderLen;
Move((pBuffer+HeaderLen)^, Msg^, MsgLen);
// Calculate the crc code
CRC16 := CRC16Calculator.HashValue(Msg^);
if CRC16 <> Header.CRC16 then begin
fCRCFailed := True;
end
else begin
fCRCFailed := False;
end;
fbNewMessage := True;
end
else begin
fbNewMessage := False;
end;
end
else begin
TypeDetected := False;
end;
end
else begin
fbNewMessage := False;
TypeDetected := False;
end;
except
raise;
end;
finally
Locker.Leave;
end;
end;
procedure TReceiver.ShiftData;
var
CRC16: Word;
begin
Locker.Enter;
try
fiPrenosLen := fiPrenosLen - Header.MsgLen;
// check if we have another entire message
if fiPrenosLen > 0 then begin
Move((pBuffer + Header.MsgLen)^, pBuffer^, fiPrenosLen);
end;
// check if we have another entire message
if (fiPrenosLen >= HeaderLen) then begin
// copy the header
Move(pBuffer^, Header, HeaderLen);
TypeDetected := True;
// do we have enough data for the entire message
if Header.MsgLen <= fiPrenosLen then begin
MsgLen := Header.MsgLen - HeaderLen;
Move((pBuffer+HeaderLen)^, Msg^, MsgLen);
// Calculate the crc code
CRC16 := CRC16Calculator.HashValue(Msg^);
if CRC16 <> Header.CRC16 then begin
fCRCFailed := True;
end
else begin
fCRCFailed := False;
end;
fbNewMessage := True;
end
else begin
fbNewMessage := False;
end;
end
else begin
TypeDetected := False;
end;
finally
Locker.Leave;
end;
end;
//
// END Communication classes
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Logging class
//
constructor TLogger.Create(LogFileName: String);
begin
fbActive := False;
OnlyOneThread := TCriticalSection.Create;
try
AssignFile(fLogFile, LogFileName);
Rewrite(fLogFile);
fbActive := True;
except
fbActive := False; //self.Destroy; // catch file i/o errors, double create file
end;
end;
destructor TLogger.Destroy;
begin
if fbActive then
CloseFile(fLogFile);
OnlyOneThread.Free;
inherited;
end;
procedure TLogger.LogEvent(Msg: String);
begin
OnlyOneThread.Enter;
try
WriteLn(fLogFile, Msg);
Flush(fLogFile);
finally
OnlyOneThread.Leave;
end;
end;
//
// Logging class
///////////////////////////////////////////////////////////////////////////////
end.
| 26.197007 | 109 | 0.596002 |
477e74d7382b196c633cbfae6309f6006114a228 | 9,110 | pas | Pascal | Digital_print_calculator/ofset.pas | delphi-pascal-archive/digital-print-calculator | 9c7eb2cea6155a316178fb29be04ed58cd725cc4 | [
"Unlicense"
]
| null | null | null | Digital_print_calculator/ofset.pas | delphi-pascal-archive/digital-print-calculator | 9c7eb2cea6155a316178fb29be04ed58cd725cc4 | [
"Unlicense"
]
| null | null | null | Digital_print_calculator/ofset.pas | delphi-pascal-archive/digital-print-calculator | 9c7eb2cea6155a316178fb29be04ed58cd725cc4 | [
"Unlicense"
]
| null | null | null | unit ofset;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, ComCtrls, Buttons, ExtCtrls, Mask, DBCtrls;
type
TForm4 = class(TForm)
TreeView1: TTreeView;
ComboBox2: TComboBox;
ComboBox4: TComboBox;
ComboBox3: TComboBox;
Image1: TImage;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
cem: TEdit;
edit3: TDBEdit;
edit7: TDBEdit;
edit6: TDBEdit;
SpeedButton7: TSpeedButton;
tiraj: TEdit;
Label14: TLabel;
CheckBox1: TCheckBox;
Label1: TLabel;
SpeedButton1: TSpeedButton;
ComboBox1: TComboBox;
procedure FormShow(Sender: TObject);
procedure SpeedButton7Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormHide(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormDestroy(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
q:array[0..300] of Currency;
hesab:currency;
lp,saat:string;
laska,lh,li,lk,lj:integer;
implementation
uses digim, prt, kagiz;
{$R *.dfm}
procedure TForm4.FormShow(Sender: TObject);
begin
if strtoint(form1.tiraj.Text)<500 then form4.Tiraj.text:='500' else form4.Tiraj.text:= form1.tiraj.Text;
form4.TreeView1.SetFocus;
end;
procedure TForm4.SpeedButton7Click(Sender: TObject);
label ggg;
var j:integer; tir:currency; m:string;
begin hesab:=0;
if TreeView1.Selected = nil then
begin laska :=1; form3.showmodal;
goto ggg;
end;
treeview1.Setfocus;
if (strtoint(tiraj.Text) >499) and (strtoint(tiraj.Text) <750) then m:='500';
if (strtoint(tiraj.Text) >751) and (strtoint(tiraj.Text) <1250) then m:='1000';
if (strtoint(tiraj.Text) >1251) and (strtoint(tiraj.Text) <1750) then m:='1500';
if (strtoint(tiraj.Text) >1751) and (strtoint(tiraj.Text) <2250) then m:='2000';
if (strtoint(tiraj.Text) >2251) and (strtoint(tiraj.Text) <2750) then m:='2500';
if (strtoint(tiraj.Text) >2751) and (strtoint(tiraj.Text) <3250) then m:='3000';
if (strtoint(tiraj.Text) >3251) and (strtoint(tiraj.Text) <3750) then m:='3500';
if (strtoint(tiraj.Text) >3751) and (strtoint(tiraj.Text) <4250) then m:='4000';
if (strtoint(tiraj.Text) >4251) and (strtoint(tiraj.Text) <4750) then m:='4500';
if (strtoint(tiraj.Text) >4751) then m:='5000';
laska:=0 ; j:=0;
if edit3.Text='' then edit3.Text:='1';
if edit7.Text='' then edit3.Text:='1';
Hesab:= (strtocurr(tiraj.Text)*
(strtocurr(price.offset.Values [inttostr(treeview1.TopItem.SelectedIndex)+m]))/1000);
if radiobutton2.Checked=true then hesab:=hesab+(hesab*(80/100)) else hesab:=hesab;
{minimal tiraj flayer}
if treeview1.Selected.Index=0 then
begin
if strtoint (tiraj.Text)<1500 then begin
showmessage ('Minimal tiraj 1500 eded olmali');
tiraj.Text:='1500';
end;
hesab := hesab/2; treeview1.SetFocus;
end;
if treeview1.Selected.Index=1 then
begin
if strtoint (tiraj.Text)<1000 then begin
showmessage ('Minimal tiraj 1000 eded olmali');
tiraj.Text:='1000';
end;
hesab := hesab/100*70; treeview1.SetFocus;
end;
if treeview1.Selected.Index=2 then
begin
if strtoint (tiraj.Text)<500 then begin
showmessage ('Minimal tiraj 500 eded olmali');
tiraj.Text:='500';
end;
hesab := hesab; treeview1.SetFocus;
end;
if treeview1.Selected.Index=3 then
begin
if strtoint (tiraj.Text)<500 then begin
showmessage ('Minimal tiraj 500 eded olmali');
tiraj.Text:='500';
end;
hesab := hesab*(150/100);treeview1.SetFocus;
end;
if treeview1.Selected.Index=4 then
begin
if strtoint (tiraj.Text)<500 then begin
showmessage ('Minimal tiraj 500 eded olmali');
tiraj.Text:='500';
end;
hesab := hesab*(250/100); treeview1.SetFocus;
end;
cem.Text:=FormatCurr('0.#', hesab);
if combobox2.ItemIndex=1 then hesab:= hesab+ (strtocurr(tiraj.Text)*(20/100));
if combobox2.ItemIndex=2 then hesab:= hesab+ (strtocurr(tiraj.Text)*(30/100));
if combobox2.ItemIndex=3 then hesab:= hesab+ (strtocurr(tiraj.Text)*(30/100));
if combobox2.ItemIndex=4 then hesab:= hesab+ (strtocurr(tiraj.Text)*(60/100));
if combobox2.ItemIndex=5 then hesab:= hesab+ (strtocurr(tiraj.Text)*(50/100));
if combobox2.ItemIndex=6 then hesab:= hesab+ (strtocurr(tiraj.Text)*(70/100));
if combobox1.ItemIndex=1 then hesab:= hesab+ (strtocurr(tiraj.Text)*(10/100));
if combobox2.ItemIndex=1 then hesab:= hesab+ (strtocurr(tiraj.Text)*(20/100));
if combobox3.ItemIndex=1 then hesab:= hesab+ (strtocurr(tiraj.Text)*(20/1000));
if combobox3.ItemIndex=2 then hesab:= hesab+ (strtocurr(tiraj.Text)*(30/1000));
if combobox3.ItemIndex=3 then hesab:= hesab+ (strtocurr(tiraj.Text)*(40/1000));
if combobox3.ItemIndex=4 then hesab:= hesab+ (strtocurr(tiraj.Text)*(50/1000));
if combobox4.ItemIndex=1 then hesab:= hesab+ (500/100);
if combobox4.ItemIndex=2 then hesab:= hesab+ (50/100);
if combobox4.ItemIndex=3 then hesab:= hesab+ (1000/100);
if hesab<50 then label14.Caption:='0';
if (hesab>51) and (hesab<100) then label14.Caption:=currtostr(10/10);
if (hesab>102) and (hesab<200) then label14.Caption:=currtostr(15/10);
if (hesab>202) and (hesab<500) then label14.Caption:=currtostr(20/10);
if (hesab>501) and (hesab<1000) then label14.Caption:=currtostr(25/10);
if (hesab>1001) and (hesab<2000) then label14.Caption:=currtostr(30/10);
if (hesab>2001) and (hesab<3000) then label14.Caption:=currtostr(35/10);
if (hesab>3001) and (hesab<4000) then label14.Caption:=currtostr(40/10);
if (hesab>4001) and (hesab<5000) then label14.Caption:=currtostr(45/10);
if (hesab>5001) and (hesab<6000) then label14.Caption:=currtostr(50/10);
if (hesab>6001) then label14.Caption:='5';
if checkbox1.Checked=true then
begin
edit7.Text:=currtostr((hesab/100)*strtocurr(label14.Caption));
end;
edit3.Text:=FormatCurr('0.#', hesab);
edit6.Text:=FormatCurr('0.#', hesab-strtocurr(edit7.text));
label1.Caption:=currtostr(strtocurr(edit6.text)/strtocurr(tiraj.Text));
ggg:
end;
procedure TForm4.FormClose(Sender: TObject; var Action: TCloseAction);
begin
form1.Show;
end;
procedure TForm4.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
form1.Show;
end;
procedure TForm4.FormHide(Sender: TObject);
begin
form1.Show;
end;
procedure TForm4.SpeedButton1Click(Sender: TObject);
begin
form1.Show; close;
end;
procedure TForm4.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
li:=1;
lh:=x;
lk:=y;
end;
procedure TForm4.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if li=1 then begin
form4.Left:=form4.Left+x-lh;
form4.top:=form4.top+y-lk;
end; end;
procedure TForm4.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
li:=0;
lk:=0;
end;
procedure TForm4.FormDestroy(Sender: TObject);
begin
form1.Show;
end;
procedure TForm4.Button3Click(Sender: TObject);
var m:string;
begin
if (strtoint(tiraj.Text) >500) and (strtoint(tiraj.Text) <999) then m:='500';
if (strtoint(tiraj.Text) >1000) and (strtoint(tiraj.Text) <1499) then m:='1000';
if (strtoint(tiraj.Text) >1500) and (strtoint(tiraj.Text) <1999) then m:='1500';
if (strtoint(tiraj.Text) >2000) and (strtoint(tiraj.Text) <2499) then m:='2000';
if (strtoint(tiraj.Text) >2500) and (strtoint(tiraj.Text) <2999) then m:='2500';
if (strtoint(tiraj.Text) >3000) and (strtoint(tiraj.Text) <3499) then m:='3000';
if (strtoint(tiraj.Text) >3500) and (strtoint(tiraj.Text) <3999) then m:='3500';
if (strtoint(tiraj.Text) >4000) and (strtoint(tiraj.Text) <4499) then m:='4000';
if (strtoint(tiraj.Text) >4500) and (strtoint(tiraj.Text) <4999) then m:='4500';
if (strtoint(tiraj.Text) >5000) then m:='5000';
end;
end.
| 35.173745 | 105 | 0.640395 |
474a4a4a71253073530e67cfed86ed19935bde32 | 7,461 | pas | Pascal | ImageLib/ExifReader.pas | jarupxx/wisteria | de213234f2ac647b65c2da0cbeaab26d7a1bcf5e | [
"MIT"
]
| 5 | 2018-09-18T01:59:24.000Z | 2021-07-21T19:11:10.000Z | ImageLib/ExifReader.pas | jarupxx/wisteria | de213234f2ac647b65c2da0cbeaab26d7a1bcf5e | [
"MIT"
]
| 39 | 2018-05-20T23:26:08.000Z | 2020-04-09T13:47:22.000Z | ImageLib/ExifReader.pas | jarupxx/wisteria | de213234f2ac647b65c2da0cbeaab26d7a1bcf5e | [
"MIT"
]
| 3 | 2018-06-01T13:41:40.000Z | 2020-03-14T11:19:22.000Z | unit ExifReader;
interface
uses
System.Classes, System.SysUtils, System.Math, Helpers;
function ExifDateTimeToDateTime(ExifDateTime: string): TDateTime;
function GetOriginalDateTime(FileName: string): AnsiString;
function GetModel(FileName: string): AnsiString;
function GetOrientation(FileName: string): Integer;
function GetGamma(FileName: string): Double;
function GetColorSpace(FileName: string): Integer;
implementation
var
IsLittleEndian: Boolean;
function ExifDateTimeToDateTime(ExifDateTime: string): TDateTime;
begin
Result := -1;
if Trim(ExifDateTime) = '' then
Exit;
// EXIF DateTime Format: 'YYYY:MM:DD HH:MM:SS'
ExifDateTime[5] := '/';
ExifDateTime[8] := '/';
try
Result := StrToDateTime(ExifDateTime);
except
on EConvertError do;
end;
end;
function TrimNullString(const S: AnsiString): AnsiString;
var
I: Integer;
begin
I := Length(S);
while (I > 0) and (S[I] = #0) do
Dec(I);
Result := Copy(S, 1, I);
end;
procedure CheckExifHeader(FileStream: TFileStream);
var
S: AnsiString;
B: Byte;
begin
IsLittleEndian := True;
// SOI Marker
if FileStream.ReadByte <> $FF then
raise Exception.Create('Marker ID is missing');
if FileStream.ReadByte <> $D8 then
raise Exception.Create('SOI Marker is missing');
// APP Marker
if FileStream.ReadByte <> $FF then
raise Exception.Create('Marker ID is missing');
B := FileStream.ReadByte;
if B = $E0 then
begin
// APP0 Marker
FileStream.Skip(16);
// APP1 marker
if FileStream.ReadByte <> $FF then
raise Exception.Create('Marker ID is missing');
if FileStream.ReadByte <> $E1 then
raise Exception.Create('APP1 Marker is missing');
end
else if B <> $E1 then
raise Exception.Create('APP1 Marker is missing');
FileStream.ReadByte;
FileStream.ReadByte;
// Exif Header
if FileStream.ReadString(6) <> 'Exif'#0#0 then
raise Exception.Create('EXIF Header is missing');
S := FileStream.ReadString(2);
if S = 'II' then
IsLittleEndian := True
else if S = 'MM' then
IsLittleEndian := False
else
raise Exception.Create('EXIF Header endian is corrupted');
// TAG Mark
if FileStream.ReadCardinal(2, IsLittleEndian) <> $002A then
raise Exception.Create('TAG Mark is missing');
// Offset to first IFD
if FileStream.ReadCardinal(4, IsLittleEndian) <> $00000008 then
raise Exception.Create('Offset is corrupted');
end;
function IsValue(FileStream: TFileStream; Size: Integer;
Value: Cardinal): Boolean;
begin
Result := FileStream.ReadCardinal(Size, IsLittleEndian) = Value;
end;
procedure SetOffset(FileStream: TFileStream);
var
NextPos: Integer;
begin
NextPos := 12 + FileStream.ReadCardinal(4, IsLittleEndian);
if FileStream.Seek(NextPos, soFromBeginning) <> NextPos then
raise Exception.Create('SetOffset failed');
end;
procedure SearchEntry(FileStream: TFileStream; Tag: Cardinal);
var
I, EntryCount: Integer;
begin
// Directory Entry Count
EntryCount := FileStream.ReadCardinal(2, IsLittleEndian);
for I := 0 to EntryCount - 1 do
begin
if IsValue(FileStream, 2, Tag) then
Exit;
FileStream.Skip(10);
end;
raise Exception.Create('Tag is not found');
end;
procedure SearchExifIfd(FileStream: TFileStream);
begin
// Search ExifIFDPointer(34665)
SearchEntry(FileStream, $8769);
if not IsValue(FileStream, 2, $0004) then
raise Exception.Create('Corrupted Data');
if not IsValue(FileStream, 4, $00000001) then
raise Exception.Create('Corrupted Data');
SetOffset(FileStream);
end;
function GetOriginalDateTime(FileName: string): AnsiString;
const
DATE_TIME_LEN = 19;
var
FileStream: TFileStream;
begin
Result := '';
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
try
CheckExifHeader(FileStream);
SearchExifIfd(FileStream);
// 0x9003
SearchEntry(FileStream, $9003);
if not IsValue(FileStream, 2, $0002) then
raise Exception.Create('Corrupted Data');
if not IsValue(FileStream, 4, 20) then
raise Exception.Create('Corrupted Data');
SetOffset(FileStream);
Result := FileStream.ReadString(DATE_TIME_LEN);
except
on Exception do;
end;
finally
FreeAndNil(FileStream);
end;
end;
function GetModel(FileName: string): AnsiString;
const
MODEL_MAX_LEN = 255;
var
FileStream: TFileStream;
ModelLength: Cardinal;
begin
Result := '';
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
try
CheckExifHeader(FileStream);
// 0x0110
SearchEntry(FileStream, $0110);
if not IsValue(FileStream, 2, $0002) then
raise Exception.Create('Corrupted Data');
ModelLength := Min(FileStream.ReadCardinal(4, IsLittleEndian),
MODEL_MAX_LEN);
SetOffset(FileStream);
Result := TrimNullString(FileStream.ReadString(ModelLength));
except
on Exception do;
end;
finally
FreeAndNil(FileStream);
end;
end;
function GetOrientation(FileName: string): Integer;
var
FileStream: TFileStream;
begin
Result := -1;
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
try
CheckExifHeader(FileStream);
// 0x0112
SearchEntry(FileStream, $0112);
if not IsValue(FileStream, 2, $0003) then
raise Exception.Create('Corrupted Data');
if not IsValue(FileStream, 4, $00000001) then
raise Exception.Create('Corrupted Data');
Result := FileStream.ReadCardinal(2, IsLittleEndian);
except
on Exception do;
end;
finally
FreeAndNil(FileStream);
end;
end;
function GetGamma(FileName: string): Double;
var
FileStream: TFileStream;
Numerator, Denominator: Cardinal;
begin
Result := 0;
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
try
CheckExifHeader(FileStream);
SearchExifIfd(FileStream);
// Search Gamma Value(42240)
SearchEntry(FileStream, $A500);
if not IsValue(FileStream, 2, $0005) then
raise Exception.Create('Corrupted Data');
if not IsValue(FileStream, 4, $00000001) then
raise Exception.Create('Corrupted Data');
SetOffset(FileStream);
Numerator := FileStream.ReadCardinal(4, IsLittleEndian);
Denominator := FileStream.ReadCardinal(4, IsLittleEndian);
if Denominator = 0 then
raise Exception.Create('Denominator is 0');
Result := Numerator / Denominator;
except
on Exception do;
end;
finally
FreeAndNil(FileStream);
end;
end;
function GetColorSpace(FileName: string): Integer;
var
FileStream: TFileStream;
begin
Result := -1;
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
try
CheckExifHeader(FileStream);
SearchExifIfd(FileStream);
// 0xA001 sRGB = 1, Uncalibrated = 65535
SearchEntry(FileStream, $A001);
if not IsValue(FileStream, 2, $0003) then
raise Exception.Create('Corrupted Data');
if not IsValue(FileStream, 4, $00000001) then
raise Exception.Create('Corrupted Data');
Result := FileStream.ReadCardinal(2, IsLittleEndian);
except
on Exception do;
end;
finally
FreeAndNil(FileStream);
end;
end;
end.
| 26.838129 | 69 | 0.666667 |
47cd7965659f3b962d31ada6a135351512dff9d7 | 9,105 | pas | Pascal | src/MUIClass.Menu.pas | alb42/MUIClass | 4223b4f456b770d40f9542707705cd94af612cd9 | [
"Unlicense"
]
| 3 | 2018-02-16T17:44:03.000Z | 2018-12-01T20:59:17.000Z | src/MUIClass.Menu.pas | alb42/MUIClass | 4223b4f456b770d40f9542707705cd94af612cd9 | [
"Unlicense"
]
| null | null | null | src/MUIClass.Menu.pas | alb42/MUIClass | 4223b4f456b770d40f9542707705cd94af612cd9 | [
"Unlicense"
]
| null | null | null | unit MUIClass.Menu;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl, Math,
Exec, Utility, AmigaDOS, Intuition, icon, mui, muihelper,
tagsparamshelper, MUIClass.Base;
{$M+}
type
// Usually it should look like this:
// TMUIApplication.MenuStrip -> TMUIMenuStrip -> TMUIMenu -> TMenuItem
// or
// TMUIWindow.MenuStrip -> TMUIMenuStrip -> TMUIMenu -> TMenuItem
TMUIMenustrip = class(TMUIFamily)
private
FEnabled: Boolean;
procedure SetEnabled(AValue: Boolean);
protected
procedure GetCreateTags(var ATagList: TATagList); override;
public
constructor Create; override;
procedure CreateObject; override;
published
property Enabled: Boolean read FEnabled write SetEnabled default True; // Enable/Disable Menu
end;
TMUIMenu = class(TMUIFamily)
private
FEnabled: Boolean;
FTitle: string;
procedure SetEnabled(AValue: Boolean);
procedure SetTitle(AValue: string);
protected
procedure GetCreateTags(var ATagList: TATagList); override;
public
constructor Create; override;
procedure CreateObject; override;
published
property Enabled: Boolean read FEnabled write SetEnabled default True; // Disable/Enable the full Menu
property Title: string read FTitle write SetTitle; // Title for the Menu
end;
TMUIMenuItem = class(TMUIFamily)
private
FEnabled: Boolean;
FTitle: string;
FChecked: Boolean;
FCheckIt: Boolean;
FCommandString: Boolean;
FExclude: LongWord;
FShortCut: string;
FToggle: Boolean;
FOnTrigger: TNotifyEvent;
function GetChecked: Boolean;
procedure SetChecked(AValue: Boolean);
procedure SetCheckit(AValue: Boolean);
procedure SetCommandString(AValue: Boolean);
procedure SetEnabled(AValue: Boolean);
procedure SetExclude(AValue: LongWord);
procedure SetShortCut(AValue: string);
procedure SetTitle(AValue: string);
procedure SetToggle(AValue: Boolean);
protected
procedure GetCreateTags(var ATagList: TATagList); override;
public
constructor Create; override;
procedure CreateObject; override;
procedure AfterCreateObject; override;
published
property Checked: Boolean read GetChecked write SetChecked default False; // Check a Checkable Menu Entry (if CheckIt is True)
property CheckIt: Boolean read FCheckIt write SetCheckIt default False; // If True the Item is Checkable
property CommandString: Boolean read FCommandString write SetCommandString default False; // if True SortCut points to a full Short Cut, else only the first Char + Amiga is used
property Enabled: Boolean read FEnabled write SetEnabled default True; // Enable/Disable this Menu Entry
property Exclude: LongWord read FExclude write SetExclude default 0; // BitField to uncheck other menu entries when this one is checked (Radio)
property ShortCut: string read FShortCut write SetShortCut; // ShortCut (just the name on the menu, the actual check you have to do yourself)
property Title: string read FTitle write SetTitle; // Title for menu Entry or '-' for a Line
property Toggle: Boolean read FToggle write SetToggle default False; // Automatically toggle Checkable Entries when selected by user
property OnTrigger: TNotifyEvent read FOnTrigger write FOnTrigger; // Event when an Entry is selected
end;
implementation
const
NM_BarLabel = -1;
{ TMUIMenuStrip }
constructor TMUIMenustrip.Create;
begin
inherited;
FEnabled := True;
end;
procedure TMUIMenustrip.GetCreateTags(var ATagList: TATagList);
begin
inherited;
if not FEnabled then
ATagList.AddTag(MUIA_Menustrip_Enabled, AsTag(FEnabled));
end;
procedure TMUIMenustrip.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_MenuStrip, TagList.GetTagPointer);
AfterCreateObject
end;
end;
procedure TMUIMenustrip.SetEnabled(AValue: Boolean);
begin
if AValue <> FEnabled then
begin
FEnabled := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_Menustrip_Enabled, FEnabled);
end;
end;
{ TMUIMenu }
constructor TMUIMenu.Create;
begin
inherited;
FEnabled := True;
FTitle := '';
end;
procedure TMUIMenu.GetCreateTags(var ATagList: TATagList);
begin
inherited;
if not FEnabled then
ATagList.AddTag(MUIA_Menu_Enabled, AsTag(FEnabled));
ATagList.AddTag(MUIA_Menu_Title, AsTag(PChar(FTitle)));
end;
procedure TMUIMenu.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_Menu, TagList.GetTagPointer);
AfterCreateObject
end;
end;
procedure TMUIMenu.SetEnabled(AValue: Boolean);
begin
if AValue <> FEnabled then
begin
FEnabled := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_Menu_Enabled, FEnabled);
end;
end;
procedure TMUIMenu.SetTitle(AValue: string);
begin
if AValue <> FTitle then
begin
FTitle := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_Menu_Title, PChar(FTitle));
end;
end;
{ TMUIMenuItem }
constructor TMUIMenuItem.Create;
begin
inherited;
FEnabled := True;
FTitle := '';
FChecked := False;
FCheckIt := False;
FCommandString := False;
FExclude := 0;
FShortCut := '';
FToggle := False;
end;
procedure TMUIMenuItem.GetCreateTags(var ATagList: TATagList);
begin
inherited;
if not FEnabled then
ATagList.AddTag(MUIA_MenuItem_Enabled, AsTag(FEnabled));
if FTitle = '-' then
ATagList.AddTag(MUIA_MenuItem_Title, AsTag(NM_BarLabel))
else
ATagList.AddTag(MUIA_MenuItem_Title, AsTag(PChar(FTitle)));
if FCheckIt then
ATagList.AddTag(MUIA_MenuItem_CheckIt, AsTag(FCheckIt));
if FChecked then
ATagList.AddTag(MUIA_MenuItem_Checked, AsTag(FChecked));
if FCommandString then
ATagList.AddTag(MUIA_MenuItem_CommandString, AsTag(FCommandString));
if FExclude > 0 then
ATagList.AddTag(MUIA_MenuItem_Exclude, AsTag(FExclude));
if FShortCut <> '' then
ATagList.AddTag(MUIA_MenuItem_ShortCut, AsTag(PChar(FShortCut)));
if FToggle then
ATagList.AddTag(MUIA_MenuItem_Toggle, AsTag(FToggle));
end;
procedure TMUIMenuItem.CreateObject;
var
TagList: TATagList;
begin
if not Assigned(FMUIObj) then
begin
BeforeCreateObject;
GetCreateTags(TagList);
FMUIObj := MUI_NewObjectA(MUIC_MenuItem, TagList.GetTagPointer);
AfterCreateObject
end;
end;
function TriggerFunc(Hook: PHook; Obj: PObject_; Msg: Pointer): PtrInt;
var
PasObj: TMUIMenuItem;
begin
try
Result := 0;
PasObj := TMUIMenuItem(Hook^.h_Data);
if Assigned(PasObj.OnTrigger) then
PasObj.OnTrigger(PasObj);
except
on E: Exception do
MUIApp.DoException(E);
end;
end;
procedure TMUIMenuItem.AfterCreateObject;
begin
inherited;
// Connect Events
ConnectHook(MUIA_Menuitem_Trigger, MUIV_EveryTime, @TriggerFunc);
end;
function TMUIMenuItem.GetChecked: Boolean;
begin
if HasObj then
FChecked := GetBoolValue(MUIA_MenuItem_Checked);
Result := FChecked;
end;
procedure TMUIMenuItem.SetChecked(AValue: Boolean);
begin
if AValue <> Checked then
begin
FChecked := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_Checked, FChecked);
end;
end;
procedure TMUIMenuItem.SetCheckit(AValue: Boolean);
begin
if AValue <> FCheckIt then
begin
FCheckIt := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_CheckIt, FCheckIt);
end;
end;
procedure TMUIMenuItem.SetCommandString(AValue: Boolean);
begin
if AValue <> FCommandString then
begin
FCommandString := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_CommandString, FCommandString);
end;
end;
procedure TMUIMenuItem.SetEnabled(AValue: Boolean);
begin
if AValue <> FEnabled then
begin
FEnabled := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_Enabled, FEnabled);
end;
end;
procedure TMUIMenuItem.SetExclude(AValue: LongWord);
begin
if AValue <> FExclude then
begin
FExclude := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_Exclude, FExclude);
end;
end;
procedure TMUIMenuItem.SetShortCut(AValue: string);
begin
if AValue <> FShortCut then
begin
FShortCut := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_ShortCut, PChar(FShortCut));
end;
end;
procedure TMUIMenuItem.SetTitle(AValue: string);
begin
if AValue <> FTitle then
begin
FTitle := AValue;
if Assigned(FMUIObj) then
begin
if FTitle = '-' then
SetValue(MUIA_MenuItem_Title, NM_BarLabel)
else
SetValue(MUIA_MenuItem_Title, PChar(FTitle));
end;
end;
end;
procedure TMUIMenuItem.SetToggle(AValue: Boolean);
begin
if AValue <> FToggle then
begin
FToggle := AValue;
if Assigned(FMUIObj) then
SetValue(MUIA_MenuItem_Toggle, FToggle);
end;
end;
end.
| 26.163793 | 181 | 0.720373 |
c328fd9797d880296dde8dc46e4a17591158f71c | 5,943 | pas | Pascal | Other/tarfile.pas | bashkirtsevich/PasZLib | c04b1b05a37723c4a66a02f7a802774747ad864f | [
"Unlicense"
]
| 4 | 2018-05-08T19:14:27.000Z | 2022-03-24T02:02:54.000Z | Other/tarfile.pas | bashkirtsevich/PasZLib | c04b1b05a37723c4a66a02f7a802774747ad864f | [
"Unlicense"
]
| null | null | null | Other/tarfile.pas | bashkirtsevich/PasZLib | c04b1b05a37723c4a66a02f7a802774747ad864f | [
"Unlicense"
]
| 2 | 2020-05-04T21:44:06.000Z | 2021-08-03T11:48:55.000Z | unit tarfile;
interface
uses classes, sysutils, math;
const EXP_FILENAME = 0;
EXP_SIZE = 1;
EXP_DATE = 2;
EXP_BODY = 3;
EXP_ERROR = 4;
EXP_EOF = 5;
SECSIZE = 512;
// SECSPERBLOCK = 120;
BUFSIZE = SECSIZE; // * SECSPERBLOCK;
type
TBuffer = Array [0..Pred(BUFSIZE)] Of byte;
TDateTime = record
sec : integer;
min : integer;
hour : integer;
day : integer;
month : integer;
year : integer;
end;
TTarFile = class
private
FTarF : TFileStream;
FExpecting : byte;
FName : string;
FBuffer : TBuffer;
FLen : longint;
FUnreadSec : integer;
function CrackUnixDateTime( UnixDate : longint) : TDateTime;
procedure AdjustFilename( var filename : string);
public
constructor Create( filename : string);
destructor Free;
function EOF : boolean;
function Progress : integer;
function GetNextFilename : string;
function GetNextSize : longint;
function GetNextDate : TDateTime;
function ReadFile( var buffer; maximum : longint) : longint;
Procedure SkipFile;
protected
end;
implementation
// **************************************************
// Private part
// **************************************************
function TTarFile.CrackUnixDateTime( UnixDate : longint) : TDateTime;
Const monlen : Array [1..12] Of byte
= (31,28,31,30,31,30,31,31,30,31,30,31);
var dt : TDateTime;
begin
dt.sec := UnixDate mod 60;
UnixDate := UnixDate div 60;
dt.min := UnixDate mod 60;
UnixDate := UnixDate div 60;
dt.hour := UnixDate mod 24;
UnixDate := UnixDate div 24;
dt.year := 1970;
while ((UnixDate>=365) and (dt.year mod 4 <> 0)) or
((UnixDate>=366) and (dt.year mod 4 = 0 )) do
begin
if dt.year mod 4 = 0 then UnixDate := UnixDate - 1;
UnixDate := UnixDate - 365;
Inc(dt.year)
end;
dt.month := 1;
if dt.year mod 4 = 0 then Inc(monlen[2]);
while UnixDate>=monlen[dt.month] do
begin
UnixDate := UnixDate - monlen[dt.month];
Inc(dt.month)
end;
if dt.year mod 4 = 0 then Dec(monlen[2]);
dt.day := UnixDate + 1;
Result := dt
end;
Procedure TTarFile.AdjustFilename(Var filename : string);
Const badletter : Set Of char = ['+',' ',':','<','>','|'];
Var i : byte;
Begin { openfile }
For i := Length(filename) DownTo 1 Do
Begin
If filename[i] = '/' Then filename[i] := '\';
If filename[i] In badletter Then filename[i] := '_';
End
end;
// **************************************************
// Public part
// **************************************************
constructor TTarFile.Create( filename : string);
begin
FTarF := TFileStream.Create( filename, fmOpenRead or fmShareDenyWrite);
end;
destructor TTarFile.Free;
begin
FTarF.Free;
end;
function TTarFile.EOF : boolean;
begin
EOF := FTarF.Size = FTarF.Position;
end;
function TTarFile.Progress : integer;
begin
Progress := Floor((FTarF.Position / FTarF.Size) * 100)
end;
function TTarFile.GetNextFilename : string;
var iread : integer;
i : integer;
begin
FName := '';
if (not(EOF) and (FExpecting = EXP_FILENAME)) then
begin
iread := FTarF.Read( FBuffer, SECSIZE);
If iread <> SECSIZE Then FExpecting := EXP_ERROR
else begin
i := 0;
While (FBuffer[i] <> 0) And (i < 254) Do
begin
FName := FName + char(FBuffer[i]);
Inc(i);
end;
if i > 0 then
begin
FExpecting := EXP_SIZE;
AdjustFilename( FName)
end
else begin
i := 0;
// Lazy evaluation needed to prvent reading from FBuffer[SECSIZE]
while (i < SECSIZE) and (FBuffer[i]=0) do Inc(i);
if i < SECSIZE then
FExpecting := EXP_FILENAME
else begin
FExpecting := EXP_EOF;
FTarF.Position := FTarF.Size
end
end
end
end;
Result := FName;
end;
function TTarFile.GetNextSize : longint;
var i : byte;
begin
FLen := 0;
GetNextSize := 0;
if (not(EOF) and (FExpecting = EXP_SIZE)) then
begin
For i := $7C To $86 Do
If (FBuffer[i] >= 48) And (FBuffer[i] <= 55) Then
FLen := 8*FLen + FBuffer[i] - 48;
if FLen > 0 then
FExpecting := EXP_DATE
else
FExpecting := EXP_FILENAME;
GetNextSize := FLen
end;
FUnreadSec := (SECSIZE - (FLen mod SECSIZE)) mod SECSIZE
end;
function TTarFile.GetNextDate : TDateTime;
var UnixDate : longint;
i : byte;
begin
UnixDate := 0;
if FExpecting = EXP_DATE then
begin
For i := $88 To $92 Do
If (FBuffer[i] >= 48) And (FBuffer[i] <= 55) Then
UnixDate := 8*UnixDate + FBuffer[i] - 48;
FExpecting := EXP_BODY
end;
Result := CrackUnixDateTime( UnixDate)
end;
function TTarFile.ReadFile( var buffer; maximum : longint) : longint;
var iread : longint;
buff : TBuffer;
begin
iread := 0;
if (FLen > FTarF.Size - FTarF.Position) or
(FExpecting <> EXP_BODY)
then FExpecting := EXP_ERROR
else begin
iread := FTarF.Read( buffer, min(maximum,FLen));
FLen := FLen - iread;
if FLen = 0 then
begin
FExpecting := EXP_FILENAME;
if FUnreadSec > 0 then FTarF.Read( buff, FUnreadSec)
end
end;
ReadFile := iread
end;
procedure TTarFile.SkipFile;
begin
if (FLen > FTarF.Size - FTarF.Position) or
(FExpecting <> EXP_BODY)
then FExpecting := EXP_ERROR
else begin
FTarF.Position := FTarF.Position + FLen + FUnreadSec;
FExpecting := EXP_FILENAME
end
end;
end.
| 25.397436 | 79 | 0.550227 |
c39e689781b8d60c563cbfeee741313b1d7dc63b | 9,796 | pas | Pascal | fpcdws/dwsSampling.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| 4 | 2018-09-18T07:35:52.000Z | 2021-02-18T18:21:54.000Z | fpcdws/dwsSampling.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| null | null | null | fpcdws/dwsSampling.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| 1 | 2020-10-30T07:24:05.000Z | 2020-10-30T07:24:05.000Z | {**********************************************************************}
{ }
{ "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. }
{ }
{ Copyright Creative IT. }
{ Current maintainer: Eric Grange }
{ }
{**********************************************************************}
unit dwsSampling;
{$I dws.inc}
interface
uses Windows, Classes, dwsDebugger, dwsUtils, dwsErrors, dwsSymbols,
SysUtils, dwsExprs, dwsJSON, MMSystem, dwsStrings;
type
TdwsSample = class (TRefCountedObject)
private
FSourceName : UnicodeString;
FFuncName : UnicodeString;
FLine : Integer;
FCount : Integer;
public
property SourceName : UnicodeString read FSourceName write FSourceName;
property FuncName : UnicodeString read FFuncName write FFuncName;
property Line : Integer read FLine write FLine;
property Count : Integer read FCount write FCount;
end;
// TdwsSamplings
//
TdwsSamplings = class(TSortedList<TdwsSample>)
private
FTemp : TdwsSample;
protected
function Compare(const item1, item2 : TdwsSample) : Integer; override;
public
constructor Create;
destructor Destroy; override;
procedure AddSample(scriptPos : TScriptPos; funcSym : TFuncSymbol);
procedure Clear;
procedure ToJSON(writer : TdwsJSONWriter);
function ToString : UnicodeString; override;
end;
// TdwsSamplingDebugger
//
TdwsSamplingDebugger = class (TdwsSimpleDebugger)
private
FSamplings : TdwsSamplings;
FSamplingPos : TScriptPos;
FSamplingFuncStack : TTightStack;
FTimerID : Integer;
FSamplingInterval : Integer;
FCollecting : Boolean;
FSuspended : Boolean;
protected
procedure StartDebug(exec : TdwsExecution); override;
procedure DoDebug(exec : TdwsExecution; expr : TExprBase); override;
procedure StopDebug(exec : TdwsExecution); override;
procedure EnterFunc(exec : TdwsExecution; funcExpr : TExprBase); override;
procedure LeaveFunc(exec : TdwsExecution; funcExpr : TExprBase); override;
procedure CollectSample;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
property Samplings : TdwsSamplings read FSamplings;
property SamplingInterval : Integer read FSamplingInterval write FSamplingInterval;
property Suspended : Boolean read FSuspended write FSuspended;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
type
// TdwsSamplingsSorter
//
TdwsSamplingsSorter = class(TSortedList<TdwsSample>)
protected
function Compare(const item1, item2 : TdwsSample) : Integer; override;
end;
// Compare
//
function TdwsSamplingsSorter.Compare(const item1, item2 : TdwsSample) : Integer;
begin
Result:=CompareStr(item1.SourceName, item2.SourceName);
if Result<>0 then Exit;
Result:=CompareStr(item1.FuncName, item2.FuncName);
if Result<>0 then Exit;
Result:=item1.Line-item2.Line;
end;
// ------------------
// ------------------ TdwsSamplings ------------------
// ------------------
// Compare
//
function TdwsSamplings.Compare(const item1, item2 : TdwsSample) : Integer;
begin
Result:=item1.Line-item2.Line;
if Result<>0 then Exit;
Result:=CompareStr(item1.FuncName, item2.FuncName);
if Result<>0 then Exit;
Result:=CompareStr(item1.SourceName, item2.SourceName);
end;
// Create
//
constructor TdwsSamplings.Create;
begin
inherited;
FTemp:=TdwsSample.Create;
end;
// Destroy
//
destructor TdwsSamplings.Destroy;
begin
Clean;
FTemp.Free;
inherited;
end;
// AddSample
//
procedure TdwsSamplings.AddSample(scriptPos : TScriptPos; funcSym : TFuncSymbol);
var
idx : Integer;
added : Boolean;
begin
if scriptPos.SourceFile<>nil then
FTemp.FSourceName:=scriptPos.SourceName
else FTemp.FSourceName:=MSG_MainModule;
if funcSym<>nil then
FTemp.FuncName:=funcSym.QualifiedName
else FTemp.FuncName:=MSG_MainFunction;
FTemp.Line:=scriptPos.Line;
idx:=AddOrFind(FTemp, added);
if added then begin
FTemp.Count:=1;
FTemp:=TdwsSample.Create;
end else begin
Inc(Items[idx].FCount);
end;
end;
// Clear
//
procedure TdwsSamplings.Clear;
begin
Clean;
end;
// ToJSON
//
procedure TdwsSamplings.ToJSON(writer : TdwsJSONWriter);
procedure BeginFunc(const func : UnicodeString);
begin
writer.BeginObject;
writer.WriteName('Func');
writer.WriteString(func);
writer.BeginArray;
end;
var
i : Integer;
sorter : TdwsSamplingsSorter;
sourceFile : UnicodeString;
func : UnicodeString;
sample : TdwsSample;
begin
writer.BeginArray;
sorter:=TdwsSamplingsSorter.Create;
try
for i:=0 to Count-1 do
sorter.Add(Items[i]);
sourceFile:='';
func:='';
for i:=0 to Count-1 do begin
sample:=sorter[i];
if sourceFile<>sample.SourceName then begin
if sourceFile<>'' then begin
writer.EndArray; // func
writer.EndObject;
writer.EndArray; // file
writer.EndObject;
end;
sourceFile:=sample.SourceName;
func:=sample.FuncName;
writer.BeginObject;
writer.WriteName('File');
writer.WriteString(sourceFile);
writer.BeginArray;
BeginFunc(func);
end;
if func<>sample.FuncName then begin
if func<>'' then begin
writer.EndArray;
writer.EndObject;
end;
func:=sample.FuncName;
BeginFunc(func);
end;
writer.BeginObject;
writer.WriteName('Line');
writer.WriteNumber(sample.Line);
writer.EndObject;
end;
sorter.Clear;
finally
sorter.Free;
end;
writer.EndArray;
end;
// ToString
//
function TdwsSamplings.ToString : UnicodeString;
var
wobs : TWriteOnlyBlockStream;
wr : TdwsJSONWriter;
begin
wobs:=TWriteOnlyBlockStream.Create;
wr:=TdwsJSONWriter.Create(wobs);
try
ToJSON(wr);
Result:=wobs.ToString;
finally
wr.Free;
wobs.Free;
end;
end;
// ------------------
// ------------------ TdwsSamplingDebugger ------------------
// ------------------
// Create
//
constructor TdwsSamplingDebugger.Create(aOwner : TComponent);
begin
inherited;
FSamplings:=TdwsSamplings.Create;
FSamplingInterval:=10;
end;
// Destroy
//
destructor TdwsSamplingDebugger.Destroy;
begin
FSamplings.Free;
FSamplingFuncStack.Free;
inherited;
end;
// CollectSample
//
procedure TdwsSamplingDebugger.CollectSample;
begin
if FSuspended then Exit;
if not FSamplingPos.Defined then Exit; // not started
if FCollecting then Exit; // ignore sample if too busy
FCollecting:=True;
try
FSamplings.AddSample(FSamplingPos, TFuncSymbol(FSamplingFuncStack.Peek));
finally
FCollecting:=False;
end;
end;
// ProfilerTimeCallBack
//
procedure ProfilerTimeCallBack(TimerID, Msg: Uint; dwUser, dw1, dw2: DWORD); pascal;
begin
TdwsSamplingDebugger(dwUser).CollectSample;
end;
// StartDebug
//
procedure TdwsSamplingDebugger.StartDebug(exec : TdwsExecution);
begin
FSamplings.Clean;
FSamplingFuncStack.Clear;
FSamplingFuncStack.Push(nil);
FSamplingPos:=cNullPos;
if FSamplingInterval<1 then
FSamplingInterval:=1;
FTimerID:=timeSetEvent(FSamplingInterval, 0, @ProfilerTimeCallBack,
Cardinal(Self), TIME_PERIODIC);
inherited;
end;
// DoDebug
//
procedure TdwsSamplingDebugger.DoDebug(exec : TdwsExecution; expr : TExprBase);
var
sample : TScriptPos;
begin
sample:=expr.ScriptPos;
if sample.Defined then
FSamplingPos:=sample;
inherited;
end;
// StopDebug
//
procedure TdwsSamplingDebugger.StopDebug(exec : TdwsExecution);
begin
if FTimerID>0 then begin
TimeKillEvent(FTimerID);
FTimerID:=0;
end;
inherited;
end;
// EnterFunc
//
procedure TdwsSamplingDebugger.EnterFunc(exec : TdwsExecution; funcExpr : TExprBase);
begin
if (funcExpr is TFuncExprBase) then
FSamplingFuncStack.Push(TFuncExprBase(funcExpr).FuncSym);
inherited;
end;
// LeaveFunc
//
procedure TdwsSamplingDebugger.LeaveFunc(exec : TdwsExecution; funcExpr : TExprBase);
begin
if (funcExpr is TFuncExprBase) then
FSamplingFuncStack.Pop;
inherited;
end;
end.
| 26.692098 | 92 | 0.595753 |
c30dc19373adda31e0dd156e7f2f9fad02cda962 | 8,718 | pas | Pascal | src/ljd.response.pas | gcarreno/lazJSONRPCData | ce7d7b4b3e8371e2dccadc9e40a2ef37b10c10a6 | [
"MIT"
]
| 2 | 2021-05-20T15:45:22.000Z | 2021-05-21T07:34:02.000Z | src/ljd.response.pas | gcarreno/lazJSONRPCData | ce7d7b4b3e8371e2dccadc9e40a2ef37b10c10a6 | [
"MIT"
]
| 9 | 2021-05-22T15:24:53.000Z | 2021-05-22T17:21:04.000Z | src/ljd.response.pas | gcarreno/lazJSONRPCData | ce7d7b4b3e8371e2dccadc9e40a2ef37b10c10a6 | [
"MIT"
]
| 2 | 2021-05-23T18:54:23.000Z | 2022-02-12T23:49:06.000Z | { Implements Response Object
Copyright (c) 2021 Gustavo Carreno <guscarreno@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
unit LJD.Response;
{$mode ObjFPC}{$H+}
interface
uses
Classes
, SysUtils
, fpjson
, jsonparser
, LJD.Error
;
type
{ EResponseNotAJSONObject }
EResponseNotAJSONObject = Exception;
{ EResponseEmptyString }
EResponseEmptyString = Exception;
{ EResponseCannotParse }
EResponseCannotParse = Exception;
{ EResponseMissingMember }
EResponseMissingMember = Exception;
{ EResponseWrongMemberType }
EResponseWrongMemberType = Exception;
{ TResponse }
TResponse = class(TObject)
private
FJSONRPC: TJSONStringType;
FHasResult: Boolean;
FResult: TJSONData;
FHasError: Boolean;
FError: TError;
FIDIsNull: Boolean;
FID: Int64;
FCompressedJSON: Boolean;
procedure setFromJSON(const AJSON: TJSONStringType);
procedure setFromJSONData(const AJSONData: TJSONData);
procedure setFromJSONObject(const AJSONObject: TJSONObject);
procedure setFromStream(const AStream: TStream);
function getAsJSON: TJSONStringType;
function getAsJSONData: TJSONData;
function getAsJSONObject: TJSONObject;
function getAsStream: TStream;
protected
public
constructor Create;
constructor Create(const AJSON: TJSONStringType);
constructor Create(const AJSONData: TJSONData);
constructor Create(const AJSONObject: TJSONObject);
constructor Create(const AStream: TStream);
destructor Destroy; override;
property JSONRPC: TJSONStringType
read FJSONRPC;
property HasResult: Boolean
read FHasResult;
property Result: TJSONData
read FResult;
property HasError: Boolean
read FHasError;
property Error: TError
read FError;
property IDIsNull: Boolean
read FIDIsNull
write FIDIsNull;
property ID: Int64
read FID
write FID;
property CompressedJSON: Boolean
read FCompressedJSON
write FCompressedJSON;
property AsJSON: TJSONStringType
read getAsJSON;
property AsJSONData: TJSONData
read getAsJSONData;
property AsJSONObject: TJSONObject
read getAsJSONObject;
property AsStream: TStream
read getAsStream;
published
end;
const
cjJSONRPCversion = '2.0';
cjJSONRPC = 'jsonrpc';
cjResult = 'result';
cjError = 'error';
cjID = 'ID';
resourcestring
rsExceptionNotAJSONObject = 'JSON Data is not an object';
rsExceptionEmptyString = 'MUST not be and empty string';
rsExceptionCannotParse = 'Cannot parse: %s';
rsExceptionMissingMember = 'Missing member: %s';
rsExceptionWrongMemberType = 'Wrong type in member: %s';
rsExceptionMissingMemberResultOrError = 'Missing one of: %s or %s';
implementation
{ TResponse }
procedure TResponse.setFromJSON(const AJSON: TJSONStringType);
var
jData: TJSONData;
begin
if trim(AJSON) = EmptyStr then
begin
raise EResponseEmptyString.Create(rsExceptionEmptyString);
end;
try
jData:= GetJSON(AJSON);
except
on E: Exception do
begin
raise EResponseCannotParse.Create(Format(rsExceptionCannotParse, [E.Message]));
end;
end;
try
setFromJSONData(jData);
finally
jData.Free;
end;
end;
procedure TResponse.setFromJSONData(const AJSONData: TJSONData);
begin
if aJSONData.JSONType <> jtObject then
begin
raise EResponseNotAJSONObject.Create(rsExceptionNotAJSONObject);
end;
setFromJSONObject(aJSONData as TJSONObject);
end;
procedure TResponse.setFromJSONObject(const AJSONObject: TJSONObject);
var
jData, jResult, jError: TJSONData;
begin
// JSONRPC
jData := AJSONObject.Find(cjJSONRPC);
if Assigned(jData) then
begin
if (jData.JSONType = jtString) and (jData.AsString = cjJSONRPCversion) then
begin
FJSONRPC:= AJSONObject.Get(cjJSONRPC, FJSONRPC);
end
else
begin
raise EResponseWrongMemberType.Create(Format(rsExceptionWrongMemberType, [cjJSONRPC]));
end;
end
else
begin
raise EResponseMissingMember.Create(Format(rsExceptionMissingMember, [cjJSONRPC]));
end;
// Result OR Error
jResult:= AJSONObject.Find(cjResult);
jError:= AJSONObject.Find(cjError);
if (jResult = nil) and (jError = nil) then
begin
raise EResponseMissingMember.Create(Format(rsExceptionMissingMemberResultOrError, [cjResult, cjError]));
end;
// Result
if (jResult <> nil) and (jError = nil) then
begin
FResult:= jResult.Clone;
FHasError:= False;
end;
if (jResult = nil) and (jError <> nil) then
begin
// Result
if jError.JSONType = jtObject then
begin
if Assigned(FError) then
begin
FreeAndNil(FError);
end;
FError:= TError.Create(jError);
FHasError:= True;
end
else
begin
raise EResponseWrongMemberType.Create(Format(rsExceptionWrongMemberType, [cjError]));
end;
end;
// ID
jData := AJSONObject.Find(cjID);
if Assigned(jData) then
begin
if (
(jData.JSONType = jtNumber) and
(
(TJSONNumber(jData).NumberType = ntInteger) or
(TJSONNumber(jData).NumberType = ntInt64)
)
) or
(jData.JSONType = jtNull) then
begin
if jData.JSONType = jtNumber then
begin
FIDIsNull:= False;
FID:= AJSONObject.Get(cjID, FID);
end;
if jData.JSONType = jtNull then
begin
FIDIsNull:= True;
FID:= -1;
end;
end
else
begin
raise EResponseWrongMemberType.Create(Format(rsExceptionWrongMemberType, [cjID]));
end;
end
else
begin
raise EResponseMissingMember.Create(Format(rsExceptionMissingMember, [cjID]));
end;
end;
procedure TResponse.setFromStream(const AStream: TStream);
var
jData: TJSONData;
begin
if AStream.Size = 0 then
begin
raise EResponseEmptyString.Create(rsExceptionEmptyString);
end;
try
jData:= GetJSON(AStream);
except
on E: Exception do
begin
raise EResponseCannotParse.Create(Format(rsExceptionCannotParse, [E.Message]));
end;
end;
try
setFromJSONData(jData);
finally
jData.Free;
end;
end;
function TResponse.getAsJSON: TJSONStringType;
var
jObject: TJSONObject;
begin
Result:= '';
jObject:= getAsJSONObject;
jObject.CompressedJSON:= FCompressedJSON;
Result:= jObject.AsJSON;
jObject.Free;
end;
function TResponse.getAsJSONData: TJSONData;
begin
Result:= getAsJSONObject as TJSONData;
end;
function TResponse.getAsJSONObject: TJSONObject;
begin
Result:= TJSONObject.Create;
Result.Add(cjJSONRPC, cjJSONRPCversion);
if FHasResult then
begin
Result.Add(cjResult, FResult.Clone);
end;
if FHasError then
begin
Result.Add(cjError, FError.AsJSONObject);
end;
case FIDIsNull of
True: Result.Add(cjID, TJSONNull.Create);
False: Result.Add(cjID, FID);
end;
end;
function TResponse.getAsStream: TStream;
begin
Result:= TStringStream.Create(getAsJSON, TEncoding.UTF8);
end;
constructor TResponse.Create;
begin
FCompressedJSON:= True;
FJSONRPC:= cjJSONRPCversion;
FHasResult:= True;
FResult:= nil;
FHasError:= False;
FError:= nil;
FIDIsNull:= False;
FID:= -1;
end;
constructor TResponse.Create(const AJSON: TJSONStringType);
begin
Create;
setFromJSON(AJSON);
end;
constructor TResponse.Create(const AJSONData: TJSONData);
begin
Create;
setFromJSONData(AJSONData);
end;
constructor TResponse.Create(const AJSONObject: TJSONObject);
begin
Create;
setFromJSONObject(AJSONObject);
end;
constructor TResponse.Create(const AStream: TStream);
begin
Create;
setFromStream(AStream);
end;
destructor TResponse.Destroy;
begin
if FHasResult then
begin
FResult.Free;
end;
if FHasError then
begin
FError.Free;
end;
inherited Destroy;
end;
end.
| 23.690217 | 108 | 0.723675 |
c3557e8d46fe505ef26fee854003202e3cccb393 | 86,788 | pas | Pascal | Source/dwsJSON.pas | gzwplato/DWScript-1 | 679f75a198c3d224fe8fcb2d8033123114a2d8e7 | [
"Condor-1.1"
]
| 61 | 2016-03-04T13:19:28.000Z | 2021-12-24T06:53:41.000Z | Source/dwsJSON.pas | gzwplato/DWScript-1 | 679f75a198c3d224fe8fcb2d8033123114a2d8e7 | [
"Condor-1.1"
]
| 6 | 2016-03-29T14:39:00.000Z | 2020-09-14T10:04:14.000Z | Source/dwsJSON.pas | CWBudde/DWScript | b84cb0afa4a24f2b99f32206f6bb4c74083d3d54 | [
"Condor-1.1"
]
| 25 | 2016-05-04T13:11:38.000Z | 2021-09-29T13:34:31.000Z | {**********************************************************************}
{ }
{ "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. }
{ }
{ Eric Grange }
{ }
{**********************************************************************}
unit dwsJSON;
{$I dws.inc}
interface
uses
Classes, SysUtils, Math, Variants,
dwsUtils, dwsXPlatform, dwsXXHash, dwsUnicode;
type
TdwsJSONArray = class;
TdwsJSONObject = class;
TdwsJSONImmediate = class;
TdwsJSONWriterState = (wsNone, wsObject, wsObjectName, wsObjectValue, wsArray, wsArrayValue, wsDone);
TdwsJSONWriterOption = (woLowerCaseNames);
TdwsJSONWriterOptions = set of TdwsJSONWriterOption;
// TdwsJSONWriter
//
TdwsJSONWriter = class
private
FStream : TWriteOnlyBlockStream;
FOwnsStream : Boolean;
FStateStack : TTightStack;
FState : TdwsJSONWriterState;
FOptions : TdwsJSONWriterOptions;
protected
procedure BeforeWriteImmediate; virtual;
procedure AfterWriteImmediate;
public
constructor Create(aStream : TWriteOnlyBlockStream = nil; aOptions : TdwsJSONWriterOptions = []);
destructor Destroy; override;
procedure BeginObject; overload; virtual;
procedure BeginObject(const aName : UnicodeString); overload; inline;
procedure EndObject; virtual;
procedure BeginArray; overload; virtual;
procedure BeginArray(const aName : UnicodeString); overload; inline;
procedure EndArray; virtual;
function WriteName(const aName : UnicodeString) : TdwsJSONWriter; overload; inline;
function WriteNameP(const aName : PWideChar) : TdwsJSONWriter; virtual;
procedure WriteString(const str : UnicodeString); overload;
procedure WriteString(const name, str : UnicodeString); overload; inline;
{$ifdef FPC}
function WriteName(const aName : String) : TdwsJSONWriter; overload; inline;
procedure WriteString(const str : String); overload; inline;
procedure WriteString(const name, str : String); overload; inline;
{$endif}
procedure WriteStringP(const p : PWideChar);
procedure WriteNumber(const n : Double); overload;
procedure WriteNumber(const name : UnicodeString; const n : Double); overload; inline;
procedure WriteInteger(const n : Int64); overload;
procedure WriteInteger(const name : UnicodeString; const n : Int64); overload; inline;
procedure WriteBoolean(b : Boolean); overload;
procedure WriteBoolean(const name : UnicodeString; b : Boolean); overload; inline;
procedure WriteNull;
// ISO 8601 Date Time
procedure WriteDate(dt : TDateTime; utc : Boolean = False);
procedure WriteStrings(const str : TStrings); overload;
procedure WriteStrings(const str : TUnicodeStringList); overload;
procedure WriteStrings(const str : array of UnicodeString); overload;
procedure WriteJSON(const json : UnicodeString);
procedure WriteVariant(const v : Variant);
function ToString : String; override; final;
function ToUnicodeString : UnicodeString;
function ToUTF8String : RawByteString; inline;
property Stream : TWriteOnlyBlockStream read FStream write FStream;
end;
IJSONWriteAble = interface
['{742CFFF7-3799-4B4B-8610-D7C8A131FCDC}']
procedure WriteToJSON(writer : TdwsJSONWriter);
end;
// TdwsJSONBeautifiedWriter
//
TdwsJSONBeautifiedWriter = class (TdwsJSONWriter)
private
FSpaces : Integer;
FSpacesPerIndent : Integer;
FSpaceCharacter : String;
FIndents : String;
procedure WriteIndents;
procedure EnterIndent;
procedure LeaveIndent;
protected
procedure BeforeWriteImmediate; override;
public
constructor Create(aStream : TWriteOnlyBlockStream; initialSpaces, spacesPerIndent : Integer; const spaceCharacter : String = #9);
procedure BeginObject; override;
procedure EndObject; override;
procedure BeginArray; override;
procedure EndArray; override;
function WriteNameP(const aName : PWideChar) : TdwsJSONWriter; override;
end;
TdwsJSONDuplicatesOptions = (jdoAccept, jdoOverwrite);
// TdwsJSONParserState
//
// Internal utility parser for TdwsJSON, a "light" tokenizer
TdwsJSONParserState = class
private
Str : UnicodeString;
Ptr, ColStart : PWideChar;
Line : Integer;
FTrailCharacter : WideChar;
DuplicatesOption : TdwsJSONDuplicatesOptions;
UnifyUnicodeStrings : Boolean;
function ParseEscapedCharacter : WideChar;
public
constructor Create(const aStr : UnicodeString);
function Location : String;
property TrailCharacter : WideChar read FTrailCharacter write FTrailCharacter;
function NeedChar : WideChar; inline;
function SkipBlanks(currentChar : WideChar) : WideChar; inline;
procedure ParseJSONUnicodeString(initialChar : WideChar; var result : UnicodeString);
procedure ParseHugeJSONNumber(initialChars : PWideChar; initialCharCount : Integer; var result : Double);
procedure ParseJSONNumber(initialChar : WideChar; var result : Double);
// reads from [ to ]
procedure ParseIntegerArray(dest : TSimpleInt64List);
procedure ParseNumberArray(dest : TSimpleDoubleList);
procedure ParseStringArray(dest : TUnicodeStringList);
end;
TdwsJSONValueType = (jvtUndefined, jvtNull, jvtObject, jvtArray, jvtString, jvtNumber, jvtBoolean);
// TdwsJSONValue
//
TdwsJSONValue = class (TRefCountedObject)
private
FRawOwner : NativeUInt; // 3 low order bytes are reserved for immediates
protected
function GetOwner : TdwsJSONValue; inline;
procedure SetOwner(aOwner : TdwsJSONValue); inline;
procedure ClearOwner; inline;
property FOwner : TdwsJSONValue read GetOwner write SetOwner;
procedure DetachChild(child : TdwsJSONValue); virtual;
function GetValueType : TdwsJSONValueType; virtual; abstract;
function GetName(index : Integer) : UnicodeString;
function DoGetName(index : Integer) : UnicodeString; virtual;
function GetElement(index : Integer) : TdwsJSONValue; inline;
function DoGetElement(index : Integer) : TdwsJSONValue; virtual;
procedure SetElement(index : Integer; const value : TdwsJSONValue); inline;
procedure DoSetElement(index : Integer; const value : TdwsJSONValue); virtual; abstract;
function GetItem(const name : UnicodeString) : TdwsJSONValue; inline;
function GetHashedItem(hash : Cardinal; const name : UnicodeString) : TdwsJSONValue; inline;
function DoGetItem(const name : UnicodeString) : TdwsJSONValue; virtual;
function DoGetHashedItem(hash : Cardinal; const name : UnicodeString) : TdwsJSONValue; virtual;
procedure SetItem(const name : UnicodeString; const value : TdwsJSONValue); inline;
procedure SetHashedItem(hash : Cardinal; const name : UnicodeString; const value : TdwsJSONValue); inline;
procedure DoSetItem(const name : UnicodeString; const value : TdwsJSONValue); virtual; abstract;
procedure DoSetHashedItem(hash : Cardinal; const name : UnicodeString; const value : TdwsJSONValue); virtual;
function DoElementCount : Integer; virtual;
function GetValue(const index : Variant) : TdwsJSONValue;
procedure SetValue(const index : Variant; const aValue : TdwsJSONValue);
function GetIsImmediateValue : Boolean; virtual;
function GetAsString : UnicodeString; inline;
procedure SetAsString(const val : UnicodeString); inline;
function GetIsNull : Boolean; inline;
procedure SetIsNull(const val : Boolean);
function GetIsDefined : Boolean; inline;
function GetAsBoolean : Boolean; inline;
procedure SetAsBoolean(const val : Boolean); inline;
function GetAsNumber : Double;
procedure SetAsNumber(const val : Double); inline;
function GetIsNaN : Boolean;
function GetAsInteger : Int64; inline;
procedure SetAsInteger(const val : Int64); inline;
procedure DoParse(initialChar : WideChar; parserState : TdwsJSONParserState); virtual; abstract;
function DoClone : TdwsJSONValue; virtual; abstract;
procedure DoExtend(other : TdwsJSONValue); virtual; abstract;
function DoIsFalsey : Boolean; virtual;
class procedure RaiseJSONException(const msg : String); static;
class procedure RaiseJSONParseError(const msg : String; c : WideChar = #0); static;
class function Parse(parserState : TdwsJSONParserState) : TdwsJSONValue; static;
public
destructor Destroy; override;
class function ParseString(const json : UnicodeString;
duplicatesOption : TdwsJSONDuplicatesOptions = jdoOverwrite) : TdwsJSONValue; static;
class function ParseFile(const fileName : TFileName) : TdwsJSONValue; static;
function Clone : TdwsJSONValue;
procedure Extend(other : TdwsJSONValue);
procedure WriteTo(writer : TdwsJSONWriter); virtual; abstract;
procedure WriteToStream(aStream : TStream); overload;
procedure WriteToStream(aStream : TWriteOnlyBlockStream); overload;
function ToString : String; override; final;
function ToUnicodeString : UnicodeString;
function ToBeautifiedString(initialTabs : Integer = 0; indentTabs : Integer = 1) : UnicodeString;
procedure Detach;
property Owner : TdwsJSONValue read GetOwner;
property Items[const name : UnicodeString] : TdwsJSONValue read GetItem write SetItem;
property HashedItems[hash : Cardinal; const name : UnicodeString] : TdwsJSONValue read GetHashedItem write SetHashedItem;
property Names[index : Integer] : UnicodeString read GetName;
property Elements[index : Integer] : TdwsJSONValue read GetElement write SetElement;
function ElementCount : Integer;
property Values[const index : Variant] : TdwsJSONValue read GetValue write SetValue; default;
function IsImmediateValue : Boolean; inline;
function Value : TdwsJSONImmediate; inline;
function ValueType : TdwsJSONValueType; inline;
function IsFalsey : Boolean;
procedure Clear;
property AsString : UnicodeString read GetAsString write SetAsString;
property IsNull : Boolean read GetIsNull write SetIsNull;
property IsDefined : Boolean read GetIsDefined;
property AsBoolean : Boolean read GetAsBoolean write SetAsBoolean;
property AsNumber : Double read GetAsNumber write SetAsNumber;
property IsNaN : Boolean read GetIsNaN;
property AsInteger : Int64 read GetAsInteger write SetAsInteger;
const ValueTypeStrings : array [TdwsJSONValueType] of UnicodeString = (
'Undefined', 'Null', 'Object', 'Array', 'String', 'Number', 'Boolean'
);
type
TElementEnumerator = record
private
FIndex, FCountMinus1 : Integer;
FOwner : TdwsJSONValue;
public
function MoveNext : Boolean; inline;
function GetCurrent : TdwsJSONValue; inline;
property Current : TdwsJSONValue read GetCurrent;
end;
function GetEnumerator : TElementEnumerator;
end;
// does not own its elements
TdwsJSONValueList = class(TSimpleList<TdwsJSONValue>)
public
procedure WriteTo(writer : TdwsJSONWriter);
function ToString : String; override; final;
function ToUnicodeString : UnicodeString;
end;
TdwsJSONPair = record
Name : UnicodeString;
Hash : Cardinal;
Value : TdwsJSONValue;
end;
PdwsJSONPair = ^TdwsJSONPair;
TdwsJSONPairArray = array [0..MaxInt shr 5] of TdwsJSONPair;
PdwsJSONPairArray = ^TdwsJSONPairArray;
// TdwsJSONObject
//
TdwsJSONObject = class sealed (TdwsJSONValue)
private
FItems : PdwsJSONPairArray;
FCapacity : Integer;
FCount : Integer;
protected
procedure Grow;
procedure SetCapacity(newCapacity : Integer);
function IndexOfHashedName(hash : Cardinal; const name : UnicodeString) : Integer; inline;
function IndexOfName(const name : UnicodeString) : Integer;
function IndexOfValue(const aValue : TdwsJSONValue) : Integer;
procedure DetachChild(child : TdwsJSONValue); override;
procedure DetachIndex(i : Integer);
function GetValueType : TdwsJSONValueType; override;
function DoGetName(index : Integer) : UnicodeString; override;
function DoGetElement(index : Integer) : TdwsJSONValue; override;
procedure DoSetElement(index : Integer; const value : TdwsJSONValue); override;
function DoGetItem(const name : UnicodeString) : TdwsJSONValue; override;
function DoGetHashedItem(hash : Cardinal; const name : UnicodeString) : TdwsJSONValue; override;
procedure DoSetItem(const name : UnicodeString; const value : TdwsJSONValue); override;
procedure DoSetHashedItem(hash : Cardinal; const name : UnicodeString; const value : TdwsJSONValue); override;
function DoElementCount : Integer; override;
procedure DoParse(initialChar : WideChar; parserState : TdwsJSONParserState); override;
function DoClone : TdwsJSONValue; override;
procedure DoExtend(other : TdwsJSONValue); override;
public
destructor Destroy; override;
function Clone : TdwsJSONObject;
procedure Clear;
procedure Add(const aName : UnicodeString; aValue : TdwsJSONValue);
procedure AddHashed(hash : Cardinal; const aName : UnicodeString; aValue : TdwsJSONValue);
function AddObject(const name : UnicodeString) : TdwsJSONObject;
function AddArray(const name : UnicodeString) : TdwsJSONArray;
function AddValue(const name : UnicodeString) : TdwsJSONImmediate; overload;
function AddValue(const name, value : UnicodeString) : TdwsJSONImmediate; overload;
function AddValue(const name : UnicodeString; const value : Double) : TdwsJSONImmediate; overload;
function AddValue(const name : UnicodeString; const value : Boolean) : TdwsJSONImmediate; overload;
procedure Delete(const name : UnicodeString);
procedure WriteTo(writer : TdwsJSONWriter); override;
procedure MergeDuplicates;
end;
PdwsJSONValueArray = ^TdwsJSONValueArray;
TdwsJSONValueArray = array [0..MaxInt shr 4] of TdwsJSONValue;
TdwsJSONValueCompareMethod = function (left, right : TdwsJSONValue) : Integer of object;
// TdwsJSONArray
//
TdwsJSONArray = class sealed (TdwsJSONValue)
private
FElements : PdwsJSONValueArray;
FCapacity : Integer;
FCount : Integer;
protected
procedure Grow;
procedure SetCapacity(newCapacity : Integer);
procedure DetachChild(child : TdwsJSONValue); override;
procedure DeleteIndex(idx : Integer);
procedure SwapNoRangeCheck(index1, index2 : NativeInt);
function GetValueType : TdwsJSONValueType; override;
function DoGetName(index : Integer) : UnicodeString; override;
function DoGetElement(index : Integer) : TdwsJSONValue; override;
procedure DoSetElement(index : Integer; const value : TdwsJSONValue); override;
function DoGetItem(const name : UnicodeString) : TdwsJSONValue; override;
procedure DoSetItem(const name : UnicodeString; const value : TdwsJSONValue); override;
function DoElementCount : Integer; override;
procedure DoParse(initialChar : WideChar; parserState : TdwsJSONParserState); override;
function DoClone : TdwsJSONValue; override;
procedure DoExtend(other : TdwsJSONValue); override;
public
destructor Destroy; override;
function Clone : TdwsJSONArray;
procedure Clear;
procedure Add(aValue : TdwsJSONValue); overload;
procedure Add(const aValue : Int64); overload;
procedure Add(const aValue : Double); overload;
procedure Add(const aValue : UnicodeString); overload;
procedure Add(const aValue : Boolean); overload;
function AddObject : TdwsJSONObject;
function AddArray : TdwsJSONArray;
function AddValue : TdwsJSONImmediate;
procedure AddNull;
procedure Delete(index : Integer);
procedure Sort(const aCompareMethod : TdwsJSONValueCompareMethod);
procedure Swap(index1, index2 : Integer);
procedure WriteTo(writer : TdwsJSONWriter); override;
end;
// TdwsJSONImmediate
//
TdwsJSONImmediate = class sealed (TdwsJSONValue)
private
FData : Double;
protected
function GetType : TdwsJSONValueType; inline;
procedure SetType(t : TdwsJSONValueType); inline;
property FType : TdwsJSONValueType read GetType write SetType;
procedure DoSetItem(const name : UnicodeString; const value : TdwsJSONValue); override;
procedure DoSetElement(index : Integer; const value : TdwsJSONValue); override;
function GetValueType : TdwsJSONValueType; override;
function GetAsVariant : Variant; overload; inline;
procedure SetAsVariant(const val : Variant);
function GetAsString : UnicodeString; inline;
procedure SetAsString(const val : UnicodeString); inline;
function GetIsNull : Boolean; inline;
procedure SetIsNull(const val : Boolean);
function GetAsBoolean : Boolean;
procedure SetAsBoolean(const val : Boolean); inline;
function GetAsNumber : Double;
procedure SetAsNumber(const val : Double); inline;
function GetAsInteger : Int64;
procedure SetAsInteger(const val : Int64);
function GetIsImmediateValue : Boolean; override;
procedure DoParse(initialChar : WideChar; parserState : TdwsJSONParserState); override;
function DoClone : TdwsJSONValue; override;
procedure DoExtend(other : TdwsJSONValue); override;
function DoIsFalsey : Boolean; override;
public
destructor Destroy; override;
class function ParseString(const json : UnicodeString) : TdwsJSONImmediate; static;
class function FromVariant(const v : Variant) : TdwsJSONImmediate; static;
class function CreateNull : TdwsJSONImmediate; static;
function Clone : TdwsJSONImmediate;
procedure WriteTo(writer : TdwsJSONWriter); override;
procedure GetAsVariant(var result : Variant); overload;
property AsVariant : Variant read GetAsVariant write SetAsVariant;
property AsString : UnicodeString read GetAsString write SetAsString;
property IsNull : Boolean read GetIsNull write SetIsNull;
property AsBoolean : Boolean read GetAsBoolean write SetAsBoolean;
property AsNumber : Double read GetAsNumber write SetAsNumber;
property AsInteger : Int64 read GetAsInteger write SetAsInteger;
procedure Clear;
end;
EdwsJSONException = class (Exception);
EdwsJSONParseError = class (EdwsJSONException);
EdwsJSONWriterError = class (EdwsJSONException);
EdwsJSONIndexOutOfRange = class (EdwsJSONException)
constructor Create(idx, count : Integer);
end;
procedure WriteJavaScriptString(destStream : TWriteOnlyBlockStream; const str : UnicodeString); overload; inline;
procedure WriteJavaScriptString(destStream : TWriteOnlyBlockStream; p : PWideChar; size : Integer); overload;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
var
vJSONFormatSettings : TFormatSettings;
vImmediate : TClassCloneConstructor<TdwsJSONImmediate>;
vObject : TClassCloneConstructor<TdwsJSONObject>;
vArray : TClassCloneConstructor<TdwsJSONArray>;
// ------------------
// ------------------ EdwsJSONIndexOutOfRange ------------------
// ------------------
// Create
//
constructor EdwsJSONIndexOutOfRange.Create(idx, count : Integer);
begin
if count = 0 then
inherited CreateFmt('Array index (%d) out of range (empty array)', [idx])
else inherited CreateFmt('Array index (%d) out of range [0..%d]', [idx, count-1]);
end;
// ------------------
// ------------------ TdwsJSONParserState ------------------
// ------------------
// Create
//
constructor TdwsJSONParserState.Create(const aStr : UnicodeString);
begin
Str:=aStr;
Ptr:=PWideChar(Str);
ColStart:=Ptr;
end;
// NeedChar
//
function TdwsJSONParserState.NeedChar : WideChar;
var
p : PWideChar;
begin
p:=Ptr;
Inc(Ptr);
if p^=#10 then begin
ColStart:=p;
Inc(Line);
end;
Result:=p^;
end;
// Location
//
function TdwsJSONParserState.Location : String;
begin
if (Line=0) then begin
Result:=Format('line 1, col %d',
[(NativeUInt(Ptr)-NativeUInt(ColStart)) div SizeOf(WideChar)]);
end else begin
Result:=Format('line %d, col %d (offset %d)',
[Line+1,
(NativeUInt(Ptr)-NativeUInt(ColStart)) div SizeOf(WideChar),
(NativeUInt(Ptr)-NativeUInt(PWideChar(Str))) div SizeOf(WideChar)]);
end;
end;
// SkipBlanks
//
function TdwsJSONParserState.SkipBlanks(currentChar : WideChar) : WideChar;
begin
Result:=currentChar;
repeat
case Result of
#9..#13, ' ' : ;
else
Break;
end;
Result:=NeedChar();
until False;
end;
// ParseEscapedCharacter
//
function TdwsJSONParserState.ParseEscapedCharacter : WideChar;
var
c : WideChar;
hexBuf, hexCount : Integer;
begin
c:=NeedChar();
case c of
'"', '\', '/' : Result:=c;
'n' : Result:=#10;
'r' : Result:=#13;
't' : Result:=#9;
'b' : Result:=#8;
'f' : Result:=#12;
'u' : begin
hexBuf:=0;
for hexCount:=1 to 4 do begin
c:=NeedChar();
case c of
'0'..'9' :
hexBuf:=(hexBuf shl 4)+Ord(c)-Ord('0');
'a'..'f' :
hexBuf:=(hexBuf shl 4)+Ord(c)-(Ord('a')-10);
'A'..'F' :
hexBuf:=(hexBuf shl 4)+Ord(c)-(Ord('A')-10);
else
TdwsJSONValue.RaiseJSONParseError('Invalid unicode hex character "%s"', c);
end;
end;
Result:=WideChar(hexBuf);
end;
else
Result := c;
TdwsJSONValue.RaiseJSONParseError('Invalid character "%s" after escape', c);
end;
end;
// ParseJSONUnicodeString
//
procedure TdwsJSONParserState.ParseJSONUnicodeString(initialChar : WideChar; var result : UnicodeString);
var
c : WideChar;
wobs : TWriteOnlyBlockStream;
n, nw : Integer;
localBufferPtr, startPr : PWideChar;
localBuffer : array [0..95] of WideChar;
begin
startPr:=Ptr;
wobs:=nil;
try
localBufferPtr:=@localBuffer[0];
repeat
c:=Ptr^;
Inc(Ptr);
case c of
#0..#31 :
if c=#0 then begin
Ptr:=startPr;
TdwsJSONValue.RaiseJSONParseError('Unterminated UnicodeString')
end else TdwsJSONValue.RaiseJSONParseError('Invalid UnicodeString character %s', c);
'"' : Break;
'\' : localBufferPtr^:=ParseEscapedCharacter;
else
localBufferPtr^:=c;
end;
if localBufferPtr=@localBuffer[High(localBuffer)] then begin
if wobs=nil then
wobs:=TWriteOnlyBlockStream.AllocFromPool;
wobs.WriteP(@localBuffer, Length(localBuffer));
localBufferPtr:=@localBuffer[0];
end else Inc(localBufferPtr);
until False;
n:=(NativeUInt(localBufferPtr)-NativeUInt(@localBuffer[0])) div SizeOf(WideChar);
if wobs<>nil then begin
nw:=(wobs.Size div SizeOf(WideChar));
SetLength(Result, n+nw);
localBufferPtr:=PWideChar(Pointer(Result));
wobs.StoreData(localBufferPtr^);
Move(localBuffer[0], localBufferPtr[nw], n*SizeOf(WideChar));
end else begin
if n>0 then begin
SetLength(Result, n);
localBufferPtr:=PWideChar(Pointer(Result));
Move(localBuffer[0], localBufferPtr^, n*SizeOf(WideChar));
end else Result:='';
end;
finally
wobs.ReturnToPool;
end;
{$ifndef FPC}
if UnifyUnicodeStrings then
Result:=UnifiedString(Result);
{$endif}
end;
// ParseJSONNumber
//
procedure TdwsJSONParserState.ParseHugeJSONNumber(
initialChars : PWideChar; initialCharCount : Integer; var result : Double);
var
buf : String;
c : WideChar;
begin
SetString(buf, initialChars, initialCharCount);
repeat
c := NeedChar();
case c of
'0'..'9', '-', '+', 'e', 'E', '.' : buf := buf + Char(c);
else
TrailCharacter := c;
Break;
end;
until False;
if not TryStrToDouble(buf, Result, vJSONFormatSettings) then
TdwsJSONValue.RaiseJSONParseError('Invalid number');
end;
// ParseJSONNumber
//
procedure TdwsJSONParserState.ParseJSONNumber(initialChar : WideChar; var result : Double);
var
bufPtr : PWideChar;
c : WideChar;
buf : array [0..50] of WideChar;
begin
buf[0]:=initialChar;
bufPtr:=@buf[1];
repeat
c:=NeedChar();
case c of
'0'..'9', '-', '+', 'e', 'E', '.' : begin
bufPtr^:=c;
Inc(bufPtr);
if bufPtr=@buf[High(buf)] then begin
ParseHugeJSONNumber(@buf[0], Length(buf)-1, result);
Exit;
end;
end;
else
TrailCharacter:=c;
Break;
end;
until False;
case NativeUInt(bufPtr)-NativeUInt(@buf[0]) of
SizeOf(WideChar) : // special case of single-character number
case buf[0] of
'0'..'9' : begin
result:=Ord(buf[0])-Ord('0');
exit;
end;
end;
2*SizeOf(WideChar) : // special case of two-characters number
case buf[0] of
'1'..'9' : begin
case buf[1] of
'0'..'9' : begin
result:=Ord(buf[0])*10+Ord(buf[1])-Ord('0')*11;
exit;
end;
end;
end;
end;
3*SizeOf(WideChar) : // special case of three-characters number
case buf[0] of
'0'..'9' : begin
case buf[1] of
'0'..'9' : begin
case buf[2] of
'0'..'9' : begin
result:=Ord(buf[0])*100+Ord(buf[1])*10+Ord(buf[2])-Ord('0')*111;
exit;
end;
end;
end;
'.' : begin
case buf[2] of
'0'..'9' : begin
result:=(Ord(buf[0])-Ord('0'))+(Ord(buf[2])-Ord('0'))*0.1;
exit;
end;
end;
end;
end;
end;
end;
end;
bufPtr^ := #0;
if not TryStrToDouble(PWideChar(@buf[0]), result) then
TdwsJSONValue.RaiseJSONParseError('Invalid number');
end;
// ParseIntegerArray
//
procedure TdwsJSONParserState.ParseIntegerArray(dest : TSimpleInt64List);
function ParseJSONInteger(initialChar : WideChar) : Int64;
var
neg : Boolean;
d : Integer;
p : PWideChar;
begin
neg := (initialChar = '-');
// branchless "Result := if not neg then initialDigit else 0"
Result := (Ord(neg)-1) and (Ord(initialChar) - Ord('0'));
p := Ptr;
while True do begin
d := Ord(p^) - Ord('0');
if Cardinal(d) <= 9 then begin
Result := Result*10 + d;
Inc(p);
if Result < 0 then
raise EdwsJSONParseError.Create('Integer overflow');
end else begin
Ptr := p;
TrailCharacter := NeedChar;
Break;
end;
end;
if neg then
Result := -Result;
end;
var
c : WideChar;
begin
c:=SkipBlanks(' ');
if c<>'[' then
raise EdwsJSONParseError.CreateFmt('"[" expected but U+%.04x encountered', [Ord(c)]);
c:=SkipBlanks(NeedChar);
if c=']' then
Exit;
repeat
case c of
'0'..'9', '-' : begin
dest.Add(ParseJSONInteger(c));
end;
else
raise EdwsJSONParseError.CreateFmt('Unexpected character U+%.04x', [Ord(c)]);
end;
if TrailCharacter <> ',' then begin
c := SkipBlanks(TrailCharacter);
case c of
',' : ;
']' : break;
else
raise EdwsJSONParseError.CreateFmt('"," expected but U+%.04x encountered', [Ord(c)]);
end;
end;
case Ptr^ of
'0'..'9' : begin
c := Ptr^;
Inc(Ptr);
end;
else
c:=SkipBlanks(NeedChar)
end;
until False;
end;
// ParseNumberArray
//
procedure TdwsJSONParserState.ParseNumberArray(dest : TSimpleDoubleList);
var
c : WideChar;
num : Double;
begin
c:=SkipBlanks(' ');
if c<>'[' then
raise EdwsJSONParseError.CreateFmt('"[" expected but U+%.04x encountered', [Ord(c)]);
c:=SkipBlanks(NeedChar);
if c=']' then
Exit;
repeat
case c of
'0'..'9', '-' : begin
ParseJSONNumber(c, num);
dest.Add(num);
end;
else
raise EdwsJSONParseError.CreateFmt('Unexpected character U+%.04x', [Ord(c)]);
end;
c:=SkipBlanks(TrailCharacter);
case c of
',' : ;
']' : break;
else
raise EdwsJSONParseError.CreateFmt('"," expected but U+%.04x encountered', [Ord(c)]);
end;
c:=SkipBlanks(NeedChar)
until False;
end;
// ParseStringArray
//
procedure TdwsJSONParserState.ParseStringArray(dest : TUnicodeStringList);
var
c : WideChar;
buf : UnicodeString;
begin
c:=SkipBlanks(' ');
if c<>'[' then
raise EdwsJSONParseError.CreateFmt('"[" expected but U+%.04x encountered', [Ord(c)]);
c:=SkipBlanks(NeedChar);
if c=']' then
Exit;
repeat
if c='"' then begin
ParseJSONUnicodeString(c, buf);
dest.Add(buf);
end else begin
raise EdwsJSONParseError.CreateFmt('Unexpected character U+%.04x', [Ord(c)]);
end;
c:=SkipBlanks(NeedChar);
case c of
',' : ;
']' : break;
else
raise EdwsJSONParseError.CreateFmt('"," expected but U+%.04x encountered', [Ord(c)]);
end;
c:=SkipBlanks(NeedChar);
until False;
end;
// WriteJavaScriptString
//
procedure WriteJavaScriptString(destStream : TWriteOnlyBlockStream; const str : UnicodeString);
begin
WriteJavaScriptString(destStream, PWideChar(Pointer(str)), Length(str));
end;
// WriteJavaScriptString
//
procedure WriteJavaScriptString(destStream : TWriteOnlyBlockStream; p : PWideChar; size : Integer); overload;
procedure WriteUTF16(destStream : TWriteOnlyBlockStream; c : Integer);
const
cIntToHex : array [0..15] of WideChar = (
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var
hex : array [0..5] of WideChar;
begin
hex[0]:='\';
hex[1]:='u';
hex[2]:=cIntToHex[c shr 12];
hex[3]:=cIntToHex[(c shr 8) and $F];
hex[4]:=cIntToHex[(c shr 4) and $F];
hex[5]:=cIntToHex[c and $F];
destStream.WriteP(@hex, 6);
end;
const
cQUOTE : WideChar = '"';
var
c : WideChar;
begin
destStream.WriteP(@cQUOTE, 1);
if p <> nil then while size > 0 do begin
c := p^;
case Ord(c) of
1..31 :
case Ord(c) of
0 : Break;
8 : destStream.WriteString('\b');
9 : destStream.WriteString('\t');
10 : destStream.WriteString('\n');
12 : destStream.WriteString('\f');
13 : destStream.WriteString('\r');
else
WriteUTF16(destStream, Ord(c));
end;
Ord('"') :
destStream.WriteString('\"');
Ord('\') :
destStream.WriteString('\\');
Ord('/') : // XSS protection when used for inline scripts in HTML
destStream.WriteString('\/');
0, $100..$FFFF :
WriteUTF16(destStream, Ord(c));
else
destStream.WriteP(p, 1);
end;
Dec(size);
Inc(p);
end;
destStream.WriteP(@cQUOTE, 1);
end;
// ------------------
// ------------------ TdwsJSONValue ------------------
// ------------------
// GetOwner
//
function TdwsJSONValue.GetOwner : TdwsJSONValue;
begin
Result:=TdwsJSONValue(FRawOwner and -8);
end;
// SetOwner
//
procedure TdwsJSONValue.SetOwner(aOwner : TdwsJSONValue);
begin
FRawOwner:=(FRawOwner and $7) or NativeUInt(aOwner);
end;
// ClearOwner
//
procedure TdwsJSONValue.ClearOwner;
begin
FRawOwner:=(FRawOwner and $7);
end;
// Destroy
//
destructor TdwsJSONValue.Destroy;
begin
if FOwner<>nil then
Detach;
inherited;
end;
// Parse
//
class function TdwsJSONValue.Parse(parserState : TdwsJSONParserState) : TdwsJSONValue;
var
c : WideChar;
begin
Result:=nil;
repeat
c:=parserState.NeedChar();
case c of
#0 : Break;
#9..#13, ' ' : ;
'{' : Result:=vObject.Create;
'[' : Result:=vArray.Create;
'0'..'9', '"', '-', 't', 'f', 'n' :
Result:=vImmediate.Create;
']', '}' : begin
// empty array or object
parserState.TrailCharacter:=c;
Exit(nil);
end;
else
RaiseJSONParseError('Invalid value start character "%s"', c);
end;
until Result<>nil;
if Result<>nil then begin
try
Result.DoParse(c, parserState);
except
Result.Free;
raise;
end;
end;
end;
// ParseString
//
class function TdwsJSONValue.ParseString(const json : UnicodeString;
duplicatesOption : TdwsJSONDuplicatesOptions = jdoOverwrite) : TdwsJSONValue;
const
cAutoUnifierTreshold = 10 * 1024 * 1024;
var
parserState : TdwsJSONParserState;
begin
{$ifndef DELPHI_TOKYO_PLUS}
Result := nil;
{$endif}
parserState := TdwsJSONParserState.Create(json);
try
parserState.UnifyUnicodeStrings := (Length(json) >= cAutoUnifierTreshold);
try
parserState.DuplicatesOption:=duplicatesOption;
Result := TdwsJSONValue.Parse(parserState);
except
on e : EdwsJSONParseError do
raise EdwsJSONParseError.CreateFmt('%s, at %s',
[e.Message, parserState.Location]);
else
raise;
end;
finally
if parserState.UnifyUnicodeStrings then
TidyStringsUnifier;
parserState.Free;
end;
end;
// ParseFile
//
class function TdwsJSONValue.ParseFile(const fileName : TFileName) : TdwsJSONValue;
begin
Result:=ParseString(LoadTextFromFile(fileName));
end;
// Clone
//
function TdwsJSONValue.Clone : TdwsJSONValue;
begin
if Self<>nil then
Result:=DoClone
else Result:=nil;
end;
// Extend
//
procedure TdwsJSONValue.Extend(other : TdwsJSONValue);
begin
if Self=nil then
RaiseJSONException('Cannot extend undefined object')
else if other<>nil then
DoExtend(other);
end;
// WriteToStream
//
procedure TdwsJSONValue.WriteToStream(aStream : TStream);
var
writer : TdwsJSONWriter;
wobs : TWriteOnlyBlockStream;
begin
if Self=nil then Exit;
wobs:=TWriteOnlyBlockStream.AllocFromPool;
writer:=TdwsJSONWriter.Create(wobs);
try
WriteTo(writer);
wobs.StoreUTF8Data(aStream);
finally
writer.Free;
wobs.ReturnToPool;
end;
end;
// WriteToStream
//
procedure TdwsJSONValue.WriteToStream(aStream : TWriteOnlyBlockStream);
var
writer : TdwsJSONWriter;
begin
if Self=nil then Exit;
writer:=TdwsJSONWriter.Create(aStream);
try
WriteTo(writer);
finally
writer.Free;
end;
end;
// ToString
//
function TdwsJSONValue.ToString : String;
begin
Result := String(ToUnicodeString);
end;
// ToUnicodeString
//
function TdwsJSONValue.ToUnicodeString : UnicodeString;
var
writer : TdwsJSONWriter;
begin
if Self=nil then Exit('');
writer:=TdwsJSONWriter.Create(nil);
try
WriteTo(writer);
Result:=writer.Stream.ToUnicodeString;
finally
writer.Free;
end;
end;
// ToBeautifiedString
//
function TdwsJSONValue.ToBeautifiedString(initialTabs, indentTabs : Integer) : UnicodeString;
var
writer : TdwsJSONBeautifiedWriter;
begin
if Self=nil then Exit('');
writer:=TdwsJSONBeautifiedWriter.Create(nil, initialTabs, indentTabs);
try
WriteTo(writer);
Result:=writer.Stream.ToUnicodeString;
finally
writer.Free;
end;
end;
// Detach
//
procedure TdwsJSONValue.Detach;
var
oldOwner : TdwsJSONValue;
begin
oldOwner:=FOwner;
if oldOwner<>nil then begin
ClearOwner;
oldOwner.DetachChild(Self);
end;
end;
// DoElementCount
//
function TdwsJSONValue.DoElementCount : Integer;
begin
Result:=0;
end;
// ElementCount
//
function TdwsJSONValue.ElementCount : Integer;
begin
if Assigned(Self) then
Result:=DoElementCount
else Result:=0;
end;
// IsImmediateValue
//
function TdwsJSONValue.IsImmediateValue : Boolean;
begin
Result:=Assigned(Self) and GetIsImmediateValue;
end;
// Value
//
function TdwsJSONValue.Value : TdwsJSONImmediate;
begin
if ClassType<>TdwsJSONImmediate then
RaiseJSONException('Not a value');
Result:=TdwsJSONImmediate(Self);
end;
// ValueType
//
function TdwsJSONValue.ValueType : TdwsJSONValueType;
begin
if Assigned(Self) then
Result:=GetValueType
else Result:=jvtUndefined;
end;
// IsFalsey
//
function TdwsJSONValue.IsFalsey : Boolean;
begin
Result:=(not Assigned(Self)) or DoIsFalsey;
end;
// Clear
//
procedure TdwsJSONValue.Clear;
begin
Value.Clear;
end;
// GetValue
//
function TdwsJSONValue.GetValue(const index : Variant) : TdwsJSONValue;
function Fallback : TdwsJSONValue;
begin
if VariantIsOrdinal(index) then
Result := Elements[index]
else Result := Items[index];
end;
begin
if Assigned(Self) then begin
case VarType(index) of
varInt64 : Result := Elements[TVarData(index).VInt64];
varUString : Result := Items[String(TVarData(index).VUString)];
else
Result := Fallback;
end;
end else Result := nil;
end;
// SetValue
//
procedure TdwsJSONValue.SetValue(const index : Variant; const aValue : TdwsJSONValue);
begin
Assert(Assigned(Self));
if VariantIsOrdinal(index) then
Elements[index]:=aValue
else Items[index]:=aValue;
end;
// GetIsImmediateValue
//
function TdwsJSONValue.GetIsImmediateValue : Boolean;
begin
Result:=False;
end;
// GetAsString
//
function TdwsJSONValue.GetAsString : UnicodeString;
begin
if Assigned(Self) then
Result:=Value.AsString
else Result:='undefined';
end;
// SetAsString
//
procedure TdwsJSONValue.SetAsString(const val : UnicodeString);
begin
Value.AsString:=val;
end;
// GetIsNull
//
function TdwsJSONValue.GetIsNull : Boolean;
begin
if Assigned(Self) then
Result:=(ValueType=jvtNull)
else Result:=False;
end;
// SetIsNull
//
procedure TdwsJSONValue.SetIsNull(const val : Boolean);
begin
Value.IsNull:=val;
end;
// GetIsDefined
//
function TdwsJSONValue.GetIsDefined : Boolean;
begin
Result:=Assigned(Self) and (ValueType<>jvtUndefined);
end;
// GetAsBoolean
//
function TdwsJSONValue.GetAsBoolean : Boolean;
begin
if Assigned(Self) then
Result:=Value.AsBoolean
else Result:=False;
end;
// SetAsBoolean
//
procedure TdwsJSONValue.SetAsBoolean(const val : Boolean);
begin
Value.AsBoolean:=val;
end;
// GetAsNumber
//
function TdwsJSONValue.GetAsNumber : Double;
begin
if Assigned(Self) then
Result:=Value.AsNumber
else Result:=NaN;
end;
// SetAsNumber
//
procedure TdwsJSONValue.SetAsNumber(const val : Double);
begin
Value.AsNumber:=val;
end;
// GetIsNaN
//
function TdwsJSONValue.GetIsNaN : Boolean;
begin
Result:=not ( Assigned(Self)
and (ValueType=jvtNumber)
and Math.IsNan(Value.AsNumber));
end;
// GetAsInteger
//
function TdwsJSONValue.GetAsInteger : Int64;
begin
if Assigned(Self) then
Result:=Value.AsInteger
else Result:=0;
end;
// SetAsInteger
//
procedure TdwsJSONValue.SetAsInteger(const val : Int64);
begin
Value.AsInteger:=val;
end;
// DetachChild
//
procedure TdwsJSONValue.DetachChild(child : TdwsJSONValue);
begin
Assert(False);
end;
// GetName
//
function TdwsJSONValue.GetName(index : Integer) : UnicodeString;
begin
if Assigned(Self) then
Result:=DoGetName(index)
else Result:='';
end;
// DoGetName
//
function TdwsJSONValue.DoGetName(index : Integer) : UnicodeString;
begin
Result:='';
end;
// GetElement
//
function TdwsJSONValue.GetElement(index : Integer) : TdwsJSONValue;
begin
if Assigned(Self) then
Result:=DoGetElement(index)
else Result:=nil;
end;
// DoGetElement
//
function TdwsJSONValue.DoGetElement(index : Integer) : TdwsJSONValue;
begin
Result:=nil;
end;
// SetElement
//
procedure TdwsJSONValue.SetElement(index : Integer; const value : TdwsJSONValue);
begin
if Assigned(Self) then
DoSetElement(index, value)
else raise EdwsJSONException.CreateFmt('Cannot set element "%d" of Undefined', [index]);
end;
// GetItem
//
function TdwsJSONValue.GetItem(const name : UnicodeString) : TdwsJSONValue;
begin
if Assigned(Self) then
Result:=DoGetItem(name)
else Result:=nil;
end;
// GetHashedItem
//
function TdwsJSONValue.GetHashedItem(hash : Cardinal; const name : UnicodeString) : TdwsJSONValue;
begin
if Assigned(Self) then
Result:=DoGetHashedItem(hash, name)
else Result:=nil;
end;
// DoGetItem
//
function TdwsJSONValue.DoGetItem(const name : UnicodeString) : TdwsJSONValue;
begin
Result:=nil;
end;
// DoGetHashedItem
//
function TdwsJSONValue.DoGetHashedItem(hash : Cardinal; const name : UnicodeString) : TdwsJSONValue;
begin
Result:=DoGetItem(name);
end;
// SetItem
//
procedure TdwsJSONValue.SetItem(const name : UnicodeString; const value : TdwsJSONValue);
begin
if Assigned(Self) then
DoSetItem(name, value)
else raise EdwsJSONException.CreateFmt('Cannot set member "%s" of Undefined', [name]);
end;
// SetHashedItem
//
procedure TdwsJSONValue.SetHashedItem(hash : Cardinal; const name : UnicodeString; const value : TdwsJSONValue);
begin
if Assigned(Self) then
DoSetHashedItem(hash, name, value)
else SetItem(name, value);
end;
// RaiseJSONException
//
class procedure TdwsJSONValue.RaiseJSONException(const msg : String);
begin
raise EdwsJSONException.Create(msg);
end;
// RaiseJSONParseError
//
class procedure TdwsJSONValue.RaiseJSONParseError(const msg : String; c : WideChar = #0);
begin
if c<=#31 then
raise EdwsJSONParseError.CreateFmt(msg, [IntToStr(Ord(c))])
else if c>#127 then
raise EdwsJSONParseError.CreateFmt(msg, ['U+'+IntToHex(Ord(c), 4)])
else raise EdwsJSONParseError.CreateFmt(msg, [UnicodeString(c)]);
end;
// GetEnumerator
//
function TdwsJSONValue.GetEnumerator : TElementEnumerator;
begin
Result.FIndex:=-1;
Result.FOwner:=Self;
Result.FCountMinus1:=ElementCount-1;
end;
// TElementEnumerator.GetCurrent
//
function TdwsJSONValue.TElementEnumerator.GetCurrent : TdwsJSONValue;
begin
Result:=FOwner.Elements[FIndex];
end;
// TElementEnumerator.MoveNext
//
function TdwsJSONValue.TElementEnumerator.MoveNext : Boolean;
begin
Result:=(FIndex<FCountMinus1);
Inc(FIndex, Integer(Result));
end;
// DoIsFalsey
//
function TdwsJSONValue.DoIsFalsey : Boolean;
begin
Result:=False;
end;
// DoSetHashedItem
//
procedure TdwsJSONValue.DoSetHashedItem(hash : Cardinal; const name : UnicodeString; const value : TdwsJSONValue);
begin
SetItem(name, value);
end;
// ------------------
// ------------------ TdwsJSONObject ------------------
// ------------------
// Destroy
//
destructor TdwsJSONObject.Destroy;
begin
Clear;
inherited;
end;
// Clone
//
function TdwsJSONObject.Clone : TdwsJSONObject;
begin
if Self<>nil then
Result:=(DoClone as TdwsJSONObject)
else Result:=nil;
end;
// WriteTo
//
procedure TdwsJSONObject.WriteTo(writer : TdwsJSONWriter);
var
i : Integer;
begin
writer.BeginObject;
for i:=0 to ElementCount-1 do begin
writer.WriteName(FItems^[i].Name);
FItems^[i].Value.WriteTo(writer);
end;
writer.EndObject;
end;
// DoElementCount
//
function TdwsJSONObject.DoElementCount : Integer;
begin
Result:=FCount;
end;
// Clear
//
procedure TdwsJSONObject.Clear;
var
i : Integer;
v : TdwsJSONValue;
begin
for i:=0 to FCount-1 do begin
v:=FItems^[i].Value;
v.ClearOwner;
v.DecRefCount;
FItems^[i].Name:='';
end;
FreeMem(FItems);
FItems:=nil;
FCount:=0;
FCapacity:=0;
end;
// Grow
//
procedure TdwsJSONObject.Grow;
begin
SetCapacity(FCapacity+8+(FCapacity shr 2));
end;
// SetCapacity
//
procedure TdwsJSONObject.SetCapacity(newCapacity : Integer);
begin
FCapacity:=newCapacity;
ReallocMem(FItems, FCapacity*SizeOf(TdwsJSONPair));
FillChar(FItems[FCount], (FCapacity-FCount)*SizeOf(TdwsJSONPair), 0);
end;
// Add
//
procedure TdwsJSONObject.Add(const aName : UnicodeString; aValue : TdwsJSONValue);
begin
AddHashed(SimpleStringHash(aName), aName, aValue);
end;
// AddHashed
//
procedure TdwsJSONObject.AddHashed(hash : Cardinal; const aName : UnicodeString; aValue : TdwsJSONValue);
begin
if aValue = nil then
aValue := vImmediate.Create;
Assert(aValue.Owner = nil);
aValue.FOwner:=Self;
if FCount=FCapacity then Grow;
FItems^[FCount].Value:=aValue;
FItems^[FCount].Name:=aName;
FItems^[FCount].Hash:=hash;
Inc(FCount);
end;
// AddObject
//
function TdwsJSONObject.AddObject(const name : UnicodeString) : TdwsJSONObject;
begin
Result:=vObject.Create;
Add(name, Result);
end;
// AddArray
//
function TdwsJSONObject.AddArray(const name : UnicodeString) : TdwsJSONArray;
begin
Result:=vArray.Create;
Add(name, Result);
end;
// AddValue
//
function TdwsJSONObject.AddValue(const name : UnicodeString) : TdwsJSONImmediate;
begin
Result:=vImmediate.Create;
Add(name, Result);
end;
// Delete
//
procedure TdwsJSONObject.Delete(const name : UnicodeString);
var
i : Integer;
begin
i := IndexOfName(name);
if i >= 0 then
DetachIndex(i);
end;
// MergeDuplicates
//
procedure TdwsJSONObject.MergeDuplicates;
var
i, j : Integer;
h : Cardinal;
begin
for i:=FCount-1 downto 1 do begin
h:=FItems[i].Hash;
for j:=i-1 downto 0 do begin
if (FItems[j].Hash=h) and (FItems[j].Name=FItems[i].Name) then
DetachIndex(j);
end;
end;
end;
// AddValue (UnicodeString)
//
function TdwsJSONObject.AddValue(const name, value : UnicodeString) : TdwsJSONImmediate;
begin
Result:=AddValue(name);
Result.AsString:=value;
end;
// AddValue (number)
//
function TdwsJSONObject.AddValue(const name : UnicodeString; const value : Double) : TdwsJSONImmediate;
begin
Result:=AddValue(name);
Result.AsNumber:=value;
end;
// AddValue (bool)
//
function TdwsJSONObject.AddValue(const name : UnicodeString; const value : Boolean) : TdwsJSONImmediate;
begin
Result:=AddValue(name);
Result.AsBoolean:=value;
end;
// DetachChild
//
procedure TdwsJSONObject.DetachChild(child : TdwsJSONValue);
var
i : Integer;
begin
i:=IndexOfValue(child);
if i>=0 then
DetachIndex(i);
end;
// DetachIndex
//
procedure TdwsJSONObject.DetachIndex(i : Integer);
var
n : Integer;
child : TdwsJSONValue;
begin
child:=FItems[i].Value;
if child.Owner=Self then begin
child.ClearOwner;
child.DecRefCount;
end;
Finalize(FItems[i]);
n:=FCount-1;
if i<n then
Move(FItems[i+1], FItems[i], (n-i)*SizeOf(TdwsJSONPair));
FillChar(FItems[n], SizeOf(TdwsJSONPair), 0);
FCount:=n;
end;
// GetValueType
//
function TdwsJSONObject.GetValueType : TdwsJSONValueType;
begin
Result:=jvtObject;
end;
// DoGetName
//
function TdwsJSONObject.DoGetName(index : Integer) : UnicodeString;
begin
if Cardinal(index)<Cardinal(FCount) then
Result:=FItems^[index].Name
else Result:='';
end;
// DoGetElement
//
function TdwsJSONObject.DoGetElement(index : Integer) : TdwsJSONValue;
begin
if Cardinal(index)<Cardinal(FCount) then
Result:=FItems^[index].Value
else Result:=nil;
end;
// DoSetElement
//
procedure TdwsJSONObject.DoSetElement(index : Integer; const value : TdwsJSONValue);
var
member : TdwsJSONValue;
begin
if Cardinal(index)<Cardinal(FCount) then begin
if value<>nil then begin
member:=FItems^[index].Value;
member.ClearOwner;
member.DecRefCount;
FItems^[index].Value:=value;
value.Detach;
value.FOwner:=Self;
end else DetachIndex(index);
end else if value<>nil then begin
Add(Int32ToStrU(index), value);
end;
end;
// DoGetItem
//
function TdwsJSONObject.DoGetItem(const name : UnicodeString) : TdwsJSONValue;
var
i : Integer;
begin
i:=IndexOfName(name);
if i>=0 then
Result:=FItems^[i].Value
else Result:=nil;
end;
// DoGetHashedItem
//
function TdwsJSONObject.DoGetHashedItem(hash : Cardinal; const name : UnicodeString) : TdwsJSONValue;
var
i : Integer;
begin
i:=IndexOfHashedName(hash, name);
if i>=0 then
Result:=FItems^[i].Value
else Result:=nil;
end;
// DoSetItem
//
procedure TdwsJSONObject.DoSetItem(const name : UnicodeString; const value : TdwsJSONValue);
var
i : Integer;
begin
i:=IndexOfName(name);
if i>=0 then
DoSetElement(i, value)
else Add(name, value);
end;
// DoSetHashedItem
//
procedure TdwsJSONObject.DoSetHashedItem(hash : Cardinal; const name : UnicodeString; const value : TdwsJSONValue);
var
i : Integer;
begin
i:=IndexOfHashedName(hash, name);
if i>=0 then
DoSetElement(i, value)
else Add(name, value);
end;
// DoParse
//
procedure TdwsJSONObject.DoParse(initialChar : WideChar; parserState : TdwsJSONParserState);
var
c : WideChar;
name : UnicodeString;
locValue : TdwsJSONValue;
begin
Assert(initialChar='{');
repeat
c:=parserState.SkipBlanks(parserState.NeedChar());
if c<>'"' then begin
if FCount=0 then Break;
RaiseJSONParseError('Invalid object pair name start character "%s"', c)
end;
parserState.ParseJSONUnicodeString(c, name);
c:=parserState.SkipBlanks(parserState.NeedChar());
if c<>':' then
RaiseJSONParseError('Invalid object pair name separator character "%s"', c);
locValue:=TdwsJSONValue.Parse(parserState);
if locValue=nil then
RaiseJSONParseError('Missing element value');
Add(name, locValue);
c:=parserState.SkipBlanks(parserState.TrailCharacter);
until c<>',';
if c<>'}' then
RaiseJSONParseError('Invalid object termination character "%s"', c);
if parserState.DuplicatesOption=jdoOverwrite then
MergeDuplicates;
parserState.TrailCharacter:=' ';
end;
// DoClone
//
function TdwsJSONObject.DoClone : TdwsJSONValue;
var
obj : TdwsJSONObject;
member : TdwsJSONValue;
i : Integer;
begin
obj:=vObject.Create;
obj.SetCapacity(FCount);
obj.FCount:=FCount;
for i:=0 to FCount-1 do begin
obj.FItems[i].Name:=FItems[i].Name;
obj.FItems[i].Hash:=FItems[i].Hash;
member:=FItems[i].Value.Clone;
member.FOwner:=obj;
obj.FItems[i].Value:=member;
end;
Result:=obj;
end;
// DoExtend
//
procedure TdwsJSONObject.DoExtend(other : TdwsJSONValue);
var
i, k : Integer;
otherObj : TdwsJSONObject;
member : TdwsJSONValue;
begin
if other.ClassType<>TdwsJSONObject then
RaiseJSONException('Can only extend Object with Object');
otherObj:=TdwsJSONObject(other);
for i:=0 to otherObj.FCount-1 do begin
k:=IndexOfName(otherObj.FItems[i].Name);
if k>=0 then begin
member:=FItems[k].Value;
member.ClearOwner;
member.DecRefCount;
member:=otherObj.FItems[i].Value.Clone;
member.FOwner:=Self;
FItems[k].Value:=member;
end else begin
Add(otherObj.FItems[i].Name, otherObj.FItems[i].Value.Clone);
end;
end;
end;
// IndexOfHashedName
//
function TdwsJSONObject.IndexOfHashedName(hash : Cardinal; const name : UnicodeString) : Integer;
var
i : Integer;
begin
for i:=0 to FCount-1 do begin
if (FItems^[i].Hash=hash) and (FItems^[i].Name=name) then
Exit(i);
end;
Result:=-1;
end;
// IndexOfName
//
function TdwsJSONObject.IndexOfName(const name : UnicodeString) : Integer;
begin
Result := IndexOfHashedName(SimpleStringHash(name), name);
end;
// IndexOfValue
//
function TdwsJSONObject.IndexOfValue(const aValue : TdwsJSONValue) : Integer;
var
i : Integer;
begin
for i:=0 to FCount-1 do
if FItems^[i].Value=aValue then
Exit(i);
Result:=-1;
end;
// ------------------
// ------------------ TdwsJSONArray ------------------
// ------------------
// Destroy
//
destructor TdwsJSONArray.Destroy;
begin
Clear;
inherited;
end;
// Clone
//
function TdwsJSONArray.Clone : TdwsJSONArray;
begin
if Self<>nil then
Result:=(DoClone as TdwsJSONArray)
else Result:=nil;
end;
// WriteTo
//
procedure TdwsJSONArray.WriteTo(writer : TdwsJSONWriter);
var
i : Integer;
begin
writer.BeginArray;
for i:=0 to ElementCount-1 do
Elements[i].WriteTo(writer);
writer.EndArray;
end;
// Grow
//
procedure TdwsJSONArray.Grow;
begin
if FCapacity<16 then
SetCapacity(FCapacity+4)
else SetCapacity(FCapacity+(FCapacity shr 2));
end;
// SetCapacity
//
procedure TdwsJSONArray.SetCapacity(newCapacity : Integer);
begin
FCapacity:=newCapacity;
ReallocMem(FElements, FCapacity*SizeOf(Pointer));
end;
// DetachChild
//
procedure TdwsJSONArray.DetachChild(child : TdwsJSONValue);
var
i : Integer;
begin
for i:=0 to FCount-1 do begin
if FElements^[i]=child then begin
DeleteIndex(i);
Break;
end;
end;
end;
// DeleteIndex
//
procedure TdwsJSONArray.DeleteIndex(idx : Integer);
var
child : TdwsJSONValue;
begin
child:=FElements[idx];
if child.FOwner=Self then begin
child.ClearOwner;
child.DecRefCount;
end;
Move(FElements[idx+1], FElements[idx], (FCount-1-idx)*SizeOf(Pointer));
Dec(FCount);
end;
// GetValueType
//
function TdwsJSONArray.GetValueType : TdwsJSONValueType;
begin
Result:=jvtArray;
end;
// DoElementCount
//
function TdwsJSONArray.DoElementCount : Integer;
begin
Result:=FCount;
end;
// Clear
//
procedure TdwsJSONArray.Clear;
var
i : Integer;
v : TdwsJSONValue;
begin
for i:=0 to FCount-1 do begin
v:=FElements^[i];
v.ClearOwner;
v.DecRefCount;
end;
FreeMem(FElements);
FElements:=nil;
FCount:=0;
FCapacity:=0;
end;
// Add (value)
//
procedure TdwsJSONArray.Add(aValue : TdwsJSONValue);
begin
if aValue.Owner<>nil then begin
aValue.IncRefCount;
aValue.Owner.DetachChild(aValue);
end;
aValue.FOwner:=Self;
if FCount=FCapacity then Grow;
FElements^[FCount]:=aValue;
Inc(FCount);
end;
// Add (int)
//
procedure TdwsJSONArray.Add(const aValue : Int64);
var
v : TdwsJSONImmediate;
begin
v:=TdwsJSONImmediate.Create;
v.AsInteger:=aValue;
Add(v);
end;
// Add (float)
//
procedure TdwsJSONArray.Add(const aValue : Double);
var
v : TdwsJSONImmediate;
begin
v:=TdwsJSONImmediate.Create;
v.AsNumber:=aValue;
Add(v);
end;
// Add (str)
//
procedure TdwsJSONArray.Add(const aValue : UnicodeString);
var
v : TdwsJSONImmediate;
begin
v:=TdwsJSONImmediate.Create;
v.AsString:=aValue;
Add(v);
end;
// Add (bool)
//
procedure TdwsJSONArray.Add(const aValue : Boolean);
var
v : TdwsJSONImmediate;
begin
v:=TdwsJSONImmediate.Create;
v.AsBoolean:=aValue;
Add(v);
end;
// AddObject
//
function TdwsJSONArray.AddObject : TdwsJSONObject;
begin
Result:=vObject.Create;
Add(Result);
end;
// AddArray
//
function TdwsJSONArray.AddArray : TdwsJSONArray;
begin
Result:=vArray.Create;
Add(Result);
end;
// AddValue
//
function TdwsJSONArray.AddValue : TdwsJSONImmediate;
begin
Result:=vImmediate.Create;
Add(Result);
end;
// AddNull
//
procedure TdwsJSONArray.AddNull;
var
v : TdwsJSONImmediate;
begin
v:=vImmediate.Create;
v.IsNull:=True;
Add(v);
end;
// Delete
//
procedure TdwsJSONArray.Delete(index : Integer);
begin
if Cardinal(index) >= Cardinal(FCount) then
raise EdwsJSONIndexOutOfRange.Create(index, FCount);
DeleteIndex(index);
end;
// Sort
//
type
TCompareAdapter = class
ValueArray : PdwsJSONValueArray;
CompareMethod : TdwsJSONValueCompareMethod;
function Compare(index1, index2 : NativeInt) : Integer;
end;
function TCompareAdapter.Compare(index1, index2 : NativeInt) : Integer;
begin
Result:=CompareMethod(ValueArray[index1], ValueArray[Index2]);
end;
procedure TdwsJSONArray.Sort(const aCompareMethod : TdwsJSONValueCompareMethod);
var
qs : TQuickSort;
adapter : TCompareAdapter;
begin
if FCount<=1 then Exit;
adapter:=TCompareAdapter.Create;
try
adapter.ValueArray:=FElements;
adapter.CompareMethod:=aCompareMethod;
qs.CompareMethod:=adapter.Compare;
qs.SwapMethod:=SwapNoRangeCheck;
qs.Sort(0, FCount-1);
finally
adapter.Free;
end;
end;
// SwapNoRangeCheck
//
procedure TdwsJSONArray.SwapNoRangeCheck(index1, index2 : NativeInt);
var
temp : TdwsJSONValue;
begin
temp := FElements[index1];
FElements[index1] := FElements[index2];
FElements[index2] := temp;
end;
// Swap
//
procedure TdwsJSONArray.Swap(index1, index2 : Integer);
begin
if Cardinal(index1) >= Cardinal(FCount) then
raise EdwsJSONIndexOutOfRange.Create(index1, FCount);
if Cardinal(index2) >= Cardinal(FCount) then
raise EdwsJSONIndexOutOfRange.Create(index1, FCount);
SwapNoRangeCheck(index1, index2);
end;
// DoGetName
//
function TdwsJSONArray.DoGetName(index : Integer) : UnicodeString;
begin
if Cardinal(index) < Cardinal(FCount) then
Result := Int32ToStrU(index)
else Result := '';
end;
// DoGetElement
//
function TdwsJSONArray.DoGetElement(index : Integer) : TdwsJSONValue;
begin
if Cardinal(index) < Cardinal(FCount) then
Result:=TdwsJSONValue(FElements^[index])
else Result:=nil;
end;
// DoSetElement
//
procedure TdwsJSONArray.DoSetElement(index : Integer; const value : TdwsJSONValue);
var
v : TdwsJSONValue;
begin
if index<0 then
raise EdwsJSONException.CreateFmt('Invalid array index "%d"', [index]);
if (value<>nil) and (value.Owner<>nil) then begin
value.IncRefCount;
value.Owner.DetachChild(value);
end;
if index<FCount then begin
if value=nil then
if index=FCount-1 then begin
DeleteIndex(index);
Exit;
end else v:=vImmediate.Create
else v:=value;
FElements[index].ClearOwner;
FElements[index].DecRefCount;
FElements[index]:=v;
v.FOwner:=Self;
end else if value<>nil then begin
while FCount<index do
AddValue;
Add(value);
end;
end;
// DoGetItem
//
function TdwsJSONArray.DoGetItem(const name : UnicodeString) : TdwsJSONValue;
var
i : Integer;
begin
i := StrUToInt64(name, -1);
Result:=DoGetElement(i);
end;
// DoSetItem
//
procedure TdwsJSONArray.DoSetItem(const name : UnicodeString; const value : TdwsJSONValue);
var
i : Integer;
begin
i := StrUToInt64(name, -1);
if i < 0 then
raise EdwsJSONException.CreateFmt('Invalid array member "%s"', [name])
else DoSetElement(i, value);
end;
// DoParse
//
procedure TdwsJSONArray.DoParse(initialChar : WideChar; parserState : TdwsJSONParserState);
var
locValue : TdwsJSONValue;
begin
Assert(initialChar='[');
repeat
locValue:=TdwsJSONValue.Parse(parserState);
if locValue=nil then Break;
Add(locValue);
parserState.TrailCharacter:=parserState.SkipBlanks(parserState.TrailCharacter);
until parserState.TrailCharacter<>',';
if parserState.TrailCharacter<>']' then
RaiseJSONParseError('Invalid array termination character "%s"', parserState.TrailCharacter);
parserState.TrailCharacter:=' ';
end;
// DoClone
//
function TdwsJSONArray.DoClone : TdwsJSONValue;
var
arr : TdwsJSONArray;
elem : TdwsJSONValue;
i : Integer;
begin
arr:=vArray.Create;
arr.SetCapacity(FCount);
arr.FCount:=FCount;
for i:=0 to FCount-1 do begin
elem:=FElements^[i].Clone;
elem.FOwner:=Self;
arr.FElements^[i]:=elem;
end;
Result:=arr;
end;
// DoExtend
//
procedure TdwsJSONArray.DoExtend(other : TdwsJSONValue);
begin
RaiseJSONException('Cannot extend arrays (yet)');
end;
// ------------------
// ------------------ TdwsJSONImmediate ------------------
// ------------------
// GetType
//
function TdwsJSONImmediate.GetType : TdwsJSONValueType;
begin
Result:=TdwsJSONValueType(FRawOwner and $7);
end;
// SetType
//
procedure TdwsJSONImmediate.SetType(t : TdwsJSONValueType);
begin
FRawOwner:=(FRawOwner and -8) or NativeUInt(t);
end;
// Destroy
//
destructor TdwsJSONImmediate.Destroy;
begin
if FType=jvtString then
PUnicodeString(@FData)^:='';
inherited;
end;
// GetAsString
//
function TdwsJSONImmediate.GetAsString : UnicodeString;
begin
if Assigned(Self) then
case FType of
jvtNull : Result := 'null';
jvtString : Result := PUnicodeString(@FData)^;
jvtNumber : Result := UnicodeString(FloatToStr(FData));
jvtBoolean :
if PBoolean(@FData)^ then
Result:='true'
else Result:='false';
else
Result:='undefined';
end
else Result:='undefined';
end;
// SetAsString
//
procedure TdwsJSONImmediate.SetAsString(const val : UnicodeString);
begin
if FType<>jvtString then
PPointer(@FData)^:=nil;
PUnicodeString(@FData)^:=val;
FType:=jvtString;
end;
// GetIsNull
//
function TdwsJSONImmediate.GetIsNull : Boolean;
begin
if Assigned(Self) then
Result:=(FType=jvtNull)
else Result:=True;
end;
// SetIsNull
//
procedure TdwsJSONImmediate.SetIsNull(const val : Boolean);
begin
if val<>GetIsNull then begin
if val then begin
if FType=jvtString then
PUnicodeString(@FData)^:='';
FType:=jvtNull;
end else AsString:='';
end;
end;
// GetAsBoolean
//
function TdwsJSONImmediate.GetAsBoolean : Boolean;
begin
if not Assigned(Self) then Exit(False);
case FType of
jvtBoolean : Result:=PBoolean(@FData)^;
jvtNumber : Result:=(FData<>0);
jvtString : Result:=(PUnicodeString(@FData)^='true');
else
Result:=False;
end;
end;
// SetAsBoolean
//
procedure TdwsJSONImmediate.SetAsBoolean(const val : Boolean);
begin
if FType=jvtString then
PUnicodeString(@FData)^:='';
PBoolean(@FData)^:=val;
FType:=jvtBoolean;
end;
// GetAsNumber
//
function TdwsJSONImmediate.GetAsNumber : Double;
begin
if not Assigned(Self) then Exit(NaN);
case FType of
jvtBoolean : if PBoolean(@FData)^ then Result:=-1 else Result:=0;
jvtNumber : Result:=FData;
jvtString : Result := StrToFloatDef(String(PUnicodeString(@FData)^), 0)
else
Result:=0;
end;
end;
// SetAsNumber
//
procedure TdwsJSONImmediate.SetAsNumber(const val : Double);
begin
if FType=jvtString then
PUnicodeString(@FData)^:='';
FData:=val;
FType:=jvtNumber;
end;
// GetAsInteger
//
function TdwsJSONImmediate.GetAsInteger : Int64;
begin
Result:=Round(GetAsNumber);
end;
// SetAsInteger
//
procedure TdwsJSONImmediate.SetAsInteger(const val : Int64);
begin
AsNumber:=val;
end;
// GetIsImmediateValue
//
function TdwsJSONImmediate.GetIsImmediateValue : Boolean;
begin
Result:=True;
end;
// DoParse
//
procedure TdwsJSONImmediate.DoParse(initialChar : WideChar; parserState : TdwsJSONParserState);
begin
parserState.TrailCharacter:=' ';
case initialChar of
'"' : begin
parserState.ParseJSONUnicodeString(initialChar, PUnicodeString(@FData)^);
FType:=jvtString;
end;
'0'..'9', '-' : begin
parserState.ParseJSONNumber(initialChar, FData);
FType:=jvtNumber;
end;
't' :
if (parserState.NeedChar()='r')
and (parserState.NeedChar()='u')
and (parserState.NeedChar()='e') then
AsBoolean:=True
else RaiseJSONParseError('Invalid immediate value');
'f' :
if (parserState.NeedChar()='a')
and (parserState.NeedChar()='l')
and (parserState.NeedChar()='s')
and (parserState.NeedChar()='e') then
AsBoolean:=False
else RaiseJSONParseError('Invalid immediate value');
'n' :
if (parserState.NeedChar()='u')
and (parserState.NeedChar()='l')
and (parserState.NeedChar()='l') then
IsNull:=True
else RaiseJSONParseError('Invalid immediate value');
else
RaiseJSONParseError('Invalid immediate value');
end;
end;
// DoClone
//
function TdwsJSONImmediate.DoClone : TdwsJSONValue;
begin
Result:=vImmediate.Create;
TdwsJSONImmediate(Result).FType:=FType;
if FType=jvtString then
PUnicodeString(@TdwsJSONImmediate(Result).FData)^:=PUnicodeString(@FData)^
else PInt64(@TdwsJSONImmediate(Result).FData)^:=PInt64(@FData)^;
end;
// DoExtend
//
procedure TdwsJSONImmediate.DoExtend(other : TdwsJSONValue);
begin
RaiseJSONException('Cannot extend immediate values');
end;
// DoIsFalsey
//
function TdwsJSONImmediate.DoIsFalsey : Boolean;
begin
case FType of
jvtUndefined, jvtNull :
Result:=True;
jvtString :
Result:=PUnicodeString(@FData)^='';
jvtNumber :
Result:=FData=0;
jvtBoolean :
Result:=not PBoolean(@FData)^;
else
Result:=False;
end;
end;
// Clone
//
function TdwsJSONImmediate.Clone : TdwsJSONImmediate;
begin
if Self<>nil then
Result:=(DoClone as TdwsJSONImmediate)
else Result:=nil;
end;
// WriteTo
//
procedure TdwsJSONImmediate.WriteTo(writer : TdwsJSONWriter);
begin
case FType of
jvtNull, jvtUndefined :
writer.WriteNull;
jvtBoolean :
writer.WriteBoolean(PBoolean(@FData)^);
jvtNumber :
writer.WriteNumber(FData);
jvtString :
writer.WriteString(PUnicodeString(@FData)^);
else
Assert(False, 'Unsupported type');
end;
end;
// ParseString
//
class function TdwsJSONImmediate.ParseString(const json : UnicodeString) : TdwsJSONImmediate;
var
locValue : TdwsJSONValue;
begin
locValue:=TdwsJSONValue.ParseString(json);
if locValue is TdwsJSONImmediate then
Result:=TdwsJSONImmediate(locValue)
else begin
locValue.Free;
Result:=nil;
end;
end;
// FromVariant
//
class function TdwsJSONImmediate.FromVariant(const v : Variant) : TdwsJSONImmediate;
begin
Result:=TdwsJSONImmediate.Create;
Result.AsVariant:=v;
end;
// CreateNull
//
class function TdwsJSONImmediate.CreateNull : TdwsJSONImmediate;
begin
Result := TdwsJSONImmediate.Create;
Result.FType := jvtNull;
end;
// DoSetItem
//
procedure TdwsJSONImmediate.DoSetItem(const name : UnicodeString; const value : TdwsJSONValue);
begin
raise EdwsJSONException.CreateFmt('Cannot set member "%s" of immediate value', [name]);
end;
// DoSetElement
//
procedure TdwsJSONImmediate.DoSetElement(index : Integer; const value : TdwsJSONValue);
begin
raise EdwsJSONException.CreateFmt('Cannot set element "%d" of immediate value', [index]);
end;
// GetValueType
//
function TdwsJSONImmediate.GetValueType : TdwsJSONValueType;
begin
Result:=FType;
end;
// GetAsVariant
//
procedure TdwsJSONImmediate.GetAsVariant(var result : Variant);
begin
case FType of
jvtNull : VarSetNull(Result);
jvtString : VarCopySafe(Result, PUnicodeString(@FData)^);
jvtNumber : VarCopySafe(Result, FData);
jvtBoolean : VarCopySafe(Result, PBoolean(@FData)^);
else
VarClearSafe(Result);
end;
end;
// Clear
//
procedure TdwsJSONImmediate.Clear;
begin
IsNull := True;
FType := jvtUndefined;
end;
// GetAsVariant
//
function TdwsJSONImmediate.GetAsVariant : Variant;
begin
GetAsVariant(Result);
end;
// SetAsVariant
//
procedure TdwsJSONImmediate.SetAsVariant(const val : Variant);
begin
case VariantType(val) of
varEmpty : Clear;
varNull : IsNull := True;
varInt64 : AsInteger := val;
{$ifdef FPC}
varString : AsString := val;
{$else}
varUString : AsString := val;
{$endif}
varDouble : AsNumber := val;
varBoolean : AsBoolean := val;
else
if VariantIsString(val) then
AsString := VariantToUnicodeString(val)
else if VariantIsFloat(val) or VariantIsOrdinal(val) then
AsNumber := VariantToFloat(val)
else raise EdwsJSONException.CreateFmt('Unsupported VarType in FromVariant (%d)',
[VariantType(val)]);
end;
end;
// ------------------
// ------------------ TdwsJSONWriter ------------------
// ------------------
// Create
//
constructor TdwsJSONWriter.Create(aStream : TWriteOnlyBlockStream = nil;
aOptions : TdwsJSONWriterOptions = []);
begin
inherited Create;
FOptions:=aOptions;
FOwnsStream:=(aStream=nil);
if FOwnsStream then
FStream:=TWriteOnlyBlockStream.AllocFromPool
else FStream:=aStream;
end;
// Destroy
//
destructor TdwsJSONWriter.Destroy;
begin
if FOwnsStream then
FStream.ReturnToPool;
FStateStack.Free;
inherited;
end;
// BeginObject
//
procedure TdwsJSONWriter.BeginObject;
begin
Assert(FState in [wsNone, wsObjectValue, wsArray, wsArrayValue]);
FStateStack.Push(TRefCountedObject(FState));
BeforeWriteImmediate;
FState:=wsObject;
FStream.WriteChar('{');
end;
// BeginObject
//
procedure TdwsJSONWriter.BeginObject(const aName : UnicodeString);
begin
WriteName(aName).BeginObject;
end;
// EndObject
//
procedure TdwsJSONWriter.EndObject;
begin
if FState in [wsObject, wsObjectName] then begin
Assert(FStateStack.Count>0);
FState:=TdwsJSONWriterState(FStateStack.Peek);
FStateStack.Pop;
FStream.WriteChar('}');
AfterWriteImmediate;
end else raise EdwsJSONWriterError.Create('Value expected');
end;
// BeginArray
//
procedure TdwsJSONWriter.BeginArray;
begin
Assert(FState in [wsNone, wsObjectValue, wsArray, wsArrayValue]);
FStateStack.Push(TRefCountedObject(FState));
BeforeWriteImmediate;
FState:=wsArray;
FStream.WriteChar('[');
end;
// BeginArray
//
procedure TdwsJSONWriter.BeginArray(const aName : UnicodeString);
begin
WriteName(aName).BeginArray;
end;
// EndArray
//
procedure TdwsJSONWriter.EndArray;
begin
Assert(FState in [wsArray, wsArrayValue]);
Assert(FStateStack.Count>0);
FState:=TdwsJSONWriterState(FStateStack.Peek);
FStateStack.Pop;
FStream.WriteChar(']');
AfterWriteImmediate;
end;
// WriteName
//
function TdwsJSONWriter.WriteName(const aName : UnicodeString) : TdwsJSONWriter;
begin
Result:=WriteNameP(PWideChar(aName));
end;
// WriteNameP
//
function TdwsJSONWriter.WriteNameP(const aName : PWideChar) : TdwsJSONWriter;
procedure WriteLowerCase(stream : TWriteOnlyBlockStream; aName : PWideChar);
var
buf : String;
begin
UnicodeLowerCase(aName, buf);
WriteJavaScriptString(FStream, buf);
end;
begin
case FState of
wsObject : ;
wsObjectName : begin
FStream.WriteChar(',');
end;
else
Assert(False);
end;
if woLowerCaseNames in FOptions then
WriteLowerCase(FStream, aName)
else WriteJavaScriptString(FStream, aName);
FStream.WriteChar(':');
FState:=wsObjectValue;
Result:=Self;
end;
// WriteString
//
procedure TdwsJSONWriter.WriteString(const str : UnicodeString);
begin
BeforeWriteImmediate;
WriteJavaScriptString(FStream, str);
AfterWriteImmediate;
end;
{$ifdef FPC}
// WriteName
//
function TdwsJSONWriter.WriteName(const aName : String) : TdwsJSONWriter;
begin
Result:=WriteName(UnicodeString(aName));
end;
// WriteString
//
procedure TdwsJSONWriter.WriteString(const str : String);
begin
WriteString(UnicodeString(str));
end;
// WriteString
//
procedure TdwsJSONWriter.WriteString(const name, str : String);
begin
WriteName(UnicodeString(name)).WriteString(UnicodeString(str));
end;
{$endif}
// WriteString
//
procedure TdwsJSONWriter.WriteString(const name, str : UnicodeString);
begin
WriteName(name).WriteString(str);
end;
// WriteStringP
//
procedure TdwsJSONWriter.WriteStringP(const p : PWideChar);
begin
BeforeWriteImmediate;
WriteJavaScriptString(FStream, p);
AfterWriteImmediate;
end;
// WriteNumber
//
procedure TdwsJSONWriter.WriteNumber(const n : Double);
var
buffer : array [0..63] of WideChar;
nc : Integer;
nExt : Extended;
begin
BeforeWriteImmediate;
nExt := n;
nc := FloatToText(buffer, nExt, fvExtended, ffGeneral, 15, 0, vJSONFormatSettings);
FStream.Write(buffer, nc*SizeOf(WideChar));
AfterWriteImmediate;
end;
// WriteNumber
//
procedure TdwsJSONWriter.WriteNumber(const name : UnicodeString; const n : Double);
begin
WriteName(name).WriteNumber(n);
end;
// WriteInteger
//
procedure TdwsJSONWriter.WriteInteger(const n : Int64);
begin
BeforeWriteImmediate;
FStream.WriteString(n);
AfterWriteImmediate;
end;
// WriteInteger
//
procedure TdwsJSONWriter.WriteInteger(const name : UnicodeString; const n : Int64);
begin
WriteName(name).WriteInteger(n);
end;
// WriteBoolean
//
procedure TdwsJSONWriter.WriteBoolean(b : Boolean);
begin
BeforeWriteImmediate;
if b then
FStream.WriteString('true')
else FStream.WriteString('false');
AfterWriteImmediate;
end;
// WriteBoolean
//
procedure TdwsJSONWriter.WriteBoolean(const name : UnicodeString; b : Boolean);
begin
WriteName(name).WriteBoolean(b);
end;
// WriteNull
//
procedure TdwsJSONWriter.WriteNull;
begin
BeforeWriteImmediate;
FStream.WriteString('null');
AfterWriteImmediate;
end;
// WriteDate
//
procedure TdwsJSONWriter.WriteDate(dt : TDateTime; utc : Boolean = False);
var
y, m, d, h, n, s, z : Word;
begin
if dt = 0 then begin
WriteNull;
Exit;
end;
BeforeWriteImmediate;
FStream.WriteChar('"');
DecodeDate(dt, y, m, d);
FStream.WriteDigits(y, 4);
FStream.WriteChar('-');
FStream.WriteDigits(m, 2);
FStream.WriteChar('-');
FStream.WriteDigits(d, 2);
DecodeTime(dt, h, n, s, z);
if (h or n or s)<>0 then begin
FStream.WriteChar('T');
FStream.WriteDigits(h, 2);
FStream.WriteChar(':');
FStream.WriteDigits(n, 2);
FStream.WriteChar(':');
FStream.WriteDigits(s, 2);
end;
if utc then
FStream.WriteString('Z"')
else FStream.WriteChar('"');
AfterWriteImmediate;
end;
// WriteStrings
//
procedure TdwsJSONWriter.WriteStrings(const str : TStrings);
var
i : Integer;
begin
BeginArray;
for i:=0 to str.Count-1 do
WriteString(UnicodeString(str[i]));
EndArray;
end;
// WriteStrings
//
procedure TdwsJSONWriter.WriteStrings(const str : TUnicodeStringList);
var
i : Integer;
begin
BeginArray;
for i:=0 to str.Count-1 do
WriteString(str[i]);
EndArray;
end;
// WriteJSON
//
procedure TdwsJSONWriter.WriteJSON(const json : UnicodeString);
begin
BeforeWriteImmediate;
FStream.WriteString(json);
AfterWriteImmediate;
end;
// WriteVariant
//
procedure TdwsJSONWriter.WriteVariant(const v : Variant);
var
i : Integer;
begin
if VarIsArray(v) then begin
BeginArray;
for i := VarArrayLowBound(v, 1) to VarArrayHighBound(v, 1) do
WriteVariant(v[i]);
EndArray;
end else case VarType(v) of
varInteger, varInt64, varSmallint, varShortInt,
varUInt64, varWord, varByte, varLongWord :
WriteInteger(v);
varSingle, varDouble :
WriteNumber(v);
varBoolean :
WriteBoolean(v);
varDate :
WriteDate(v);
varNull, varEmpty :
WriteNull;
else
WriteString(v);
end;
end;
// WriteStrings
//
procedure TdwsJSONWriter.WriteStrings(const str : array of UnicodeString);
var
i : Integer;
begin
BeginArray;
for i:=0 to High(str) do
WriteString(str[i]);
EndArray;
end;
// ToString
//
function TdwsJSONWriter.ToString : String;
begin
Result:=FStream.ToString;
end;
// ToUnicodeString
//
function TdwsJSONWriter.ToUnicodeString : UnicodeString;
begin
Result:=FStream.ToUnicodeString;
end;
// ToUTF8String
//
function TdwsJSONWriter.ToUTF8String : RawByteString;
begin
Result:=FStream.ToUTF8String;
end;
// BeforeWriteImmediate
//
procedure TdwsJSONWriter.BeforeWriteImmediate;
begin
case FState of
wsArrayValue :
FStream.WriteChar(',');
wsObject :
raise EdwsJSONWriterError.Create('Name expected');
wsDone :
Assert(False);
end;
end;
// AfterWriteImmediate
//
procedure TdwsJSONWriter.AfterWriteImmediate;
begin
case FState of
wsNone :
FState:=wsDone;
wsArray :
FState:=wsArrayValue;
wsObjectValue :
FState:=wsObjectName;
end;
end;
// ------------------
// ------------------ TdwsJSONBeautifiedWriter ------------------
// ------------------
// Create
//
constructor TdwsJSONBeautifiedWriter.Create(aStream : TWriteOnlyBlockStream; initialSpaces, spacesPerIndent : Integer; const spaceCharacter : String = #9);
begin
inherited Create(aStream);
FSpaces := initialSpaces;
FSpacesPerIndent := spacesPerIndent;
FSpaceCharacter := spaceCharacter;
end;
// WriteIndents
//
procedure TdwsJSONBeautifiedWriter.WriteIndents;
procedure PrepareIndents;
begin
end;
var
target, current : Integer;
begin
target := FSpaces * FSpacesPerIndent * FSpaceCharacter.Length;
current := Length(FIndents);
if current <> target then begin
if current > target then
SetLength(FIndents, target)
else while current < target do begin
FIndents := FIndents + FSpaceCharacter;
current := Length(FIndents);
end;
end;
if target > 0 then
FStream.WriteString(FIndents);
end;
// EnterIndent
//
procedure TdwsJSONBeautifiedWriter.EnterIndent;
begin
Inc(FSpaces, FSpacesPerIndent);
end;
// LeaveIndent
//
procedure TdwsJSONBeautifiedWriter.LeaveIndent;
begin
Dec(FSpaces, FSpacesPerIndent);
if FState in [wsObjectName, wsArrayValue] then begin
FStream.WriteString(#13#10);
WriteIndents;
end else FStream.WriteChar(' ');
end;
// BeforeWriteImmediate
//
procedure TdwsJSONBeautifiedWriter.BeforeWriteImmediate;
begin
inherited;
case FState of
wsArray, wsArrayValue : begin
FStream.WriteString(#13#10);
WriteIndents;
end;
end;
end;
// BeginObject
//
procedure TdwsJSONBeautifiedWriter.BeginObject;
begin
inherited;
EnterIndent;
end;
// EndObject
//
procedure TdwsJSONBeautifiedWriter.EndObject;
begin
LeaveIndent;
inherited;
end;
// BeginArray
//
procedure TdwsJSONBeautifiedWriter.BeginArray;
begin
inherited;
EnterIndent;
end;
// EndArray
//
procedure TdwsJSONBeautifiedWriter.EndArray;
begin
LeaveIndent;
inherited;
end;
// WriteNameP
//
function TdwsJSONBeautifiedWriter.WriteNameP(const aName : PWideChar) : TdwsJSONWriter;
begin
case FState of
wsObject :
FStream.WriteString(#13#10);
wsObjectName :
FStream.WriteString(','#13#10);
else
Assert(False);
end;
WriteIndents;
WriteJavaScriptString(FStream, aName);
FStream.WriteString(' : ');
FState:=wsObjectValue;
Result:=Self;
end;
// ------------------
// ------------------ TdwsJSONValueList ------------------
// ------------------
// ToString
//
function TdwsJSONValueList.ToString : String;
var
wr : TdwsJSONWriter;
wobs : TWriteOnlyBlockStream;
begin
if Count=0 then Exit('[]');
wobs:=TWriteOnlyBlockStream.AllocFromPool;
wr:=TdwsJSONWriter.Create(wobs);
try
WriteTo(wr);
Result:=wobs.ToString;
finally
wr.Free;
wobs.ReturnToPool;
end;
end;
// ToUnicodeString
//
function TdwsJSONValueList.ToUnicodeString : UnicodeString;
var
wr : TdwsJSONWriter;
wobs : TWriteOnlyBlockStream;
begin
if Count=0 then Exit('[]');
wobs:=TWriteOnlyBlockStream.AllocFromPool;
wr:=TdwsJSONWriter.Create(wobs);
try
WriteTo(wr);
Result:=wobs.ToUnicodeString;
finally
wr.Free;
wobs.ReturnToPool;
end;
end;
// WriteTo
//
procedure TdwsJSONValueList.WriteTo(writer : TdwsJSONWriter);
var
i : Integer;
begin
writer.BeginArray;
for i:=0 to Count-1 do
Items[i].WriteTo(writer);
writer.EndArray;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
vJSONFormatSettings := FormatSettings;
vJSONFormatSettings.DecimalSeparator:='.';
vImmediate.Initialize(TdwsJSONImmediate.Create);
vObject.Initialize(TdwsJSONObject.Create);
vArray.Initialize(TdwsJSONArray.Create);
finalization
vImmediate.Finalize;
vObject.Finalize;
vArray.Finalize;
end.
| 26.4759 | 156 | 0.62451 |
c3b8b300f28a918bfabd024d0dbe74344bd06878 | 2,758 | pas | Pascal | lib/unDebugUnitInitOrder.pas | matheusd/DelphiProfileInit | 95f8511b4982c586c0f4e5db515cab92a4ed3dd1 | [
"Unlicense"
]
| null | null | null | lib/unDebugUnitInitOrder.pas | matheusd/DelphiProfileInit | 95f8511b4982c586c0f4e5db515cab92a4ed3dd1 | [
"Unlicense"
]
| null | null | null | lib/unDebugUnitInitOrder.pas | matheusd/DelphiProfileInit | 95f8511b4982c586c0f4e5db515cab92a4ed3dd1 | [
"Unlicense"
]
| null | null | null | unit unDebugUnitInitOrder;
interface
uses
Windows, SysUtils, Classes, Forms, StrUtils, JclDebug;
procedure extractUnitOrder;
implementation
var
CtxPtr: PInitContext = nil; // Global var
Symbols: TStringList;
Segments: array of DWORD;
type
TUnitInitOrderExtractor = class(TObject)
public
procedure MapClassTable(Sender: TObject; const Address: TJclMapAddress;
Len: Integer; const SectionName, GroupName: string);
procedure PublicsByValue(Sender: TObject; const Address: TJclMapAddress;
const Name: string);
procedure extract;
end;
procedure TUnitInitOrderExtractor.MapClassTable(Sender: TObject; const Address: TJclMapAddress;
Len: Integer; const SectionName, GroupName: string);
begin
SetLength(Segments, Length(Segments) + 1);
SegMents[Address.Segment-1] := Address.Offset;
end;
procedure TUnitInitOrderExtractor.PublicsByValue(Sender: TObject; const Address: TJclMapAddress;
const Name: string);
const
InitContextStr = 'System.InitContext';
begin
if RightStr(Name, Length(InitContextStr)) = InitContextStr then
begin
CtxPtr := PInitContext(Segments[Address.Segment-1] + Address.Offset);
end
else begin
Symbols.AddObject(Name, TObject(Segments[Address.Segment-1] + Address.Offset));
end;
end;
procedure TUnitInitOrderExtractor.extract;
var
MapParser: TJclMapParser;
MapFile: String;
sl: TStringList;
ps: PShortString;
i: Integer;
s: String;
Idx: Integer;
begin
MapFile := ChangeFileExt(Application.ExeName, '.map');
MapParser := TJclMapParser.Create(MapFile);
try
MapParser.OnPublicsByValue := self.PublicsByValue;
MapParser.OnClassTable := self.MapClassTable;
//Memo1.Lines.BeginUpdate;
MapParser.Parse;
//Memo1.Lines.EndUpdate;
finally
MapParser.Free;
end;
if CtxPtr = nil then
Exit;
sl := TStringList.Create;
try
for i := 0 to CtxPtr^.InitTable.UnitCount-1 do
begin
if Assigned(CtxPtr^.InitTable.UnitInfo^[i].Init) then
begin
s := Format('$%.8x', [DWORD(CtxPtr^.InitTable.UnitInfo^[i].Init)]);
Idx := Symbols.IndexOfObject(TObject(CtxPtr^.InitTable.UnitInfo^[i].Init));
if Idx > -1 then
begin
sl.Add(Format('%.4d: %s', [i, Symbols[Idx]]));
end;
end;
end;
sl.saveToFile('unit-order.txt');
finally
sl.Free;
end;
end;
procedure extractUnitOrder;
var
ex: TUnitInitOrderExtractor;
begin
ex:= TUnitInitOrderExtractor.Create;
ex.extract;
ex.Free;
end;
initialization
Symbols := TStringList.Create;
Symbols.Sorted := True;
Symbols.Duplicates := dupIgnore;
finalization
FreeAndNil(Symbols);
end.
| 23.57265 | 97 | 0.680566 |
c3d010a4397a0182085f72ff2c95296ab2e8c347 | 13,173 | pas | Pascal | windows/src/ext/jedi/jvcl/jvcl/examples/JvPreviewDocument/MainFrm.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/jvcl/examples/JvPreviewDocument/MainFrm.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/jvcl/examples/JvPreviewDocument/MainFrm.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {******************************************************************
JEDI-VCL Demo
Copyright (C) 2002 Project JEDI
Original author:
Contributor(s):
You may retrieve the latest version of this file at the JEDI-JVCL
home page, located at http://jvcl.delphi-jedi.org
The contents of this file are used with permission, 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/MPL-1_1Final.html
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.
******************************************************************}
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, JvPrvwDoc, ComCtrls, StdCtrls, ExtCtrls, Menus, jpeg,
JvPrvwRender, JvExStdCtrls, JvRichEdit {, GIFImage};
type
TfrmMain = class(TForm)
pnlBottom: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
edCols: TEdit;
udCols: TUpDown;
edRows: TEdit;
udRows: TUpDown;
edShadow: TEdit;
udShadowWidth: TUpDown;
Label4: TLabel;
edScale: TEdit;
udZoom: TUpDown;
PrinterSetupDialog1: TPrinterSetupDialog;
cbPreview: TComboBox;
Label5: TLabel;
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
N1: TMenuItem;
Printer1: TMenuItem;
N2: TMenuItem;
Exit1: TMenuItem;
View1: TMenuItem;
First1: TMenuItem;
Previous1: TMenuItem;
Next1: TMenuItem;
Last1: TMenuItem;
Help1: TMenuItem;
About1: TMenuItem;
Options1: TMenuItem;
mnuMargins: TMenuItem;
PageControl1: TPageControl;
tabPreview: TTabSheet;
tabOriginal: TTabSheet;
OpenDialog1: TOpenDialog;
reOriginal: TJvRichEdit;
PrintDialog1: TPrintDialog;
Print1: TMenuItem;
Label6: TLabel;
cbScaleMode: TComboBox;
StatusBar1: TStatusBar;
N3: TMenuItem;
mnuPreview: TMenuItem;
Control1: TMenuItem;
Clear1: TMenuItem;
Label7: TLabel;
edVert: TEdit;
udVertSpacing: TUpDown;
Label8: TLabel;
edHorz: TEdit;
udHorzSpacing: TUpDown;
procedure FormCreate(Sender: TObject);
procedure udColsClick(Sender: TObject; Button: TUDBtnType);
procedure udRowsClick(Sender: TObject; Button: TUDBtnType);
procedure udShadowWidthClick(Sender: TObject; Button: TUDBtnType);
procedure udZoomClick(Sender: TObject; Button: TUDBtnType);
procedure cbPreviewChange(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure Printer1Click(Sender: TObject);
procedure mnuMarginsClick(Sender: TObject);
procedure First1Click(Sender: TObject);
procedure Previous1Click(Sender: TObject);
procedure Next1Click(Sender: TObject);
procedure Last1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure Print1Click(Sender: TObject);
procedure cbScaleModeChange(Sender: TObject);
procedure Control1Click(Sender: TObject);
procedure Clear1Click(Sender: TObject);
procedure udVertSpacingClick(Sender: TObject; Button: TUDBtnType);
procedure udHorzSpacingClick(Sender: TObject; Button: TUDBtnType);
private
{ Private declarations }
procedure OpenRTFFile(const Filename: string);
procedure OpenImages(Files: TStrings);
procedure OpenTxtFile(const Filename: string);
procedure OpenImage(const Filename: string);
procedure DoChange(Sender: TObject);
procedure DoAfterScroll(Sender: TObject);
procedure DoScrollHint(Sender: TObject; AScrollPos: integer; var AHint: string);
procedure BuildRTFPreview;
procedure BuildTXTPreview;
procedure BuildImagePreview;
procedure BuildControlMenu;
public
{ Public declarations }
pd: TJvPreviewControl;
JvRTF: TJvPreviewRenderJvRichEdit;
JvTxt: TJvPreviewRenderStrings;
JvImg: TJvPreviewRenderGraphics;
end;
var
frmMain: TfrmMain;
implementation
uses
Printers;
{$R *.dfm}
procedure TfrmMain.Print1Click(Sender: TObject);
var
i: integer;
jp: TJvPreviewPrinter;
begin
PrintDialog1.PrintRange := prAllPages;
if pd.PageCount < 1 then
PrintDialog1.Options := PrintDialog1.Options - [poPageNums]
else
begin
PrintDialog1.Options := PrintDialog1.Options + [poPageNums];
PrintDialog1.FromPage := 1;
PrintDialog1.ToPage := pd.PageCount;
end;
if PrintDialog1.Execute then
begin
i := cbPreview.ItemIndex;
try
// create output suitable for the selected printer
cbPreview.ItemIndex := 1;
cbPreviewChange(Sender);
jp := TJvPreviewPrinter.Create(nil);
try
jp.Assign(PrintDialog1);
jp.Printer := Printer;
jp.PrintPreview := pd;
jp.Print;
finally
jp.Free;
end;
finally
cbPreview.ItemIndex := i;
cbPreviewChange(Sender);
end;
end;
end;
function Max(Val1, Val2: integer): integer;
begin
Result := Val1;
if Val2 > Val1 then
Result := Val2;
end;
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
begin
OpenDialog1.Filter := OpenDialog1.Filter + '|' + GraphicFilter(TGraphic);
JvImg := TJvPreviewRenderGraphics.Create(self);
JvRTF := TJvPreviewRenderJvRichEdit.Create(self);
JvTxt := TJvPreviewRenderStrings.Create(self);
pd := TJvPreviewControl.Create(self);
pd.Name := 'JvPreviewDoc1';
pd.Parent := tabPreview;
pd.Align := alClient;
pd.TabStop := true;
pd.BeginUpdate;
pd.OnChange := DoChange;
try
pd.Options.DrawMargins := mnuMargins.Checked;
pd.Options.Rows := udRows.Position;
pd.Options.Cols := udCols.Position;
pd.Options.Shadow.Offset := udShadowWidth.Position;
pd.Options.Scale := udZoom.Position;
pd.OnAfterScroll := DoAfterScroll;
pd.OnScrollHint := DoScrollHint;
cbPreview.ItemIndex := 1; // printer
cbPreviewChange(nil);
cbScaleMode.ItemIndex := 0; // full page
cbScaleModeChange(nil);
finally
pd.EndUpdate;
end;
BuildControlMenu;
end;
procedure TfrmMain.DoChange(Sender: TObject);
begin
udCols.Position := pd.Options.Cols;
udRows.Position := pd.Options.Rows;
udShadowWidth.Position := pd.Options.Shadow.Offset;
udZoom.Position := pd.Options.Scale;
mnuMargins.Checked := pd.Options.DrawMargins;
cbScaleMode.ItemIndex := Ord(pd.Options.ScaleMode);
udVertSpacing.Position := pd.Options.VertSpacing;
udHorzSpacing.Position := pd.Options.HorzSpacing;
Statusbar1.Panels[0].Text := ExtractFilename(OpenDialog1.Filename);
Statusbar1.Panels[1].Text := Format('%d pages', [pd.PageCount]);
Statusbar1.Panels[2].Text := Format('Cols: %d, Rows: %d, Row %d', [pd.TotalCols, pd.VisibleRows, pd.TopRow]);
end;
procedure TfrmMain.udColsClick(Sender: TObject; Button: TUDBtnType);
begin
pd.Options.Cols := udCols.Position;
udCols.Position := pd.Options.Cols;
end;
procedure TfrmMain.udRowsClick(Sender: TObject; Button: TUDBtnType);
begin
pd.Options.Rows := udRows.Position;
udRows.Position := pd.Options.Rows;
end;
procedure TfrmMain.udShadowWidthClick(Sender: TObject; Button: TUDBtnType);
begin
pd.Options.Shadow.Offset := udShadowWidth.Position;
udShadowWidth.Position := pd.Options.Shadow.Offset;
end;
procedure TfrmMain.udZoomClick(Sender: TObject; Button: TUDBtnType);
begin
pd.Options.Scale := udZoom.Position;
udZoom.Position := pd.Options.Scale;
end;
procedure TfrmMain.cbPreviewChange(Sender: TObject);
var Ext: string;
begin
case cbPreview.ItemIndex of
0:
pd.DeviceInfo.ReferenceHandle := 0; // reset to default (screen)
1:
pd.DeviceInfo.ReferenceHandle := Printer.Handle;
end;
// set at least 0.5 inch margins
pd.DeviceInfo.OffsetLeft := Max(pd.DeviceInfo.InchToXPx(0.5), pd.DeviceInfo.OffsetLeft);
pd.DeviceInfo.OffsetRight := Max(pd.DeviceInfo.InchToXPx(0.5), pd.DeviceInfo.OffsetRight);
pd.DeviceInfo.OffsetTop := Max(pd.DeviceInfo.InchToYPx(0.5), pd.DeviceInfo.OffsetTop);
pd.DeviceInfo.OffsetBottom := Max(pd.DeviceInfo.InchToYPx(0.5), pd.DeviceInfo.OffsetBottom);
Ext := AnsiLowerCase(ExtractFileExt(OpenDialog1.Filename));
case OpenDialog1.FilterIndex of
1: BuildRTFPreview;
2: BuildTxtPreview;
else if Pos(Ext, AnsiLowerCase(GraphicFilter(TGraphic))) > 0 then
BuildImagePreview
else
BuildRTFPreview;
end;
end;
procedure TfrmMain.OpenRTFFile(const Filename: string);
begin
Screen.Cursor := crHourGlass;
try
reOriginal.Lines.LoadFromFile(OpenDialog1.Filename);
BuildRTFPreview;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmMain.OpenTxtFile(const Filename: string);
begin
Screen.Cursor := crHourGlass;
try
reOriginal.Lines.Clear;
reOriginal.Font.Name := 'Courier New';
reOriginal.Font.Size := 10;
reOriginal.Font.Color := clWindowText;
reOriginal.DefAttributes.Assign(reOriginal.Font);
reOriginal.Lines.LoadFromFile(OpenDialog1.Filename);
BuildTxtPreview;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmMain.OpenImage(const Filename: string);
begin
with JvImg.Images.Add do
Picture.LoadFromFile(Filename);
end;
procedure TfrmMain.OpenImages(Files: TStrings);
var i: integer;
begin
Screen.Cursor := crHourGlass;
try
for i := 0 to Files.Count - 1 do
OpenImage(Files[i]);
BuildImagePreview;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmMain.Open1Click(Sender: TObject);
var Ext: string;
begin
if OpenDialog1.Execute then
begin
Ext := AnsiLowerCase(ExtractFileExt(OpenDialog1.Filename));
case OpenDialog1.FilterIndex of
1: OpenRTFFile(OpenDialog1.Filename);
2: OpenTxtFile(OpenDialog1.Filename);
else if Pos(Ext, AnsiLowerCase(GraphicFilter(TGraphic))) > 0 then
OpenImages(OpenDialog1.Files)
else
OpenRTFFile(OpenDialog1.Filename);
end; // case
end; // if
end;
procedure TfrmMain.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.Printer1Click(Sender: TObject);
begin
PrinterSetupDialog1.Execute;
// update preview
cbPreviewChange(Sender);
end;
procedure TfrmMain.mnuMarginsClick(Sender: TObject);
begin
mnuMargins.Checked := not mnuMargins.Checked;
pd.Options.DrawMargins := mnuMargins.Checked;
end;
procedure TfrmMain.First1Click(Sender: TObject);
begin
pd.First;
end;
procedure TfrmMain.Previous1Click(Sender: TObject);
begin
pd.Prior;
end;
procedure TfrmMain.Next1Click(Sender: TObject);
begin
pd.Next;
end;
procedure TfrmMain.Last1Click(Sender: TObject);
begin
pd.Last;
end;
procedure TfrmMain.About1Click(Sender: TObject);
begin
ShowMessage('JvPreviewControl Demo');
end;
procedure TfrmMain.cbScaleModeChange(Sender: TObject);
begin
pd.Options.ScaleMode := TJvPreviewScaleMode(cbScaleMode.ItemIndex);
cbScaleMode.ItemIndex := Ord(pd.Options.ScaleMode);
end;
procedure TfrmMain.DoAfterScroll(Sender: TObject);
begin
Statusbar1.Panels[2].Text := Format('Cols: %d, Rows: %d, Row %d', [pd.TotalCols, pd.VisibleRows, pd.TopRow]);
end;
procedure TfrmMain.BuildRTFPreview;
begin
with JvRTF do
begin
RichEdit := reOriginal;
PrintPreview := pd;
CreatePreview(false);
end;
end;
procedure TfrmMain.BuildImagePreview;
begin
with JvImg do
begin
PrintPreview := pd;
CreatePreview(false);
end;
end;
procedure TfrmMain.BuildTXTPreview;
begin
with JvTxt do
begin
PrintPreview := pd;
Strings := reOriginal.Lines;
Font := reOriginal.Font;
Font.Size := 12;
CreatePreview(false);
end;
end;
procedure TfrmMain.Control1Click(Sender: TObject);
begin
with TJvPreviewRenderControl.Create(nil) do
try
pd.First;
PrintPreview := pd;
Control := TControl((Sender as TMenuItem).Tag);
CreatePreview(false);
finally
Free;
end;
end;
procedure TfrmMain.BuildControlMenu;
var m: TMenuItem;
i: integer;
begin
mnuPreview.Clear;
for i := -1 to ComponentCount - 1 do
if (i < 0) or (Components[i] is TControl) then
begin
m := TMenuItem.Create(self);
if i < 0 then
begin
m.Tag := integer(self);
m.Caption := self.Name;
end
else
begin
m.Tag := integer(Components[i]);
m.Caption := Components[i].Name;
end;
m.OnClick := Control1Click;
mnuPreview.Add(m);
end;
end;
procedure TfrmMain.Clear1Click(Sender: TObject);
begin
pd.Clear;
JvImg.Images.Clear;
reOriginal.Lines.Clear;
JvTxt.Strings.Clear;
end;
procedure TfrmMain.udVertSpacingClick(Sender: TObject; Button: TUDBtnType);
begin
pd.Options.VertSpacing := udVertSpacing.Position;
udVertSpacing.Position := pd.Options.VertSpacing;
end;
procedure TfrmMain.udHorzSpacingClick(Sender: TObject; Button: TUDBtnType);
begin
pd.Options.HorzSpacing := udHorzSpacing.Position;
udHorzSpacing.Position := pd.Options.HorzSpacing;
end;
procedure TfrmMain.DoScrollHint(Sender: TObject; AScrollPos: integer;
var AHint: string);
begin
AHint := Format('Page %d', [Cardinal(pd.TopRow) * pd.Options.Cols + 1]);
end;
end.
| 26.451807 | 111 | 0.711759 |
47abb34c07299681da31cc04df66a9670d8751ec | 203,819 | pas | Pascal | samples/DiocpCoders/superobject.pas | Stoby/diocp-v5 | 7d10768e5deadba5fee3b330f3ea05e9913012a1 | [
"BSD-2-Clause"
]
| 229 | 2015-02-25T14:32:37.000Z | 2022-03-29T13:54:06.000Z | samples/DiocpCoders/superobject.pas | Stoby/diocp-v5 | 7d10768e5deadba5fee3b330f3ea05e9913012a1 | [
"BSD-2-Clause"
]
| 3 | 2016-12-30T15:08:57.000Z | 2019-08-15T02:06:11.000Z | samples/DiocpCoders/superobject.pas | Stoby/diocp-v5 | 7d10768e5deadba5fee3b330f3ea05e9913012a1 | [
"BSD-2-Clause"
]
| 127 | 2015-02-23T16:29:52.000Z | 2022-02-23T01:10:31.000Z | (*
* Super Object Toolkit
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Embarcadero Technologies Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
*
* This unit is inspired from the json c lib:
* Michael Clark <michael@metaparadigm.com>
* http://oss.metaparadigm.com/json-c/
*
* CHANGES:
* v1.2
* + support of currency data type
* + right trim unquoted string
* + read Unicode Files and streams (Litle Endian with BOM)
* + Fix bug on javadate functions + windows nt compatibility
* + Now you can force to parse only the canonical syntax of JSON using the stric parameter
* + Delphi 2010 RTTI marshalling
* v1.1
* + Double licence MPL or LGPL.
* + Delphi 2009 compatibility & Unicode support.
* + AsString return a string instead of PChar.
* + Escaped and Unascaped JSON serialiser.
* + Missed FormFeed added \f
* - Removed @ trick, uses forcepath() method instead.
* + Fixed parse error with uppercase E symbol in numbers.
* + Fixed possible buffer overflow when enlarging array.
* + Added "delete", "pack", "insert" methods for arrays and/or objects
* + Multi parametters when calling methods
* + Delphi Enumerator (for obj1 in obj2 do ...)
* + Format method ex: obj.format('<%name%>%tab[1]%</%name%>')
* + ParseFile and ParseStream methods
* + Parser now understand hexdecimal c syntax ex: \xFF
* + Null Object Design Patern (ex: for obj in values.N['path'] do ...)
* v1.0
* + renamed class
* + interfaced object
* + added a new data type: the method
* + parser can now evaluate properties and call methods
* - removed obselet rpc class
* - removed "find" method, now you can use "parse" method instead
* v0.6
* + refactoring
* v0.5
* + new find method to get or set value using a path syntax
* ex: obj.s['obj.prop[1]'] := 'string value';
* obj.a['@obj.array'].b[n] := true; // @ -> create property if necessary
* v0.4
* + bug corrected: AVL tree badly balanced.
* v0.3
* + New validator partially based on the Kwalify syntax.
* + extended syntax to parse unquoted fields.
* + Freepascal compatibility win32/64 Linux32/64.
* + JavaToDelphiDateTime and DelphiToJavaDateTime improved for UTC.
* + new TJsonObject.Compare function.
* v0.2
* + Hashed string list replaced with a faster AVL tree
* + JsonInt data type can be changed to int64
* + JavaToDelphiDateTime and DelphiToJavaDateTime helper fonctions
* + from json-c v0.7
* + Add escaping of backslash to json output
* + Add escaping of foward slash on tokenizing and output
* + Changes to internal tokenizer from using recursion to
* using a depth state structure to allow incremental parsing
* v0.1
* + first release
*)
{$IFDEF FPC}
{$MODE OBJFPC}{$H+}
{$ENDIF}
{$DEFINE SUPER_METHOD}
{$DEFINE WINDOWSNT_COMPATIBILITY}
{.$DEFINE DEBUG} // track memory leack
{$if defined(FPC) or defined(VER170) or defined(VER180) or defined(VER190) or defined(VER200) or defined(VER210)}
{$DEFINE HAVE_INLINE}
{$ifend}
{$if defined(VER210) or defined(VER220) or defined(VER230)}
{$define HAVE_RTTI}
{$ifend}
{$if defined(VER230)}
{$define NEED_FORMATSETTINGS}
{$ifend}
{$if defined(FPC) and defined(VER2_6)}
{$define NEED_FORMATSETTINGS}
{$ifend}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
unit superobject;
{$if CompilerVersion>= 23}
{$define NEED_FORMATSETTINGS}
{$ifend}
interface
uses
Classes
{$IFDEF HAVE_RTTI}
,Generics.Collections, RTTI, TypInfo
{$ENDIF}
;
type
{$IFNDEF FPC}
{$IFDEF CPUX64}
PtrInt = Int64;
PtrUInt = UInt64;
{$ELSE}
PtrInt = longint;
PtrUInt = Longword;
{$ENDIF}
{$ENDIF}
SuperInt = Int64;
{$if (sizeof(Char) = 1)}
SOChar = WideChar;
SOIChar = Word;
PSOChar = PWideChar;
{$IFDEF FPC}
SOString = UnicodeString;
{$ELSE}
SOString = WideString;
{$ENDIF}
{$else}
SOChar = Char;
SOIChar = Word;
PSOChar = PChar;
SOString = string;
{$ifend}
const
SUPER_ARRAY_LIST_DEFAULT_SIZE = 32;
SUPER_TOKENER_MAX_DEPTH = 32;
SUPER_AVL_MAX_DEPTH = sizeof(longint) * 8;
SUPER_AVL_MASK_HIGH_BIT = not ((not longword(0)) shr 1);
type
// forward declarations
TSuperObject = class;
ISuperObject = interface;
TSuperArray = class;
(* AVL Tree
* This is a "special" autobalanced AVL tree
* It use a hash value for fast compare
*)
{$IFDEF SUPER_METHOD}
TSuperMethod = procedure(const This, Params: ISuperObject; var Result: ISuperObject);
{$ENDIF}
TSuperAvlBitArray = set of 0..SUPER_AVL_MAX_DEPTH - 1;
TSuperAvlSearchType = (stEQual, stLess, stGreater);
TSuperAvlSearchTypes = set of TSuperAvlSearchType;
TSuperAvlIterator = class;
TSuperAvlEntry = class
private
FGt, FLt: TSuperAvlEntry;
FBf: integer;
FHash: Cardinal;
FName: SOString;
FPtr: Pointer;
function GetValue: ISuperObject;
procedure SetValue(const val: ISuperObject);
public
class function Hash(const k: SOString): Cardinal; virtual;
constructor Create(const AName: SOString; Obj: Pointer); virtual;
property Name: SOString read FName;
property Ptr: Pointer read FPtr;
property Value: ISuperObject read GetValue write SetValue;
end;
TSuperAvlTree = class
private
FRoot: TSuperAvlEntry;
FCount: Integer;
function balance(bal: TSuperAvlEntry): TSuperAvlEntry;
protected
procedure doDeleteEntry(Entry: TSuperAvlEntry; all: boolean); virtual;
function CompareNodeNode(node1, node2: TSuperAvlEntry): integer; virtual;
function CompareKeyNode(const k: SOString; h: TSuperAvlEntry): integer; virtual;
function Insert(h: TSuperAvlEntry): TSuperAvlEntry; virtual;
function Search(const k: SOString; st: TSuperAvlSearchTypes = [stEqual]): TSuperAvlEntry; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function IsEmpty: boolean;
procedure Clear(all: boolean = false); virtual;
procedure Pack(all: boolean);
function Delete(const k: SOString): ISuperObject;
function GetEnumerator: TSuperAvlIterator;
property count: Integer read FCount;
end;
TSuperTableString = class(TSuperAvlTree)
protected
procedure doDeleteEntry(Entry: TSuperAvlEntry; all: boolean); override;
procedure PutO(const k: SOString; const value: ISuperObject);
function GetO(const k: SOString): ISuperObject;
procedure PutS(const k: SOString; const value: SOString);
function GetS(const k: SOString): SOString;
procedure PutI(const k: SOString; value: SuperInt);
function GetI(const k: SOString): SuperInt;
procedure PutD(const k: SOString; value: Double);
function GetD(const k: SOString): Double;
procedure PutB(const k: SOString; value: Boolean);
function GetB(const k: SOString): Boolean;
{$IFDEF SUPER_METHOD}
procedure PutM(const k: SOString; value: TSuperMethod);
function GetM(const k: SOString): TSuperMethod;
{$ENDIF}
procedure PutN(const k: SOString; const value: ISuperObject);
function GetN(const k: SOString): ISuperObject;
procedure PutC(const k: SOString; value: Currency);
function GetC(const k: SOString): Currency;
public
property O[const k: SOString]: ISuperObject read GetO write PutO; default;
property S[const k: SOString]: SOString read GetS write PutS;
property I[const k: SOString]: SuperInt read GetI write PutI;
property D[const k: SOString]: Double read GetD write PutD;
property B[const k: SOString]: Boolean read GetB write PutB;
{$IFDEF SUPER_METHOD}
property M[const k: SOString]: TSuperMethod read GetM write PutM;
{$ENDIF}
property N[const k: SOString]: ISuperObject read GetN write PutN;
property C[const k: SOString]: Currency read GetC write PutC;
function GetValues: ISuperObject;
function GetNames: ISuperObject;
function Find(const k: SOString; var value: ISuperObject): Boolean;
function Exists(const k: SOString): Boolean;
end;
TSuperAvlIterator = class
private
FTree: TSuperAvlTree;
FBranch: TSuperAvlBitArray;
FDepth: LongInt;
FPath: array[0..SUPER_AVL_MAX_DEPTH - 2] of TSuperAvlEntry;
public
constructor Create(tree: TSuperAvlTree); virtual;
procedure Search(const k: SOString; st: TSuperAvlSearchTypes = [stEQual]);
procedure First;
procedure Last;
function GetIter: TSuperAvlEntry;
procedure Next;
procedure Prior;
// delphi enumerator
function MoveNext: Boolean;
property Current: TSuperAvlEntry read GetIter;
end;
TSuperObjectArray = array[0..(high(Integer) div sizeof(TSuperObject))-1] of ISuperObject;
PSuperObjectArray = ^TSuperObjectArray;
TSuperArray = class
private
FArray: PSuperObjectArray;
FLength: Integer;
FSize: Integer;
procedure Expand(max: Integer);
protected
function GetO(const index: integer): ISuperObject;
procedure PutO(const index: integer; const Value: ISuperObject);
function GetB(const index: integer): Boolean;
procedure PutB(const index: integer; Value: Boolean);
function GetI(const index: integer): SuperInt;
procedure PutI(const index: integer; Value: SuperInt);
function GetD(const index: integer): Double;
procedure PutD(const index: integer; Value: Double);
function GetC(const index: integer): Currency;
procedure PutC(const index: integer; Value: Currency);
function GetS(const index: integer): SOString;
procedure PutS(const index: integer; const Value: SOString);
{$IFDEF SUPER_METHOD}
function GetM(const index: integer): TSuperMethod;
procedure PutM(const index: integer; Value: TSuperMethod);
{$ENDIF}
function GetN(const index: integer): ISuperObject;
procedure PutN(const index: integer; const Value: ISuperObject);
public
constructor Create; virtual;
destructor Destroy; override;
function Add(const Data: ISuperObject): Integer; overload;
function Add(Data: SuperInt): Integer; overload;
function Add(const Data: SOString): Integer; overload;
function Add(Data: Boolean): Integer; overload;
function Add(Data: Double): Integer; overload;
function AddC(const Data: Currency): Integer;
function Delete(index: Integer): ISuperObject;
procedure Insert(index: Integer; const value: ISuperObject);
procedure Clear(all: boolean = false);
procedure Pack(all: boolean);
property Length: Integer read FLength;
property N[const index: integer]: ISuperObject read GetN write PutN;
property O[const index: integer]: ISuperObject read GetO write PutO; default;
property B[const index: integer]: boolean read GetB write PutB;
property I[const index: integer]: SuperInt read GetI write PutI;
property D[const index: integer]: Double read GetD write PutD;
property C[const index: integer]: Currency read GetC write PutC;
property S[const index: integer]: SOString read GetS write PutS;
{$IFDEF SUPER_METHOD}
property M[const index: integer]: TSuperMethod read GetM write PutM;
{$ENDIF}
end;
TSuperWriter = class
public
// abstact methods to overide
function Append(buf: PSOChar; Size: Integer): Integer; overload; virtual; abstract;
function Append(buf: PSOChar): Integer; overload; virtual; abstract;
procedure Reset; virtual; abstract;
end;
TSuperWriterString = class(TSuperWriter)
private
FBuf: PSOChar;
FBPos: integer;
FSize: integer;
public
function Append(buf: PSOChar; Size: Integer): Integer; overload; override;
function Append(buf: PSOChar): Integer; overload; override;
procedure Reset; override;
procedure TrimRight;
constructor Create; virtual;
destructor Destroy; override;
function GetString: SOString;
property Data: PSOChar read FBuf;
property Size: Integer read FSize;
property Position: integer read FBPos;
end;
TSuperWriterStream = class(TSuperWriter)
private
FStream: TStream;
public
function Append(buf: PSOChar): Integer; override;
procedure Reset; override;
constructor Create(AStream: TStream); reintroduce; virtual;
end;
TSuperAnsiWriterStream = class(TSuperWriterStream)
public
function Append(buf: PSOChar; Size: Integer): Integer; override;
end;
TSuperUnicodeWriterStream = class(TSuperWriterStream)
public
function Append(buf: PSOChar; Size: Integer): Integer; override;
end;
TSuperWriterFake = class(TSuperWriter)
private
FSize: Integer;
public
function Append(buf: PSOChar; Size: Integer): Integer; override;
function Append(buf: PSOChar): Integer; override;
procedure Reset; override;
constructor Create; reintroduce; virtual;
property size: integer read FSize;
end;
TSuperWriterSock = class(TSuperWriter)
private
FSocket: longint;
FSize: Integer;
public
function Append(buf: PSOChar; Size: Integer): Integer; override;
function Append(buf: PSOChar): Integer; override;
procedure Reset; override;
constructor Create(ASocket: longint); reintroduce; virtual;
property Socket: longint read FSocket;
property Size: Integer read FSize;
end;
TSuperTokenizerError = (
teSuccess,
teContinue,
teDepth,
teParseEof,
teParseUnexpected,
teParseNull,
teParseBoolean,
teParseNumber,
teParseArray,
teParseObjectKeyName,
teParseObjectKeySep,
teParseObjectValueSep,
teParseString,
teParseComment,
teEvalObject,
teEvalArray,
teEvalMethod,
teEvalInt
);
TSuperTokenerState = (
tsEatws,
tsStart,
tsFinish,
tsNull,
tsCommentStart,
tsComment,
tsCommentEol,
tsCommentEnd,
tsString,
tsStringEscape,
tsIdentifier,
tsEscapeUnicode,
tsEscapeHexadecimal,
tsBoolean,
tsNumber,
tsArray,
tsArrayAdd,
tsArraySep,
tsObjectFieldStart,
tsObjectField,
tsObjectUnquotedField,
tsObjectFieldEnd,
tsObjectValue,
tsObjectValueAdd,
tsObjectSep,
tsEvalProperty,
tsEvalArray,
tsEvalMethod,
tsParamValue,
tsParamPut,
tsMethodValue,
tsMethodPut
);
PSuperTokenerSrec = ^TSuperTokenerSrec;
TSuperTokenerSrec = record
state, saved_state: TSuperTokenerState;
obj: ISuperObject;
current: ISuperObject;
field_name: SOString;
parent: ISuperObject;
gparent: ISuperObject;
end;
TSuperTokenizer = class
public
str: PSOChar;
pb: TSuperWriterString;
depth, is_double, floatcount, st_pos, char_offset: Integer;
err: TSuperTokenizerError;
ucs_char: Word;
quote_char: SOChar;
stack: array[0..SUPER_TOKENER_MAX_DEPTH-1] of TSuperTokenerSrec;
line, col: Integer;
public
constructor Create; virtual;
destructor Destroy; override;
procedure ResetLevel(adepth: integer);
procedure Reset;
end;
// supported object types
TSuperType = (
stNull,
stBoolean,
stDouble,
stCurrency,
stInt,
stObject,
stArray,
stString
{$IFDEF SUPER_METHOD}
,stMethod
{$ENDIF}
);
TSuperValidateError = (
veRuleMalformated,
veFieldIsRequired,
veInvalidDataType,
veFieldNotFound,
veUnexpectedField,
veDuplicateEntry,
veValueNotInEnum,
veInvalidLength,
veInvalidRange
);
TSuperFindOption = (
foCreatePath,
foPutValue,
foDelete
{$IFDEF SUPER_METHOD}
,foCallMethod
{$ENDIF}
);
TSuperFindOptions = set of TSuperFindOption;
TSuperCompareResult = (cpLess, cpEqu, cpGreat, cpError);
TSuperOnValidateError = procedure(sender: Pointer; error: TSuperValidateError; const objpath: SOString);
TSuperEnumerator = class
private
FObj: ISuperObject;
FObjEnum: TSuperAvlIterator;
FCount: Integer;
public
constructor Create(const obj: ISuperObject); virtual;
destructor Destroy; override;
function MoveNext: Boolean;
function GetCurrent: ISuperObject;
property Current: ISuperObject read GetCurrent;
end;
ISuperObject = interface
['{4B86A9E3-E094-4E5A-954A-69048B7B6327}']
function GetEnumerator: TSuperEnumerator;
function GetDataType: TSuperType;
function GetProcessing: boolean;
procedure SetProcessing(value: boolean);
function ForcePath(const path: SOString; dataType: TSuperType = stObject): ISuperObject;
function Format(const str: SOString; BeginSep: SOChar = '%'; EndSep: SOChar = '%'): SOString;
function GetO(const path: SOString): ISuperObject;
procedure PutO(const path: SOString; const Value: ISuperObject);
function GetB(const path: SOString): Boolean;
procedure PutB(const path: SOString; Value: Boolean);
function GetI(const path: SOString): SuperInt;
procedure PutI(const path: SOString; Value: SuperInt);
function GetD(const path: SOString): Double;
procedure PutC(const path: SOString; Value: Currency);
function GetC(const path: SOString): Currency;
procedure PutD(const path: SOString; Value: Double);
function GetS(const path: SOString): SOString;
procedure PutS(const path: SOString; const Value: SOString);
{$IFDEF SUPER_METHOD}
function GetM(const path: SOString): TSuperMethod;
procedure PutM(const path: SOString; Value: TSuperMethod);
{$ENDIF}
function GetA(const path: SOString): TSuperArray;
// Null Object Design patern
function GetN(const path: SOString): ISuperObject;
procedure PutN(const path: SOString; const Value: ISuperObject);
// Writers
function Write(writer: TSuperWriter; indent: boolean; escape: boolean; level: integer): Integer;
function SaveTo(stream: TStream; indent: boolean = false; escape: boolean = true): integer; overload;
function SaveTo(const FileName: string; indent: boolean = false; escape: boolean = true): integer; overload;
function SaveTo(socket: longint; indent: boolean = false; escape: boolean = true): integer; overload;
function CalcSize(indent: boolean = false; escape: boolean = true): integer;
// convert
function AsBoolean: Boolean;
function AsInteger: SuperInt;
function AsDouble: Double;
function AsCurrency: Currency;
function AsString: SOString;
function AsArray: TSuperArray;
function AsObject: TSuperTableString;
{$IFDEF SUPER_METHOD}
function AsMethod: TSuperMethod;
{$ENDIF}
function AsJSon(indent: boolean = false; escape: boolean = true): SOString;
procedure Clear(all: boolean = false);
procedure Pack(all: boolean = false);
property N[const path: SOString]: ISuperObject read GetN write PutN;
property O[const path: SOString]: ISuperObject read GetO write PutO; default;
property B[const path: SOString]: boolean read GetB write PutB;
property I[const path: SOString]: SuperInt read GetI write PutI;
property D[const path: SOString]: Double read GetD write PutD;
property C[const path: SOString]: Currency read GetC write PutC;
property S[const path: SOString]: SOString read GetS write PutS;
{$IFDEF SUPER_METHOD}
property M[const path: SOString]: TSuperMethod read GetM write PutM;
{$ENDIF}
property A[const path: SOString]: TSuperArray read GetA;
{$IFDEF SUPER_METHOD}
function call(const path: SOString; const param: ISuperObject = nil): ISuperObject; overload;
function call(const path, param: SOString): ISuperObject; overload;
{$ENDIF}
// clone a node
function Clone: ISuperObject;
function Delete(const path: SOString): ISuperObject;
// merges tow objects of same type, if reference is true then nodes are not cloned
procedure Merge(const obj: ISuperObject; reference: boolean = false); overload;
procedure Merge(const str: SOString); overload;
// validate methods
function Validate(const rules: SOString; const defs: SOString = ''; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
function Validate(const rules: ISuperObject; const defs: ISuperObject = nil; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
// compare
function Compare(const obj: ISuperObject): TSuperCompareResult; overload;
function Compare(const str: SOString): TSuperCompareResult; overload;
// the data type
function IsType(AType: TSuperType): boolean;
property DataType: TSuperType read GetDataType;
property Processing: boolean read GetProcessing write SetProcessing;
function GetDataPtr: Pointer;
procedure SetDataPtr(const Value: Pointer);
property DataPtr: Pointer read GetDataPtr write SetDataPtr;
end;
TSuperObject = class(TObject, ISuperObject)
private
FRefCount: Integer;
FProcessing: boolean;
FDataType: TSuperType;
FDataPtr: Pointer;
{.$if true}
FO: record
case TSuperType of
stBoolean: (c_boolean: boolean);
stDouble: (c_double: double);
stCurrency: (c_currency: Currency);
stInt: (c_int: SuperInt);
stObject: (c_object: TSuperTableString);
stArray: (c_array: TSuperArray);
{$IFDEF SUPER_METHOD}
stMethod: (c_method: TSuperMethod);
{$ENDIF}
end;
{.$ifend}
FOString: SOString;
function GetDataType: TSuperType;
function GetDataPtr: Pointer;
procedure SetDataPtr(const Value: Pointer);
protected
{$IFDEF FPC}
function QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} iid: tguid; out obj): longint;{$IFNDEF WINDOWS}cdecl{$ELSE}stdcall{$ENDIF};
{$ELSE}
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
{$ENDIF}
function _AddRef: Integer; virtual; stdcall;
function _Release: Integer; virtual; stdcall;
function GetO(const path: SOString): ISuperObject;
procedure PutO(const path: SOString; const Value: ISuperObject);
function GetB(const path: SOString): Boolean;
procedure PutB(const path: SOString; Value: Boolean);
function GetI(const path: SOString): SuperInt;
procedure PutI(const path: SOString; Value: SuperInt);
function GetD(const path: SOString): Double;
procedure PutD(const path: SOString; Value: Double);
procedure PutC(const path: SOString; Value: Currency);
function GetC(const path: SOString): Currency;
function GetS(const path: SOString): SOString;
procedure PutS(const path: SOString; const Value: SOString);
{$IFDEF SUPER_METHOD}
function GetM(const path: SOString): TSuperMethod;
procedure PutM(const path: SOString; Value: TSuperMethod);
{$ENDIF}
function GetA(const path: SOString): TSuperArray;
function Write(writer: TSuperWriter; indent: boolean; escape: boolean; level: integer): Integer; virtual;
public
function GetEnumerator: TSuperEnumerator;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
function GetProcessing: boolean;
procedure SetProcessing(value: boolean);
// Writers
function SaveTo(stream: TStream; indent: boolean = false; escape: boolean = true): integer; overload;
function SaveTo(const FileName: string; indent: boolean = false; escape: boolean = true): integer; overload;
function SaveTo(socket: longint; indent: boolean = false; escape: boolean = true): integer; overload;
function CalcSize(indent: boolean = false; escape: boolean = true): integer;
function AsJSon(indent: boolean = false; escape: boolean = true): SOString;
// parser ... owned!
class function ParseString(s: PSOChar; strict: Boolean; partial: boolean = true; const this: ISuperObject = nil; options: TSuperFindOptions = [];
const put: ISuperObject = nil; dt: TSuperType = stNull): ISuperObject;
class function ParseStream(stream: TStream; strict: Boolean; partial: boolean = true; const this: ISuperObject = nil; options: TSuperFindOptions = [];
const put: ISuperObject = nil; dt: TSuperType = stNull): ISuperObject;
class function ParseFile(const FileName: string; strict: Boolean; partial: boolean = true; const this: ISuperObject = nil; options: TSuperFindOptions = [];
const put: ISuperObject = nil; dt: TSuperType = stNull): ISuperObject;
class function ParseEx(tok: TSuperTokenizer; str: PSOChar; len: integer; strict: Boolean; const this: ISuperObject = nil;
options: TSuperFindOptions = []; const put: ISuperObject = nil; dt: TSuperType = stNull): ISuperObject;
// constructors / destructor
constructor Create(jt: TSuperType = stObject); overload; virtual;
constructor Create(b: boolean); overload; virtual;
constructor Create(i: SuperInt); overload; virtual;
constructor Create(d: double); overload; virtual;
constructor CreateCurrency(c: Currency); overload; virtual;
constructor Create(const s: SOString); overload; virtual;
{$IFDEF SUPER_METHOD}
constructor Create(m: TSuperMethod); overload; virtual;
{$ENDIF}
destructor Destroy; override;
// convert
function AsBoolean: Boolean; virtual;
function AsInteger: SuperInt; virtual;
function AsDouble: Double; virtual;
function AsCurrency: Currency; virtual;
function AsString: SOString; virtual;
function AsArray: TSuperArray; virtual;
function AsObject: TSuperTableString; virtual;
{$IFDEF SUPER_METHOD}
function AsMethod: TSuperMethod; virtual;
{$ENDIF}
procedure Clear(all: boolean = false); virtual;
procedure Pack(all: boolean = false); virtual;
function GetN(const path: SOString): ISuperObject;
procedure PutN(const path: SOString; const Value: ISuperObject);
function ForcePath(const path: SOString; dataType: TSuperType = stObject): ISuperObject;
function Format(const str: SOString; BeginSep: SOChar = '%'; EndSep: SOChar = '%'): SOString;
property N[const path: SOString]: ISuperObject read GetN write PutN;
property O[const path: SOString]: ISuperObject read GetO write PutO; default;
property B[const path: SOString]: boolean read GetB write PutB;
property I[const path: SOString]: SuperInt read GetI write PutI;
property D[const path: SOString]: Double read GetD write PutD;
property C[const path: SOString]: Currency read GetC write PutC;
property S[const path: SOString]: SOString read GetS write PutS;
{$IFDEF SUPER_METHOD}
property M[const path: SOString]: TSuperMethod read GetM write PutM;
{$ENDIF}
property A[const path: SOString]: TSuperArray read GetA;
{$IFDEF SUPER_METHOD}
function call(const path: SOString; const param: ISuperObject = nil): ISuperObject; overload; virtual;
function call(const path, param: SOString): ISuperObject; overload; virtual;
{$ENDIF}
// clone a node
function Clone: ISuperObject; virtual;
function Delete(const path: SOString): ISuperObject;
// merges tow objects of same type, if reference is true then nodes are not cloned
procedure Merge(const obj: ISuperObject; reference: boolean = false); overload;
procedure Merge(const str: SOString); overload;
// validate methods
function Validate(const rules: SOString; const defs: SOString = ''; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
function Validate(const rules: ISuperObject; const defs: ISuperObject = nil; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean; overload;
// compare
function Compare(const obj: ISuperObject): TSuperCompareResult; overload;
function Compare(const str: SOString): TSuperCompareResult; overload;
// the data type
function IsType(AType: TSuperType): boolean;
property DataType: TSuperType read GetDataType;
// a data pointer to link to something ele, a treeview for example
property DataPtr: Pointer read GetDataPtr write SetDataPtr;
property Processing: boolean read GetProcessing;
end;
{$IFDEF HAVE_RTTI}
TSuperRttiContext = class;
TSerialFromJson = function(ctx: TSuperRttiContext; const obj: ISuperObject; var Value: TValue): Boolean;
TSerialToJson = function(ctx: TSuperRttiContext; var value: TValue; const index: ISuperObject): ISuperObject;
TSuperAttribute = class(TCustomAttribute)
private
FName: string;
public
constructor Create(const AName: string);
property Name: string read FName;
end;
SOName = class(TSuperAttribute);
SODefault = class(TSuperAttribute);
TSuperRttiContext = class
private
class function GetFieldName(r: TRttiField): string;
class function GetFieldDefault(r: TRttiField; const obj: ISuperObject): ISuperObject;
public
Context: TRttiContext;
SerialFromJson: TDictionary<PTypeInfo, TSerialFromJson>;
SerialToJson: TDictionary<PTypeInfo, TSerialToJson>;
constructor Create; virtual;
destructor Destroy; override;
function FromJson(TypeInfo: PTypeInfo; const obj: ISuperObject; var Value: TValue): Boolean; virtual;
function ToJson(var value: TValue; const index: ISuperObject): ISuperObject; virtual;
function AsType<T>(const obj: ISuperObject): T;
function AsJson<T>(const obj: T; const index: ISuperObject = nil): ISuperObject;
end;
TSuperObjectHelper = class helper for TObject
public
function ToJson(ctx: TSuperRttiContext = nil): ISuperObject;
constructor FromJson(const obj: ISuperObject; ctx: TSuperRttiContext = nil); overload;
constructor FromJson(const str: string; ctx: TSuperRttiContext = nil); overload;
end;
{$ENDIF}
TSuperObjectIter = record
key: SOString;
val: ISuperObject;
Ite: TSuperAvlIterator;
end;
function ObjectIsError(obj: TSuperObject): boolean;
function ObjectIsType(const obj: ISuperObject; typ: TSuperType): boolean;
function ObjectGetType(const obj: ISuperObject): TSuperType;
function ObjectIsNull(const obj: ISuperObject): Boolean;
function ObjectFindFirst(const obj: ISuperObject; var F: TSuperObjectIter): boolean;
function ObjectFindNext(var F: TSuperObjectIter): boolean;
procedure ObjectFindClose(var F: TSuperObjectIter);
function SO(const s: SOString = '{}'): ISuperObject; overload;
function SO(const value: Variant): ISuperObject; overload;
function SO(const Args: array of const): ISuperObject; overload;
function SA(const Args: array of const): ISuperObject; overload;
function JavaToDelphiDateTime(const dt: int64): TDateTime;
function DelphiToJavaDateTime(const dt: TDateTime): int64;
function TryObjectToDate(const obj: ISuperObject; var dt: TDateTime): Boolean;
function ISO8601DateToJavaDateTime(const str: SOString; var ms: Int64): Boolean;
function ISO8601DateToDelphiDateTime(const str: SOString; var dt: TDateTime): Boolean;
function DelphiDateTimeToISO8601Date(dt: TDateTime): SOString;
function UUIDToString(const g: TGUID): SOString;
function StringToUUID(const str: SOString; var g: TGUID): Boolean;
{$IFDEF HAVE_RTTI}
type
TSuperInvokeResult = (
irSuccess,
irMethothodError, // method don't exist
irParamError, // invalid parametters
irError // other error
);
function TrySOInvoke(var ctx: TSuperRttiContext; const obj: TValue; const method: string; const params: ISuperObject; var Return: ISuperObject): TSuperInvokeResult; overload;
function SOInvoke(const obj: TValue; const method: string; const params: ISuperObject; ctx: TSuperRttiContext = nil): ISuperObject; overload;
function SOInvoke(const obj: TValue; const method: string; const params: string; ctx: TSuperRttiContext = nil): ISuperObject; overload;
{$ENDIF}
implementation
uses sysutils,
{$IFDEF UNIX}
baseunix, unix, DateUtils
{$ELSE}
Windows
{$ENDIF}
{$IFDEF FPC}
,sockets
{$ELSE}
,WinSock
{$ENDIF};
{$IFDEF DEBUG}
var
debugcount: integer = 0;
{$ENDIF}
const
super_number_chars_set = ['0'..'9','.','+','-','e','E'];
super_hex_chars: PSOChar = '0123456789abcdef';
super_hex_chars_set = ['0'..'9','a'..'f','A'..'F'];
ESC_BS: PSOChar = '\b';
ESC_LF: PSOChar = '\n';
ESC_CR: PSOChar = '\r';
ESC_TAB: PSOChar = '\t';
ESC_FF: PSOChar = '\f';
ESC_QUOT: PSOChar = '\"';
ESC_SL: PSOChar = '\\';
ESC_SR: PSOChar = '\/';
ESC_ZERO: PSOChar = '\u0000';
TOK_CRLF: PSOChar = #13#10;
TOK_SP: PSOChar = #32;
TOK_BS: PSOChar = #8;
TOK_TAB: PSOChar = #9;
TOK_LF: PSOChar = #10;
TOK_FF: PSOChar = #12;
TOK_CR: PSOChar = #13;
// TOK_SL: PSOChar = '\';
// TOK_SR: PSOChar = '/';
TOK_NULL: PSOChar = 'null';
TOK_CBL: PSOChar = '{'; // curly bracket left
TOK_CBR: PSOChar = '}'; // curly bracket right
TOK_ARL: PSOChar = '[';
TOK_ARR: PSOChar = ']';
TOK_ARRAY: PSOChar = '[]';
TOK_OBJ: PSOChar = '{}'; // empty object
TOK_COM: PSOChar = ','; // Comma
TOK_DQT: PSOChar = '"'; // Double Quote
TOK_TRUE: PSOChar = 'true';
TOK_FALSE: PSOChar = 'false';
{$if (sizeof(Char) = 1)}
function StrLComp(const Str1, Str2: PSOChar; MaxLen: Cardinal): Integer;
var
P1, P2: PWideChar;
I: Cardinal;
C1, C2: WideChar;
begin
P1 := Str1;
P2 := Str2;
I := 0;
while I < MaxLen do
begin
C1 := P1^;
C2 := P2^;
if (C1 <> C2) or (C1 = #0) then
begin
Result := Ord(C1) - Ord(C2);
Exit;
end;
Inc(P1);
Inc(P2);
Inc(I);
end;
Result := 0;
end;
function StrComp(const Str1, Str2: PSOChar): Integer;
var
P1, P2: PWideChar;
C1, C2: WideChar;
begin
P1 := Str1;
P2 := Str2;
while True do
begin
C1 := P1^;
C2 := P2^;
if (C1 <> C2) or (C1 = #0) then
begin
Result := Ord(C1) - Ord(C2);
Exit;
end;
Inc(P1);
Inc(P2);
end;
end;
function StrLen(const Str: PSOChar): Cardinal;
var
p: PSOChar;
begin
Result := 0;
if Str <> nil then
begin
p := Str;
while p^ <> #0 do inc(p);
Result := (p - Str);
end;
end;
{$ifend}
function FloatToJson(const value: Double): SOString;
var
p: PSOChar;
begin
Result := FloatToStr(value);
if {$if defined(NEED_FORMATSETTINGS)}FormatSettings.{$ifend}DecimalSeparator <> '.' then
begin
p := PSOChar(Result);
while p^ <> #0 do
if p^ <> SOChar({$if defined(NEED_FORMATSETTINGS)}FormatSettings.{$ifend}DecimalSeparator) then
inc(p) else
begin
p^ := '.';
Exit;
end;
end;
end;
function CurrToJson(const value: Currency): SOString;
var
p: PSOChar;
begin
Result := CurrToStr(value);
if {$if defined(NEED_FORMATSETTINGS)}FormatSettings.{$ifend}DecimalSeparator <> '.' then
begin
p := PSOChar(Result);
while p^ <> #0 do
if p^ <> SOChar({$if defined(NEED_FORMATSETTINGS)}FormatSettings.{$ifend}DecimalSeparator) then
inc(p) else
begin
p^ := '.';
Exit;
end;
end;
end;
{$IFDEF UNIX}
function GetTimeBias: integer;
var
TimeVal: TTimeVal;
TimeZone: TTimeZone;
begin
fpGetTimeOfDay(@TimeVal, @TimeZone);
Result := TimeZone.tz_minuteswest;
end;
{$ELSE}
function GetTimeBias: integer;
var
tzi : TTimeZoneInformation;
begin
case GetTimeZoneInformation(tzi) of
TIME_ZONE_ID_UNKNOWN : Result := tzi.Bias;
TIME_ZONE_ID_STANDARD: Result := tzi.Bias + tzi.StandardBias;
TIME_ZONE_ID_DAYLIGHT: Result := tzi.Bias + tzi.DaylightBias;
else
Result := 0;
end;
end;
{$ENDIF}
{$IFDEF UNIX}
type
ptm = ^tm;
tm = record
tm_sec: Integer; (* Seconds: 0-59 (K&R says 0-61?) *)
tm_min: Integer; (* Minutes: 0-59 *)
tm_hour: Integer; (* Hours since midnight: 0-23 *)
tm_mday: Integer; (* Day of the month: 1-31 *)
tm_mon: Integer; (* Months *since* january: 0-11 *)
tm_year: Integer; (* Years since 1900 *)
tm_wday: Integer; (* Days since Sunday (0-6) *)
tm_yday: Integer; (* Days since Jan. 1: 0-365 *)
tm_isdst: Integer; (* +1 Daylight Savings Time, 0 No DST, -1 don't know *)
end;
function mktime(p: ptm): LongInt; cdecl; external;
function gmtime(const t: PLongint): ptm; cdecl; external;
function localtime (const t: PLongint): ptm; cdecl; external;
function DelphiToJavaDateTime(const dt: TDateTime): Int64;
var
p: ptm;
l, ms: Integer;
v: Int64;
begin
v := Round((dt - 25569) * 86400000);
ms := v mod 1000;
l := v div 1000;
p := localtime(@l);
Result := Int64(mktime(p)) * 1000 + ms;
end;
function JavaToDelphiDateTime(const dt: int64): TDateTime;
var
p: ptm;
l, ms: Integer;
begin
l := dt div 1000;
ms := dt mod 1000;
p := gmtime(@l);
Result := EncodeDateTime(p^.tm_year+1900, p^.tm_mon+1, p^.tm_mday, p^.tm_hour, p^.tm_min, p^.tm_sec, ms);
end;
{$ELSE}
{$IFDEF WINDOWSNT_COMPATIBILITY}
function DayLightCompareDate(const date: PSystemTime;
const compareDate: PSystemTime): Integer;
var
limit_day, dayinsecs, weekofmonth: Integer;
First: Word;
begin
if (date^.wMonth < compareDate^.wMonth) then
begin
Result := -1; (* We are in a month before the date limit. *)
Exit;
end;
if (date^.wMonth > compareDate^.wMonth) then
begin
Result := 1; (* We are in a month after the date limit. *)
Exit;
end;
(* if year is 0 then date is in day-of-week format, otherwise
* it's absolute date.
*)
if (compareDate^.wYear = 0) then
begin
(* compareDate.wDay is interpreted as number of the week in the month
* 5 means: the last week in the month *)
weekofmonth := compareDate^.wDay;
(* calculate the day of the first DayOfWeek in the month *)
First := (6 + compareDate^.wDayOfWeek - date^.wDayOfWeek + date^.wDay) mod 7 + 1;
limit_day := First + 7 * (weekofmonth - 1);
(* check needed for the 5th weekday of the month *)
if (limit_day > MonthDays[(date^.wMonth=2) and IsLeapYear(date^.wYear)][date^.wMonth]) then
dec(limit_day, 7);
end
else
limit_day := compareDate^.wDay;
(* convert to seconds *)
limit_day := ((limit_day * 24 + compareDate^.wHour) * 60 + compareDate^.wMinute ) * 60;
dayinsecs := ((date^.wDay * 24 + date^.wHour) * 60 + date^.wMinute ) * 60 + date^.wSecond;
(* and compare *)
if dayinsecs < limit_day then
Result := -1 else
if dayinsecs > limit_day then
Result := 1 else
Result := 0; (* date is equal to the date limit. *)
end;
function CompTimeZoneID(const pTZinfo: PTimeZoneInformation;
lpFileTime: PFileTime; islocal: Boolean): LongWord;
var
ret: Integer;
beforeStandardDate, afterDaylightDate: Boolean;
llTime: Int64;
SysTime: TSystemTime;
ftTemp: TFileTime;
begin
llTime := 0;
if (pTZinfo^.DaylightDate.wMonth <> 0) then
begin
(* if year is 0 then date is in day-of-week format, otherwise
* it's absolute date.
*)
if ((pTZinfo^.StandardDate.wMonth = 0) or
((pTZinfo^.StandardDate.wYear = 0) and
((pTZinfo^.StandardDate.wDay < 1) or
(pTZinfo^.StandardDate.wDay > 5) or
(pTZinfo^.DaylightDate.wDay < 1) or
(pTZinfo^.DaylightDate.wDay > 5)))) then
begin
SetLastError(ERROR_INVALID_PARAMETER);
Result := TIME_ZONE_ID_INVALID;
Exit;
end;
if (not islocal) then
begin
llTime := PInt64(lpFileTime)^;
dec(llTime, Int64(pTZinfo^.Bias + pTZinfo^.DaylightBias) * 600000000);
PInt64(@ftTemp)^ := llTime;
lpFileTime := @ftTemp;
end;
FileTimeToSystemTime(lpFileTime^, SysTime);
(* check for daylight savings *)
ret := DayLightCompareDate(@SysTime, @pTZinfo^.StandardDate);
if (ret = -2) then
begin
Result := TIME_ZONE_ID_INVALID;
Exit;
end;
beforeStandardDate := ret < 0;
if (not islocal) then
begin
dec(llTime, Int64(pTZinfo^.StandardBias - pTZinfo^.DaylightBias) * 600000000);
PInt64(@ftTemp)^ := llTime;
FileTimeToSystemTime(lpFileTime^, SysTime);
end;
ret := DayLightCompareDate(@SysTime, @pTZinfo^.DaylightDate);
if (ret = -2) then
begin
Result := TIME_ZONE_ID_INVALID;
Exit;
end;
afterDaylightDate := ret >= 0;
Result := TIME_ZONE_ID_STANDARD;
if( pTZinfo^.DaylightDate.wMonth < pTZinfo^.StandardDate.wMonth ) then
begin
(* Northern hemisphere *)
if( beforeStandardDate and afterDaylightDate) then
Result := TIME_ZONE_ID_DAYLIGHT;
end else (* Down south *)
if( beforeStandardDate or afterDaylightDate) then
Result := TIME_ZONE_ID_DAYLIGHT;
end else
(* No transition date *)
Result := TIME_ZONE_ID_UNKNOWN;
end;
function GetTimezoneBias(const pTZinfo: PTimeZoneInformation;
lpFileTime: PFileTime; islocal: Boolean; pBias: PLongint): Boolean;
var
bias: LongInt;
tzid: LongWord;
begin
bias := pTZinfo^.Bias;
tzid := CompTimeZoneID(pTZinfo, lpFileTime, islocal);
if( tzid = TIME_ZONE_ID_INVALID) then
begin
Result := False;
Exit;
end;
if (tzid = TIME_ZONE_ID_DAYLIGHT) then
inc(bias, pTZinfo^.DaylightBias)
else if (tzid = TIME_ZONE_ID_STANDARD) then
inc(bias, pTZinfo^.StandardBias);
pBias^ := bias;
Result := True;
end;
function SystemTimeToTzSpecificLocalTime(
lpTimeZoneInformation: PTimeZoneInformation;
lpUniversalTime, lpLocalTime: PSystemTime): BOOL;
var
ft: TFileTime;
lBias: LongInt;
llTime: Int64;
tzinfo: TTimeZoneInformation;
begin
if (lpTimeZoneInformation <> nil) then
tzinfo := lpTimeZoneInformation^ else
if (GetTimeZoneInformation(tzinfo) = TIME_ZONE_ID_INVALID) then
begin
Result := False;
Exit;
end;
if (not SystemTimeToFileTime(lpUniversalTime^, ft)) then
begin
Result := False;
Exit;
end;
llTime := PInt64(@ft)^;
if (not GetTimezoneBias(@tzinfo, @ft, False, @lBias)) then
begin
Result := False;
Exit;
end;
(* convert minutes to 100-nanoseconds-ticks *)
dec(llTime, Int64(lBias) * 600000000);
PInt64(@ft)^ := llTime;
Result := FileTimeToSystemTime(ft, lpLocalTime^);
end;
function TzSpecificLocalTimeToSystemTime(
const lpTimeZoneInformation: PTimeZoneInformation;
const lpLocalTime: PSystemTime; lpUniversalTime: PSystemTime): BOOL;
var
ft: TFileTime;
lBias: LongInt;
t: Int64;
tzinfo: TTimeZoneInformation;
begin
if (lpTimeZoneInformation <> nil) then
tzinfo := lpTimeZoneInformation^
else
if (GetTimeZoneInformation(tzinfo) = TIME_ZONE_ID_INVALID) then
begin
Result := False;
Exit;
end;
if (not SystemTimeToFileTime(lpLocalTime^, ft)) then
begin
Result := False;
Exit;
end;
t := PInt64(@ft)^;
if (not GetTimezoneBias(@tzinfo, @ft, True, @lBias)) then
begin
Result := False;
Exit;
end;
(* convert minutes to 100-nanoseconds-ticks *)
inc(t, Int64(lBias) * 600000000);
PInt64(@ft)^ := t;
Result := FileTimeToSystemTime(ft, lpUniversalTime^);
end;
{$ELSE}
function TzSpecificLocalTimeToSystemTime(
lpTimeZoneInformation: PTimeZoneInformation;
lpLocalTime, lpUniversalTime: PSystemTime): BOOL; stdcall; external 'kernel32.dll';
function SystemTimeToTzSpecificLocalTime(
lpTimeZoneInformation: PTimeZoneInformation;
lpUniversalTime, lpLocalTime: PSystemTime): BOOL; stdcall; external 'kernel32.dll';
{$ENDIF}
function JavaToDelphiDateTime(const dt: int64): TDateTime;
var
t: TSystemTime;
begin
DateTimeToSystemTime(25569 + (dt / 86400000), t);
SystemTimeToTzSpecificLocalTime(nil, @t, @t);
Result := SystemTimeToDateTime(t);
end;
function DelphiToJavaDateTime(const dt: TDateTime): int64;
var
t: TSystemTime;
begin
DateTimeToSystemTime(dt, t);
TzSpecificLocalTimeToSystemTime(nil, @t, @t);
Result := Round((SystemTimeToDateTime(t) - 25569) * 86400000)
end;
{$ENDIF}
function ISO8601DateToJavaDateTime(const str: SOString; var ms: Int64): Boolean;
type
TState = (
stStart, stYear, stMonth, stWeek, stWeekDay, stDay, stDayOfYear,
stHour, stMin, stSec, stMs, stUTC, stGMTH, stGMTM,
stGMTend, stEnd);
TPerhaps = (yes, no, perhaps);
TDateTimeInfo = record
year: Word;
month: Word;
week: Word;
weekday: Word;
day: Word;
dayofyear: Integer;
hour: Word;
minute: Word;
second: Word;
ms: Word;
bias: Integer;
end;
var
p: PSOChar;
state: TState;
pos, v: Word;
sep: TPerhaps;
inctz, havetz, havedate: Boolean;
st: TDateTimeInfo;
DayTable: PDayTable;
function get(var v: Word; c: SOChar): Boolean; {$IFDEF HAVE_INLINE} inline;{$ENDIF}
begin
if (c < #256) and (AnsiChar(c) in ['0'..'9']) then
begin
Result := True;
v := v * 10 + Ord(c) - Ord('0');
end else
Result := False;
end;
label
error;
begin
p := PSOChar(str);
sep := perhaps;
state := stStart;
pos := 0;
FillChar(st, SizeOf(st), 0);
havedate := True;
inctz := False;
havetz := False;
while true do
case state of
stStart:
case p^ of
'0'..'9': state := stYear;
'T', 't':
begin
state := stHour;
pos := 0;
inc(p);
havedate := False;
end;
else
goto error;
end;
stYear:
case pos of
0..1,3:
if get(st.year, p^) then
begin
Inc(pos);
Inc(p);
end else
goto error;
2: case p^ of
'0'..'9':
begin
st.year := st.year * 10 + ord(p^) - ord('0');
Inc(pos);
Inc(p);
end;
':':
begin
havedate := false;
st.hour := st.year;
st.year := 0;
inc(p);
pos := 0;
state := stMin;
sep := yes;
end;
else
goto error;
end;
4: case p^ of
'-': begin
pos := 0;
Inc(p);
sep := yes;
state := stMonth;
end;
'0'..'9':
begin
sep := no;
pos := 0;
state := stMonth;
end;
'W', 'w' :
begin
pos := 0;
Inc(p);
state := stWeek;
end;
'T', 't', ' ':
begin
state := stHour;
pos := 0;
inc(p);
st.month := 1;
st.day := 1;
end;
#0:
begin
st.month := 1;
st.day := 1;
state := stEnd;
end;
else
goto error;
end;
end;
stMonth:
case pos of
0: case p^ of
'0'..'9':
begin
st.month := ord(p^) - ord('0');
Inc(pos);
Inc(p);
end;
'W', 'w':
begin
pos := 0;
Inc(p);
state := stWeek;
end;
else
goto error;
end;
1: if get(st.month, p^) then
begin
Inc(pos);
Inc(p);
end else
goto error;
2: case p^ of
'-':
if (sep in [yes, perhaps]) then
begin
pos := 0;
Inc(p);
state := stDay;
sep := yes;
end else
goto error;
'0'..'9':
if sep in [no, perhaps] then
begin
pos := 0;
state := stDay;
sep := no;
end else
begin
st.dayofyear := st.month * 10 + Ord(p^) - Ord('0');
st.month := 0;
inc(p);
pos := 3;
state := stDayOfYear;
end;
'T', 't', ' ':
begin
state := stHour;
pos := 0;
inc(p);
st.day := 1;
end;
#0:
begin
st.day := 1;
state := stEnd;
end;
else
goto error;
end;
end;
stDay:
case pos of
0: if get(st.day, p^) then
begin
Inc(pos);
Inc(p);
end else
goto error;
1: if get(st.day, p^) then
begin
Inc(pos);
Inc(p);
end else
if sep in [no, perhaps] then
begin
st.dayofyear := st.month * 10 + st.day;
st.day := 0;
st.month := 0;
state := stDayOfYear;
end else
goto error;
2: case p^ of
'T', 't', ' ':
begin
pos := 0;
Inc(p);
state := stHour;
end;
#0: state := stEnd;
else
goto error;
end;
end;
stDayOfYear:
begin
if (st.dayofyear <= 0) then goto error;
case p^ of
'T', 't', ' ':
begin
pos := 0;
Inc(p);
state := stHour;
end;
#0: state := stEnd;
else
goto error;
end;
end;
stWeek:
begin
case pos of
0..1: if get(st.week, p^) then
begin
inc(pos);
inc(p);
end else
goto error;
2: case p^ of
'-': if (sep in [yes, perhaps]) then
begin
Inc(p);
state := stWeekDay;
sep := yes;
end else
goto error;
'1'..'7':
if sep in [no, perhaps] then
begin
state := stWeekDay;
sep := no;
end else
goto error;
else
goto error;
end;
end;
end;
stWeekDay:
begin
if (st.week > 0) and get(st.weekday, p^) then
begin
inc(p);
v := st.year - 1;
v := ((v * 365) + (v div 4) - (v div 100) + (v div 400)) mod 7 + 1;
st.dayofyear := (st.weekday - v) + ((st.week) * 7) + 1;
if v <= 4 then dec(st.dayofyear, 7);
case p^ of
'T', 't', ' ':
begin
pos := 0;
Inc(p);
state := stHour;
end;
#0: state := stEnd;
else
goto error;
end;
end else
goto error;
end;
stHour:
case pos of
0: case p^ of
'0'..'9':
if get(st.hour, p^) then
begin
inc(pos);
inc(p);
end else
goto error;
'-':
begin
inc(p);
state := stMin;
end;
else
goto error;
end;
1: if get(st.hour, p^) then
begin
inc(pos);
inc(p);
end else
goto error;
2: case p^ of
':': if sep in [yes, perhaps] then
begin
sep := yes;
pos := 0;
Inc(p);
state := stMin;
end else
goto error;
',', '.':
begin
Inc(p);
state := stMs;
end;
'+':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
end else
goto error;
'-':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
inctz := True;
end else
goto error;
'Z', 'z':
if havedate then
state := stUTC else
goto error;
'0'..'9':
if sep in [no, perhaps] then
begin
pos := 0;
state := stMin;
sep := no;
end else
goto error;
#0: state := stEnd;
else
goto error;
end;
end;
stMin:
case pos of
0: case p^ of
'0'..'9':
if get(st.minute, p^) then
begin
inc(pos);
inc(p);
end else
goto error;
'-':
begin
inc(p);
state := stSec;
end;
else
goto error;
end;
1: if get(st.minute, p^) then
begin
inc(pos);
inc(p);
end else
goto error;
2: case p^ of
':': if sep in [yes, perhaps] then
begin
pos := 0;
Inc(p);
state := stSec;
sep := yes;
end else
goto error;
',', '.':
begin
Inc(p);
state := stMs;
end;
'+':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
end else
goto error;
'-':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
inctz := True;
end else
goto error;
'Z', 'z':
if havedate then
state := stUTC else
goto error;
'0'..'9':
if sep in [no, perhaps] then
begin
pos := 0;
state := stSec;
end else
goto error;
#0: state := stEnd;
else
goto error;
end;
end;
stSec:
case pos of
0..1: if get(st.second, p^) then
begin
inc(pos);
inc(p);
end else
goto error;
2: case p^ of
',', '.':
begin
Inc(p);
state := stMs;
end;
'+':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
end else
goto error;
'-':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
inctz := True;
end else
goto error;
'Z', 'z':
if havedate then
state := stUTC else
goto error;
#0: state := stEnd;
else
goto error;
end;
end;
stMs:
case p^ of
'0'..'9':
begin
st.ms := st.ms * 10 + ord(p^) - ord('0');
inc(p);
end;
'+':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
end else
goto error;
'-':
if havedate then
begin
state := stGMTH;
pos := 0;
v := 0;
inc(p);
inctz := True;
end else
goto error;
'Z', 'z':
if havedate then
state := stUTC else
goto error;
#0: state := stEnd;
else
goto error;
end;
stUTC: // = GMT 0
begin
havetz := True;
inc(p);
if p^ = #0 then
Break else
goto error;
end;
stGMTH:
begin
havetz := True;
case pos of
0..1: if get(v, p^) then
begin
inc(p);
inc(pos);
end else
goto error;
2:
begin
st.bias := v * 60;
case p^ of
':': if sep in [yes, perhaps] then
begin
state := stGMTM;
inc(p);
pos := 0;
v := 0;
sep := yes;
end else
goto error;
'0'..'9':
if sep in [no, perhaps] then
begin
state := stGMTM;
pos := 1;
sep := no;
inc(p);
v := ord(p^) - ord('0');
end else
goto error;
#0: state := stGMTend;
else
goto error;
end;
end;
end;
end;
stGMTM:
case pos of
0..1: if get(v, p^) then
begin
inc(p);
inc(pos);
end else
goto error;
2: case p^ of
#0:
begin
state := stGMTend;
inc(st.Bias, v);
end;
else
goto error;
end;
end;
stGMTend:
begin
if not inctz then
st.Bias := -st.bias;
Break;
end;
stEnd:
begin
Break;
end;
end;
if (st.hour >= 24) or (st.minute >= 60) or (st.second >= 60) or (st.ms >= 1000) or (st.week > 53)
then goto error;
if not havetz then
st.bias := GetTimeBias;
ms := st.ms + st.second * 1000 + (st.minute + st.bias) * 60000 + st.hour * 3600000;
if havedate then
begin
DayTable := @MonthDays[IsLeapYear(st.year)];
if st.month <> 0 then
begin
if not (st.month in [1..12]) or (DayTable^[st.month] < st.day) then
goto error;
for v := 1 to st.month - 1 do
Inc(ms, DayTable^[v] * 86400000);
end;
dec(st.year);
ms := ms + (int64((st.year * 365) + (st.year div 4) - (st.year div 100) +
(st.year div 400) + st.day + st.dayofyear - 719163) * 86400000);
end;
Result := True;
Exit;
error:
Result := False;
end;
function ISO8601DateToDelphiDateTime(const str: SOString; var dt: TDateTime): Boolean;
var
ms: Int64;
begin
Result := ISO8601DateToJavaDateTime(str, ms);
if Result then
dt := JavaToDelphiDateTime(ms)
end;
function DelphiDateTimeToISO8601Date(dt: TDateTime): SOString;
var
year, month, day, hour, min, sec, msec: Word;
tzh: SmallInt;
tzm: Word;
sign: SOChar;
bias: Integer;
begin
DecodeDate(dt, year, month, day);
DecodeTime(dt, hour, min, sec, msec);
bias := GetTimeBias;
tzh := Abs(bias) div 60;
tzm := Abs(bias) - tzh * 60;
if Bias > 0 then
sign := '-' else
sign := '+';
Result := Format('%.4d-%.2d-%.2dT%.2d:%.2d:%.2d,%d%s%.2d:%.2d',
[year, month, day, hour, min, sec, msec, sign, tzh, tzm]);
end;
function TryObjectToDate(const obj: ISuperObject; var dt: TDateTime): Boolean;
var
i: Int64;
begin
case ObjectGetType(obj) of
stInt:
begin
dt := JavaToDelphiDateTime(obj.AsInteger);
Result := True;
end;
stString:
begin
if ISO8601DateToJavaDateTime(obj.AsString, i) then
begin
dt := JavaToDelphiDateTime(i);
Result := True;
end else
Result := TryStrToDateTime(obj.AsString, dt);
end;
else
Result := False;
end;
end;
function SO(const s: SOString): ISuperObject; overload;
begin
Result := TSuperObject.ParseString(PSOChar(s), False);
end;
function SA(const Args: array of const): ISuperObject; overload;
type
TByteArray = array[0..sizeof(integer) - 1] of byte;
PByteArray = ^TByteArray;
var
j: Integer;
intf: IInterface;
begin
Result := TSuperObject.Create(stArray);
for j := 0 to length(Args) - 1 do
with Result.AsArray do
case TVarRec(Args[j]).VType of
vtInteger : Add(TSuperObject.Create(TVarRec(Args[j]).VInteger));
vtInt64 : Add(TSuperObject.Create(TVarRec(Args[j]).VInt64^));
vtBoolean : Add(TSuperObject.Create(TVarRec(Args[j]).VBoolean));
vtChar : Add(TSuperObject.Create(SOString(TVarRec(Args[j]).VChar)));
vtWideChar: Add(TSuperObject.Create(SOChar(TVarRec(Args[j]).VWideChar)));
vtExtended: Add(TSuperObject.Create(TVarRec(Args[j]).VExtended^));
vtCurrency: Add(TSuperObject.CreateCurrency(TVarRec(Args[j]).VCurrency^));
vtString : Add(TSuperObject.Create(SOString(TVarRec(Args[j]).VString^)));
vtPChar : Add(TSuperObject.Create(SOString(TVarRec(Args[j]).VPChar^)));
vtAnsiString: Add(TSuperObject.Create(SOString(AnsiString(TVarRec(Args[j]).VAnsiString))));
vtWideString: Add(TSuperObject.Create(SOString(PWideChar(TVarRec(Args[j]).VWideString))));
vtInterface:
if TVarRec(Args[j]).VInterface = nil then
Add(nil) else
if IInterface(TVarRec(Args[j]).VInterface).QueryInterface(ISuperObject, intf) = 0 then
Add(ISuperObject(intf)) else
Add(nil);
vtPointer :
if TVarRec(Args[j]).VPointer = nil then
Add(nil) else
Add(TSuperObject.Create(PtrInt(TVarRec(Args[j]).VPointer)));
vtVariant:
Add(SO(TVarRec(Args[j]).VVariant^));
vtObject:
if TVarRec(Args[j]).VPointer = nil then
Add(nil) else
Add(TSuperObject.Create(PtrInt(TVarRec(Args[j]).VPointer)));
vtClass:
if TVarRec(Args[j]).VPointer = nil then
Add(nil) else
Add(TSuperObject.Create(PtrInt(TVarRec(Args[j]).VPointer)));
{$if declared(vtUnicodeString)}
vtUnicodeString:
Add(TSuperObject.Create(SOString(string(TVarRec(Args[j]).VUnicodeString))));
{$ifend}
else
assert(false);
end;
end;
function SO(const Args: array of const): ISuperObject; overload;
var
j: Integer;
arr: ISuperObject;
begin
Result := TSuperObject.Create(stObject);
arr := SA(Args);
with arr.AsArray do
for j := 0 to (Length div 2) - 1 do
Result.AsObject.PutO(O[j*2].AsString, O[(j*2) + 1]);
end;
function SO(const value: Variant): ISuperObject; overload;
begin
with TVarData(value) do
case VType of
varNull: Result := nil;
varEmpty: Result := nil;
varSmallInt: Result := TSuperObject.Create(VSmallInt);
varInteger: Result := TSuperObject.Create(VInteger);
varSingle: Result := TSuperObject.Create(VSingle);
varDouble: Result := TSuperObject.Create(VDouble);
varCurrency: Result := TSuperObject.CreateCurrency(VCurrency);
varDate: Result := TSuperObject.Create(DelphiToJavaDateTime(vDate));
varOleStr: Result := TSuperObject.Create(SOString(VOleStr));
varBoolean: Result := TSuperObject.Create(VBoolean);
varShortInt: Result := TSuperObject.Create(VShortInt);
varByte: Result := TSuperObject.Create(VByte);
varWord: Result := TSuperObject.Create(VWord);
varLongWord: Result := TSuperObject.Create(VLongWord);
varInt64: Result := TSuperObject.Create(VInt64);
varString: Result := TSuperObject.Create(SOString(AnsiString(VString)));
{$if declared(varUString)}
{$IFDEF FPC}
varUString: Result := TSuperObject.Create(SOString(UnicodeString(VString)));
{$ELSE}
varUString: Result := TSuperObject.Create(SOString(string(VUString)));
{$ENDIF}
{$ifend}
else
raise Exception.CreateFmt('Unsuported variant data type: %d', [VType]);
end;
end;
function ObjectIsError(obj: TSuperObject): boolean;
begin
Result := PtrUInt(obj) > PtrUInt(-4000);
end;
function ObjectIsType(const obj: ISuperObject; typ: TSuperType): boolean;
begin
if obj <> nil then
Result := typ = obj.DataType else
Result := typ = stNull;
end;
function ObjectGetType(const obj: ISuperObject): TSuperType;
begin
if obj <> nil then
Result := obj.DataType else
Result := stNull;
end;
function ObjectIsNull(const obj: ISuperObject): Boolean;
begin
Result := ObjectIsType(obj, stNull);
end;
function ObjectFindFirst(const obj: ISuperObject; var F: TSuperObjectIter): boolean;
var
i: TSuperAvlEntry;
begin
if ObjectIsType(obj, stObject) then
begin
F.Ite := TSuperAvlIterator.Create(obj.AsObject);
F.Ite.First;
i := F.Ite.GetIter;
if i <> nil then
begin
f.key := i.Name;
f.val := i.Value;
Result := true;
end else
Result := False;
end else
Result := False;
end;
function ObjectFindNext(var F: TSuperObjectIter): boolean;
var
i: TSuperAvlEntry;
begin
F.Ite.Next;
i := F.Ite.GetIter;
if i <> nil then
begin
f.key := i.FName;
f.val := i.Value;
Result := true;
end else
Result := False;
end;
procedure ObjectFindClose(var F: TSuperObjectIter);
begin
F.Ite.Free;
F.val := nil;
end;
function UuidFromString(p: PSOChar; Uuid: PGUID): Boolean;
const
hex2bin: array[48..102] of Byte = (
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,10,11,12,13,14,15);
type
TState = (stEatSpaces, stStart, stHEX, stBracket, stEnd);
TUUID = record
case byte of
0: (guid: TGUID);
1: (bytes: array[0..15] of Byte);
2: (words: array[0..7] of Word);
3: (ints: array[0..3] of Cardinal);
4: (i64s: array[0..1] of UInt64);
end;
function ishex(const c: SOChar): Boolean; {$IFDEF HAVE_INLINE} inline;{$ENDIF}
begin
result := (c < #256) and (AnsiChar(c) in ['0'..'9', 'a'..'z', 'A'..'Z'])
end;
var
pos: Byte;
state, saved: TState;
bracket, separator: Boolean;
label
redo;
begin
FillChar(Uuid^, SizeOf(TGUID), 0);
saved := stStart;
state := stEatSpaces;
bracket := false;
separator := false;
pos := 0;
while true do
redo:
case state of
stEatSpaces:
begin
while true do
case p^ of
' ', #13, #10, #9: inc(p);
else
state := saved;
goto redo;
end;
end;
stStart:
case p^ of
'{':
begin
bracket := true;
inc(p);
state := stEatSpaces;
saved := stHEX;
pos := 0;
end;
else
state := stHEX;
end;
stHEX:
case pos of
0..7:
if ishex(p^) then
begin
Uuid^.D1 := (Uuid^.D1 * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
8:
if (p^ = '-') then
begin
separator := true;
inc(p);
inc(pos)
end else
inc(pos);
13,18,23:
if separator then
begin
if p^ <> '-' then
begin
Result := False;
Exit;
end;
inc(p);
inc(pos);
end else
inc(pos);
9..12:
if ishex(p^) then
begin
TUUID(Uuid^).words[2] := (TUUID(Uuid^).words[2] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
14..17:
if ishex(p^) then
begin
TUUID(Uuid^).words[3] := (TUUID(Uuid^).words[3] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
19..20:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[8] := (TUUID(Uuid^).bytes[8] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
21..22:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[9] := (TUUID(Uuid^).bytes[9] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
24..25:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[10] := (TUUID(Uuid^).bytes[10] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
26..27:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[11] := (TUUID(Uuid^).bytes[11] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
28..29:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[12] := (TUUID(Uuid^).bytes[12] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
30..31:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[13] := (TUUID(Uuid^).bytes[13] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
32..33:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[14] := (TUUID(Uuid^).bytes[14] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
34..35:
if ishex(p^) then
begin
TUUID(Uuid^).bytes[15] := (TUUID(Uuid^).bytes[15] * 16) + hex2bin[Ord(p^)];
inc(p);
inc(pos);
end else
begin
Result := False;
Exit;
end;
36: if bracket then
begin
state := stEatSpaces;
saved := stBracket;
end else
begin
state := stEatSpaces;
saved := stEnd;
end;
end;
stBracket:
begin
if p^ <> '}' then
begin
Result := False;
Exit;
end;
inc(p);
state := stEatSpaces;
saved := stEnd;
end;
stEnd:
begin
if p^ <> #0 then
begin
Result := False;
Exit;
end;
Break;
end;
end;
Result := True;
end;
function UUIDToString(const g: TGUID): SOString;
begin
Result := format('%.8x%.4x%.4x%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x',
[g.D1, g.D2, g.D3,
g.D4[0], g.D4[1], g.D4[2],
g.D4[3], g.D4[4], g.D4[5],
g.D4[6], g.D4[7]]);
end;
function StringToUUID(const str: SOString; var g: TGUID): Boolean;
begin
Result := UuidFromString(PSOChar(str), @g);
end;
{$IFDEF HAVE_RTTI}
function serialtoboolean(ctx: TSuperRttiContext; var value: TValue; const index: ISuperObject): ISuperObject;
begin
Result := TSuperObject.Create(TValueData(value).FAsSLong <> 0);
end;
function serialtodatetime(ctx: TSuperRttiContext; var value: TValue; const index: ISuperObject): ISuperObject;
begin
Result := TSuperObject.Create(DelphiToJavaDateTime(TValueData(value).FAsDouble));
end;
function serialtoguid(ctx: TSuperRttiContext; var value: TValue; const index: ISuperObject): ISuperObject;
var
g: TGUID;
begin
value.ExtractRawData(@g);
Result := TSuperObject.Create(
format('%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x',
[g.D1, g.D2, g.D3,
g.D4[0], g.D4[1], g.D4[2],
g.D4[3], g.D4[4], g.D4[5],
g.D4[6], g.D4[7]])
);
end;
function serialfromboolean(ctx: TSuperRttiContext; const obj: ISuperObject; var Value: TValue): Boolean;
var
o: ISuperObject;
begin
case ObjectGetType(obj) of
stBoolean:
begin
TValueData(Value).FAsSLong := obj.AsInteger;
Result := True;
end;
stInt:
begin
TValueData(Value).FAsSLong := ord(obj.AsInteger <> 0);
Result := True;
end;
stString:
begin
o := SO(obj.AsString);
if not ObjectIsType(o, stString) then
Result := serialfromboolean(ctx, SO(obj.AsString), Value) else
Result := False;
end;
else
Result := False;
end;
end;
function serialfromdatetime(ctx: TSuperRttiContext; const obj: ISuperObject; var Value: TValue): Boolean;
var
dt: TDateTime;
i: Int64;
begin
case ObjectGetType(obj) of
stInt:
begin
TValueData(Value).FAsDouble := JavaToDelphiDateTime(obj.AsInteger);
Result := True;
end;
stString:
begin
if ISO8601DateToJavaDateTime(obj.AsString, i) then
begin
TValueData(Value).FAsDouble := JavaToDelphiDateTime(i);
Result := True;
end else
if TryStrToDateTime(obj.AsString, dt) then
begin
TValueData(Value).FAsDouble := dt;
Result := True;
end else
Result := False;
end;
else
Result := False;
end;
end;
function serialfromguid(ctx: TSuperRttiContext; const obj: ISuperObject; var Value: TValue): Boolean;
begin
case ObjectGetType(obj) of
stNull:
begin
FillChar(Value.GetReferenceToRawData^, SizeOf(TGUID), 0);
Result := True;
end;
stString: Result := UuidFromString(PSOChar(obj.AsString), Value.GetReferenceToRawData);
else
Result := False;
end;
end;
function SOInvoke(const obj: TValue; const method: string; const params: ISuperObject; ctx: TSuperRttiContext): ISuperObject; overload;
var
owned: Boolean;
begin
if ctx = nil then
begin
ctx := TSuperRttiContext.Create;
owned := True;
end else
owned := False;
try
if TrySOInvoke(ctx, obj, method, params, Result) <> irSuccess then
raise Exception.Create('Invalid method call');
finally
if owned then
ctx.Free;
end;
end;
function SOInvoke(const obj: TValue; const method: string; const params: string; ctx: TSuperRttiContext): ISuperObject; overload;
begin
Result := SOInvoke(obj, method, so(params), ctx)
end;
function TrySOInvoke(var ctx: TSuperRttiContext; const obj: TValue;
const method: string; const params: ISuperObject;
var Return: ISuperObject): TSuperInvokeResult;
var
t: TRttiInstanceType;
m: TRttiMethod;
a: TArray<TValue>;
ps: TArray<TRttiParameter>;
v: TValue;
index: ISuperObject;
function GetParams: Boolean;
var
i: Integer;
begin
case ObjectGetType(params) of
stArray:
for i := 0 to Length(ps) - 1 do
if (pfOut in ps[i].Flags) then
TValue.Make(nil, ps[i].ParamType.Handle, a[i]) else
if not ctx.FromJson(ps[i].ParamType.Handle, params.AsArray[i], a[i]) then
Exit(False);
stObject:
for i := 0 to Length(ps) - 1 do
if (pfOut in ps[i].Flags) then
TValue.Make(nil, ps[i].ParamType.Handle, a[i]) else
if not ctx.FromJson(ps[i].ParamType.Handle, params.AsObject[ps[i].Name], a[i]) then
Exit(False);
stNull: ;
else
Exit(False);
end;
Result := True;
end;
procedure SetParams;
var
i: Integer;
begin
case ObjectGetType(params) of
stArray:
for i := 0 to Length(ps) - 1 do
if (ps[i].Flags * [pfVar, pfOut]) <> [] then
params.AsArray[i] := ctx.ToJson(a[i], index);
stObject:
for i := 0 to Length(ps) - 1 do
if (ps[i].Flags * [pfVar, pfOut]) <> [] then
params.AsObject[ps[i].Name] := ctx.ToJson(a[i], index);
end;
end;
begin
Result := irSuccess;
index := SO;
case obj.Kind of
tkClass:
begin
t := TRttiInstanceType(ctx.Context.GetType(obj.AsObject.ClassType));
m := t.GetMethod(method);
if m = nil then Exit(irMethothodError);
ps := m.GetParameters;
SetLength(a, Length(ps));
if not GetParams then Exit(irParamError);
if m.IsClassMethod then
begin
v := m.Invoke(obj.AsObject.ClassType, a);
Return := ctx.ToJson(v, index);
SetParams;
end else
begin
v := m.Invoke(obj, a);
Return := ctx.ToJson(v, index);
SetParams;
end;
end;
tkClassRef:
begin
t := TRttiInstanceType(ctx.Context.GetType(obj.AsClass));
m := t.GetMethod(method);
if m = nil then Exit(irMethothodError);
ps := m.GetParameters;
SetLength(a, Length(ps));
if not GetParams then Exit(irParamError);
if m.IsClassMethod then
begin
v := m.Invoke(obj, a);
Return := ctx.ToJson(v, index);
SetParams;
end else
Exit(irError);
end;
else
Exit(irError);
end;
end;
{$ENDIF}
{ TSuperEnumerator }
constructor TSuperEnumerator.Create(const obj: ISuperObject);
begin
FObj := obj;
FCount := -1;
if ObjectIsType(FObj, stObject) then
FObjEnum := FObj.AsObject.GetEnumerator else
FObjEnum := nil;
end;
destructor TSuperEnumerator.Destroy;
begin
if FObjEnum <> nil then
FObjEnum.Free;
end;
function TSuperEnumerator.MoveNext: Boolean;
begin
case ObjectGetType(FObj) of
stObject: Result := FObjEnum.MoveNext;
stArray:
begin
inc(FCount);
if FCount < FObj.AsArray.Length then
Result := True else
Result := False;
end;
else
Result := false;
end;
end;
function TSuperEnumerator.GetCurrent: ISuperObject;
begin
case ObjectGetType(FObj) of
stObject: Result := FObjEnum.Current.Value;
stArray: Result := FObj.AsArray.GetO(FCount);
else
Result := FObj;
end;
end;
{ TSuperObject }
constructor TSuperObject.Create(jt: TSuperType);
begin
inherited Create;
{$IFDEF DEBUG}
InterlockedIncrement(debugcount);
{$ENDIF}
FProcessing := false;
FDataPtr := nil;
FDataType := jt;
case FDataType of
stObject: FO.c_object := TSuperTableString.Create;
stArray: FO.c_array := TSuperArray.Create;
stString: FOString := '';
else
FO.c_object := nil;
end;
end;
constructor TSuperObject.Create(b: boolean);
begin
Create(stBoolean);
FO.c_boolean := b;
end;
constructor TSuperObject.Create(i: SuperInt);
begin
Create(stInt);
FO.c_int := i;
end;
constructor TSuperObject.Create(d: double);
begin
Create(stDouble);
FO.c_double := d;
end;
constructor TSuperObject.CreateCurrency(c: Currency);
begin
Create(stCurrency);
FO.c_currency := c;
end;
destructor TSuperObject.Destroy;
begin
{$IFDEF DEBUG}
InterlockedDecrement(debugcount);
{$ENDIF}
case FDataType of
stObject: FO.c_object.Free;
stArray: FO.c_array.Free;
end;
inherited;
end;
function TSuperObject.Write(writer: TSuperWriter; indent: boolean; escape: boolean; level: integer): Integer;
function DoEscape(str: PSOChar; len: Integer): Integer;
var
pos, start_offset: Integer;
c: SOChar;
buf: array[0..5] of SOChar;
type
TByteChar = record
case integer of
0: (a, b: Byte);
1: (c: WideChar);
end;
begin
if str = nil then
begin
Result := 0;
exit;
end;
pos := 0; start_offset := 0;
with writer do
while pos < len do
begin
c := str[pos];
case c of
#8,#9,#10,#12,#13,'"','\','/':
begin
if(pos - start_offset > 0) then
Append(str + start_offset, pos - start_offset);
if(c = #8) then Append(ESC_BS, 2)
else if (c = #9) then Append(ESC_TAB, 2)
else if (c = #10) then Append(ESC_LF, 2)
else if (c = #12) then Append(ESC_FF, 2)
else if (c = #13) then Append(ESC_CR, 2)
else if (c = '"') then Append(ESC_QUOT, 2)
else if (c = '\') then Append(ESC_SL, 2)
else if (c = '/') then Append(ESC_SR, 2);
inc(pos);
start_offset := pos;
end;
else
if (SOIChar(c) > 255) then
begin
if(pos - start_offset > 0) then
Append(str + start_offset, pos - start_offset);
buf[0] := '\';
buf[1] := 'u';
buf[2] := super_hex_chars[TByteChar(c).b shr 4];
buf[3] := super_hex_chars[TByteChar(c).b and $f];
buf[4] := super_hex_chars[TByteChar(c).a shr 4];
buf[5] := super_hex_chars[TByteChar(c).a and $f];
Append(@buf, 6);
inc(pos);
start_offset := pos;
end else
if (c < #32) or (c > #127) then
begin
if(pos - start_offset > 0) then
Append(str + start_offset, pos - start_offset);
buf[0] := '\';
buf[1] := 'u';
buf[2] := '0';
buf[3] := '0';
buf[4] := super_hex_chars[ord(c) shr 4];
buf[5] := super_hex_chars[ord(c) and $f];
Append(buf, 6);
inc(pos);
start_offset := pos;
end else
inc(pos);
end;
end;
if(pos - start_offset > 0) then
writer.Append(str + start_offset, pos - start_offset);
Result := 0;
end;
function DoMinimalEscape(str: PSOChar; len: Integer): Integer;
var
pos, start_offset: Integer;
c: SOChar;
type
TByteChar = record
case integer of
0: (a, b: Byte);
1: (c: WideChar);
end;
begin
if str = nil then
begin
Result := 0;
exit;
end;
pos := 0; start_offset := 0;
with writer do
while pos < len do
begin
c := str[pos];
case c of
#0:
begin
if(pos - start_offset > 0) then
Append(str + start_offset, pos - start_offset);
Append(ESC_ZERO, 6);
inc(pos);
start_offset := pos;
end;
'"':
begin
if(pos - start_offset > 0) then
Append(str + start_offset, pos - start_offset);
Append(ESC_QUOT, 2);
inc(pos);
start_offset := pos;
end;
'\':
begin
if(pos - start_offset > 0) then
Append(str + start_offset, pos - start_offset);
Append(ESC_SL, 2);
inc(pos);
start_offset := pos;
end;
else
inc(pos);
end;
end;
if(pos - start_offset > 0) then
writer.Append(str + start_offset, pos - start_offset);
Result := 0;
end;
procedure _indent(i: shortint; r: boolean);
begin
inc(level, i);
if r then
with writer do
begin
{$IFDEF MSWINDOWS}
Append(TOK_CRLF, 2);
{$ELSE}
Append(TOK_LF, 1);
{$ENDIF}
for i := 0 to level - 1 do
Append(TOK_SP, 1);
end;
end;
var
k,j: Integer;
iter: TSuperObjectIter;
st: AnsiString;
val: ISuperObject;
const
ENDSTR_A: PSOChar = '": ';
ENDSTR_B: PSOChar = '":';
begin
if FProcessing then
begin
Result := writer.Append(TOK_NULL, 4);
Exit;
end;
FProcessing := true;
with writer do
try
case FDataType of
stObject:
if FO.c_object.FCount > 0 then
begin
k := 0;
Append(TOK_CBL, 1);
if indent then _indent(1, false);
if ObjectFindFirst(Self, iter) then
repeat
{$IFDEF SUPER_METHOD}
if (iter.val = nil) or not ObjectIsType(iter.val, stMethod) then
begin
{$ENDIF}
if (iter.val = nil) or (not iter.val.Processing) then
begin
if(k <> 0) then
Append(TOK_COM, 1);
if indent then _indent(0, true);
Append(TOK_DQT, 1);
if escape then
doEscape(PSOChar(iter.key), Length(iter.key)) else
DoMinimalEscape(PSOChar(iter.key), Length(iter.key));
if indent then
Append(ENDSTR_A, 3) else
Append(ENDSTR_B, 2);
if(iter.val = nil) then
Append(TOK_NULL, 4) else
iter.val.write(writer, indent, escape, level);
inc(k);
end;
{$IFDEF SUPER_METHOD}
end;
{$ENDIF}
until not ObjectFindNext(iter);
ObjectFindClose(iter);
if indent then _indent(-1, true);
Result := Append(TOK_CBR, 1);
end else
Result := Append(TOK_OBJ, 2);
stBoolean:
begin
if (FO.c_boolean) then
Result := Append(TOK_TRUE, 4) else
Result := Append(TOK_FALSE, 5);
end;
stInt:
begin
str(FO.c_int, st);
Result := Append(PSOChar(SOString(st)));
end;
stDouble:
Result := Append(PSOChar(FloatToJson(FO.c_double)));
stCurrency:
begin
Result := Append(PSOChar(CurrToJson(FO.c_currency)));
end;
stString:
begin
Append(TOK_DQT, 1);
if escape then
doEscape(PSOChar(FOString), Length(FOString)) else
DoMinimalEscape(PSOChar(FOString), Length(FOString));
Append(TOK_DQT, 1);
Result := 0;
end;
stArray:
if FO.c_array.FLength > 0 then
begin
Append(TOK_ARL, 1);
if indent then _indent(1, true);
k := 0;
j := 0;
while k < FO.c_array.FLength do
begin
val := FO.c_array.GetO(k);
{$IFDEF SUPER_METHOD}
if not ObjectIsType(val, stMethod) then
begin
{$ENDIF}
if (val = nil) or (not val.Processing) then
begin
if (j <> 0) then
Append(TOK_COM, 1);
if(val = nil) then
Append(TOK_NULL, 4) else
val.write(writer, indent, escape, level);
inc(j);
end;
{$IFDEF SUPER_METHOD}
end;
{$ENDIF}
inc(k);
end;
if indent then _indent(-1, false);
Result := Append(TOK_ARR, 1);
end else
Result := Append(TOK_ARRAY, 2);
stNull:
Result := Append(TOK_NULL, 4);
else
Result := 0;
end;
finally
FProcessing := false;
end;
end;
function TSuperObject.IsType(AType: TSuperType): boolean;
begin
Result := AType = FDataType;
end;
function TSuperObject.AsBoolean: boolean;
begin
case FDataType of
stBoolean: Result := FO.c_boolean;
stInt: Result := (FO.c_int <> 0);
stDouble: Result := (FO.c_double <> 0);
stCurrency: Result := (FO.c_currency <> 0);
stString: Result := (Length(FOString) <> 0);
stNull: Result := False;
else
Result := True;
end;
end;
function TSuperObject.AsInteger: SuperInt;
var
code: integer;
cint: SuperInt;
begin
case FDataType of
stInt: Result := FO.c_int;
stDouble: Result := round(FO.c_double);
stCurrency: Result := round(FO.c_currency);
stBoolean: Result := ord(FO.c_boolean);
stString:
begin
Val(FOString, cint, code);
if code = 0 then
Result := cint else
Result := 0;
end;
else
Result := 0;
end;
end;
function TSuperObject.AsDouble: Double;
var
code: integer;
cdouble: double;
begin
case FDataType of
stDouble: Result := FO.c_double;
stCurrency: Result := FO.c_currency;
stInt: Result := FO.c_int;
stBoolean: Result := ord(FO.c_boolean);
stString:
begin
Val(FOString, cdouble, code);
if code = 0 then
Result := cdouble else
Result := 0.0;
end;
else
Result := 0.0;
end;
end;
function TSuperObject.AsCurrency: Currency;
var
code: integer;
cdouble: double;
begin
case FDataType of
stDouble: Result := FO.c_double;
stCurrency: Result := FO.c_currency;
stInt: Result := FO.c_int;
stBoolean: Result := ord(FO.c_boolean);
stString:
begin
Val(FOString, cdouble, code);
if code = 0 then
Result := cdouble else
Result := 0.0;
end;
else
Result := 0.0;
end;
end;
function TSuperObject.AsString: SOString;
begin
case FDataType of
stString: Result := FOString;
stNull: Result := '';
else
Result := AsJSon(false, false);
end;
end;
function TSuperObject.GetEnumerator: TSuperEnumerator;
begin
Result := TSuperEnumerator.Create(Self);
end;
procedure TSuperObject.AfterConstruction;
begin
InterlockedDecrement(FRefCount);
end;
procedure TSuperObject.BeforeDestruction;
begin
if RefCount <> 0 then
raise Exception.Create('Invalid pointer');
end;
function TSuperObject.AsArray: TSuperArray;
begin
if FDataType = stArray then
Result := FO.c_array else
Result := nil;
end;
function TSuperObject.AsObject: TSuperTableString;
begin
if FDataType = stObject then
Result := FO.c_object else
Result := nil;
end;
function TSuperObject.AsJSon(indent, escape: boolean): SOString;
var
pb: TSuperWriterString;
begin
pb := TSuperWriterString.Create;
try
if(Write(pb, indent, escape, 0) < 0) then
begin
Result := '';
Exit;
end;
if pb.FBPos > 0 then
Result := pb.FBuf else
Result := '';
finally
pb.Free;
end;
end;
class function TSuperObject.ParseString(s: PSOChar; strict: Boolean; partial: boolean; const this: ISuperObject;
options: TSuperFindOptions; const put: ISuperObject; dt: TSuperType): ISuperObject;
var
tok: TSuperTokenizer;
obj: ISuperObject;
begin
tok := TSuperTokenizer.Create;
obj := ParseEx(tok, s, -1, strict, this, options, put, dt);
if(tok.err <> teSuccess) or (not partial and (s[tok.char_offset] <> #0)) then
Result := nil else
Result := obj;
tok.Free;
end;
class function TSuperObject.ParseStream(stream: TStream; strict: Boolean;
partial: boolean; const this: ISuperObject; options: TSuperFindOptions;
const put: ISuperObject; dt: TSuperType): ISuperObject;
const
BUFFER_SIZE = 1024;
var
tok: TSuperTokenizer;
buffera: array[0..BUFFER_SIZE-1] of AnsiChar;
bufferw: array[0..BUFFER_SIZE-1] of SOChar;
bom: array[0..1] of byte;
unicode: boolean;
j, size: Integer;
st: string;
begin
st := '';
tok := TSuperTokenizer.Create;
if (stream.Read(bom, sizeof(bom)) = 2) and (bom[0] = $FF) and (bom[1] = $FE) then
begin
unicode := true;
size := stream.Read(bufferw, BUFFER_SIZE * SizeOf(SoChar)) div SizeOf(SoChar);
end else
begin
unicode := false;
stream.Seek(0, soFromBeginning);
size := stream.Read(buffera, BUFFER_SIZE);
end;
while size > 0 do
begin
if not unicode then
for j := 0 to size - 1 do
bufferw[j] := SOChar(buffera[j]);
ParseEx(tok, bufferw, size, strict, this, options, put, dt);
if tok.err = teContinue then
begin
if not unicode then
size := stream.Read(buffera, BUFFER_SIZE) else
size := stream.Read(bufferw, BUFFER_SIZE * SizeOf(SoChar)) div SizeOf(SoChar);
end else
Break;
end;
if(tok.err <> teSuccess) or (not partial and (st[tok.char_offset] <> #0)) then
Result := nil else
Result := tok.stack[tok.depth].current;
tok.Free;
end;
class function TSuperObject.ParseFile(const FileName: string; strict: Boolean;
partial: boolean; const this: ISuperObject; options: TSuperFindOptions;
const put: ISuperObject; dt: TSuperType): ISuperObject;
var
stream: TFileStream;
begin
stream := TFileStream.Create(FileName, fmOpenRead, fmShareDenyWrite);
try
Result := ParseStream(stream, strict, partial, this, options, put, dt);
finally
stream.Free;
end;
end;
class function TSuperObject.ParseEx(tok: TSuperTokenizer; str: PSOChar; len: integer;
strict: Boolean; const this: ISuperObject; options: TSuperFindOptions; const put: ISuperObject; dt: TSuperType): ISuperObject;
const
spaces = [#32,#8,#9,#10,#12,#13];
delimiters = ['"', '.', '[', ']', '{', '}', '(', ')', ',', ':', #0];
reserved = delimiters + spaces;
path = ['a'..'z', 'A'..'Z', '.', '_'];
function hexdigit(x: SOChar): byte; {$IFDEF HAVE_INLINE} inline;{$ENDIF}
begin
if x <= '9' then
Result := byte(x) - byte('0') else
Result := (byte(x) and 7) + 9;
end;
function min(v1, v2: integer): integer;{$IFDEF HAVE_INLINE} inline;{$ENDIF}
begin if v1 < v2 then result := v1 else result := v2 end;
var
obj: ISuperObject;
v: SOChar;
{$IFDEF SUPER_METHOD}
sm: TSuperMethod;
{$ENDIF}
numi: SuperInt;
numd: Double;
code: integer;
TokRec: PSuperTokenerSrec;
evalstack: integer;
p: PSOChar;
function IsEndDelimiter(v: AnsiChar): Boolean;
begin
if tok.depth > 0 then
case tok.stack[tok.depth - 1].state of
tsArrayAdd: Result := v in [',', ']', #0];
tsObjectValueAdd: Result := v in [',', '}', #0];
else
Result := v = #0;
end else
Result := v = #0;
end;
label out, redo_char;
begin
evalstack := 0;
obj := nil;
Result := nil;
TokRec := @tok.stack[tok.depth];
tok.char_offset := 0;
tok.err := teSuccess;
repeat
if (tok.char_offset = len) then
begin
if (tok.depth = 0) and (TokRec^.state = tsEatws) and
(TokRec^.saved_state = tsFinish) then
tok.err := teSuccess else
tok.err := teContinue;
goto out;
end;
v := str^;
case v of
#10:
begin
inc(tok.line);
tok.col := 0;
end;
#9: inc(tok.col, 4);
else
inc(tok.col);
end;
redo_char:
case TokRec^.state of
tsEatws:
begin
if (SOIChar(v) < 256) and (AnsiChar(v) in spaces) then {nop} else
if (v = '/') then
begin
tok.pb.Reset;
tok.pb.Append(@v, 1);
TokRec^.state := tsCommentStart;
end else begin
TokRec^.state := TokRec^.saved_state;
goto redo_char;
end
end;
tsStart:
case v of
'"',
'''':
begin
TokRec^.state := tsString;
tok.pb.Reset;
tok.quote_char := v;
end;
'-':
begin
TokRec^.state := tsNumber;
tok.pb.Reset;
tok.is_double := 0;
tok.floatcount := -1;
goto redo_char;
end;
'0'..'9':
begin
if (tok.depth = 0) then
case ObjectGetType(this) of
stObject:
begin
TokRec^.state := tsIdentifier;
TokRec^.current := this;
goto redo_char;
end;
end;
TokRec^.state := tsNumber;
tok.pb.Reset;
tok.is_double := 0;
tok.floatcount := -1;
goto redo_char;
end;
'{':
begin
TokRec^.state := tsEatws;
TokRec^.saved_state := tsObjectFieldStart;
TokRec^.current := TSuperObject.Create(stObject);
end;
'[':
begin
TokRec^.state := tsEatws;
TokRec^.saved_state := tsArray;
TokRec^.current := TSuperObject.Create(stArray);
end;
{$IFDEF SUPER_METHOD}
'(':
begin
if (tok.depth = 0) and ObjectIsType(this, stMethod) then
begin
TokRec^.current := this;
TokRec^.state := tsParamValue;
end;
end;
{$ENDIF}
'N',
'n':
begin
TokRec^.state := tsNull;
tok.pb.Reset;
tok.st_pos := 0;
goto redo_char;
end;
'T',
't',
'F',
'f':
begin
TokRec^.state := tsBoolean;
tok.pb.Reset;
tok.st_pos := 0;
goto redo_char;
end;
else
TokRec^.state := tsIdentifier;
tok.pb.Reset;
goto redo_char;
end;
tsFinish:
begin
if(tok.depth = 0) then goto out;
obj := TokRec^.current;
tok.ResetLevel(tok.depth);
dec(tok.depth);
TokRec := @tok.stack[tok.depth];
goto redo_char;
end;
tsNull:
begin
tok.pb.Append(@v, 1);
if (StrLComp(TOK_NULL, PSOChar(tok.pb.FBuf), min(tok.st_pos + 1, 4)) = 0) then
begin
if (tok.st_pos = 4) then
if (((SOIChar(v) < 256) and (AnsiChar(v) in path)) or (SOIChar(v) >= 256)) then
TokRec^.state := tsIdentifier else
begin
TokRec^.current := TSuperObject.Create(stNull);
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
goto redo_char;
end;
end else
begin
TokRec^.state := tsIdentifier;
tok.pb.FBuf[tok.st_pos] := #0;
dec(tok.pb.FBPos);
goto redo_char;
end;
inc(tok.st_pos);
end;
tsCommentStart:
begin
if(v = '*') then
begin
TokRec^.state := tsComment;
end else
if (v = '/') then
begin
TokRec^.state := tsCommentEol;
end else
begin
tok.err := teParseComment;
goto out;
end;
tok.pb.Append(@v, 1);
end;
tsComment:
begin
if(v = '*') then
TokRec^.state := tsCommentEnd;
tok.pb.Append(@v, 1);
end;
tsCommentEol:
begin
if (v = #10) then
TokRec^.state := tsEatws else
tok.pb.Append(@v, 1);
end;
tsCommentEnd:
begin
tok.pb.Append(@v, 1);
if (v = '/') then
TokRec^.state := tsEatws else
TokRec^.state := tsComment;
end;
tsString:
begin
if (v = tok.quote_char) then
begin
TokRec^.current := TSuperObject.Create(SOString(tok.pb.GetString));
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
end else
if (v = '\') then
begin
TokRec^.saved_state := tsString;
TokRec^.state := tsStringEscape;
end else
begin
tok.pb.Append(@v, 1);
end
end;
tsEvalProperty:
begin
if (TokRec^.current = nil) and (foCreatePath in options) then
begin
TokRec^.current := TSuperObject.Create(stObject);
TokRec^.parent.AsObject.PutO(tok.pb.Fbuf, TokRec^.current)
end else
if not ObjectIsType(TokRec^.current, stObject) then
begin
tok.err := teEvalObject;
goto out;
end;
tok.pb.Reset;
TokRec^.state := tsIdentifier;
goto redo_char;
end;
tsEvalArray:
begin
if (TokRec^.current = nil) and (foCreatePath in options) then
begin
TokRec^.current := TSuperObject.Create(stArray);
TokRec^.parent.AsObject.PutO(tok.pb.Fbuf, TokRec^.current)
end else
if not ObjectIsType(TokRec^.current, stArray) then
begin
tok.err := teEvalArray;
goto out;
end;
tok.pb.Reset;
TokRec^.state := tsParamValue;
goto redo_char;
end;
{$IFDEF SUPER_METHOD}
tsEvalMethod:
begin
if ObjectIsType(TokRec^.current, stMethod) and assigned(TokRec^.current.AsMethod) then
begin
tok.pb.Reset;
TokRec^.obj := TSuperObject.Create(stArray);
TokRec^.state := tsMethodValue;
goto redo_char;
end else
begin
tok.err := teEvalMethod;
goto out;
end;
end;
tsMethodValue:
begin
case v of
')':
TokRec^.state := tsIdentifier;
else
if (tok.depth >= SUPER_TOKENER_MAX_DEPTH-1) then
begin
tok.err := teDepth;
goto out;
end;
inc(evalstack);
TokRec^.state := tsMethodPut;
inc(tok.depth);
tok.ResetLevel(tok.depth);
TokRec := @tok.stack[tok.depth];
goto redo_char;
end;
end;
tsMethodPut:
begin
TokRec^.obj.AsArray.Add(obj);
case v of
',':
begin
tok.pb.Reset;
TokRec^.saved_state := tsMethodValue;
TokRec^.state := tsEatws;
end;
')':
begin
if TokRec^.obj.AsArray.Length = 1 then
TokRec^.obj := TokRec^.obj.AsArray.GetO(0);
dec(evalstack);
tok.pb.Reset;
TokRec^.saved_state := tsIdentifier;
TokRec^.state := tsEatws;
end;
else
tok.err := teEvalMethod;
goto out;
end;
end;
{$ENDIF}
tsParamValue:
begin
case v of
']':
TokRec^.state := tsIdentifier;
else
if (tok.depth >= SUPER_TOKENER_MAX_DEPTH-1) then
begin
tok.err := teDepth;
goto out;
end;
inc(evalstack);
TokRec^.state := tsParamPut;
inc(tok.depth);
tok.ResetLevel(tok.depth);
TokRec := @tok.stack[tok.depth];
goto redo_char;
end;
end;
tsParamPut:
begin
dec(evalstack);
TokRec^.obj := obj;
tok.pb.Reset;
TokRec^.saved_state := tsIdentifier;
TokRec^.state := tsEatws;
if v <> ']' then
begin
tok.err := teEvalArray;
goto out;
end;
end;
tsIdentifier:
begin
if (this = nil) then
begin
if (SOIChar(v) < 256) and IsEndDelimiter(AnsiChar(v)) then
begin
if not strict then
begin
tok.pb.TrimRight;
TokRec^.current := TSuperObject.Create(tok.pb.Fbuf);
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
goto redo_char;
end else
begin
tok.err := teParseString;
goto out;
end;
end else
if (v = '\') then
begin
TokRec^.saved_state := tsIdentifier;
TokRec^.state := tsStringEscape;
end else
tok.pb.Append(@v, 1);
end else
begin
if (SOIChar(v) < 256) and (AnsiChar(v) in reserved) then
begin
TokRec^.gparent := TokRec^.parent;
if TokRec^.current = nil then
TokRec^.parent := this else
TokRec^.parent := TokRec^.current;
case ObjectGetType(TokRec^.parent) of
stObject:
case v of
'.':
begin
TokRec^.state := tsEvalProperty;
if tok.pb.FBPos > 0 then
TokRec^.current := TokRec^.parent.AsObject.GetO(tok.pb.Fbuf);
end;
'[':
begin
TokRec^.state := tsEvalArray;
if tok.pb.FBPos > 0 then
TokRec^.current := TokRec^.parent.AsObject.GetO(tok.pb.Fbuf);
end;
'(':
begin
TokRec^.state := tsEvalMethod;
if tok.pb.FBPos > 0 then
TokRec^.current := TokRec^.parent.AsObject.GetO(tok.pb.Fbuf);
end;
else
if tok.pb.FBPos > 0 then
TokRec^.current := TokRec^.parent.AsObject.GetO(tok.pb.Fbuf);
if (foPutValue in options) and (evalstack = 0) then
begin
TokRec^.parent.AsObject.PutO(tok.pb.Fbuf, put);
TokRec^.current := put
end else
if (foDelete in options) and (evalstack = 0) then
begin
TokRec^.current := TokRec^.parent.AsObject.Delete(tok.pb.Fbuf);
end else
if (TokRec^.current = nil) and (foCreatePath in options) then
begin
TokRec^.current := TSuperObject.Create(dt);
TokRec^.parent.AsObject.PutO(tok.pb.Fbuf, TokRec^.current);
end;
TokRec^.current := TokRec^.parent.AsObject.GetO(tok.pb.Fbuf);
TokRec^.state := tsFinish;
goto redo_char;
end;
stArray:
begin
if TokRec^.obj <> nil then
begin
if not ObjectIsType(TokRec^.obj, stInt) or (TokRec^.obj.AsInteger < 0) then
begin
tok.err := teEvalInt;
TokRec^.obj := nil;
goto out;
end;
numi := TokRec^.obj.AsInteger;
TokRec^.obj := nil;
TokRec^.current := TokRec^.parent.AsArray.GetO(numi);
case v of
'.':
if (TokRec^.current = nil) and (foCreatePath in options) then
begin
TokRec^.current := TSuperObject.Create(stObject);
TokRec^.parent.AsArray.PutO(numi, TokRec^.current);
end else
if (TokRec^.current = nil) then
begin
tok.err := teEvalObject;
goto out;
end;
'[':
begin
if (TokRec^.current = nil) and (foCreatePath in options) then
begin
TokRec^.current := TSuperObject.Create(stArray);
TokRec^.parent.AsArray.Add(TokRec^.current);
end else
if (TokRec^.current = nil) then
begin
tok.err := teEvalArray;
goto out;
end;
TokRec^.state := tsEvalArray;
end;
'(': TokRec^.state := tsEvalMethod;
else
if (foPutValue in options) and (evalstack = 0) then
begin
TokRec^.parent.AsArray.PutO(numi, put);
TokRec^.current := put;
end else
if (foDelete in options) and (evalstack = 0) then
begin
TokRec^.current := TokRec^.parent.AsArray.Delete(numi);
end else
TokRec^.current := TokRec^.parent.AsArray.GetO(numi);
TokRec^.state := tsFinish;
goto redo_char
end;
end else
begin
case v of
'.':
begin
if (foPutValue in options) then
begin
TokRec^.current := TSuperObject.Create(stObject);
TokRec^.parent.AsArray.Add(TokRec^.current);
end else
TokRec^.current := TokRec^.parent.AsArray.GetO(TokRec^.parent.AsArray.FLength - 1);
end;
'[':
begin
if (foPutValue in options) then
begin
TokRec^.current := TSuperObject.Create(stArray);
TokRec^.parent.AsArray.Add(TokRec^.current);
end else
TokRec^.current := TokRec^.parent.AsArray.GetO(TokRec^.parent.AsArray.FLength - 1);
TokRec^.state := tsEvalArray;
end;
'(':
begin
if not (foPutValue in options) then
TokRec^.current := TokRec^.parent.AsArray.GetO(TokRec^.parent.AsArray.FLength - 1) else
TokRec^.current := nil;
TokRec^.state := tsEvalMethod;
end;
else
if (foPutValue in options) and (evalstack = 0) then
begin
TokRec^.parent.AsArray.Add(put);
TokRec^.current := put;
end else
if tok.pb.FBPos = 0 then
TokRec^.current := TokRec^.parent.AsArray.GetO(TokRec^.parent.AsArray.FLength - 1);
TokRec^.state := tsFinish;
goto redo_char
end;
end;
end;
{$IFDEF SUPER_METHOD}
stMethod:
case v of
'.':
begin
TokRec^.current := nil;
sm := TokRec^.parent.AsMethod;
sm(TokRec^.gparent, TokRec^.obj, TokRec^.current);
TokRec^.obj := nil;
end;
'[':
begin
TokRec^.current := nil;
sm := TokRec^.parent.AsMethod;
sm(TokRec^.gparent, TokRec^.obj, TokRec^.current);
TokRec^.state := tsEvalArray;
TokRec^.obj := nil;
end;
'(':
begin
TokRec^.current := nil;
sm := TokRec^.parent.AsMethod;
sm(TokRec^.gparent, TokRec^.obj, TokRec^.current);
TokRec^.state := tsEvalMethod;
TokRec^.obj := nil;
end;
else
if not (foPutValue in options) or (evalstack > 0) then
begin
TokRec^.current := nil;
sm := TokRec^.parent.AsMethod;
sm(TokRec^.gparent, TokRec^.obj, TokRec^.current);
TokRec^.obj := nil;
TokRec^.state := tsFinish;
goto redo_char
end else
begin
tok.err := teEvalMethod;
TokRec^.obj := nil;
goto out;
end;
end;
{$ENDIF}
end;
end else
tok.pb.Append(@v, 1);
end;
end;
tsStringEscape:
case v of
'b',
'n',
'r',
't',
'f':
begin
if(v = 'b') then tok.pb.Append(TOK_BS, 1)
else if(v = 'n') then tok.pb.Append(TOK_LF, 1)
else if(v = 'r') then tok.pb.Append(TOK_CR, 1)
else if(v = 't') then tok.pb.Append(TOK_TAB, 1)
else if(v = 'f') then tok.pb.Append(TOK_FF, 1);
TokRec^.state := TokRec^.saved_state;
end;
'u':
begin
tok.ucs_char := 0;
tok.st_pos := 0;
TokRec^.state := tsEscapeUnicode;
end;
'x':
begin
tok.ucs_char := 0;
tok.st_pos := 0;
TokRec^.state := tsEscapeHexadecimal;
end
else
tok.pb.Append(@v, 1);
TokRec^.state := TokRec^.saved_state;
end;
tsEscapeUnicode:
begin
if ((SOIChar(v) < 256) and (AnsiChar(v) in super_hex_chars_set)) then
begin
inc(tok.ucs_char, (Word(hexdigit(v)) shl ((3-tok.st_pos)*4)));
inc(tok.st_pos);
if (tok.st_pos = 4) then
begin
tok.pb.Append(@tok.ucs_char, 1);
TokRec^.state := TokRec^.saved_state;
end
end else
begin
tok.err := teParseString;
goto out;
end
end;
tsEscapeHexadecimal:
begin
if ((SOIChar(v) < 256) and (AnsiChar(v) in super_hex_chars_set)) then
begin
inc(tok.ucs_char, (Word(hexdigit(v)) shl ((1-tok.st_pos)*4)));
inc(tok.st_pos);
if (tok.st_pos = 2) then
begin
tok.pb.Append(@tok.ucs_char, 1);
TokRec^.state := TokRec^.saved_state;
end
end else
begin
tok.err := teParseString;
goto out;
end
end;
tsBoolean:
begin
tok.pb.Append(@v, 1);
if (StrLComp('true', PSOChar(tok.pb.FBuf), min(tok.st_pos + 1, 4)) = 0) then
begin
if (tok.st_pos = 4) then
if (((SOIChar(v) < 256) and (AnsiChar(v) in path)) or (SOIChar(v) >= 256)) then
TokRec^.state := tsIdentifier else
begin
TokRec^.current := TSuperObject.Create(true);
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
goto redo_char;
end
end else
if (StrLComp('false', PSOChar(tok.pb.FBuf), min(tok.st_pos + 1, 5)) = 0) then
begin
if (tok.st_pos = 5) then
if (((SOIChar(v) < 256) and (AnsiChar(v) in path)) or (SOIChar(v) >= 256)) then
TokRec^.state := tsIdentifier else
begin
TokRec^.current := TSuperObject.Create(false);
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
goto redo_char;
end
end else
begin
TokRec^.state := tsIdentifier;
tok.pb.FBuf[tok.st_pos] := #0;
dec(tok.pb.FBPos);
goto redo_char;
end;
inc(tok.st_pos);
end;
tsNumber:
begin
if (SOIChar(v) < 256) and (AnsiChar(v) in super_number_chars_set) then
begin
tok.pb.Append(@v, 1);
if (SOIChar(v) < 256) then
case v of
'.': begin
tok.is_double := 1;
tok.floatcount := 0;
end;
'e','E':
begin
tok.is_double := 1;
tok.floatcount := -1;
end;
'0'..'9':
begin
if (tok.is_double = 1) and (tok.floatcount >= 0) then
begin
inc(tok.floatcount);
if tok.floatcount > 4 then
tok.floatcount := -1;
end;
end;
end;
end else
begin
if (tok.is_double = 0) then
begin
val(tok.pb.FBuf, numi, code);
if ObjectIsType(this, stArray) then
begin
if (foPutValue in options) and (evalstack = 0) then
begin
this.AsArray.PutO(numi, put);
TokRec^.current := put;
end else
if (foDelete in options) and (evalstack = 0) then
TokRec^.current := this.AsArray.Delete(numi) else
TokRec^.current := this.AsArray.GetO(numi);
end else
TokRec^.current := TSuperObject.Create(numi);
end else
if (tok.is_double <> 0) then
begin
if tok.floatcount >= 0 then
begin
p := tok.pb.FBuf;
while p^ <> '.' do inc(p);
for code := 0 to tok.floatcount - 1 do
begin
p^ := p[1];
inc(p);
end;
p^ := #0;
val(tok.pb.FBuf, numi, code);
case tok.floatcount of
0: numi := numi * 10000;
1: numi := numi * 1000;
2: numi := numi * 100;
3: numi := numi * 10;
end;
TokRec^.current := TSuperObject.CreateCurrency(PCurrency(@numi)^);
end else
begin
val(tok.pb.FBuf, numd, code);
TokRec^.current := TSuperObject.Create(numd);
end;
end else
begin
tok.err := teParseNumber;
goto out;
end;
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
goto redo_char;
end
end;
tsArray:
begin
if (v = ']') then
begin
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
end else
begin
if(tok.depth >= SUPER_TOKENER_MAX_DEPTH-1) then
begin
tok.err := teDepth;
goto out;
end;
TokRec^.state := tsArrayAdd;
inc(tok.depth);
tok.ResetLevel(tok.depth);
TokRec := @tok.stack[tok.depth];
goto redo_char;
end
end;
tsArrayAdd:
begin
TokRec^.current.AsArray.Add(obj);
TokRec^.saved_state := tsArraySep;
TokRec^.state := tsEatws;
goto redo_char;
end;
tsArraySep:
begin
if (v = ']') then
begin
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
end else
if (v = ',') then
begin
TokRec^.saved_state := tsArray;
TokRec^.state := tsEatws;
end else
begin
tok.err := teParseArray;
goto out;
end
end;
tsObjectFieldStart:
begin
if (v = '}') then
begin
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
end else
if (SOIChar(v) < 256) and (AnsiChar(v) in ['"', '''']) then
begin
tok.quote_char := v;
tok.pb.Reset;
TokRec^.state := tsObjectField;
end else
if not((SOIChar(v) < 256) and ((AnsiChar(v) in reserved) or strict)) then
begin
TokRec^.state := tsObjectUnquotedField;
tok.pb.Reset;
goto redo_char;
end else
begin
tok.err := teParseObjectKeyName;
goto out;
end
end;
tsObjectField:
begin
if (v = tok.quote_char) then
begin
TokRec^.field_name := tok.pb.FBuf;
TokRec^.saved_state := tsObjectFieldEnd;
TokRec^.state := tsEatws;
end else
if (v = '\') then
begin
TokRec^.saved_state := tsObjectField;
TokRec^.state := tsStringEscape;
end else
begin
tok.pb.Append(@v, 1);
end
end;
tsObjectUnquotedField:
begin
if (SOIChar(v) < 256) and (AnsiChar(v) in [':', #0]) then
begin
TokRec^.field_name := tok.pb.FBuf;
TokRec^.saved_state := tsObjectFieldEnd;
TokRec^.state := tsEatws;
goto redo_char;
end else
if (v = '\') then
begin
TokRec^.saved_state := tsObjectUnquotedField;
TokRec^.state := tsStringEscape;
end else
tok.pb.Append(@v, 1);
end;
tsObjectFieldEnd:
begin
if (v = ':') then
begin
TokRec^.saved_state := tsObjectValue;
TokRec^.state := tsEatws;
end else
begin
tok.err := teParseObjectKeySep;
goto out;
end
end;
tsObjectValue:
begin
if (tok.depth >= SUPER_TOKENER_MAX_DEPTH-1) then
begin
tok.err := teDepth;
goto out;
end;
TokRec^.state := tsObjectValueAdd;
inc(tok.depth);
tok.ResetLevel(tok.depth);
TokRec := @tok.stack[tok.depth];
goto redo_char;
end;
tsObjectValueAdd:
begin
TokRec^.current.AsObject.PutO(TokRec^.field_name, obj);
TokRec^.field_name := '';
TokRec^.saved_state := tsObjectSep;
TokRec^.state := tsEatws;
goto redo_char;
end;
tsObjectSep:
begin
if (v = '}') then
begin
TokRec^.saved_state := tsFinish;
TokRec^.state := tsEatws;
end else
if (v = ',') then
begin
TokRec^.saved_state := tsObjectFieldStart;
TokRec^.state := tsEatws;
end else
begin
tok.err := teParseObjectValueSep;
goto out;
end
end;
end;
inc(str);
inc(tok.char_offset);
until v = #0;
if(TokRec^.state <> tsFinish) and
(TokRec^.saved_state <> tsFinish) then
tok.err := teParseEof;
out:
if(tok.err in [teSuccess]) then
begin
{$IFDEF SUPER_METHOD}
if (foCallMethod in options) and ObjectIsType(TokRec^.current, stMethod) and assigned(TokRec^.current.AsMethod) then
begin
sm := TokRec^.current.AsMethod;
sm(TokRec^.parent, put, Result);
end else
{$ENDIF}
Result := TokRec^.current;
end else
Result := nil;
end;
procedure TSuperObject.PutO(const path: SOString; const Value: ISuperObject);
begin
ParseString(PSOChar(path), true, False, self, [foCreatePath, foPutValue], Value);
end;
procedure TSuperObject.PutB(const path: SOString; Value: Boolean);
begin
ParseString(PSOChar(path), true, False, self, [foCreatePath, foPutValue], TSuperObject.Create(Value));
end;
procedure TSuperObject.PutD(const path: SOString; Value: Double);
begin
ParseString(PSOChar(path), true, False, self, [foCreatePath, foPutValue], TSuperObject.Create(Value));
end;
procedure TSuperObject.PutC(const path: SOString; Value: Currency);
begin
ParseString(PSOChar(path), true, False, self, [foCreatePath, foPutValue], TSuperObject.CreateCurrency(Value));
end;
procedure TSuperObject.PutI(const path: SOString; Value: SuperInt);
begin
ParseString(PSOChar(path), true, False, self, [foCreatePath, foPutValue], TSuperObject.Create(Value));
end;
procedure TSuperObject.PutS(const path: SOString; const Value: SOString);
begin
ParseString(PSOChar(path), true, False, self, [foCreatePath, foPutValue], TSuperObject.Create(Value));
end;
{$IFDEF FPC}
function TSuperObject.QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} iid: tguid; out obj): longint;{$IFNDEF WINDOWS}cdecl{$ELSE}stdcall{$ENDIF};
{$ELSE}
function TSuperObject.QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
{$ENDIF}
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TSuperObject.SaveTo(stream: TStream; indent, escape: boolean): integer;
var
pb: TSuperWriterStream;
begin
if escape then
pb := TSuperAnsiWriterStream.Create(stream) else
pb := TSuperUnicodeWriterStream.Create(stream);
if(Write(pb, indent, escape, 0) < 0) then
begin
pb.Reset;
pb.Free;
Result := 0;
Exit;
end;
Result := stream.Size;
pb.Free;
end;
function TSuperObject.CalcSize(indent, escape: boolean): integer;
var
pb: TSuperWriterFake;
begin
pb := TSuperWriterFake.Create;
if(Write(pb, indent, escape, 0) < 0) then
begin
pb.Free;
Result := 0;
Exit;
end;
Result := pb.FSize;
pb.Free;
end;
function TSuperObject.SaveTo(socket: Integer; indent, escape: boolean): integer;
var
pb: TSuperWriterSock;
begin
pb := TSuperWriterSock.Create(socket);
if(Write(pb, indent, escape, 0) < 0) then
begin
pb.Free;
Result := 0;
Exit;
end;
Result := pb.FSize;
pb.Free;
end;
constructor TSuperObject.Create(const s: SOString);
begin
Create(stString);
FOString := s;
end;
procedure TSuperObject.Clear(all: boolean);
begin
if FProcessing then exit;
FProcessing := true;
try
case FDataType of
stBoolean: FO.c_boolean := false;
stDouble: FO.c_double := 0.0;
stCurrency: FO.c_currency := 0.0;
stInt: FO.c_int := 0;
stObject: FO.c_object.Clear(all);
stArray: FO.c_array.Clear(all);
stString: FOString := '';
{$IFDEF SUPER_METHOD}
stMethod: FO.c_method := nil;
{$ENDIF}
end;
finally
FProcessing := false;
end;
end;
procedure TSuperObject.Pack(all: boolean = false);
begin
if FProcessing then exit;
FProcessing := true;
try
case FDataType of
stObject: FO.c_object.Pack(all);
stArray: FO.c_array.Pack(all);
end;
finally
FProcessing := false;
end;
end;
function TSuperObject.GetN(const path: SOString): ISuperObject;
begin
Result := ParseString(PSOChar(path), False, true, self);
if Result = nil then
Result := TSuperObject.Create(stNull);
end;
procedure TSuperObject.PutN(const path: SOString; const Value: ISuperObject);
begin
if Value = nil then
ParseString(PSOChar(path), False, True, self, [foCreatePath, foPutValue], TSuperObject.Create(stNull)) else
ParseString(PSOChar(path), False, True, self, [foCreatePath, foPutValue], Value);
end;
function TSuperObject.Delete(const path: SOString): ISuperObject;
begin
Result := ParseString(PSOChar(path), False, true, self, [foDelete]);
end;
function TSuperObject.Clone: ISuperObject;
var
ite: TSuperObjectIter;
arr: TSuperArray;
j: integer;
begin
case FDataType of
stBoolean: Result := TSuperObject.Create(FO.c_boolean);
stDouble: Result := TSuperObject.Create(FO.c_double);
stCurrency: Result := TSuperObject.CreateCurrency(FO.c_currency);
stInt: Result := TSuperObject.Create(FO.c_int);
stString: Result := TSuperObject.Create(FOString);
{$IFDEF SUPER_METHOD}
stMethod: Result := TSuperObject.Create(FO.c_method);
{$ENDIF}
stObject:
begin
Result := TSuperObject.Create(stObject);
if ObjectFindFirst(self, ite) then
with Result.AsObject do
repeat
PutO(ite.key, ite.val.Clone);
until not ObjectFindNext(ite);
ObjectFindClose(ite);
end;
stArray:
begin
Result := TSuperObject.Create(stArray);
arr := AsArray;
with Result.AsArray do
for j := 0 to arr.Length - 1 do
Add(arr.GetO(j).Clone);
end;
else
Result := nil;
end;
end;
procedure TSuperObject.Merge(const obj: ISuperObject; reference: boolean);
var
prop1, prop2: ISuperObject;
ite: TSuperObjectIter;
arr: TSuperArray;
j: integer;
begin
if ObjectIsType(obj, FDataType) then
case FDataType of
stBoolean: FO.c_boolean := obj.AsBoolean;
stDouble: FO.c_double := obj.AsDouble;
stCurrency: FO.c_currency := obj.AsCurrency;
stInt: FO.c_int := obj.AsInteger;
stString: FOString := obj.AsString;
{$IFDEF SUPER_METHOD}
stMethod: FO.c_method := obj.AsMethod;
{$ENDIF}
stObject:
begin
if ObjectFindFirst(obj, ite) then
with FO.c_object do
repeat
prop1 := FO.c_object.GetO(ite.key);
if (prop1 <> nil) and (ite.val <> nil) and (prop1.DataType = ite.val.DataType) then
prop1.Merge(ite.val) else
if reference then
PutO(ite.key, ite.val) else
if ite.val <> nil then
PutO(ite.key, ite.val.Clone) else
PutO(ite.key, nil)
until not ObjectFindNext(ite);
ObjectFindClose(ite);
end;
stArray:
begin
arr := obj.AsArray;
with FO.c_array do
for j := 0 to arr.Length - 1 do
begin
prop1 := GetO(j);
prop2 := arr.GetO(j);
if (prop1 <> nil) and (prop2 <> nil) and (prop1.DataType = prop2.DataType) then
prop1.Merge(prop2) else
if reference then
PutO(j, prop2) else
if prop2 <> nil then
PutO(j, prop2.Clone) else
PutO(j, nil);
end;
end;
end;
end;
procedure TSuperObject.Merge(const str: SOString);
begin
Merge(TSuperObject.ParseString(PSOChar(str), False), true);
end;
class function TSuperObject.NewInstance: TObject;
begin
Result := inherited NewInstance;
TSuperObject(Result).FRefCount := 1;
end;
function TSuperObject.ForcePath(const path: SOString; dataType: TSuperType = stObject): ISuperObject;
begin
Result := ParseString(PSOChar(path), False, True, Self, [foCreatePath], nil, dataType);
end;
function TSuperObject.Format(const str: SOString; BeginSep: SOChar; EndSep: SOChar): SOString;
var
p1, p2: PSOChar;
begin
Result := '';
p2 := PSOChar(str);
p1 := p2;
while true do
if p2^ = BeginSep then
begin
if p2 > p1 then
Result := Result + Copy(p1, 0, p2-p1);
inc(p2);
p1 := p2;
while true do
if p2^ = EndSep then Break else
if p2^ = #0 then Exit else
inc(p2);
Result := Result + GetS(copy(p1, 0, p2-p1));
inc(p2);
p1 := p2;
end
else if p2^ = #0 then
begin
if p2 > p1 then
Result := Result + Copy(p1, 0, p2-p1);
Break;
end else
inc(p2);
end;
function TSuperObject.GetO(const path: SOString): ISuperObject;
begin
Result := ParseString(PSOChar(path), False, True, Self);
end;
function TSuperObject.GetA(const path: SOString): TSuperArray;
var
obj: ISuperObject;
begin
obj := ParseString(PSOChar(path), False, True, Self);
if obj <> nil then
Result := obj.AsArray else
Result := nil;
end;
function TSuperObject.GetB(const path: SOString): Boolean;
var
obj: ISuperObject;
begin
obj := GetO(path);
if obj <> nil then
Result := obj.AsBoolean else
Result := false;
end;
function TSuperObject.GetD(const path: SOString): Double;
var
obj: ISuperObject;
begin
obj := GetO(path);
if obj <> nil then
Result := obj.AsDouble else
Result := 0.0;
end;
function TSuperObject.GetC(const path: SOString): Currency;
var
obj: ISuperObject;
begin
obj := GetO(path);
if obj <> nil then
Result := obj.AsCurrency else
Result := 0.0;
end;
function TSuperObject.GetI(const path: SOString): SuperInt;
var
obj: ISuperObject;
begin
obj := GetO(path);
if obj <> nil then
Result := obj.AsInteger else
Result := 0;
end;
function TSuperObject.GetDataPtr: Pointer;
begin
Result := FDataPtr;
end;
function TSuperObject.GetDataType: TSuperType;
begin
Result := FDataType
end;
function TSuperObject.GetS(const path: SOString): SOString;
var
obj: ISuperObject;
begin
obj := GetO(path);
if obj <> nil then
Result := obj.AsString else
Result := '';
end;
function TSuperObject.SaveTo(const FileName: string; indent, escape: boolean): integer;
var
stream: TFileStream;
begin
stream := TFileStream.Create(FileName, fmCreate);
try
Result := SaveTo(stream, indent, escape);
finally
stream.Free;
end;
end;
function TSuperObject.Validate(const rules: SOString; const defs: SOString = ''; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean;
begin
Result := Validate(TSuperObject.ParseString(PSOChar(rules), False), TSuperObject.ParseString(PSOChar(defs), False), callback, sender);
end;
function TSuperObject.Validate(const rules: ISuperObject; const defs: ISuperObject = nil; callback: TSuperOnValidateError = nil; sender: Pointer = nil): boolean;
type
TDataType = (dtUnknown, dtStr, dtInt, dtFloat, dtNumber, dtText, dtBool,
dtMap, dtSeq, dtScalar, dtAny);
var
datatypes: ISuperObject;
names: ISuperObject;
function FindInheritedProperty(const prop: PSOChar; p: ISuperObject): ISuperObject;
var
o: ISuperObject;
e: TSuperAvlEntry;
begin
o := p[prop];
if o <> nil then
result := o else
begin
o := p['inherit'];
if (o <> nil) and ObjectIsType(o, stString) then
begin
e := names.AsObject.Search(o.AsString);
if (e <> nil) then
Result := FindInheritedProperty(prop, e.Value) else
Result := nil;
end else
Result := nil;
end;
end;
function FindDataType(o: ISuperObject): TDataType;
var
e: TSuperAvlEntry;
obj: ISuperObject;
begin
obj := FindInheritedProperty('type', o);
if obj <> nil then
begin
e := datatypes.AsObject.Search(obj.AsString);
if e <> nil then
Result := TDataType(e.Value.AsInteger) else
Result := dtUnknown;
end else
Result := dtUnknown;
end;
procedure GetNames(o: ISuperObject);
var
obj: ISuperObject;
f: TSuperObjectIter;
begin
obj := o['name'];
if ObjectIsType(obj, stString) then
names[obj.AsString] := o;
case FindDataType(o) of
dtMap:
begin
obj := o['mapping'];
if ObjectIsType(obj, stObject) then
begin
if ObjectFindFirst(obj, f) then
repeat
if ObjectIsType(f.val, stObject) then
GetNames(f.val);
until not ObjectFindNext(f);
ObjectFindClose(f);
end;
end;
dtSeq:
begin
obj := o['sequence'];
if ObjectIsType(obj, stObject) then
GetNames(obj);
end;
end;
end;
function FindInheritedField(const prop: SOString; p: ISuperObject): ISuperObject;
var
o: ISuperObject;
e: TSuperAvlEntry;
begin
o := p['mapping'];
if ObjectIsType(o, stObject) then
begin
o := o.AsObject.GetO(prop);
if o <> nil then
begin
Result := o;
Exit;
end;
end;
o := p['inherit'];
if ObjectIsType(o, stString) then
begin
e := names.AsObject.Search(o.AsString);
if (e <> nil) then
Result := FindInheritedField(prop, e.Value) else
Result := nil;
end else
Result := nil;
end;
function InheritedFieldExist(const obj: ISuperObject; p: ISuperObject; const name: SOString = ''): boolean;
var
o: ISuperObject;
e: TSuperAvlEntry;
j: TSuperAvlIterator;
begin
Result := true;
o := p['mapping'];
if ObjectIsType(o, stObject) then
begin
j := TSuperAvlIterator.Create(o.AsObject);
try
j.First;
e := j.GetIter;
while e <> nil do
begin
if obj.AsObject.Search(e.Name) = nil then
begin
Result := False;
if assigned(callback) then
callback(sender, veFieldNotFound, name + '.' + e.Name);
end;
j.Next;
e := j.GetIter;
end;
finally
j.Free;
end;
end;
o := p['inherit'];
if ObjectIsType(o, stString) then
begin
e := names.AsObject.Search(o.AsString);
if (e <> nil) then
Result := InheritedFieldExist(obj, e.Value, name) and Result;
end;
end;
function getInheritedBool(f: PSOChar; p: ISuperObject; default: boolean = false): boolean;
var
o: ISuperObject;
begin
o := FindInheritedProperty(f, p);
case ObjectGetType(o) of
stBoolean: Result := o.AsBoolean;
stNull: Result := Default;
else
Result := default;
if assigned(callback) then
callback(sender, veRuleMalformated, f);
end;
end;
procedure GetInheritedFieldList(list: ISuperObject; p: ISuperObject);
var
o: ISuperObject;
e: TSuperAvlEntry;
i: TSuperAvlIterator;
begin
Result := true;
o := p['mapping'];
if ObjectIsType(o, stObject) then
begin
i := TSuperAvlIterator.Create(o.AsObject);
try
i.First;
e := i.GetIter;
while e <> nil do
begin
if list.AsObject.Search(e.Name) = nil then
list[e.Name] := e.Value;
i.Next;
e := i.GetIter;
end;
finally
i.Free;
end;
end;
o := p['inherit'];
if ObjectIsType(o, stString) then
begin
e := names.AsObject.Search(o.AsString);
if (e <> nil) then
GetInheritedFieldList(list, e.Value);
end;
end;
function CheckEnum(o: ISuperObject; p: ISuperObject; name: SOString = ''): boolean;
var
enum: ISuperObject;
i: integer;
begin
Result := false;
enum := FindInheritedProperty('enum', p);
case ObjectGetType(enum) of
stArray:
for i := 0 to enum.AsArray.Length - 1 do
if (o.AsString = enum.AsArray[i].AsString) then
begin
Result := true;
exit;
end;
stNull: Result := true;
else
Result := false;
if assigned(callback) then
callback(sender, veRuleMalformated, '');
Exit;
end;
if (not Result) and assigned(callback) then
callback(sender, veValueNotInEnum, name);
end;
function CheckLength(len: integer; p: ISuperObject; const objpath: SOString): boolean;
var
length, o: ISuperObject;
begin
result := true;
length := FindInheritedProperty('length', p);
case ObjectGetType(length) of
stObject:
begin
o := length.AsObject.GetO('min');
if (o <> nil) and (o.AsInteger > len) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidLength, objpath);
end;
o := length.AsObject.GetO('max');
if (o <> nil) and (o.AsInteger < len) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidLength, objpath);
end;
o := length.AsObject.GetO('minex');
if (o <> nil) and (o.AsInteger >= len) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidLength, objpath);
end;
o := length.AsObject.GetO('maxex');
if (o <> nil) and (o.AsInteger <= len) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidLength, objpath);
end;
end;
stNull: ;
else
Result := false;
if assigned(callback) then
callback(sender, veRuleMalformated, '');
end;
end;
function CheckRange(obj: ISuperObject; p: ISuperObject; const objpath: SOString): boolean;
var
length, o: ISuperObject;
begin
result := true;
length := FindInheritedProperty('range', p);
case ObjectGetType(length) of
stObject:
begin
o := length.AsObject.GetO('min');
if (o <> nil) and (o.Compare(obj) = cpGreat) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidRange, objpath);
end;
o := length.AsObject.GetO('max');
if (o <> nil) and (o.Compare(obj) = cpLess) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidRange, objpath);
end;
o := length.AsObject.GetO('minex');
if (o <> nil) and (o.Compare(obj) in [cpGreat, cpEqu]) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidRange, objpath);
end;
o := length.AsObject.GetO('maxex');
if (o <> nil) and (o.Compare(obj) in [cpLess, cpEqu]) then
begin
Result := false;
if assigned(callback) then
callback(sender, veInvalidRange, objpath);
end;
end;
stNull: ;
else
Result := false;
if assigned(callback) then
callback(sender, veRuleMalformated, '');
end;
end;
function process(o: ISuperObject; p: ISuperObject; objpath: SOString = ''): boolean;
var
ite: TSuperAvlIterator;
ent: TSuperAvlEntry;
p2, o2, sequence: ISuperObject;
s: SOString;
i: integer;
uniquelist, fieldlist: ISuperObject;
begin
Result := true;
if (o = nil) then
begin
if getInheritedBool('required', p) then
begin
if assigned(callback) then
callback(sender, veFieldIsRequired, objpath);
result := false;
end;
end else
case FindDataType(p) of
dtStr:
case ObjectGetType(o) of
stString:
begin
Result := Result and CheckLength(Length(o.AsString), p, objpath);
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtBool:
case ObjectGetType(o) of
stBoolean:
begin
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtInt:
case ObjectGetType(o) of
stInt:
begin
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtFloat:
case ObjectGetType(o) of
stDouble, stCurrency:
begin
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtMap:
case ObjectGetType(o) of
stObject:
begin
// all objects have and match a rule ?
ite := TSuperAvlIterator.Create(o.AsObject);
try
ite.First;
ent := ite.GetIter;
while ent <> nil do
begin
p2 := FindInheritedField(ent.Name, p);
if ObjectIsType(p2, stObject) then
result := process(ent.Value, p2, objpath + '.' + ent.Name) and result else
begin
if assigned(callback) then
callback(sender, veUnexpectedField, objpath + '.' + ent.Name);
result := false; // field have no rule
end;
ite.Next;
ent := ite.GetIter;
end;
finally
ite.Free;
end;
// all expected field exists ?
Result := InheritedFieldExist(o, p, objpath) and Result;
end;
stNull: {nop};
else
result := false;
if assigned(callback) then
callback(sender, veRuleMalformated, objpath);
end;
dtSeq:
case ObjectGetType(o) of
stArray:
begin
sequence := FindInheritedProperty('sequence', p);
if sequence <> nil then
case ObjectGetType(sequence) of
stObject:
begin
for i := 0 to o.AsArray.Length - 1 do
result := process(o.AsArray.GetO(i), sequence, objpath + '[' + IntToStr(i) + ']') and result;
if getInheritedBool('unique', sequence) then
begin
// type is unique ?
uniquelist := TSuperObject.Create(stObject);
try
for i := 0 to o.AsArray.Length - 1 do
begin
s := o.AsArray.GetO(i).AsString;
if (s <> '') then
begin
if uniquelist.AsObject.Search(s) = nil then
uniquelist[s] := nil else
begin
Result := False;
if Assigned(callback) then
callback(sender, veDuplicateEntry, objpath + '[' + IntToStr(i) + ']');
end;
end;
end;
finally
uniquelist := nil;
end;
end;
// field is unique ?
if (FindDataType(sequence) = dtMap) then
begin
fieldlist := TSuperObject.Create(stObject);
try
GetInheritedFieldList(fieldlist, sequence);
ite := TSuperAvlIterator.Create(fieldlist.AsObject);
try
ite.First;
ent := ite.GetIter;
while ent <> nil do
begin
if getInheritedBool('unique', ent.Value) then
begin
uniquelist := TSuperObject.Create(stObject);
try
for i := 0 to o.AsArray.Length - 1 do
begin
o2 := o.AsArray.GetO(i);
if o2 <> nil then
begin
s := o2.AsObject.GetO(ent.Name).AsString;
if (s <> '') then
if uniquelist.AsObject.Search(s) = nil then
uniquelist[s] := nil else
begin
Result := False;
if Assigned(callback) then
callback(sender, veDuplicateEntry, objpath + '[' + IntToStr(i) + '].' + ent.name);
end;
end;
end;
finally
uniquelist := nil;
end;
end;
ite.Next;
ent := ite.GetIter;
end;
finally
ite.Free;
end;
finally
fieldlist := nil;
end;
end;
end;
stNull: {nop};
else
result := false;
if assigned(callback) then
callback(sender, veRuleMalformated, objpath);
end;
Result := Result and CheckLength(o.AsArray.Length, p, objpath);
end;
else
result := false;
if assigned(callback) then
callback(sender, veRuleMalformated, objpath);
end;
dtNumber:
case ObjectGetType(o) of
stInt,
stDouble, stCurrency:
begin
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtText:
case ObjectGetType(o) of
stInt,
stDouble,
stCurrency,
stString:
begin
result := result and CheckLength(Length(o.AsString), p, objpath);
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtScalar:
case ObjectGetType(o) of
stBoolean,
stDouble,
stCurrency,
stInt,
stString:
begin
result := result and CheckLength(Length(o.AsString), p, objpath);
Result := Result and CheckRange(o, p, objpath);
end;
else
if assigned(callback) then
callback(sender, veInvalidDataType, objpath);
result := false;
end;
dtAny:;
else
if assigned(callback) then
callback(sender, veRuleMalformated, objpath);
result := false;
end;
Result := Result and CheckEnum(o, p, objpath)
end;
var
j: integer;
begin
Result := False;
datatypes := TSuperObject.Create(stObject);
names := TSuperObject.Create;
try
datatypes.I['str'] := ord(dtStr);
datatypes.I['int'] := ord(dtInt);
datatypes.I['float'] := ord(dtFloat);
datatypes.I['number'] := ord(dtNumber);
datatypes.I['text'] := ord(dtText);
datatypes.I['bool'] := ord(dtBool);
datatypes.I['map'] := ord(dtMap);
datatypes.I['seq'] := ord(dtSeq);
datatypes.I['scalar'] := ord(dtScalar);
datatypes.I['any'] := ord(dtAny);
if ObjectIsType(defs, stArray) then
for j := 0 to defs.AsArray.Length - 1 do
if ObjectIsType(defs.AsArray[j], stObject) then
GetNames(defs.AsArray[j]) else
begin
if assigned(callback) then
callback(sender, veRuleMalformated, '');
Exit;
end;
if ObjectIsType(rules, stObject) then
GetNames(rules) else
begin
if assigned(callback) then
callback(sender, veRuleMalformated, '');
Exit;
end;
Result := process(self, rules);
finally
datatypes := nil;
names := nil;
end;
end;
function TSuperObject._AddRef: Integer; stdcall;
begin
Result := InterlockedIncrement(FRefCount);
end;
function TSuperObject._Release: Integer; stdcall;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
Destroy;
end;
function TSuperObject.Compare(const str: SOString): TSuperCompareResult;
begin
Result := Compare(TSuperObject.ParseString(PSOChar(str), False));
end;
function TSuperObject.Compare(const obj: ISuperObject): TSuperCompareResult;
function GetIntCompResult(const i: int64): TSuperCompareResult;
begin
if i < 0 then result := cpLess else
if i = 0 then result := cpEqu else
Result := cpGreat;
end;
function GetDblCompResult(const d: double): TSuperCompareResult;
begin
if d < 0 then result := cpLess else
if d = 0 then result := cpEqu else
Result := cpGreat;
end;
begin
case DataType of
stBoolean:
case ObjectGetType(obj) of
stBoolean: Result := GetIntCompResult(ord(FO.c_boolean) - ord(obj.AsBoolean));
stDouble: Result := GetDblCompResult(ord(FO.c_boolean) - obj.AsDouble);
stCurrency:Result := GetDblCompResult(ord(FO.c_boolean) - obj.AsCurrency);
stInt: Result := GetIntCompResult(ord(FO.c_boolean) - obj.AsInteger);
stString: Result := GetIntCompResult(StrComp(PSOChar(AsString), PSOChar(obj.AsString)));
else
Result := cpError;
end;
stDouble:
case ObjectGetType(obj) of
stBoolean: Result := GetDblCompResult(FO.c_double - ord(obj.AsBoolean));
stDouble: Result := GetDblCompResult(FO.c_double - obj.AsDouble);
stCurrency:Result := GetDblCompResult(FO.c_double - obj.AsCurrency);
stInt: Result := GetDblCompResult(FO.c_double - obj.AsInteger);
stString: Result := GetIntCompResult(StrComp(PSOChar(AsString), PSOChar(obj.AsString)));
else
Result := cpError;
end;
stCurrency:
case ObjectGetType(obj) of
stBoolean: Result := GetDblCompResult(FO.c_currency - ord(obj.AsBoolean));
stDouble: Result := GetDblCompResult(FO.c_currency - obj.AsDouble);
stCurrency:Result := GetDblCompResult(FO.c_currency - obj.AsCurrency);
stInt: Result := GetDblCompResult(FO.c_currency - obj.AsInteger);
stString: Result := GetIntCompResult(StrComp(PSOChar(AsString), PSOChar(obj.AsString)));
else
Result := cpError;
end;
stInt:
case ObjectGetType(obj) of
stBoolean: Result := GetIntCompResult(FO.c_int - ord(obj.AsBoolean));
stDouble: Result := GetDblCompResult(FO.c_int - obj.AsDouble);
stCurrency:Result := GetDblCompResult(FO.c_int - obj.AsCurrency);
stInt: Result := GetIntCompResult(FO.c_int - obj.AsInteger);
stString: Result := GetIntCompResult(StrComp(PSOChar(AsString), PSOChar(obj.AsString)));
else
Result := cpError;
end;
stString:
case ObjectGetType(obj) of
stBoolean,
stDouble,
stCurrency,
stInt,
stString: Result := GetIntCompResult(StrComp(PSOChar(AsString), PSOChar(obj.AsString)));
else
Result := cpError;
end;
else
Result := cpError;
end;
end;
{$IFDEF SUPER_METHOD}
function TSuperObject.AsMethod: TSuperMethod;
begin
if FDataType = stMethod then
Result := FO.c_method else
Result := nil;
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
constructor TSuperObject.Create(m: TSuperMethod);
begin
Create(stMethod);
FO.c_method := m;
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
function TSuperObject.GetM(const path: SOString): TSuperMethod;
var
v: ISuperObject;
begin
v := ParseString(PSOChar(path), False, True, Self);
if (v <> nil) and (ObjectGetType(v) = stMethod) then
Result := v.AsMethod else
Result := nil;
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
procedure TSuperObject.PutM(const path: SOString; Value: TSuperMethod);
begin
ParseString(PSOChar(path), False, True, Self, [foCreatePath, foPutValue], TSuperObject.Create(Value));
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
function TSuperObject.call(const path: SOString; const param: ISuperObject): ISuperObject;
begin
Result := ParseString(PSOChar(path), False, True, Self, [foCallMethod], param);
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
function TSuperObject.call(const path, param: SOString): ISuperObject;
begin
Result := ParseString(PSOChar(path), False, True, Self, [foCallMethod], TSuperObject.ParseString(PSOChar(param), False));
end;
{$ENDIF}
function TSuperObject.GetProcessing: boolean;
begin
Result := FProcessing;
end;
procedure TSuperObject.SetDataPtr(const Value: Pointer);
begin
FDataPtr := Value;
end;
procedure TSuperObject.SetProcessing(value: boolean);
begin
FProcessing := value;
end;
{ TSuperArray }
function TSuperArray.Add(const Data: ISuperObject): Integer;
begin
Result := FLength;
PutO(Result, data);
end;
function TSuperArray.Add(Data: SuperInt): Integer;
begin
Result := Add(TSuperObject.Create(Data));
end;
function TSuperArray.Add(const Data: SOString): Integer;
begin
Result := Add(TSuperObject.Create(Data));
end;
function TSuperArray.Add(Data: Boolean): Integer;
begin
Result := Add(TSuperObject.Create(Data));
end;
function TSuperArray.Add(Data: Double): Integer;
begin
Result := Add(TSuperObject.Create(Data));
end;
function TSuperArray.AddC(const Data: Currency): Integer;
begin
Result := Add(TSuperObject.CreateCurrency(Data));
end;
function TSuperArray.Delete(index: Integer): ISuperObject;
begin
if (Index >= 0) and (Index < FLength) then
begin
Result := FArray^[index];
FArray^[index] := nil;
Dec(FLength);
if Index < FLength then
begin
Move(FArray^[index + 1], FArray^[index],
(FLength - index) * SizeOf(Pointer));
Pointer(FArray^[FLength]) := nil;
end;
end;
end;
procedure TSuperArray.Insert(index: Integer; const value: ISuperObject);
begin
if (Index >= 0) then
if (index < FLength) then
begin
if FLength = FSize then
Expand(index);
if Index < FLength then
Move(FArray^[index], FArray^[index + 1],
(FLength - index) * SizeOf(Pointer));
Pointer(FArray^[index]) := nil;
FArray^[index] := value;
Inc(FLength);
end else
PutO(index, value);
end;
procedure TSuperArray.Clear(all: boolean);
var
j: Integer;
begin
for j := 0 to FLength - 1 do
if FArray^[j] <> nil then
begin
if all then
FArray^[j].Clear(all);
FArray^[j] := nil;
end;
FLength := 0;
end;
procedure TSuperArray.Pack(all: boolean);
var
PackedCount, StartIndex, EndIndex, j: Integer;
begin
if FLength > 0 then
begin
PackedCount := 0;
StartIndex := 0;
repeat
while (StartIndex < FLength) and (FArray^[StartIndex] = nil) do
Inc(StartIndex);
if StartIndex < FLength then
begin
EndIndex := StartIndex;
while (EndIndex < FLength) and (FArray^[EndIndex] <> nil) do
Inc(EndIndex);
Dec(EndIndex);
if StartIndex > PackedCount then
Move(FArray^[StartIndex], FArray^[PackedCount], (EndIndex - StartIndex + 1) * SizeOf(Pointer));
Inc(PackedCount, EndIndex - StartIndex + 1);
StartIndex := EndIndex + 1;
end;
until StartIndex >= FLength;
FillChar(FArray^[PackedCount], (FLength - PackedCount) * sizeof(Pointer), 0);
FLength := PackedCount;
if all then
for j := 0 to FLength - 1 do
FArray^[j].Pack(all);
end;
end;
constructor TSuperArray.Create;
begin
inherited Create;
FSize := SUPER_ARRAY_LIST_DEFAULT_SIZE;
FLength := 0;
GetMem(FArray, sizeof(Pointer) * FSize);
FillChar(FArray^, sizeof(Pointer) * FSize, 0);
end;
destructor TSuperArray.Destroy;
begin
Clear;
FreeMem(FArray);
inherited;
end;
procedure TSuperArray.Expand(max: Integer);
var
new_size: Integer;
begin
if (max < FSize) then
Exit;
if max < (FSize shl 1) then
new_size := (FSize shl 1) else
new_size := max + 1;
ReallocMem(FArray, new_size * sizeof(Pointer));
FillChar(FArray^[FSize], (new_size - FSize) * sizeof(Pointer), 0);
FSize := new_size;
end;
function TSuperArray.GetO(const index: Integer): ISuperObject;
begin
if(index >= FLength) then
Result := nil else
Result := FArray^[index];
end;
function TSuperArray.GetB(const index: integer): Boolean;
var
obj: ISuperObject;
begin
obj := GetO(index);
if obj <> nil then
Result := obj.AsBoolean else
Result := false;
end;
function TSuperArray.GetD(const index: integer): Double;
var
obj: ISuperObject;
begin
obj := GetO(index);
if obj <> nil then
Result := obj.AsDouble else
Result := 0.0;
end;
function TSuperArray.GetI(const index: integer): SuperInt;
var
obj: ISuperObject;
begin
obj := GetO(index);
if obj <> nil then
Result := obj.AsInteger else
Result := 0;
end;
function TSuperArray.GetS(const index: integer): SOString;
var
obj: ISuperObject;
begin
obj := GetO(index);
if obj <> nil then
Result := obj.AsString else
Result := '';
end;
procedure TSuperArray.PutO(const index: Integer; const Value: ISuperObject);
begin
Expand(index);
FArray^[index] := value;
if(FLength <= index) then FLength := index + 1;
end;
function TSuperArray.GetN(const index: integer): ISuperObject;
begin
Result := GetO(index);
if Result = nil then
Result := TSuperObject.Create(stNull);
end;
procedure TSuperArray.PutN(const index: integer; const Value: ISuperObject);
begin
if Value <> nil then
PutO(index, Value) else
PutO(index, TSuperObject.Create(stNull));
end;
procedure TSuperArray.PutB(const index: integer; Value: Boolean);
begin
PutO(index, TSuperObject.Create(Value));
end;
procedure TSuperArray.PutD(const index: integer; Value: Double);
begin
PutO(index, TSuperObject.Create(Value));
end;
function TSuperArray.GetC(const index: integer): Currency;
var
obj: ISuperObject;
begin
obj := GetO(index);
if obj <> nil then
Result := obj.AsCurrency else
Result := 0.0;
end;
procedure TSuperArray.PutC(const index: integer; Value: Currency);
begin
PutO(index, TSuperObject.CreateCurrency(Value));
end;
procedure TSuperArray.PutI(const index: integer; Value: SuperInt);
begin
PutO(index, TSuperObject.Create(Value));
end;
procedure TSuperArray.PutS(const index: integer; const Value: SOString);
begin
PutO(index, TSuperObject.Create(Value));
end;
{$IFDEF SUPER_METHOD}
function TSuperArray.GetM(const index: integer): TSuperMethod;
var
v: ISuperObject;
begin
v := GetO(index);
if (ObjectGetType(v) = stMethod) then
Result := v.AsMethod else
Result := nil;
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
procedure TSuperArray.PutM(const index: integer; Value: TSuperMethod);
begin
PutO(index, TSuperObject.Create(Value));
end;
{$ENDIF}
{ TSuperWriterString }
function TSuperWriterString.Append(buf: PSOChar; Size: Integer): Integer;
function max(a, b: Integer): integer; begin if a > b then Result := a else Result := b end;
begin
Result := size;
if Size > 0 then
begin
if (FSize - FBPos <= size) then
begin
FSize := max(FSize * 2, FBPos + size + 8);
ReallocMem(FBuf, FSize * SizeOf(SOChar));
end;
// fast move
case size of
1: FBuf[FBPos] := buf^;
2: PInteger(@FBuf[FBPos])^ := PInteger(buf)^;
4: PInt64(@FBuf[FBPos])^ := PInt64(buf)^;
else
move(buf^, FBuf[FBPos], size * SizeOf(SOChar));
end;
inc(FBPos, size);
FBuf[FBPos] := #0;
end;
end;
function TSuperWriterString.Append(buf: PSOChar): Integer;
begin
Result := Append(buf, strlen(buf));
end;
constructor TSuperWriterString.Create;
begin
inherited;
FSize := 32;
FBPos := 0;
GetMem(FBuf, FSize * SizeOf(SOChar));
end;
destructor TSuperWriterString.Destroy;
begin
inherited;
if FBuf <> nil then
FreeMem(FBuf)
end;
function TSuperWriterString.GetString: SOString;
begin
SetString(Result, FBuf, FBPos);
end;
procedure TSuperWriterString.Reset;
begin
FBuf[0] := #0;
FBPos := 0;
end;
procedure TSuperWriterString.TrimRight;
begin
while (FBPos > 0) and (FBuf[FBPos-1] < #256) and (AnsiChar(FBuf[FBPos-1]) in [#32, #13, #10]) do
begin
dec(FBPos);
FBuf[FBPos] := #0;
end;
end;
{ TSuperWriterStream }
function TSuperWriterStream.Append(buf: PSOChar): Integer;
begin
Result := Append(buf, StrLen(buf));
end;
constructor TSuperWriterStream.Create(AStream: TStream);
begin
inherited Create;
FStream := AStream;
end;
procedure TSuperWriterStream.Reset;
begin
FStream.Size := 0;
end;
{ TSuperWriterStream }
function TSuperAnsiWriterStream.Append(buf: PSOChar; Size: Integer): Integer;
var
Buffer: array[0..1023] of AnsiChar;
pBuffer: PAnsiChar;
i: Integer;
begin
if Size = 1 then
Result := FStream.Write(buf^, Size) else
begin
if Size > SizeOf(Buffer) then
GetMem(pBuffer, Size) else
pBuffer := @Buffer;
try
for i := 0 to Size - 1 do
pBuffer[i] := AnsiChar(buf[i]);
Result := FStream.Write(pBuffer^, Size);
finally
if pBuffer <> @Buffer then
FreeMem(pBuffer);
end;
end;
end;
{ TSuperUnicodeWriterStream }
function TSuperUnicodeWriterStream.Append(buf: PSOChar; Size: Integer): Integer;
begin
Result := FStream.Write(buf^, Size * 2);
end;
{ TSuperWriterFake }
function TSuperWriterFake.Append(buf: PSOChar; Size: Integer): Integer;
begin
inc(FSize, Size);
Result := FSize;
end;
function TSuperWriterFake.Append(buf: PSOChar): Integer;
begin
inc(FSize, Strlen(buf));
Result := FSize;
end;
constructor TSuperWriterFake.Create;
begin
inherited Create;
FSize := 0;
end;
procedure TSuperWriterFake.Reset;
begin
FSize := 0;
end;
{ TSuperWriterSock }
function TSuperWriterSock.Append(buf: PSOChar; Size: Integer): Integer;
var
Buffer: array[0..1023] of AnsiChar;
pBuffer: PAnsiChar;
i: Integer;
begin
if Size = 1 then
{$IFDEF FPC}
Result := fpsend(FSocket, buf, size, 0) else
{$ELSE}
Result := send(FSocket, buf^, size, 0) else
{$ENDIF}
begin
if Size > SizeOf(Buffer) then
GetMem(pBuffer, Size) else
pBuffer := @Buffer;
try
for i := 0 to Size - 1 do
pBuffer[i] := AnsiChar(buf[i]);
{$IFDEF FPC}
Result := fpsend(FSocket, pBuffer, size, 0);
{$ELSE}
Result := send(FSocket, pBuffer^, size, 0);
{$ENDIF}
finally
if pBuffer <> @Buffer then
FreeMem(pBuffer);
end;
end;
inc(FSize, Result);
end;
function TSuperWriterSock.Append(buf: PSOChar): Integer;
begin
Result := Append(buf, StrLen(buf));
end;
constructor TSuperWriterSock.Create(ASocket: Integer);
begin
inherited Create;
FSocket := ASocket;
FSize := 0;
end;
procedure TSuperWriterSock.Reset;
begin
FSize := 0;
end;
{ TSuperTokenizer }
constructor TSuperTokenizer.Create;
begin
pb := TSuperWriterString.Create;
line := 1;
col := 0;
Reset;
end;
destructor TSuperTokenizer.Destroy;
begin
Reset;
pb.Free;
inherited;
end;
procedure TSuperTokenizer.Reset;
var
i: integer;
begin
for i := depth downto 0 do
ResetLevel(i);
depth := 0;
err := teSuccess;
end;
procedure TSuperTokenizer.ResetLevel(adepth: integer);
begin
stack[adepth].state := tsEatws;
stack[adepth].saved_state := tsStart;
stack[adepth].current := nil;
stack[adepth].field_name := '';
stack[adepth].obj := nil;
stack[adepth].parent := nil;
stack[adepth].gparent := nil;
end;
{ TSuperAvlTree }
constructor TSuperAvlTree.Create;
begin
FRoot := nil;
FCount := 0;
end;
destructor TSuperAvlTree.Destroy;
begin
Clear;
inherited;
end;
function TSuperAvlTree.IsEmpty: boolean;
begin
result := FRoot = nil;
end;
function TSuperAvlTree.balance(bal: TSuperAvlEntry): TSuperAvlEntry;
var
deep, old: TSuperAvlEntry;
bf: integer;
begin
if (bal.FBf > 0) then
begin
deep := bal.FGt;
if (deep.FBf < 0) then
begin
old := bal;
bal := deep.FLt;
old.FGt := bal.FLt;
deep.FLt := bal.FGt;
bal.FLt := old;
bal.FGt := deep;
bf := bal.FBf;
if (bf <> 0) then
begin
if (bf > 0) then
begin
old.FBf := -1;
deep.FBf := 0;
end else
begin
deep.FBf := 1;
old.FBf := 0;
end;
bal.FBf := 0;
end else
begin
old.FBf := 0;
deep.FBf := 0;
end;
end else
begin
bal.FGt := deep.FLt;
deep.FLt := bal;
if (deep.FBf = 0) then
begin
deep.FBf := -1;
bal.FBf := 1;
end else
begin
deep.FBf := 0;
bal.FBf := 0;
end;
bal := deep;
end;
end else
begin
(* "Less than" subtree is deeper. *)
deep := bal.FLt;
if (deep.FBf > 0) then
begin
old := bal;
bal := deep.FGt;
old.FLt := bal.FGt;
deep.FGt := bal.FLt;
bal.FGt := old;
bal.FLt := deep;
bf := bal.FBf;
if (bf <> 0) then
begin
if (bf < 0) then
begin
old.FBf := 1;
deep.FBf := 0;
end else
begin
deep.FBf := -1;
old.FBf := 0;
end;
bal.FBf := 0;
end else
begin
old.FBf := 0;
deep.FBf := 0;
end;
end else
begin
bal.FLt := deep.FGt;
deep.FGt := bal;
if (deep.FBf = 0) then
begin
deep.FBf := 1;
bal.FBf := -1;
end else
begin
deep.FBf := 0;
bal.FBf := 0;
end;
bal := deep;
end;
end;
Result := bal;
end;
function TSuperAvlTree.Insert(h: TSuperAvlEntry): TSuperAvlEntry;
var
unbal, parentunbal, hh, parent: TSuperAvlEntry;
depth, unbaldepth: longint;
cmp: integer;
unbalbf: integer;
branch: TSuperAvlBitArray;
p: Pointer;
begin
inc(FCount);
h.FLt := nil;
h.FGt := nil;
h.FBf := 0;
branch := [];
if (FRoot = nil) then
FRoot := h
else
begin
unbal := nil;
parentunbal := nil;
depth := 0;
unbaldepth := 0;
hh := FRoot;
parent := nil;
repeat
if (hh.FBf <> 0) then
begin
unbal := hh;
parentunbal := parent;
unbaldepth := depth;
end;
if hh.FHash <> h.FHash then
begin
if hh.FHash < h.FHash then cmp := -1 else
if hh.FHash > h.FHash then cmp := 1 else
cmp := 0;
end else
cmp := CompareNodeNode(h, hh);
if (cmp = 0) then
begin
Result := hh;
//exchange data
p := hh.Ptr;
hh.FPtr := h.Ptr;
h.FPtr := p;
doDeleteEntry(h, false);
dec(FCount);
exit;
end;
parent := hh;
if (cmp > 0) then
begin
hh := hh.FGt;
include(branch, depth);
end else
begin
hh := hh.FLt;
exclude(branch, depth);
end;
inc(depth);
until (hh = nil);
if (cmp < 0) then
parent.FLt := h else
parent.FGt := h;
depth := unbaldepth;
if (unbal = nil) then
hh := FRoot
else
begin
if depth in branch then
cmp := 1 else
cmp := -1;
inc(depth);
unbalbf := unbal.FBf;
if (cmp < 0) then
dec(unbalbf) else
inc(unbalbf);
if cmp < 0 then
hh := unbal.FLt else
hh := unbal.FGt;
if ((unbalbf <> -2) and (unbalbf <> 2)) then
begin
unbal.FBf := unbalbf;
unbal := nil;
end;
end;
if (hh <> nil) then
while (h <> hh) do
begin
if depth in branch then
cmp := 1 else
cmp := -1;
inc(depth);
if (cmp < 0) then
begin
hh.FBf := -1;
hh := hh.FLt;
end else (* cmp > 0 *)
begin
hh.FBf := 1;
hh := hh.FGt;
end;
end;
if (unbal <> nil) then
begin
unbal := balance(unbal);
if (parentunbal = nil) then
FRoot := unbal
else
begin
depth := unbaldepth - 1;
if depth in branch then
cmp := 1 else
cmp := -1;
if (cmp < 0) then
parentunbal.FLt := unbal else
parentunbal.FGt := unbal;
end;
end;
end;
result := h;
end;
function TSuperAvlTree.Search(const k: SOString; st: TSuperAvlSearchTypes): TSuperAvlEntry;
var
cmp, target_cmp: integer;
match_h, h: TSuperAvlEntry;
ha: Cardinal;
begin
ha := TSuperAvlEntry.Hash(k);
match_h := nil;
h := FRoot;
if (stLess in st) then
target_cmp := 1 else
if (stGreater in st) then
target_cmp := -1 else
target_cmp := 0;
while (h <> nil) do
begin
if h.FHash < ha then cmp := -1 else
if h.FHash > ha then cmp := 1 else
cmp := 0;
if cmp = 0 then
cmp := CompareKeyNode(PSOChar(k), h);
if (cmp = 0) then
begin
if (stEqual in st) then
begin
match_h := h;
break;
end;
cmp := -target_cmp;
end
else
if (target_cmp <> 0) then
if ((cmp xor target_cmp) and SUPER_AVL_MASK_HIGH_BIT) = 0 then
match_h := h;
if cmp < 0 then
h := h.FLt else
h := h.FGt;
end;
result := match_h;
end;
function TSuperAvlTree.Delete(const k: SOString): ISuperObject;
var
depth, rm_depth: longint;
branch: TSuperAvlBitArray;
h, parent, child, path, rm, parent_rm: TSuperAvlEntry;
cmp, cmp_shortened_sub_with_path, reduced_depth, bf: integer;
ha: Cardinal;
begin
ha := TSuperAvlEntry.Hash(k);
cmp_shortened_sub_with_path := 0;
branch := [];
depth := 0;
h := FRoot;
parent := nil;
while true do
begin
if (h = nil) then
exit;
if h.FHash < ha then cmp := -1 else
if h.FHash > ha then cmp := 1 else
cmp := 0;
if cmp = 0 then
cmp := CompareKeyNode(k, h);
if (cmp = 0) then
break;
parent := h;
if (cmp > 0) then
begin
h := h.FGt;
include(branch, depth)
end else
begin
h := h.FLt;
exclude(branch, depth)
end;
inc(depth);
cmp_shortened_sub_with_path := cmp;
end;
rm := h;
parent_rm := parent;
rm_depth := depth;
if (h.FBf < 0) then
begin
child := h.FLt;
exclude(branch, depth);
cmp := -1;
end else
begin
child := h.FGt;
include(branch, depth);
cmp := 1;
end;
inc(depth);
if (child <> nil) then
begin
cmp := -cmp;
repeat
parent := h;
h := child;
if (cmp < 0) then
begin
child := h.FLt;
exclude(branch, depth);
end else
begin
child := h.FGt;
include(branch, depth);
end;
inc(depth);
until (child = nil);
if (parent = rm) then
cmp_shortened_sub_with_path := -cmp else
cmp_shortened_sub_with_path := cmp;
if cmp > 0 then
child := h.FLt else
child := h.FGt;
end;
if (parent = nil) then
FRoot := child else
if (cmp_shortened_sub_with_path < 0) then
parent.FLt := child else
parent.FGt := child;
if parent = rm then
path := h else
path := parent;
if (h <> rm) then
begin
h.FLt := rm.FLt;
h.FGt := rm.FGt;
h.FBf := rm.FBf;
if (parent_rm = nil) then
FRoot := h
else
begin
depth := rm_depth - 1;
if (depth in branch) then
parent_rm.FGt := h else
parent_rm.FLt := h;
end;
end;
if (path <> nil) then
begin
h := FRoot;
parent := nil;
depth := 0;
while (h <> path) do
begin
if (depth in branch) then
begin
child := h.FGt;
h.FGt := parent;
end else
begin
child := h.FLt;
h.FLt := parent;
end;
inc(depth);
parent := h;
h := child;
end;
reduced_depth := 1;
cmp := cmp_shortened_sub_with_path;
while true do
begin
if (reduced_depth <> 0) then
begin
bf := h.FBf;
if (cmp < 0) then
inc(bf) else
dec(bf);
if ((bf = -2) or (bf = 2)) then
begin
h := balance(h);
bf := h.FBf;
end else
h.FBf := bf;
reduced_depth := integer(bf = 0);
end;
if (parent = nil) then
break;
child := h;
h := parent;
dec(depth);
if depth in branch then
cmp := 1 else
cmp := -1;
if (cmp < 0) then
begin
parent := h.FLt;
h.FLt := child;
end else
begin
parent := h.FGt;
h.FGt := child;
end;
end;
FRoot := h;
end;
if rm <> nil then
begin
Result := rm.GetValue;
doDeleteEntry(rm, false);
dec(FCount);
end;
end;
procedure TSuperAvlTree.Pack(all: boolean);
var
node1, node2: TSuperAvlEntry;
list: TList;
i: Integer;
begin
node1 := FRoot;
list := TList.Create;
while node1 <> nil do
begin
if (node1.FLt = nil) then
begin
node2 := node1.FGt;
if (node1.FPtr = nil) then
list.Add(node1) else
if all then
node1.Value.Pack(all);
end
else
begin
node2 := node1.FLt;
node1.FLt := node2.FGt;
node2.FGt := node1;
end;
node1 := node2;
end;
for i := 0 to list.Count - 1 do
Delete(TSuperAvlEntry(list[i]).FName);
list.Free;
end;
procedure TSuperAvlTree.Clear(all: boolean);
var
node1, node2: TSuperAvlEntry;
begin
node1 := FRoot;
while node1 <> nil do
begin
if (node1.FLt = nil) then
begin
node2 := node1.FGt;
doDeleteEntry(node1, all);
end
else
begin
node2 := node1.FLt;
node1.FLt := node2.FGt;
node2.FGt := node1;
end;
node1 := node2;
end;
FRoot := nil;
FCount := 0;
end;
function TSuperAvlTree.CompareKeyNode(const k: SOString; h: TSuperAvlEntry): integer;
begin
Result := StrComp(PSOChar(k), PSOChar(h.FName));
end;
function TSuperAvlTree.CompareNodeNode(node1, node2: TSuperAvlEntry): integer;
begin
Result := StrComp(PSOChar(node1.FName), PSOChar(node2.FName));
end;
{ TSuperAvlIterator }
(* Initialize depth to invalid value, to indicate iterator is
** invalid. (Depth is zero-base.) It's not necessary to initialize
** iterators prior to passing them to the "start" function.
*)
constructor TSuperAvlIterator.Create(tree: TSuperAvlTree);
begin
FDepth := not 0;
FTree := tree;
end;
procedure TSuperAvlIterator.Search(const k: SOString; st: TSuperAvlSearchTypes);
var
h: TSuperAvlEntry;
d: longint;
cmp, target_cmp: integer;
ha: Cardinal;
begin
ha := TSuperAvlEntry.Hash(k);
h := FTree.FRoot;
d := 0;
FDepth := not 0;
if (h = nil) then
exit;
if (stLess in st) then
target_cmp := 1 else
if (stGreater in st) then
target_cmp := -1 else
target_cmp := 0;
while true do
begin
if h.FHash < ha then cmp := -1 else
if h.FHash > ha then cmp := 1 else
cmp := 0;
if cmp = 0 then
cmp := FTree.CompareKeyNode(k, h);
if (cmp = 0) then
begin
if (stEqual in st) then
begin
FDepth := d;
break;
end;
cmp := -target_cmp;
end
else
if (target_cmp <> 0) then
if ((cmp xor target_cmp) and SUPER_AVL_MASK_HIGH_BIT) = 0 then
FDepth := d;
if cmp < 0 then
h := h.FLt else
h := h.FGt;
if (h = nil) then
break;
if (cmp > 0) then
include(FBranch, d) else
exclude(FBranch, d);
FPath[d] := h;
inc(d);
end;
end;
procedure TSuperAvlIterator.First;
var
h: TSuperAvlEntry;
begin
h := FTree.FRoot;
FDepth := not 0;
FBranch := [];
while (h <> nil) do
begin
if (FDepth <> not 0) then
FPath[FDepth] := h;
inc(FDepth);
h := h.FLt;
end;
end;
procedure TSuperAvlIterator.Last;
var
h: TSuperAvlEntry;
begin
h := FTree.FRoot;
FDepth := not 0;
FBranch := [0..SUPER_AVL_MAX_DEPTH - 1];
while (h <> nil) do
begin
if (FDepth <> not 0) then
FPath[FDepth] := h;
inc(FDepth);
h := h.FGt;
end;
end;
function TSuperAvlIterator.MoveNext: boolean;
begin
if FDepth = not 0 then
First else
Next;
Result := GetIter <> nil;
end;
function TSuperAvlIterator.GetIter: TSuperAvlEntry;
begin
if (FDepth = not 0) then
begin
result := nil;
exit;
end;
if FDepth = 0 then
Result := FTree.FRoot else
Result := FPath[FDepth - 1];
end;
procedure TSuperAvlIterator.Next;
var
h: TSuperAvlEntry;
begin
if (FDepth <> not 0) then
begin
if FDepth = 0 then
h := FTree.FRoot.FGt else
h := FPath[FDepth - 1].FGt;
if (h = nil) then
repeat
if (FDepth = 0) then
begin
FDepth := not 0;
break;
end;
dec(FDepth);
until (not (FDepth in FBranch))
else
begin
include(FBranch, FDepth);
FPath[FDepth] := h;
inc(FDepth);
while true do
begin
h := h.FLt;
if (h = nil) then
break;
exclude(FBranch, FDepth);
FPath[FDepth] := h;
inc(FDepth);
end;
end;
end;
end;
procedure TSuperAvlIterator.Prior;
var
h: TSuperAvlEntry;
begin
if (FDepth <> not 0) then
begin
if FDepth = 0 then
h := FTree.FRoot.FLt else
h := FPath[FDepth - 1].FLt;
if (h = nil) then
repeat
if (FDepth = 0) then
begin
FDepth := not 0;
break;
end;
dec(FDepth);
until (FDepth in FBranch)
else
begin
exclude(FBranch, FDepth);
FPath[FDepth] := h;
inc(FDepth);
while true do
begin
h := h.FGt;
if (h = nil) then
break;
include(FBranch, FDepth);
FPath[FDepth] := h;
inc(FDepth);
end;
end;
end;
end;
procedure TSuperAvlTree.doDeleteEntry(Entry: TSuperAvlEntry; all: boolean);
begin
Entry.Free;
end;
function TSuperAvlTree.GetEnumerator: TSuperAvlIterator;
begin
Result := TSuperAvlIterator.Create(Self);
end;
{ TSuperAvlEntry }
constructor TSuperAvlEntry.Create(const AName: SOString; Obj: Pointer);
begin
FName := AName;
FPtr := Obj;
FHash := Hash(FName);
end;
function TSuperAvlEntry.GetValue: ISuperObject;
begin
Result := ISuperObject(FPtr)
end;
class function TSuperAvlEntry.Hash(const k: SOString): Cardinal;
var
h: cardinal;
i: Integer;
begin
h := 0;
for i := 1 to Length(k) do
h := h*129 + ord(k[i]) + $9e370001;
Result := h;
end;
procedure TSuperAvlEntry.SetValue(const val: ISuperObject);
begin
ISuperObject(FPtr) := val;
end;
{ TSuperTableString }
function TSuperTableString.GetValues: ISuperObject;
var
ite: TSuperAvlIterator;
obj: TSuperAvlEntry;
begin
Result := TSuperObject.Create(stArray);
ite := TSuperAvlIterator.Create(Self);
try
ite.First;
obj := ite.GetIter;
while obj <> nil do
begin
Result.AsArray.Add(obj.Value);
ite.Next;
obj := ite.GetIter;
end;
finally
ite.Free;
end;
end;
function TSuperTableString.GetNames: ISuperObject;
var
ite: TSuperAvlIterator;
obj: TSuperAvlEntry;
begin
Result := TSuperObject.Create(stArray);
ite := TSuperAvlIterator.Create(Self);
try
ite.First;
obj := ite.GetIter;
while obj <> nil do
begin
Result.AsArray.Add(TSuperObject.Create(obj.FName));
ite.Next;
obj := ite.GetIter;
end;
finally
ite.Free;
end;
end;
procedure TSuperTableString.doDeleteEntry(Entry: TSuperAvlEntry; all: boolean);
begin
if Entry.Ptr <> nil then
begin
if all then Entry.Value.Clear(true);
Entry.Value := nil;
end;
inherited;
end;
function TSuperTableString.Find(const k: SOString; var value: ISuperObject): Boolean;
var
e: TSuperAvlEntry;
begin
e := Search(k);
if e <> nil then
begin
value := e.Value;
Result := True;
end else
Result := False;
end;
function TSuperTableString.Exists(const k: SOString): Boolean;
begin
Result := Search(k) <> nil;
end;
function TSuperTableString.GetO(const k: SOString): ISuperObject;
var
e: TSuperAvlEntry;
begin
e := Search(k);
if e <> nil then
Result := e.Value else
Result := nil
end;
procedure TSuperTableString.PutO(const k: SOString; const value: ISuperObject);
var
entry: TSuperAvlEntry;
begin
entry := Insert(TSuperAvlEntry.Create(k, Pointer(value)));
if entry.FPtr <> nil then
ISuperObject(entry.FPtr)._AddRef;
end;
procedure TSuperTableString.PutS(const k: SOString; const value: SOString);
begin
PutO(k, TSuperObject.Create(Value));
end;
function TSuperTableString.GetS(const k: SOString): SOString;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj.AsString else
Result := '';
end;
procedure TSuperTableString.PutI(const k: SOString; value: SuperInt);
begin
PutO(k, TSuperObject.Create(Value));
end;
function TSuperTableString.GetI(const k: SOString): SuperInt;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj.AsInteger else
Result := 0;
end;
procedure TSuperTableString.PutD(const k: SOString; value: Double);
begin
PutO(k, TSuperObject.Create(Value));
end;
procedure TSuperTableString.PutC(const k: SOString; value: Currency);
begin
PutO(k, TSuperObject.CreateCurrency(Value));
end;
function TSuperTableString.GetC(const k: SOString): Currency;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj.AsCurrency else
Result := 0.0;
end;
function TSuperTableString.GetD(const k: SOString): Double;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj.AsDouble else
Result := 0.0;
end;
procedure TSuperTableString.PutB(const k: SOString; value: Boolean);
begin
PutO(k, TSuperObject.Create(Value));
end;
function TSuperTableString.GetB(const k: SOString): Boolean;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj.AsBoolean else
Result := False;
end;
{$IFDEF SUPER_METHOD}
procedure TSuperTableString.PutM(const k: SOString; value: TSuperMethod);
begin
PutO(k, TSuperObject.Create(Value));
end;
{$ENDIF}
{$IFDEF SUPER_METHOD}
function TSuperTableString.GetM(const k: SOString): TSuperMethod;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj.AsMethod else
Result := nil;
end;
{$ENDIF}
procedure TSuperTableString.PutN(const k: SOString; const value: ISuperObject);
begin
if value <> nil then
PutO(k, TSuperObject.Create(stNull)) else
PutO(k, value);
end;
function TSuperTableString.GetN(const k: SOString): ISuperObject;
var
obj: ISuperObject;
begin
obj := GetO(k);
if obj <> nil then
Result := obj else
Result := TSuperObject.Create(stNull);
end;
{$IFDEF HAVE_RTTI}
{ TSuperAttribute }
constructor TSuperAttribute.Create(const AName: string);
begin
FName := AName;
end;
{ TSuperRttiContext }
constructor TSuperRttiContext.Create;
begin
Context := TRttiContext.Create;
SerialFromJson := TDictionary<PTypeInfo, TSerialFromJson>.Create;
SerialToJson := TDictionary<PTypeInfo, TSerialToJson>.Create;
SerialFromJson.Add(TypeInfo(Boolean), serialfromboolean);
SerialFromJson.Add(TypeInfo(TDateTime), serialfromdatetime);
SerialFromJson.Add(TypeInfo(TGUID), serialfromguid);
SerialToJson.Add(TypeInfo(Boolean), serialtoboolean);
SerialToJson.Add(TypeInfo(TDateTime), serialtodatetime);
SerialToJson.Add(TypeInfo(TGUID), serialtoguid);
end;
destructor TSuperRttiContext.Destroy;
begin
SerialFromJson.Free;
SerialToJson.Free;
Context.Free;
end;
class function TSuperRttiContext.GetFieldName(r: TRttiField): string;
var
o: TCustomAttribute;
begin
for o in r.GetAttributes do
if o is SOName then
Exit(SOName(o).Name);
Result := r.Name;
end;
class function TSuperRttiContext.GetFieldDefault(r: TRttiField; const obj: ISuperObject): ISuperObject;
var
o: TCustomAttribute;
begin
if not ObjectIsType(obj, stNull) then Exit(obj);
for o in r.GetAttributes do
if o is SODefault then
Exit(SO(SODefault(o).Name));
Result := obj;
end;
function TSuperRttiContext.AsType<T>(const obj: ISuperObject): T;
var
ret: TValue;
begin
if FromJson(TypeInfo(T), obj, ret) then
Result := ret.AsType<T> else
raise exception.Create('Marshalling error');
end;
function TSuperRttiContext.AsJson<T>(const obj: T; const index: ISuperObject = nil): ISuperObject;
var
v: TValue;
begin
TValue.Make(@obj, TypeInfo(T), v);
if index <> nil then
Result := ToJson(v, index) else
Result := ToJson(v, so);
end;
function TSuperRttiContext.FromJson(TypeInfo: PTypeInfo; const obj: ISuperObject;
var Value: TValue): Boolean;
procedure FromChar;
begin
if ObjectIsType(obj, stString) and (Length(obj.AsString) = 1) then
begin
Value := string(AnsiString(obj.AsString)[1]);
Result := True;
end else
Result := False;
end;
procedure FromWideChar;
begin
if ObjectIsType(obj, stString) and (Length(obj.AsString) = 1) then
begin
Value := obj.AsString[1];
Result := True;
end else
Result := False;
end;
procedure FromInt64;
var
i: Int64;
begin
case ObjectGetType(obj) of
stInt:
begin
TValue.Make(nil, TypeInfo, Value);
TValueData(Value).FAsSInt64 := obj.AsInteger;
Result := True;
end;
stString:
begin
if TryStrToInt64(obj.AsString, i) then
begin
TValue.Make(nil, TypeInfo, Value);
TValueData(Value).FAsSInt64 := i;
Result := True;
end else
Result := False;
end;
else
Result := False;
end;
end;
procedure FromInt(const obj: ISuperObject);
var
TypeData: PTypeData;
i: Integer;
o: ISuperObject;
begin
case ObjectGetType(obj) of
stInt, stBoolean:
begin
i := obj.AsInteger;
TypeData := GetTypeData(TypeInfo);
if TypeData.MaxValue > TypeData.MinValue then
Result := (i >= TypeData.MinValue) and (i <= TypeData.MaxValue) else
Result := (i >= TypeData.MinValue) and (i <= Int64(PCardinal(@TypeData.MaxValue)^));
if Result then
TValue.Make(@i, TypeInfo, Value);
end;
stString:
begin
o := SO(obj.AsString);
if not ObjectIsType(o, stString) then
FromInt(o) else
Result := False;
end;
else
Result := False;
end;
end;
procedure fromSet;
var
i: Integer;
begin
case ObjectGetType(obj) of
stInt:
begin
TValue.Make(nil, TypeInfo, Value);
TValueData(Value).FAsSLong := obj.AsInteger;
Result := True;
end;
stString:
begin
if TryStrToInt(obj.AsString, i) then
begin
TValue.Make(nil, TypeInfo, Value);
TValueData(Value).FAsSLong := i;
Result := True;
end else
Result := False;
end;
else
Result := False;
end;
end;
procedure FromFloat(const obj: ISuperObject);
var
o: ISuperObject;
begin
case ObjectGetType(obj) of
stInt, stDouble, stCurrency:
begin
TValue.Make(nil, TypeInfo, Value);
case GetTypeData(TypeInfo).FloatType of
ftSingle: TValueData(Value).FAsSingle := obj.AsDouble;
ftDouble: TValueData(Value).FAsDouble := obj.AsDouble;
ftExtended: TValueData(Value).FAsExtended := obj.AsDouble;
ftComp: TValueData(Value).FAsSInt64 := obj.AsInteger;
ftCurr: TValueData(Value).FAsCurr := obj.AsCurrency;
end;
Result := True;
end;
stString:
begin
o := SO(obj.AsString);
if not ObjectIsType(o, stString) then
FromFloat(o) else
Result := False;
end
else
Result := False;
end;
end;
procedure FromString;
begin
case ObjectGetType(obj) of
stObject, stArray:
Result := False;
stnull:
begin
Value := '';
Result := True;
end;
else
Value := obj.AsString;
Result := True;
end;
end;
procedure FromClass;
var
f: TRttiField;
v: TValue;
begin
case ObjectGetType(obj) of
stObject:
begin
Result := True;
if Value.Kind <> tkClass then
Value := GetTypeData(TypeInfo).ClassType.Create;
for f in Context.GetType(Value.AsObject.ClassType).GetFields do
if f.FieldType <> nil then
begin
v := TValue.Empty;
Result := FromJson(f.FieldType.Handle, GetFieldDefault(f, obj.AsObject[GetFieldName(f)]), v);
if Result then
f.SetValue(Value.AsObject, v) else
Exit;
end;
end;
stNull:
begin
Value := nil;
Result := True;
end
else
// error
Value := nil;
Result := False;
end;
end;
procedure FromRecord;
var
f: TRttiField;
p: Pointer;
v: TValue;
begin
Result := True;
TValue.Make(nil, TypeInfo, Value);
for f in Context.GetType(TypeInfo).GetFields do
begin
if ObjectIsType(obj, stObject) and (f.FieldType <> nil) then
begin
{$IFDEF VER210}
p := IValueData(TValueData(Value).FHeapData).GetReferenceToRawData;
{$ELSE}
p := TValueData(Value).FValueData.GetReferenceToRawData;
{$ENDIF}
Result := FromJson(f.FieldType.Handle, GetFieldDefault(f, obj.AsObject[GetFieldName(f)]), v);
if Result then
f.SetValue(p, v) else
begin
//Writeln(f.Name);
Exit;
end;
end else
begin
Result := False;
Exit;
end;
end;
end;
procedure FromDynArray;
var
i: Integer;
p: Pointer;
pb: PByte;
val: TValue;
typ: PTypeData;
el: PTypeInfo;
begin
case ObjectGetType(obj) of
stArray:
begin
i := obj.AsArray.Length;
p := nil;
DynArraySetLength(p, TypeInfo, 1, @i);
pb := p;
typ := GetTypeData(TypeInfo);
if typ.elType <> nil then
el := typ.elType^ else
el := typ.elType2^;
Result := True;
for i := 0 to i - 1 do
begin
Result := FromJson(el, obj.AsArray[i], val);
if not Result then
Break;
val.ExtractRawData(pb);
val := TValue.Empty;
Inc(pb, typ.elSize);
end;
if Result then
TValue.MakeWithoutCopy(@p, TypeInfo, Value) else
DynArrayClear(p, TypeInfo);
end;
stNull:
begin
TValue.MakeWithoutCopy(nil, TypeInfo, Value);
Result := True;
end;
else
i := 1;
p := nil;
DynArraySetLength(p, TypeInfo, 1, @i);
pb := p;
typ := GetTypeData(TypeInfo);
if typ.elType <> nil then
el := typ.elType^ else
el := typ.elType2^;
Result := FromJson(el, obj, val);
val.ExtractRawData(pb);
val := TValue.Empty;
if Result then
TValue.MakeWithoutCopy(@p, TypeInfo, Value) else
DynArrayClear(p, TypeInfo);
end;
end;
procedure FromArray;
var
ArrayData: PArrayTypeData;
idx: Integer;
function ProcessDim(dim: Byte; const o: ISuperobject): Boolean;
var
i: Integer;
v: TValue;
a: PTypeData;
begin
if ObjectIsType(o, stArray) and (ArrayData.Dims[dim-1] <> nil) then
begin
a := @GetTypeData(ArrayData.Dims[dim-1]^).ArrayData;
if (a.MaxValue - a.MinValue + 1) <> o.AsArray.Length then
begin
Result := False;
Exit;
end;
Result := True;
if dim = ArrayData.DimCount then
for i := a.MinValue to a.MaxValue do
begin
Result := FromJson(ArrayData.ElType^, o.AsArray[i], v);
if not Result then
Exit;
Value.SetArrayElement(idx, v);
inc(idx);
end
else
for i := a.MinValue to a.MaxValue do
begin
Result := ProcessDim(dim + 1, o.AsArray[i]);
if not Result then
Exit;
end;
end else
Result := False;
end;
var
i: Integer;
v: TValue;
begin
TValue.Make(nil, TypeInfo, Value);
ArrayData := @GetTypeData(TypeInfo).ArrayData;
idx := 0;
if ArrayData.DimCount = 1 then
begin
if ObjectIsType(obj, stArray) and (obj.AsArray.Length = ArrayData.ElCount) then
begin
Result := True;
for i := 0 to ArrayData.ElCount - 1 do
begin
Result := FromJson(ArrayData.ElType^, obj.AsArray[i], v);
if not Result then
Exit;
Value.SetArrayElement(idx, v);
v := TValue.Empty;
inc(idx);
end;
end else
Result := False;
end else
Result := ProcessDim(1, obj);
end;
procedure FromClassRef;
var
r: TRttiType;
begin
if ObjectIsType(obj, stString) then
begin
r := Context.FindType(obj.AsString);
if r <> nil then
begin
Value := TRttiInstanceType(r).MetaclassType;
Result := True;
end else
Result := False;
end else
Result := False;
end;
procedure FromUnknown;
begin
case ObjectGetType(obj) of
stBoolean:
begin
Value := obj.AsBoolean;
Result := True;
end;
stDouble:
begin
Value := obj.AsDouble;
Result := True;
end;
stCurrency:
begin
Value := obj.AsCurrency;
Result := True;
end;
stInt:
begin
Value := obj.AsInteger;
Result := True;
end;
stString:
begin
Value := obj.AsString;
Result := True;
end
else
Value := nil;
Result := False;
end;
end;
procedure FromInterface;
const soguid: TGuid = '{4B86A9E3-E094-4E5A-954A-69048B7B6327}';
var
o: ISuperObject;
begin
if CompareMem(@GetTypeData(TypeInfo).Guid, @soguid, SizeOf(TGUID)) then
begin
if obj <> nil then
TValue.Make(@obj, TypeInfo, Value) else
begin
o := TSuperObject.Create(stNull);
TValue.Make(@o, TypeInfo, Value);
end;
Result := True;
end else
Result := False;
end;
var
Serial: TSerialFromJson;
begin
if TypeInfo <> nil then
begin
if not SerialFromJson.TryGetValue(TypeInfo, Serial) then
case TypeInfo.Kind of
tkChar: FromChar;
tkInt64: FromInt64;
tkEnumeration, tkInteger: FromInt(obj);
tkSet: fromSet;
tkFloat: FromFloat(obj);
tkString, tkLString, tkUString, tkWString: FromString;
tkClass: FromClass;
tkMethod: ;
tkWChar: FromWideChar;
tkRecord: FromRecord;
tkPointer: ;
tkInterface: FromInterface;
tkArray: FromArray;
tkDynArray: FromDynArray;
tkClassRef: FromClassRef;
else
FromUnknown
end else
begin
TValue.Make(nil, TypeInfo, Value);
Result := Serial(Self, obj, Value);
end;
end else
Result := False;
end;
function TSuperRttiContext.ToJson(var value: TValue; const index: ISuperObject): ISuperObject;
procedure ToInt64;
begin
Result := TSuperObject.Create(SuperInt(Value.AsInt64));
end;
procedure ToChar;
begin
Result := TSuperObject.Create(string(Value.AsType<AnsiChar>));
end;
procedure ToInteger;
begin
Result := TSuperObject.Create(TValueData(Value).FAsSLong);
end;
procedure ToFloat;
begin
case Value.TypeData.FloatType of
ftSingle: Result := TSuperObject.Create(TValueData(Value).FAsSingle);
ftDouble: Result := TSuperObject.Create(TValueData(Value).FAsDouble);
ftExtended: Result := TSuperObject.Create(TValueData(Value).FAsExtended);
ftComp: Result := TSuperObject.Create(TValueData(Value).FAsSInt64);
ftCurr: Result := TSuperObject.CreateCurrency(TValueData(Value).FAsCurr);
end;
end;
procedure ToString;
begin
Result := TSuperObject.Create(string(Value.AsType<string>));
end;
procedure ToClass;
var
o: ISuperObject;
f: TRttiField;
v: TValue;
begin
if TValueData(Value).FAsObject <> nil then
begin
o := index[IntToStr(Integer(Value.AsObject))];
if o = nil then
begin
Result := TSuperObject.Create(stObject);
index[IntToStr(Integer(Value.AsObject))] := Result;
for f in Context.GetType(Value.AsObject.ClassType).GetFields do
if f.FieldType <> nil then
begin
v := f.GetValue(Value.AsObject);
Result.AsObject[GetFieldName(f)] := ToJson(v, index);
end
end else
Result := o;
end else
Result := nil;
end;
procedure ToWChar;
begin
Result := TSuperObject.Create(string(Value.AsType<WideChar>));
end;
procedure ToVariant;
begin
Result := SO(Value.AsVariant);
end;
procedure ToRecord;
var
f: TRttiField;
v: TValue;
begin
Result := TSuperObject.Create(stObject);
for f in Context.GetType(Value.TypeInfo).GetFields do
begin
{$IFDEF VER210}
v := f.GetValue(IValueData(TValueData(Value).FHeapData).GetReferenceToRawData);
{$ELSE}
v := f.GetValue(TValueData(Value).FValueData.GetReferenceToRawData);
{$ENDIF}
Result.AsObject[GetFieldName(f)] := ToJson(v, index);
end;
end;
procedure ToArray;
var
idx: Integer;
ArrayData: PArrayTypeData;
procedure ProcessDim(dim: Byte; const o: ISuperObject);
var
dt: PTypeData;
i: Integer;
o2: ISuperObject;
v: TValue;
begin
if ArrayData.Dims[dim-1] = nil then Exit;
dt := GetTypeData(ArrayData.Dims[dim-1]^);
if Dim = ArrayData.DimCount then
for i := dt.MinValue to dt.MaxValue do
begin
v := Value.GetArrayElement(idx);
o.AsArray.Add(toJSon(v, index));
inc(idx);
end
else
for i := dt.MinValue to dt.MaxValue do
begin
o2 := TSuperObject.Create(stArray);
o.AsArray.Add(o2);
ProcessDim(dim + 1, o2);
end;
end;
var
i: Integer;
v: TValue;
begin
Result := TSuperObject.Create(stArray);
ArrayData := @Value.TypeData.ArrayData;
idx := 0;
if ArrayData.DimCount = 1 then
for i := 0 to ArrayData.ElCount - 1 do
begin
v := Value.GetArrayElement(i);
Result.AsArray.Add(toJSon(v, index))
end
else
ProcessDim(1, Result);
end;
procedure ToDynArray;
var
i: Integer;
v: TValue;
begin
Result := TSuperObject.Create(stArray);
for i := 0 to Value.GetArrayLength - 1 do
begin
v := Value.GetArrayElement(i);
Result.AsArray.Add(toJSon(v, index));
end;
end;
procedure ToClassRef;
begin
if TValueData(Value).FAsClass <> nil then
Result := TSuperObject.Create(string(
TValueData(Value).FAsClass.UnitName + '.' +
TValueData(Value).FAsClass.ClassName)) else
Result := nil;
end;
procedure ToInterface;
{$IFNDEF VER210}
var
intf: IInterface;
{$ENDIF}
begin
{$IFDEF VER210}
if TValueData(Value).FHeapData <> nil then
TValueData(Value).FHeapData.QueryInterface(ISuperObject, Result) else
Result := nil;
{$ELSE}
if TValueData(Value).FValueData <> nil then
begin
intf := IInterface(PPointer(TValueData(Value).FValueData.GetReferenceToRawData)^);
if intf <> nil then
intf.QueryInterface(ISuperObject, Result) else
Result := nil;
end else
Result := nil;
{$ENDIF}
end;
var
Serial: TSerialToJson;
begin
if not SerialToJson.TryGetValue(value.TypeInfo, Serial) then
case Value.Kind of
tkInt64: ToInt64;
tkChar: ToChar;
tkSet, tkInteger, tkEnumeration: ToInteger;
tkFloat: ToFloat;
tkString, tkLString, tkUString, tkWString: ToString;
tkClass: ToClass;
tkWChar: ToWChar;
tkVariant: ToVariant;
tkRecord: ToRecord;
tkArray: ToArray;
tkDynArray: ToDynArray;
tkClassRef: ToClassRef;
tkInterface: ToInterface;
else
result := nil;
end else
Result := Serial(Self, value, index);
end;
{ TSuperObjectHelper }
constructor TSuperObjectHelper.FromJson(const obj: ISuperObject; ctx: TSuperRttiContext = nil);
var
v: TValue;
ctxowned: Boolean;
begin
if ctx = nil then
begin
ctx := TSuperRttiContext.Create;
ctxowned := True;
end else
ctxowned := False;
try
v := Self;
if not ctx.FromJson(v.TypeInfo, obj, v) then
raise Exception.Create('Invalid object');
finally
if ctxowned then
ctx.Free;
end;
end;
constructor TSuperObjectHelper.FromJson(const str: string; ctx: TSuperRttiContext = nil);
begin
FromJson(SO(str), ctx);
end;
function TSuperObjectHelper.ToJson(ctx: TSuperRttiContext = nil): ISuperObject;
var
v: TValue;
ctxowned: boolean;
begin
if ctx = nil then
begin
ctx := TSuperRttiContext.Create;
ctxowned := True;
end else
ctxowned := False;
try
v := Self;
Result := ctx.ToJson(v, SO);
finally
if ctxowned then
ctx.Free;
end;
end;
{$ENDIF}
{$IFDEF DEBUG}
initialization
finalization
Assert(debugcount = 0, 'Memory leak');
{$ENDIF}
end.
| 26.74439 | 174 | 0.568985 |
837e19788b9fce778d1e5b4f5da3860b293e5db4 | 6,407 | pas | Pascal | Demos/Camera/Views/CD.View.Camera.pas | jonahzheng/Kastri | d9550b8e09ca16a3eb7bcfe6737eddfd6dce465b | [
"MIT"
]
| null | null | null | Demos/Camera/Views/CD.View.Camera.pas | jonahzheng/Kastri | d9550b8e09ca16a3eb7bcfe6737eddfd6dce465b | [
"MIT"
]
| null | null | null | Demos/Camera/Views/CD.View.Camera.pas | jonahzheng/Kastri | d9550b8e09ca16a3eb7bcfe6737eddfd6dce465b | [
"MIT"
]
| null | null | null | unit CD.View.Camera;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.TabControl, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects,
DW.NativeImage, DW.Camera, DW.Types,
CD.Types;
type
TCameraView = class(TForm)
RootLayout: TLayout;
TabControl: TTabControl;
PreviewTab: TTabItem;
BottomLayout: TLayout;
CaptureTab: TTabItem;
CaptureButtonLayout: TLayout;
PreviewLayout: TLayout;
TopLayout: TLayout;
procedure RootLayoutResized(Sender: TObject);
private
FAcceptImage: TNativeImage;
FCamera: TCamera;
FCancelImage: TNativeImage;
FCameraImage: TNativeImage;
FCameraSwapImage: TNativeImage;
FCaptureImage: TNativeImage;
FImageStream: TMemoryStream;
procedure CameraAuthorizationStatusHandler(Sender: TObject; const AStatus: TAuthorizationStatus);
procedure CameraImageCapturedHandler(Sender: TObject; const AImageStream: TStream);
procedure CameraImageClickHandler(Sender: TObject);
procedure CameraStatusChange(Sender: TObject);
procedure CameraSwapImageClickHandler(Sender: TObject);
procedure CreateAcceptImage;
procedure CreateCamera;
procedure CreateCancelImage;
procedure CreateCameraImage;
procedure CreateCameraSwapImage;
procedure CreateCaptureImage;
procedure EnableButtons(const AEnable: Boolean);
procedure InternalShowPreview;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ShowPreview(const AShow: Boolean);
property Camera: TCamera read FCamera;
property AcceptImage: TNativeImage read FAcceptImage;
property CancelImage: TNativeImage read FCancelImage;
property CaptureImage: TNativeImage read FCaptureImage;
property ImageStream: TMemoryStream read FImageStream;
end;
var
CameraView: TCameraView;
implementation
{$R *.fmx}
uses
FMX.Media,
DW.UIHelper;
{ TCameraView }
constructor TCameraView.Create(AOwner: TComponent);
begin
inherited Create(Application);
FImageStream := TMemoryStream.Create;
CreateAcceptImage;
CreateCancelImage;
CreateCaptureImage;
CreateCameraImage;
CreateCameraSwapImage;
CreateCamera;
RootLayout.Visible := False;
RootLayout.Parent := TFmxObject(AOwner);
end;
destructor TCameraView.Destroy;
begin
FImageStream.Free;
inherited;
end;
procedure TCameraView.RootLayoutResized(Sender: TObject);
begin
TopLayout.Margins.Top := TUIHelper.GetOffsetRect.Top;
end;
procedure TCameraView.CreateAcceptImage;
begin
FAcceptImage := TNativeImage.Create(Self);
FAcceptImage.Height := 64;
FAcceptImage.Width := 64;
FAcceptImage.Align := TAlignLayout.Right;
FAcceptImage.LoadFromResource('AcceptPlainGreen64');
FAcceptImage.Visible := False;
FAcceptImage.Parent := TopLayout;
end;
procedure TCameraView.CreateCancelImage;
begin
FCancelImage := TNativeImage.Create(Self);
FCancelImage.Height := 64;
FCancelImage.Width := 64;
FCancelImage.Align := TAlignLayout.Left;
FCancelImage.LoadFromResource('CancelPlainRed64');
FCancelImage.Parent := TopLayout;
end;
procedure TCameraView.CreateCaptureImage;
begin
FCaptureImage := TNativeImage.Create(Self);
FCaptureImage.Align := TAlignLayout.Contents;
FCaptureImage.Parent := CaptureTab;
end;
procedure TCameraView.CreateCameraImage;
begin
FCameraImage := TNativeImage.Create(Self);
FCameraImage.OnClick := CameraImageClickHandler;
FCameraImage.Height := 64;
FCameraImage.Width := 64;
FCameraImage.Align := TAlignLayout.Center;
FCameraImage.LoadFromResource('CameraPlainBlue64');
FCameraImage.Parent := CaptureButtonLayout;
end;
procedure TCameraView.CreateCameraSwapImage;
begin
FCameraSwapImage := TNativeImage.Create(Self);
FCameraSwapImage.OnClick := CameraSwapImageClickHandler;
FCameraSwapImage.Height := 64;
FCameraSwapImage.Width := 64;
FCameraSwapImage.Margins.Right := 4;
FCameraSwapImage.Align := TAlignLayout.Right;
FCameraSwapImage.LoadFromResource('CameraSwapPlainPurple64');
FCameraSwapImage.Parent := BottomLayout;
end;
procedure TCameraView.CreateCamera;
begin
FCamera := TCamera.Create;
FCamera.CameraPosition := TDevicePosition.Back;
FCamera.OnImageCaptured := CameraImageCapturedHandler;
FCamera.OnAuthorizationStatus := CameraAuthorizationStatusHandler;
FCamera.OnStatusChange := CameraStatusChange;
FCamera.PreviewControl.Parent := PreviewLayout;
end;
procedure TCameraView.CameraImageClickHandler(Sender: TObject);
begin
if not FAcceptImage.Visible then
begin
EnableButtons(False);
FCamera.CaptureImage;
end
else
ShowPreview(True);
end;
procedure TCameraView.CameraAuthorizationStatusHandler(Sender: TObject; const AStatus: TAuthorizationStatus);
begin
if AStatus = TAuthorizationStatus.Authorized then
InternalShowPreview;
end;
procedure TCameraView.CameraImageCapturedHandler(Sender: TObject; const AImageStream: TStream);
begin
FImageStream.Clear;
FImageStream.CopyFrom(AImageStream);
FCaptureImage.LoadFromStream(FImageStream);
TabControl.ActiveTab := CaptureTab;
EnableButtons(True);
FAcceptImage.Visible := True;
FCameraSwapImage.Visible := False;
end;
procedure TCameraView.CameraStatusChange(Sender: TObject);
begin
//
end;
procedure TCameraView.CameraSwapImageClickHandler(Sender: TObject);
begin
if FCamera.CameraPosition = TDevicePosition.Front then
FCamera.CameraPosition := TDevicePosition.Back
else
FCamera.CameraPosition := TDevicePosition.Front;
end;
procedure TCameraView.EnableButtons(const AEnable: Boolean);
begin
FCameraImage.Enabled := AEnable;
FCameraSwapImage.Enabled := AEnable;
FCancelImage.Enabled := AEnable;
end;
procedure TCameraView.ShowPreview(const AShow: Boolean);
begin
if AShow then
FCamera.RequestPermission
else
begin
RootLayout.Visible := False;
FCamera.IsActive := False;
end;
end;
procedure TCameraView.InternalShowPreview;
begin
FAcceptImage.Visible := False;
TabControl.ActiveTab := PreviewTab;
FCameraSwapImage.Visible := True;
RootLayout.Visible := True;
FCamera.IsActive := True;
end;
end.
| 28.86036 | 148 | 0.753395 |
c376134ef6e1d28a84c3454e2c6c70ccf7524829 | 12,931 | pas | Pascal | source/cpp.utils.pas | atkins126/Delphi-OpenCV-Class | 6c788c24687155e1d9a895ca661d94de84dbb0d0 | [
"Apache-2.0"
]
| 20 | 2021-10-30T22:27:54.000Z | 2022-03-29T16:10:18.000Z | source/cpp.utils.pas | atkins126/Delphi-OpenCV-Class | 6c788c24687155e1d9a895ca661d94de84dbb0d0 | [
"Apache-2.0"
]
| 9 | 2021-11-23T15:00:46.000Z | 2022-03-31T10:25:42.000Z | source/cpp.utils.pas | atkins126/Delphi-OpenCV-Class | 6c788c24687155e1d9a895ca661d94de84dbb0d0 | [
"Apache-2.0"
]
| 5 | 2021-11-06T00:03:13.000Z | 2022-03-04T16:21:24.000Z | (*
This file is part of Delphi-OpenCV-Class project.
https://github.com/Laex/Delphi-OpenCV-Class
It is subject to the license terms in the LICENSE file found in the top-level directory
of this distribution and at https://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2021, Laentir Valetov, laex@bk.ru
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 cpp.utils;
{$I opt.inc}
interface
Uses
System.SysUtils,
System.Math,
System.Generics.Collections
{$IFDEF USE_TYPEINFO}
, System.TypInfo
{$ENDIF}
;
{$I core/version.inc}
const
INT_MIN = Pred(-MaxInt);
INT_MAX = MaxInt;
DBL_MAX = MaxDouble;
CHAR_BIT = 8;
SCHAR_MIN = (-128);
SCHAR_MAX = 127;
UCHAR_MAX = $ff;
Type
BOOL = ByteBool;
TVectorType = //
( //
{$I vectortype.inc}
);
pVector = type Pointer;
Vector<T> = record
private
{$HINTS OFF}
// release 24
// Data: array [0 .. 24 - 1] of Byte;
A: UInt64;
B: UInt64;
C: UInt64;
{$IFDEF DEBUG}
// debug 32
// Data: array [0 .. 32 - 1] of Byte;
D: UInt64;
{$ENDIF}
{$HINTS ON}
class function vt: TVectorType; static;
function GetItems(const index: UInt64): T;
procedure setItems(const index: UInt64; const Value: T);
public
class operator Initialize(out Dest: Vector<T>);
class operator Finalize(var Dest: Vector<T>);
class operator assign(var Dest: Vector<T>; const [ref] Src: Vector<T>);
class function Vector: Vector<T>; static; {$IFDEF USE_INLINE}inline; {$ENDIF}
function size: { UInt64 } Int64; {$IFDEF USE_INLINE}inline; {$ENDIF}
function empty: BOOL; {$IFDEF USE_INLINE}inline; {$ENDIF}
procedure push_back(const Value: T); {$IFDEF USE_INLINE}inline; {$ENDIF}
procedure resize(const NewSize: UInt64); {$IFDEF USE_INLINE}inline; {$ENDIF}
procedure clear(); {$IFDEF USE_INLINE}inline; {$ENDIF}
//
function pT(const index: UInt64): Pointer; {$IFDEF USE_INLINE}inline; {$ENDIF}
property v[const index: UInt64]: T read GetItems write setItems; default;
class operator Implicit(const A: TArray<T>): Vector<T>; {$IFDEF USE_INLINE}inline; {$ENDIF}
class operator Implicit(const size: integer): Vector<T>; {$IFDEF USE_INLINE}inline; {$ENDIF}
class function noVector: Vector<T>; static; {$IFDEF USE_INLINE}inline; {$ENDIF}
end;
pCppString = ^CppString;
CppString = record
private
{$HINTS OFF}
Dummy: array [0 .. 39] of Byte;
{$HINTS ON}
public
class operator Initialize(out Dest: CppString);
class operator Finalize(var Dest: CppString);
function length: UInt64; {$IFDEF USE_INLINE}inline; {$ENDIF}
function size: UInt64; {$IFDEF USE_INLINE}inline; {$ENDIF}
procedure erase(const _Off: UInt64 = 0); {$IFDEF USE_INLINE}inline; {$ENDIF}
procedure assign(const p: pAnsiChar); {$IFDEF USE_INLINE}inline; {$ENDIF}
class operator assign(var Dest: CppString; const [ref] Src: CppString);
class operator Implicit(const p: pAnsiChar): CppString; {$IFDEF USE_INLINE}inline; {$ENDIF}
class operator Implicit(const s: string): CppString; {$IFDEF USE_INLINE}inline; {$ENDIF}
class operator Implicit(const s: CppString): string; {$IFDEF USE_INLINE}inline; {$ENDIF}
end;
TPtr<T{: record }> = record
public type
pT = ^T;
public
_Ptr: pT;
_Rep: Pointer;
_Ref: integer;
function v: pT; {$IFDEF USE_INLINE}inline; {$ENDIF}
class operator assign(var Dest: TPtr<T>; const [ref] Src: TPtr<T>);
class operator Finalize(var Dest: TPtr<T>);
class operator Equal(const A: TPtr<T>; const B: boolean): boolean; {$IFDEF USE_INLINE}inline; {$ENDIF}
end;
makePtr<T: record > = record
public type
pT = ^T;
public
class function Create(const v: T): TPtr<T>; static; {$IFDEF USE_INLINE}inline; {$ENDIF}
end;
TSet<T> = record
private
FDict: TDictionary<T, integer>;
public
class operator Initialize(out Dest: TSet<T>);
class operator Finalize(var Dest: TSet<T>);
class operator assign(var Dest: TSet<T>; const [ref] Src: TSet<T>);
class operator In (const A: T; const B: TSet<T>): boolean;
class operator Implicit(const A: TArray<T>): TSet<T>;
class operator Implicit(const A: TSet<T>): TArray<T>;
function Contains(const Value: T): boolean; inline;
procedure Include(const Value: T); inline;
procedure Exclude(const Value: T); inline;
end;
vftable_func = type Pointer;
pvftable = ^vftable_func;
function vftable(const vft: vftable_func; const index: integer): Pointer; {$IFDEF USE_INLINE}inline; {$ENDIF}
const
endl: String = #13#10;
type
Tcout = record
class operator Add(const C: Tcout; const B: String): Tcout; inline;
class operator Add(const C: Tcout; const B: double): Tcout; inline;
end;
function CppReplace(const text: String): String;
{$I 'external/cpp.std.import.inc'}
Var
cout: Tcout;
cerr: Tcout;
argv: TArray<string>;
argc: integer;
function isIntNumber(const v: String): boolean;
function isIntNumberWithDefault(const v: String; const D: integer = 0): integer;
type
TSwap = record
class procedure swap<T>(var A, B: Vector<T>); static; {$IFDEF USE_INLINE}inline; {$ENDIF}
end;
procedure printf(const text: string); {$IFDEF USE_INLINE}inline; {$ENDIF}
Type
iif = record
class function iif<T>(const Cond: boolean; const ifTrue, ifFalse: T): T; static; inline;
end;
implementation
Uses
cv.opencv;
{ vector<T> }
class operator Vector<T>.assign(var Dest: Vector<T>; const [ref] Src: Vector<T>);
begin
CopyStdVector(@Dest, @Src, vt);
end;
procedure Vector<T>.clear;
begin
clearStdVector(@Self, vt);
end;
function Vector<T>.empty: BOOL;
begin
Result := StdEmpty(@Self, vt);
end;
class operator Vector<T>.Finalize(var Dest: Vector<T>);
begin
DestroyStdVector(@Dest, vt);
end;
function Vector<T>.GetItems(const index: UInt64): T;
begin
StdGetItem(@Self, vt, index, @Result);
end;
class operator Vector<T>.Implicit(const A: TArray<T>): Vector<T>;
begin
for Var i := 0 to High(A) do
StdPushBack(@Result, @A[i], vt);
end;
class operator Vector<T>.Implicit(const size: integer): Vector<T>;
begin
Result.resize(size);
end;
class operator Vector<T>.Initialize(out Dest: Vector<T>);
begin
FillChar(Dest, SizeOf(Dest), 0);
CreateStdVector(@Dest, vt);
end;
class function Vector<T>.noVector: Vector<T>;
begin
Initialize(Result);
end;
function Vector<T>.pT(const index: UInt64): Pointer;
begin
StdGetPItem(@Self, vt, index, pVector(Result));
end;
procedure Vector<T>.push_back(const Value: T);
begin
StdPushBack(@Self, @Value, vt);
end;
procedure Vector<T>.resize(const NewSize: UInt64);
begin
resizeStdVector(@Self, NewSize, vt);
end;
procedure Vector<T>.setItems(const index: UInt64; const Value: T);
begin
StdSetItem(@Self, vt, index, @Value);
end;
function Vector<T>.size: { UInt64 } Int64;
begin
Result := StdSize(@Self, vt);
end;
class function Vector<T>.Vector: Vector<T>;
begin
Initialize(Result);
end;
class function Vector<T>.vt: TVectorType;
begin
if TypeInfo(T) = TypeInfo(TMat) then
vt := vtMat
else if TypeInfo(T) = TypeInfo(TRect) then
vt := vtRect
else if TypeInfo(T) = TypeInfo(TPoint) then
vt := vtPoint
else if TypeInfo(T) = TypeInfo(Vector<TPoint>) then
vt := vtVectorPoint
else if TypeInfo(T) = TypeInfo(TPoint2f) then
vt := vtPoint2f
else if TypeInfo(T) = TypeInfo(TScalar) then
vt := vtScalar
else if TypeInfo(T) = TypeInfo(uchar) then // vector<uchar>
vt := vtUchar
else if TypeInfo(T) = TypeInfo(float) then // vector<float>
vt := vtFloat
else if TypeInfo(T) = TypeInfo(Int) then // vector<float>
vt := vtInt
else if TypeInfo(T) = TypeInfo(TVec4i) then // vector<float>
vt := vtVec4i
else if TypeInfo(T) = TypeInfo(TVec6f) then // vector<float>
vt := vtVec6f
else if TypeInfo(T) = TypeInfo(Vector<TPoint2f>) then // vector<float>
vt := vtVectorPoint2f
else if TypeInfo(T) = TypeInfo(Vector<TMat>) then // vector<float>
vt := vtVectorMat
// else if TypeInfo(T) = TypeInfo(TGMat) then // vector<GMat>
// vt := vtGMat
// else if TypeInfo(T) = TypeInfo(TGCompileArg) then // vector<GCompileArg>
// vt := vtGCompileArg
// else if TypeInfo(T) = TypeInfo(pMat) then // vector<GCompileArg>
// vt := vtpVoid
else
begin
Var
AssertMsg := 'VectorType - not defined type'
{$IFDEF USE_TYPEINFO}
+ ' "' + GetTypeName(TypeInfo(T)) + '"'
{$ENDIF}
;
Assert(false, AssertMsg);
end;
end;
{ CppString }
procedure CppString.assign(const p: pAnsiChar);
begin
assign_CppString(@Self, p);
end;
class operator CppString.assign(var Dest: CppString; const [ref] Src: CppString);
begin
assign_CppString(pCppString(@Dest), pCppString(@Src));
end;
procedure CppString.erase(const _Off: UInt64);
begin
erase_CppString(@Self, _Off);
end;
class operator CppString.Finalize(var Dest: CppString);
begin
Destructor_CppString(@Dest);
end;
class operator CppString.Implicit(const s: string): CppString;
begin
Result.assign(pAnsiChar(AnsiString(s)));
end;
class operator CppString.Implicit(const p: pAnsiChar): CppString;
begin
Result.assign(p);
end;
class operator CppString.Implicit(const s: CppString): string;
begin
Result := string(c_str_CppString(@s));
end;
class operator CppString.Initialize(out Dest: CppString);
begin
Constructor_CppString(@Dest);
end;
function CppString.length: UInt64;
begin
Result := length_CppString(@Self);
end;
function CppString.size: UInt64;
begin
Result := size_CppString(@Self);
end;
{ TPtr<T> }
class operator TPtr<T>.assign(var Dest: TPtr<T>; const [ref] Src: TPtr<T>);
Var
p: ^TPtr<T>;
begin
Move(Src, Dest, SizeOf(Dest));
p := @Src;
Inc(p^._Ref);
end;
class operator TPtr<T>.Equal(const A: TPtr<T>; const B: boolean): boolean;
begin
Result := Assigned(A._Ptr) = B;
end;
class operator TPtr<T>.Finalize(var Dest: TPtr<T>);
begin
if Dest._Ref = 0 then
Finalize(pT(Dest._Ptr)^)
else
Dec(Dest._Ref);
end;
function TPtr<T>.v: pT;
begin
Result := _Ptr;
end;
function CppReplace(const text: String): String;
begin
Result := text.Replace('\n', #13#10).Replace('\t', #9);
end;
{ Tcout }
class operator Tcout.Add(const C: Tcout; const B: String): Tcout;
begin
write(CppReplace(B));
Result := C;
end;
class operator Tcout.Add(const C: Tcout; const B: double): Tcout;
begin
write(B.ToString);
Result := C;
end;
{ TSet<T> }
class operator TSet<T>.assign(var Dest: TSet<T>; const [ref] Src: TSet<T>);
begin
// Dest.FDict.ToArray
// Src.FDict.F
// .Assign(Src.FDict);
end;
function TSet<T>.Contains(const Value: T): boolean;
begin
Result := FDict.ContainsKey(Value);
end;
procedure TSet<T>.Exclude(const Value: T);
begin
FDict.Remove(Value);
end;
class operator TSet<T>.Finalize(var Dest: TSet<T>);
begin
Dest.FDict.Free;
end;
class operator TSet<T>.Implicit(const A: TArray<T>): TSet<T>;
begin
for Var v: T in A do
Result.Include(v);
end;
class operator TSet<T>.Implicit(const A: TSet<T>): TArray<T>;
begin
Result := A.FDict.Keys.ToArray;
end;
class operator TSet<T>.In(const A: T; const B: TSet<T>): boolean;
begin
Result := B.Contains(A);
end;
procedure TSet<T>.Include(const Value: T);
begin
FDict.AddOrSetValue(Value, 0);
end;
class operator TSet<T>.Initialize(out Dest: TSet<T>);
begin
Dest.FDict := TDictionary<T, integer>.Create;
end;
function vftable(const vft: vftable_func; const index: integer): Pointer;
begin
Result := pvftable(vft)[index];
end;
{ makePtr<T> }
class function makePtr<T>.Create(const v: T): TPtr<T>;
begin
Result._Ptr := @v;
end;
function isIntNumber(const v: String): boolean;
Var
R: integer;
begin
Result := TryStrToInt(v, R);
end;
function isIntNumberWithDefault(const v: String; const D: integer = 0): integer;
begin
if not TryStrToInt(v, Result) then
Result := D;
end;
{ TSwap }
class procedure TSwap.swap<T>(var A, B: Vector<T>);
Var
C: Pointer;
cs: size_t;
begin
cs := SizeOf(A);
C := AllocMem(cs);
try
Move(A, C^, cs);
Move(B, A, cs);
Move(C^, B, cs);
finally
FreeMem(C);
end;
end;
procedure printf(const text: string);
begin
cout + text;
end;
{ iif }
class function iif.iif<T>(const Cond: boolean; const ifTrue, ifFalse: T): T;
begin
if Cond then
Result := ifTrue
else
Result := ifFalse;
end;
initialization
argv := [ExtractFileName(ParamStr(0))];
for Var i := 1 to ParamCount do
argv := argv + [ParamStr(i)];
argc := 1 + ParamCount;
end.
| 24.170093 | 109 | 0.683242 |
c351ebe7cba4fafd94c77948ebc80efd058d8f9f | 544 | pas | Pascal | MinInLines.pas | igororeshin/Homeworks | 18f8737ba407d0eadf825be91c2d2c3b6978d075 | [
"Apache-2.0"
]
| null | null | null | MinInLines.pas | igororeshin/Homeworks | 18f8737ba407d0eadf825be91c2d2c3b6978d075 | [
"Apache-2.0"
]
| null | null | null | MinInLines.pas | igororeshin/Homeworks | 18f8737ba407d0eadf825be91c2d2c3b6978d075 | [
"Apache-2.0"
]
| null | null | null | type
matrix = array [1..3, 1..3] of integer;
var a : matrix;
procedure read_matrix();
var i, j : integer;
begin
for i := 1 to 3 do
for j := 1 to 3 do
begin
readln(a[i,j]);
end;
end;
procedure min_element(a : matrix);
var i, j, min : integer;
begin
for i := 1 to 3 do
begin
min := a[i, 1];
for j := 2 to 3 do
if a[i, j] < min then min := a[i, j];
writeln('Минимальное значение в строке', ' ', i, ' : ', min);
end;
end;
begin
read_matrix;
min_element(a);
end.
| 17 | 69 | 0.523897 |
c348c0169056b486304f10dced884f14e64e6da8 | 32,460 | pas | Pascal | windows/src/ext/jedi/jvcl/donations/DSMixAdvanced/Directx9/D3DEnumeration.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/donations/DSMixAdvanced/Directx9/D3DEnumeration.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/donations/DSMixAdvanced/Directx9/D3DEnumeration.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | (*----------------------------------------------------------------------------*
* DirectX 9 C++ common framework adaptation for Delphi by Alexey Barkovoy *
* E-Mail: clootie@reactor.ru *
* *
* Desc: Direct3D part of framework. *
* Delphi versions 5-7 are supported *
* *
* Modified: 11-Feb-2003 *
* *
* Latest version can be downloaded from: *
* http://clootie.narod.ru/delphi *
*----------------------------------------------------------------------------*)
//-----------------------------------------------------------------------------
// File: D3DEnumeration.h D3DEnumeration.cpp
//
// Desc: Enumerates D3D adapters, devices, modes, etc.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
unit D3DEnumeration;
{$I DirectX.inc}
interface
uses
Windows, Classes, Direct3D9, DXUtil;
type
//-----------------------------------------------------------------------------
// Name: enum VertexProcessingType
// Desc: Enumeration of all possible D3D vertex processing types.
//-----------------------------------------------------------------------------
TVertexProcessingType = (
SOFTWARE_VP,
MIXED_VP,
HARDWARE_VP,
PURE_HARDWARE_VP
);
//-----------------------------------------------------------------------------
// Name: struct D3DAdapterInfo
// Desc: Info about a display adapter.
//-----------------------------------------------------------------------------
PD3DAdapterInfo = ^TD3DAdapterInfo;
TD3DAdapterInfo = record {class}
AdapterOrdinal: Integer;
AdapterIdentifier: TD3DAdapterIdentifier9;
pDisplayModeList: CArrayList; // List of D3DDISPLAYMODEs
pDeviceInfoList: CArrayList; // List of D3DDeviceInfo pointers
// destructor Destroy; override;
end;
procedure D3DAdapterInfo_Destroy(const item: TD3DAdapterInfo);
type
//-----------------------------------------------------------------------------
// Name: struct D3DDeviceInfo
// Desc: Info about a D3D device, including a list of D3DDeviceCombos (see below)
// that work with the device.
//-----------------------------------------------------------------------------
PD3DDeviceInfo = ^TD3DDeviceInfo;
TD3DDeviceInfo = record {class}
AdapterOrdinal: Integer;
DevType: TD3DDevType;
Caps: TD3DCaps9;
pDeviceComboList: CArrayList; // List of D3DDeviceCombo pointers
// destructor Destroy; override;
end;
procedure D3DDeviceInfo_Destroy(const item: TD3DDeviceInfo);
type
//-----------------------------------------------------------------------------
// Name: struct D3DDSMSConflict
// Desc: A depth/stencil buffer format that is incompatible with a
// multisample type.
//-----------------------------------------------------------------------------
PD3DDSMSConflict = ^TD3DDSMSConflict;
TD3DDSMSConflict = record
DSFormat: TD3DFormat;
MSType: TD3DMultiSampleType;
end;
//-----------------------------------------------------------------------------
// Name: struct D3DDeviceCombo
// Desc: A combination of adapter format, back buffer format, and windowed/fullscreen
// that is compatible with a particular D3D device (and the app).
//-----------------------------------------------------------------------------
PD3DDeviceCombo = ^TD3DDeviceCombo;
TD3DDeviceCombo = record {class}
AdapterOrdinal: Integer;
DevType: TD3DDevType;
AdapterFormat: TD3DFormat;
BackBufferFormat: TD3DFormat;
IsWindowed: Boolean;
pDepthStencilFormatList: CArrayList; // List of D3DFORMATs
pMultiSampleTypeList: CArrayList; // List of D3DMULTISAMPLE_TYPEs
pMultiSampleQualityList: CArrayList; // List of DWORDs (number of quality
// levels for each multisample type)
pDSMSConflictList: CArrayList; // List of D3DDSMSConflicts
pVertexProcessingTypeList: CArrayList; // List of VertexProcessingTypes
pPresentIntervalList: CArrayList; // List of D3DPRESENT_INTERVALs
// destructor Destroy; override;
end;
procedure D3DDeviceCombo_Destroy(const item: TD3DDeviceCombo);
type
TConfirmDeviceCallback = function(const pCaps: TD3DCaps9;
vertexProcessingType: TVertexProcessingType;
adapterFormat, backBufferFormat: TD3DFormat): Boolean;
//-----------------------------------------------------------------------------
// Name: class CD3DEnumeration
// Desc: Enumerates available D3D adapters, devices, modes, etc.
//-----------------------------------------------------------------------------
CD3DEnumeration = class
private
m_pD3D: IDirect3D9;
private
function EnumerateDevices(pAdapterInfo: PD3DAdapterInfo;
pAdapterFormatList: CArrayList): HRESULT;
function EnumerateDeviceCombos(pDeviceInfo: PD3DDeviceInfo;
pAdapterFormatList: CArrayList): HRESULT;
procedure BuildDepthStencilFormatList(pDeviceCombo: PD3DDeviceCombo);
procedure BuildMultiSampleTypeList(pDeviceCombo: PD3DDeviceCombo);
procedure BuildDSMSConflictList(pDeviceCombo: PD3DDeviceCombo);
procedure BuildVertexProcessingTypeList(pDeviceInfo: PD3DDeviceInfo;
pDeviceCombo: PD3DDeviceCombo);
procedure BuildPresentIntervalList(pDeviceInfo: PD3DDeviceInfo;
pDeviceCombo: PD3DDeviceCombo);
public
m_pAdapterInfoList: CArrayList;
// The following variables can be used to limit what modes, formats,
// etc. are enumerated. Set them to the values you want before calling
// Enumerate().
ConfirmDeviceCallback: TConfirmDeviceCallback;
AppMinFullscreenWidth: LongWord;
AppMinFullscreenHeight: LongWord;
AppMinColorChannelBits: LongWord; // min color bits per channel in adapter format
AppMinAlphaChannelBits: LongWord; // min alpha bits per pixel in back buffer format
AppMinDepthBits: LongWord;
AppMinStencilBits: LongWord;
AppUsesDepthBuffer: Boolean;
AppUsesMixedVP: Boolean; // whether app can take advantage of mixed vp mode
AppRequiresWindowed: Boolean;
AppRequiresFullscreen: Boolean;
m_pAllowedAdapterFormatList: CArrayList; // list of D3DFORMATs
constructor Create;
destructor Destroy; override;
procedure SetD3D(pD3D: IDirect3D9); // { m_pD3D = pD3D; }
function Enumerate: HRESULT;
property D3D: IDirect3D9 read m_pD3D write SetD3D;
end;
type
QSortCB = function (const arg1, arg2: Pointer): Integer;
Size_t = Cardinal;
procedure QSort(base: Pointer; num: Size_t; width: Size_t; compare: QSortCB);
implementation
uses SysUtils;
// Implementation of QSort C++ function
procedure qsort_int(base: Pointer; width: Integer; compare: QSortCB;
Left, Right: Integer; TempBuffer, TempBuffer2: Pointer);
var
Lo, Hi: Integer;
P: Pointer;
begin
Lo := Left;
Hi := Right;
P := Pointer(Integer(base) + ((Lo + Hi) div 2)*width);
Move(P^, TempBuffer2^, width);
repeat
while compare(Pointer(Integer(base) + Lo*width), TempBuffer2) < 0 do Inc(Lo);
while compare(Pointer(Integer(base) + Hi*width), TempBuffer2) > 0 do Dec(Hi);
if Lo <= Hi then
begin
Move(Pointer(Integer(base) + Lo*width)^, TempBuffer^, width);
Move(Pointer(Integer(base) + Hi*width)^, Pointer(Integer(base) + Lo*width)^, width);
Move(TempBuffer^, Pointer(Integer(base) + Hi*width)^, width);
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
if Hi > Left then qsort_int(base, width, compare, Left, Hi, TempBuffer, TempBuffer2);
if Lo < Right then qsort_int(base, width, compare, Lo, Right, TempBuffer, TempBuffer2);
end;
procedure QSort(base: Pointer; num: Size_t; width: Size_t; compare: QSortCB);
var
p, p1: Pointer;
begin
GetMem(p, width);
GetMem(p1, width);
try
qsort_int(base, width, compare, 0, num - 1, p, p1);
finally
FreeMem(p1, width);
FreeMem(p, width);
end;
end;
//-----------------------------------------------------------------------------
// Name: ColorChannelBits
// Desc: Returns the number of color channel bits in the specified D3DFORMAT
//-----------------------------------------------------------------------------
function ColorChannelBits(fmt: TD3DFormat): LongWord;
begin
case fmt of
D3DFMT_R8G8B8: Result:= 8;
D3DFMT_A8R8G8B8: Result:= 8;
D3DFMT_X8R8G8B8: Result:= 8;
D3DFMT_R5G6B5: Result:= 5;
D3DFMT_X1R5G5B5: Result:= 5;
D3DFMT_A1R5G5B5: Result:= 5;
D3DFMT_A4R4G4B4: Result:= 4;
D3DFMT_R3G3B2: Result:= 2;
D3DFMT_A8R3G3B2: Result:= 2;
D3DFMT_X4R4G4B4: Result:= 4;
D3DFMT_A2B10G10R10: Result:= 10;
D3DFMT_A2R10G10B10: Result:= 10;
else
Result:= 0;
end;
end;
//-----------------------------------------------------------------------------
// Name: AlphaChannelBits
// Desc: Returns the number of alpha channel bits in the specified D3DFORMAT
//-----------------------------------------------------------------------------
function AlphaChannelBits(fmt: TD3DFormat): LongWord;
begin
case fmt of
D3DFMT_R8G8B8: Result:= 0;
D3DFMT_A8R8G8B8: Result:= 8;
D3DFMT_X8R8G8B8: Result:= 0;
D3DFMT_R5G6B5: Result:= 0;
D3DFMT_X1R5G5B5: Result:= 0;
D3DFMT_A1R5G5B5: Result:= 1;
D3DFMT_A4R4G4B4: Result:= 4;
D3DFMT_R3G3B2: Result:= 0;
D3DFMT_A8R3G3B2: Result:= 8;
D3DFMT_X4R4G4B4: Result:= 0;
D3DFMT_A2B10G10R10: Result:= 2;
D3DFMT_A2R10G10B10: Result:= 2;
else
Result:= 0;
end;
end;
//-----------------------------------------------------------------------------
// Name: DepthBits
// Desc: Returns the number of depth bits in the specified D3DFORMAT
//-----------------------------------------------------------------------------
function DepthBits(fmt: TD3DFormat): LongWord;
begin
case fmt of
D3DFMT_D16: Result:= 16;
D3DFMT_D15S1: Result:= 15;
D3DFMT_D24X8: Result:= 24;
D3DFMT_D24S8: Result:= 24;
D3DFMT_D24X4S4: Result:= 24;
D3DFMT_D32: Result:= 32;
else
Result:= 0;
end;
end;
//-----------------------------------------------------------------------------
// Name: StencilBits
// Desc: Returns the number of stencil bits in the specified D3DFORMAT
//-----------------------------------------------------------------------------
function StencilBits(fmt: TD3DFormat): LongWord;
begin
case fmt of
D3DFMT_D16: Result:= 0;
D3DFMT_D15S1: Result:= 1;
D3DFMT_D24X8: Result:= 0;
D3DFMT_D24S8: Result:= 8;
D3DFMT_D24X4S4: Result:= 4;
D3DFMT_D32: Result:= 0;
else
Result:= 0;
end;
end;
//-----------------------------------------------------------------------------
// Name: D3DAdapterInfo destructor
// Desc:
//-----------------------------------------------------------------------------
//destructor TD3DAdapterInfo.Destroy;
procedure D3DAdapterInfo_Destroy(const item: TD3DAdapterInfo);
var
idi: Integer;
begin with item do begin
if (pDisplayModeList <> nil) then pDisplayModeList.Free;
if (pDeviceInfoList <> nil) then
begin
for idi:= 0 to pDeviceInfoList.Count - 1 do
D3DDeviceInfo_Destroy(PD3DDeviceInfo(pDeviceInfoList.GetPtr(idi))^);
// TD3DDeviceInfo(pDeviceInfoList.GetPtr(idi)).Free;
pDeviceInfoList.Free;
end;
end; end;
//-----------------------------------------------------------------------------
// Name: D3DDeviceInfo destructor
// Desc:
//-----------------------------------------------------------------------------
// destructor TD3DDeviceInfo.Destroy;
procedure D3DDeviceInfo_Destroy(const item: TD3DDeviceInfo);
var
idc: Integer;
begin with item do begin
if (pDeviceComboList <> nil) then
begin
for idc:= 0 to pDeviceComboList.Count - 1 do
D3DDeviceCombo_Destroy(PD3DDeviceCombo(pDeviceComboList.GetPtr(idc))^);
// TD3DDeviceCombo(pDeviceComboList.GetPtr(idc)).Free;
pDeviceComboList.Free;
end;
end; end;
//-----------------------------------------------------------------------------
// Name: D3DDeviceCombo destructor
// Desc:
//-----------------------------------------------------------------------------
// destructor TD3DDeviceCombo.Destroy;
procedure D3DDeviceCombo_Destroy(const item: TD3DDeviceCombo);
begin with item do begin
if (pDepthStencilFormatList <> nil) then pDepthStencilFormatList.Free;
if (pMultiSampleTypeList <> nil) then pMultiSampleTypeList.Free;
if (pMultiSampleQualityList <> nil) then pMultiSampleQualityList.Free;
if (pDSMSConflictList <> nil) then pDSMSConflictList.Free;
if (pVertexProcessingTypeList <> nil) then pVertexProcessingTypeList.Free;
if (pPresentIntervalList <> nil) then pPresentIntervalList.Free;
end; end;
//-----------------------------------------------------------------------------
// Name: CD3DEnumeration constructor
// Desc:
//-----------------------------------------------------------------------------
constructor CD3DEnumeration.Create;
begin
m_pAdapterInfoList := nil;
m_pAllowedAdapterFormatList := nil;
AppMinFullscreenWidth := 640;
AppMinFullscreenHeight := 480;
AppMinColorChannelBits := 5;
AppMinAlphaChannelBits := 0;
AppMinDepthBits := 15;
AppMinStencilBits := 0;
AppUsesDepthBuffer := false;
AppUsesMixedVP := false;
AppRequiresWindowed := false;
AppRequiresFullscreen := false;
end;
//-----------------------------------------------------------------------------
// Name: CD3DEnumeration destructor
// Desc:
//-----------------------------------------------------------------------------
destructor CD3DEnumeration.Destroy;
var
iai: Integer;
begin
if (m_pAdapterInfoList <> nil) then
begin
for iai:= 0 to m_pAdapterInfoList.Count - 1 do
D3DAdapterInfo_Destroy(TD3DAdapterInfo(m_pAdapterInfoList.GetPtr(iai)^));
// TD3DAdapterInfo(m_pAdapterInfoList.GetPtr(iai)).Free;
m_pAdapterInfoList.Free;
end;
SAFE_DELETE(m_pAllowedAdapterFormatList);
end;
procedure CD3DEnumeration.SetD3D(pD3D: IDirect3D9); // { m_pD3D = pD3D; }
begin
m_pD3D := pD3D;
end;
//-----------------------------------------------------------------------------
// Name: SortModesCallback
// Desc: Used to sort D3DDISPLAYMODEs
//-----------------------------------------------------------------------------
function SortModesCallback(const arg1, arg2: Pointer): Integer;
var
pdm1: PD3DDisplayMode;
pdm2: PD3DDisplayMode;
begin
pdm1:= PD3DDisplayMode(arg1);
pdm2:= PD3DDisplayMode(arg2);
if (pdm1.Width > pdm2.Width) then begin Result:= 1; Exit; end;
if (pdm1.Width < pdm2.Width) then begin Result:= -1; Exit; end;
if (pdm1.Height > pdm2.Height) then begin Result:= 1; Exit; end;
if (pdm1.Height < pdm2.Height) then begin Result:= -1; Exit; end;
if (pdm1.Format > pdm2.Format) then begin Result:= 1; Exit; end;
if (pdm1.Format < pdm2.Format) then begin Result:= -1; Exit; end;
if (pdm1.RefreshRate > pdm2.RefreshRate) then begin Result:= 1; Exit; end;
if (pdm1.RefreshRate < pdm2.RefreshRate) then begin Result:= -1; Exit; end;
Result:= 0;
end;
//-----------------------------------------------------------------------------
// Name: Enumerate
// Desc: Enumerates available D3D adapters, devices, modes, etc.
//-----------------------------------------------------------------------------
function CD3DEnumeration.Enumerate: HRESULT;
var
adapterFormatList: CArrayList;
fmt: TD3DFormat;
pAdapterInfo: PD3DAdapterInfo;
numAdapters: LongWord;
adapterOrdinal: LongWord;
iaaf: Integer;
allowedAdapterFormat: TD3DFormat;
numAdapterModes: LongWord;
mode: Integer;
displayMode: TD3DDisplayMode;
begin
pAdapterInfo := nil;
try
adapterFormatList:= CArrayList.Create(AL_VALUE, SizeOf(TD3DFormat));
if (m_pD3D = nil) then
begin
Result:= E_FAIL;
Exit;
end;
m_pAdapterInfoList := CArrayList.Create(AL_REFERENCE);
m_pAllowedAdapterFormatList := CArrayList.Create(AL_VALUE, SizeOf(TD3DFormat));
fmt := D3DFMT_X8R8G8B8;
Result:= m_pAllowedAdapterFormatList.Add(@fmt); if FAILED(Result) then Exit;
fmt := D3DFMT_X1R5G5B5;
Result:= m_pAllowedAdapterFormatList.Add(@fmt); if FAILED(Result) then Exit;
fmt := D3DFMT_R5G6B5;
Result:= m_pAllowedAdapterFormatList.Add(@fmt); if FAILED(Result) then Exit;
fmt := D3DFMT_A2R10G10B10;
Result:= m_pAllowedAdapterFormatList.Add(@fmt); if FAILED(Result) then Exit;
numAdapters := m_pD3D.GetAdapterCount;
if (numAdapters > 0) then
for adapterOrdinal := 0 to numAdapters - 1 do
begin
New(pAdapterInfo);
pAdapterInfo.pDisplayModeList := CArrayList.Create(AL_VALUE, SizeOf(TD3DDisplayMode));
pAdapterInfo.pDeviceInfoList := CArrayList.Create(AL_REFERENCE);
pAdapterInfo.AdapterOrdinal := adapterOrdinal;
m_pD3D.GetAdapterIdentifier(adapterOrdinal, 0, pAdapterInfo.AdapterIdentifier);
// Get list of all display modes on this adapter.
// Also build a temporary list of all display adapter formats.
adapterFormatList.Clear;
for iaaf := 0 to m_pAllowedAdapterFormatList.Count - 1 do
begin
allowedAdapterFormat := PD3DFormat(m_pAllowedAdapterFormatList.GetPtr(iaaf))^;
numAdapterModes := m_pD3D.GetAdapterModeCount(adapterOrdinal, allowedAdapterFormat);
for mode:= 0 to numAdapterModes - 1 do
begin
m_pD3D.EnumAdapterModes(adapterOrdinal, allowedAdapterFormat, mode, displayMode);
if (displayMode.Width < AppMinFullscreenWidth) or
(displayMode.Height < AppMinFullscreenHeight) or
(ColorChannelBits(displayMode.Format) < AppMinColorChannelBits)
then Continue;
pAdapterInfo.pDisplayModeList.Add(@displayMode);
if (not adapterFormatList.Contains(@displayMode.Format)) then
adapterFormatList.Add(@displayMode.Format);
end;
end;
// Sort displaymode list
QSort(pAdapterInfo.pDisplayModeList.GetPtr(0),
pAdapterInfo.pDisplayModeList.Count, SizeOf(TD3DDisplayMode),
SortModesCallback);
// Get info for each device on this adapter
Result:= EnumerateDevices(pAdapterInfo, adapterFormatList);
if FAILED(Result) then
begin
Dispose(pAdapterInfo);
Exit;
end;
// If at least one device on this adapter is available and compatible
// with the app, add the adapterInfo to the list
if (pAdapterInfo.pDeviceInfoList.Count = 0)
then Dispose(pAdapterInfo)
else m_pAdapterInfoList.Add(pAdapterInfo);
end;
except
on EOutOfMemory do
begin
Dispose(pAdapterInfo);
Result:= E_OUTOFMEMORY;
Exit;
end;
else
raise;
end;
Result:= S_OK;
end;
//-----------------------------------------------------------------------------
// Name: EnumerateDevices
// Desc: Enumerates D3D devices for a particular adapter.
//-----------------------------------------------------------------------------
function CD3DEnumeration.EnumerateDevices(pAdapterInfo: PD3DAdapterInfo;
pAdapterFormatList: CArrayList): HRESULT;
const
devTypeArray: array[0..2] of TD3DDevType = (D3DDEVTYPE_HAL, D3DDEVTYPE_SW, D3DDEVTYPE_REF);
devTypeArrayCount = LongWord(SizeOf(devTypeArray) div SizeOf(devTypeArray[0]));
var
pDeviceInfo: PD3DDeviceInfo;
idt: Integer;
begin
pDeviceInfo:= nil;
try
for idt := 0 to devTypeArrayCount - 1 do
begin
New(pDeviceInfo);
pDeviceInfo.pDeviceComboList := CArrayList.Create(AL_REFERENCE);
pDeviceInfo.AdapterOrdinal := pAdapterInfo.AdapterOrdinal;
pDeviceInfo.DevType := devTypeArray[idt];
Result:= m_pD3D.GetDeviceCaps(pAdapterInfo.AdapterOrdinal,
pDeviceInfo.DevType, pDeviceInfo.Caps);
if FAILED(Result) then
begin
Dispose(pDeviceInfo);
Continue;
end;
// Get info for each devicecombo on this device
Result:= EnumerateDeviceCombos(pDeviceInfo, pAdapterFormatList);
if FAILED(Result) then
begin
Dispose(pDeviceInfo);
Exit;
end;
// If at least one devicecombo for this device is found,
// add the deviceInfo to the list
if (pDeviceInfo.pDeviceComboList.Count = 0) then
begin
Dispose(pDeviceInfo);
Continue;
end;
pAdapterInfo.pDeviceInfoList.Add(pDeviceInfo);
end;
except
on EOutOfMemory do
begin
Dispose(pDeviceInfo);
Result:= E_OUTOFMEMORY;
Exit;
end;
else
raise
end;
Result:= S_OK;
end;
//-----------------------------------------------------------------------------
// Name: EnumerateDeviceCombos
// Desc: Enumerates DeviceCombos for a particular device.
//-----------------------------------------------------------------------------
function CD3DEnumeration.EnumerateDeviceCombos(pDeviceInfo: PD3DDeviceInfo;
pAdapterFormatList: CArrayList): HRESULT;
const
backBufferFormatArray: array[0..5] of TD3DFormat = (
D3DFMT_A8R8G8B8, D3DFMT_X8R8G8B8, D3DFMT_A2R10G10B10,
D3DFMT_R5G6B5, D3DFMT_A1R5G5B5, D3DFMT_X1R5G5B5);
backBufferFormatArrayCount =
LongWord(SizeOf(backBufferFormatArray) div SizeOf(backBufferFormatArray[0]));
isWindowedArray: array[0..1] of Boolean = (False, True);
var
adapterFormat: TD3DFormat;
iaf, ibbf, iiw: Integer;
backBufferFormat: TD3DFormat;
isWindowed: BOOL;
pDeviceCombo: PD3DDeviceCombo;
begin
// See which adapter formats are supported by this device
pDeviceCombo:= nil;
try
for iaf := 0 to pAdapterFormatList.Count - 1 do
begin
adapterFormat := PD3DFormat(pAdapterFormatList.GetPtr(iaf))^;
for ibbf := 0 to backBufferFormatArrayCount - 1 do
begin
backBufferFormat := backBufferFormatArray[ibbf];
if (AlphaChannelBits(backBufferFormat) < AppMinAlphaChannelBits) then Continue;
for iiw := 0 to 1 do
begin
isWindowed := isWindowedArray[iiw];
if (not isWindowed and AppRequiresWindowed) then Continue;
if (isWindowed and AppRequiresFullscreen) then Continue;
if FAILED(m_pD3D.CheckDeviceType(pDeviceInfo.AdapterOrdinal, pDeviceInfo.DevType,
adapterFormat, backBufferFormat, isWindowed)) then Continue;
// At this point, we have an adapter/device/adapterformat/backbufferformat/iswindowed
// DeviceCombo that is supported by the system. We still need to confirm that it's
// compatible with the app, and find one or more suitable depth/stencil buffer format,
// multisample type, vertex processing type, and present interval.
// pDeviceCombo := nil; -- never used
New(pDeviceCombo);
pDeviceCombo.pDepthStencilFormatList := CArrayList.Create(AL_VALUE, SizeOf(TD3DFormat));
pDeviceCombo.pMultiSampleTypeList := CArrayList.Create(AL_VALUE, SizeOf(TD3DMultiSampleType));
pDeviceCombo.pMultiSampleQualityList := CArrayList.Create(AL_VALUE, SizeOf(DWORD));
pDeviceCombo.pDSMSConflictList := CArrayList.Create(AL_VALUE, SizeOf(TD3DDSMSConflict));
pDeviceCombo.pVertexProcessingTypeList := CArrayList.Create(AL_VALUE, SizeOf(TVertexProcessingType));
pDeviceCombo.pPresentIntervalList := CArrayList.Create(AL_VALUE, SizeOf(LongWord));
pDeviceCombo.AdapterOrdinal := pDeviceInfo.AdapterOrdinal;
pDeviceCombo.DevType := pDeviceInfo.DevType;
pDeviceCombo.AdapterFormat := adapterFormat;
pDeviceCombo.BackBufferFormat := backBufferFormat;
pDeviceCombo.IsWindowed := isWindowed;
if (AppUsesDepthBuffer) then
begin
BuildDepthStencilFormatList(pDeviceCombo);
if (pDeviceCombo.pDepthStencilFormatList.Count = 0) then
begin
Dispose(pDeviceCombo);
Continue;
end;
end;
BuildMultiSampleTypeList(pDeviceCombo);
if (pDeviceCombo.pMultiSampleTypeList.Count = 0) then
begin
Dispose(pDeviceCombo);
Continue;
end;
BuildDSMSConflictList(pDeviceCombo);
BuildVertexProcessingTypeList(pDeviceInfo, pDeviceCombo);
if (pDeviceCombo.pVertexProcessingTypeList.Count = 0) then
begin
Dispose(pDeviceCombo);
Continue;
end;
BuildPresentIntervalList(pDeviceInfo, pDeviceCombo);
pDeviceInfo.pDeviceComboList.Add(pDeviceCombo);
pDeviceCombo:= nil;
end;
end;
end;
except
on EOutOfMemory do
begin
Dispose(pDeviceCombo);
Result:= E_OUTOFMEMORY;
Exit;
end;
else
raise
end;
Result:= S_OK;
end;
//-----------------------------------------------------------------------------
// Name: BuildDepthStencilFormatList
// Desc: Adds all depth/stencil formats that are compatible with the device
// and app to the given D3DDeviceCombo.
//-----------------------------------------------------------------------------
procedure CD3DEnumeration.BuildDepthStencilFormatList(pDeviceCombo: PD3DDeviceCombo);
const
depthStencilFormatArray: array[0..5] of TD3DFormat = (
D3DFMT_D16,
D3DFMT_D15S1,
D3DFMT_D24X8,
D3DFMT_D24S8,
D3DFMT_D24X4S4,
D3DFMT_D32
);
depthStencilFormatArrayCount =
LongWord(SizeOf(depthStencilFormatArray) div SizeOf(depthStencilFormatArray[0]));
var
depthStencilFmt: TD3DFormat;
idsf: LongWord;
begin
for idsf:= 0 to depthStencilFormatArrayCount - 1 do
begin
depthStencilFmt := depthStencilFormatArray[idsf];
if (DepthBits(depthStencilFmt) < AppMinDepthBits) then Continue;
if (StencilBits(depthStencilFmt) < AppMinStencilBits) then Continue;
if (SUCCEEDED(m_pD3D.CheckDeviceFormat(pDeviceCombo.AdapterOrdinal,
pDeviceCombo.DevType, pDeviceCombo.AdapterFormat,
D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFmt))) then
begin
if (SUCCEEDED(m_pD3D.CheckDepthStencilMatch(pDeviceCombo.AdapterOrdinal,
pDeviceCombo.DevType, pDeviceCombo.AdapterFormat,
pDeviceCombo.BackBufferFormat, depthStencilFmt))) then
begin
pDeviceCombo.pDepthStencilFormatList.Add(@depthStencilFmt);
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// Name: BuildMultiSampleTypeList
// Desc: Adds all multisample types that are compatible with the device and app to
// the given D3DDeviceCombo.
//-----------------------------------------------------------------------------
procedure CD3DEnumeration.BuildMultiSampleTypeList(pDeviceCombo: PD3DDeviceCombo);
const
msTypeArray: array[0..16] of TD3DMultiSampleType = (
D3DMULTISAMPLE_NONE,
D3DMULTISAMPLE_NONMASKABLE,
D3DMULTISAMPLE_2_SAMPLES,
D3DMULTISAMPLE_3_SAMPLES,
D3DMULTISAMPLE_4_SAMPLES,
D3DMULTISAMPLE_5_SAMPLES,
D3DMULTISAMPLE_6_SAMPLES,
D3DMULTISAMPLE_7_SAMPLES,
D3DMULTISAMPLE_8_SAMPLES,
D3DMULTISAMPLE_9_SAMPLES,
D3DMULTISAMPLE_10_SAMPLES,
D3DMULTISAMPLE_11_SAMPLES,
D3DMULTISAMPLE_12_SAMPLES,
D3DMULTISAMPLE_13_SAMPLES,
D3DMULTISAMPLE_14_SAMPLES,
D3DMULTISAMPLE_15_SAMPLES,
D3DMULTISAMPLE_16_SAMPLES
);
msTypeArrayCount = LongWord(SizeOf(msTypeArray) div SizeOf(msTypeArray[0]));
var
msType: TD3DMultiSampleType;
msQuality: DWORD;
imst: LongWord;
begin
for imst := 0 to msTypeArrayCount - 1 do
begin
msType := msTypeArray[imst];
if (SUCCEEDED(m_pD3D.CheckDeviceMultiSampleType(pDeviceCombo.AdapterOrdinal, pDeviceCombo.DevType,
pDeviceCombo.BackBufferFormat, pDeviceCombo.IsWindowed, msType, @msQuality))) then
begin
pDeviceCombo.pMultiSampleTypeList.Add(@msType);
pDeviceCombo.pMultiSampleQualityList.Add(@msQuality);
end;
end;
end;
//-----------------------------------------------------------------------------
// Name: BuildDSMSConflictList
// Desc: Find any conflicts between the available depth/stencil formats and
// multisample types.
//-----------------------------------------------------------------------------
procedure CD3DEnumeration.BuildDSMSConflictList(pDeviceCombo: PD3DDeviceCombo);
var
DSMSConflict: TD3DDSMSConflict;
dsFmt: TD3DFormat;
ids, ims: Integer;
msType: TD3DMultiSampleType;
begin
for ids := 0 to pDeviceCombo.pDepthStencilFormatList.Count - 1 do
begin
dsFmt := PD3DFormat(pDeviceCombo.pDepthStencilFormatList.GetPtr(ids))^;
for ims := 0 to pDeviceCombo.pMultiSampleTypeList.Count - 1 do
begin
msType := TD3DMultiSampleType(pDeviceCombo.pMultiSampleTypeList.GetPtr(ims)^);
if FAILED(m_pD3D.CheckDeviceMultiSampleType(pDeviceCombo.AdapterOrdinal, pDeviceCombo.DevType,
dsFmt, pDeviceCombo.IsWindowed, msType, nil)) then
begin
DSMSConflict.DSFormat := dsFmt;
DSMSConflict.MSType := msType;
pDeviceCombo.pDSMSConflictList.Add(@DSMSConflict);
end;
end;
end;
end;
//-----------------------------------------------------------------------------
// Name: BuildVertexProcessingTypeList
// Desc: Adds all vertex processing types that are compatible with the device
// and app to the given D3DDeviceCombo.
//-----------------------------------------------------------------------------
procedure CD3DEnumeration.BuildVertexProcessingTypeList(pDeviceInfo: PD3DDeviceInfo;
pDeviceCombo: PD3DDeviceCombo);
var
vpt: TVertexProcessingType;
begin
if ((pDeviceInfo.Caps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT) <> 0) then
begin
if ((pDeviceInfo.Caps.DevCaps and D3DDEVCAPS_PUREDEVICE) <> 0) then
begin
if (@ConfirmDeviceCallback = nil) or
ConfirmDeviceCallback(pDeviceInfo.Caps, PURE_HARDWARE_VP,
pDeviceCombo.AdapterFormat, pDeviceCombo.BackBufferFormat) then
begin
vpt := PURE_HARDWARE_VP;
pDeviceCombo.pVertexProcessingTypeList.Add(@vpt);
end;
end;
if (@ConfirmDeviceCallback = nil) or
ConfirmDeviceCallback(pDeviceInfo.Caps, HARDWARE_VP,
pDeviceCombo.AdapterFormat, pDeviceCombo.BackBufferFormat) then
begin
vpt := HARDWARE_VP;
pDeviceCombo.pVertexProcessingTypeList.Add(@vpt);
end;
if (AppUsesMixedVP and (@ConfirmDeviceCallback = nil) or
ConfirmDeviceCallback(pDeviceInfo.Caps, MIXED_VP,
pDeviceCombo.AdapterFormat, pDeviceCombo.BackBufferFormat)) then
begin
vpt := MIXED_VP;
pDeviceCombo.pVertexProcessingTypeList.Add(@vpt);
end;
end;
if (@ConfirmDeviceCallback = nil) or
ConfirmDeviceCallback(pDeviceInfo.Caps, SOFTWARE_VP,
pDeviceCombo.AdapterFormat, pDeviceCombo.BackBufferFormat) then
begin
vpt := SOFTWARE_VP;
pDeviceCombo.pVertexProcessingTypeList.Add(@vpt);
end;
end;
//-----------------------------------------------------------------------------
// Name: BuildPresentIntervalList
// Desc: Adds all present intervals that are compatible with the device and app
// to the given D3DDeviceCombo.
//-----------------------------------------------------------------------------
procedure CD3DEnumeration.BuildPresentIntervalList(pDeviceInfo: PD3DDeviceInfo;
pDeviceCombo: PD3DDeviceCombo);
const
piArray: array[0..5] of LongWord = (
D3DPRESENT_INTERVAL_IMMEDIATE,
D3DPRESENT_INTERVAL_DEFAULT,
D3DPRESENT_INTERVAL_ONE,
D3DPRESENT_INTERVAL_TWO,
D3DPRESENT_INTERVAL_THREE,
D3DPRESENT_INTERVAL_FOUR
);
piArrayCount = LongWord(SizeOf(piArray) div SizeOf(piArray[0]));
var
pi: LongWord;
ipi: LongWord;
begin
for ipi := 0 to piArrayCount - 1 do
begin
pi := piArray[ipi];
if (pDeviceCombo.IsWindowed) then
begin
if (pi = D3DPRESENT_INTERVAL_TWO) or
(pi = D3DPRESENT_INTERVAL_THREE) or
(pi = D3DPRESENT_INTERVAL_FOUR) then
begin
// These intervals are not supported in windowed mode.
Continue;
end;
end;
// Note that D3DPRESENT_INTERVAL_DEFAULT is zero, so you
// can't do a caps check for it -- it is always available.
if (pi = D3DPRESENT_INTERVAL_DEFAULT) or
(pDeviceInfo.Caps.PresentationIntervals and pi <> 0) then
begin
pDeviceCombo.pPresentIntervalList.Add(@pi);
end;
end;
end;
end.
| 35.592105 | 109 | 0.613278 |
c368016cf2a6ce330601a5b2ab9c34f2f6353abe | 183,658 | pas | Pascal | fpcdws/dwsComp.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| 4 | 2018-09-18T07:35:52.000Z | 2021-02-18T18:21:54.000Z | fpcdws/dwsComp.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| null | null | null | fpcdws/dwsComp.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| 1 | 2020-10-30T07:24:05.000Z | 2020-10-30T07:24:05.000Z | {**********************************************************************}
{ }
{ "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 Initial Developer of the Original Code is Matthias }
{ Ackermann. For other initial contributors, see contributors.txt }
{ Subsequent portions Copyright Creative IT. }
{ }
{ Current maintainer: Eric Grange }
{ }
{**********************************************************************}
unit dwsComp;
{$I dws.inc}
interface
uses
Variants, Classes, SysUtils, TypInfo,
dwsCompiler, dwsExprs, dwsSymbols, dwsDataContext, dwsExprList,
dwsStack, dwsFunctions, dwsStrings, dwsLanguageExtension,
dwsTokenizer, dwsUtils, dwsOperators, dwsUnitSymbols, dwsXPlatform,
// Built-In functions
{$IFNDEF DWS_NO_BUILTIN_FUNCTIONS}
dwsMathFunctions, dwsStringFunctions, dwsTimeFunctions, dwsVariantFunctions,
{$ENDIF}
dwsMagicExprs, dwsErrors;
type
TDelphiWebScript = class;
// TdwsCustomLangageExtension
//
TdwsCustomLangageExtension = class (TComponent)
private
FExtension : TdwsLanguageExtension;
FScript : TDelphiWebScript;
protected
function CreateExtension : TdwsLanguageExtension; virtual; abstract;
procedure SetScript(const val : TDelphiWebScript);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property Extension : TdwsLanguageExtension read FExtension write FExtension;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Script : TDelphiWebScript read FScript write SetScript;
end;
TdwsEmptyUnit = class(TComponent, IUnknown, IdwsUnit)
private
function GetUnitName: UnicodeString;
function GetDependencies: TStrings;
function GetUnitTable(systemTable : TSystemSymbolTable;
unitSyms : TUnitMainSymbols;
operators : TOperators;
rootTable : TSymbolTable) : TUnitSymbolTable;
function GetUnitFlags : TIdwsUnitFlags;
function GetDeprecatedMessage : UnicodeString;
protected
FUnitName: UnicodeString;
FDependencies: TStrings;
procedure AddUnitSymbols(SymbolTable: TSymbolTable); virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TdwsUnitComponent = class(TdwsEmptyUnit)
private
FScript: TDelphiWebScript;
protected
procedure SetScript(const Value: TDelphiWebScript);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
destructor Destroy; override;
published
property Script: TDelphiWebScript read FScript write SetScript;
end;
TNeedLocalizerEvent = function (Sender : TObject) : IdwsLocalizer;
// TDelphiWebScript
//
TDelphiWebScript = class (TdwsEmptyUnit)
private
FCompiler : IdwsCompiler;
FConfig : TdwsConfiguration;
FExtensions : TdwsLanguageExtensionAggregator;
FLock : TFixedCriticalSection;
protected
function GetOnInclude: TIncludeEvent;
procedure SetOnInclude(const Value: TIncludeEvent);
function GetOnExecutionStarted : TdwsExecutionEvent;
procedure SetOnExecutionStarted(const val : TdwsExecutionEvent);
function GetOnExecutionEnded : TdwsExecutionEvent;
procedure SetOnExecutionEnded(const val : TdwsExecutionEvent);
function GetVersion: UnicodeString;
procedure SetVersion(const Value: UnicodeString);
function GetOnNeedUnit : TdwsOnNeedUnitEvent;
procedure SetOnNeedUnit(const val : TdwsOnNeedUnitEvent);
function GetOnResource : TdwsResourceEvent;
procedure SetOnResource(const val : TdwsResourceEvent);
procedure SetConfig(const Value: TdwsConfiguration);
procedure AddUnitSymbols(SymbolTable: TSymbolTable); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetupExtensions;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddUnit(const Un: IdwsUnit);
function RemoveUnit(const Un: IdwsUnit): Boolean;
function Compile(const Text: UnicodeString): IdwsProgram; virtual;
procedure RecompileInContext(const prog : IdwsProgram; const text : UnicodeString); virtual;
procedure AbortCompilation;
procedure Lock;
procedure UnLock;
property Compiler : IdwsCompiler read FCompiler;
property Extensions : TdwsLanguageExtensionAggregator read FExtensions;
published
property Config : TdwsConfiguration read FConfig write SetConfig stored True;
property OnNeedUnit : TdwsOnNeedUnitEvent read GetOnNeedUnit write SetOnNeedUnit stored False;
property OnInclude : TIncludeEvent read GetOnInclude write SetOnInclude stored False;
property OnResource : TdwsResourceEvent read GetOnResource write SetOnResource;
property OnExecutionStarted : TdwsExecutionEvent read GetOnExecutionStarted write SetOnExecutionStarted;
property OnExecutionEnded : TdwsExecutionEvent read GetOnExecutionEnded write SetOnExecutionEnded;
property Version : UnicodeString read GetVersion write SetVersion stored False;
end;
TLocalizeSymbolEvent = procedure (Sender : TObject; aResSymbol : TResourceStringSymbol; var result : UnicodeString) of object;
TLocalizeStringEvent = procedure (Sender : TObject; const aString : UnicodeString; var result : UnicodeString) of object;
TGetLocalizerEvent = procedure (Sender : TObject; var localizer : IdwsLocalizer) of object;
TEventBasedLocalizer = class (TInterfacedSelfObject, IdwsLocalizer)
private
FSender : TObject;
FOnLocalizeSymbol : TLocalizeSymbolEvent;
FOnLocalizeString : TLocalizeStringEvent;
public
procedure LocalizeSymbol(aResSymbol : TResourceStringSymbol; var Result : UnicodeString);
procedure LocalizeString(const aString : UnicodeString; var Result : UnicodeString);
property Sender : TObject read FSender write FSender;
property OnLocalizeSymbol : TLocalizeSymbolEvent read FOnLocalizeSymbol write FOnLocalizeSymbol;
property OnLocalizeString : TLocalizeStringEvent read FOnLocalizeString write FOnLocalizeString;
end;
// TdwsCustomLocalizer
//
TdwsCustomLocalizer = class (TdwsLocalizerComponent)
private
FOnLocalizeSymbol : TLocalizeSymbolEvent;
FOnLocalizeString : TLocalizeStringEvent;
FOnGetLocalizer : TGetLocalizerEvent;
public
function GetLocalizer : IdwsLocalizer; override;
published
property OnLocalizeSymbol : TLocalizeSymbolEvent read FOnLocalizeSymbol write FOnLocalizeSymbol;
property OnLocalizeString : TLocalizeStringEvent read FOnLocalizeString write FOnLocalizeString;
property OnGetLocalizer : TGetLocalizerEvent read FOnGetLocalizer write FOnGetLocalizer;
end;
// TdwsAbstractUnit
//
TdwsAbstractUnit = class(TComponent, IUnknown, IdwsUnit)
private
FDependencies : TStrings;
FScript : TDelphiWebScript;
FUnitName : UnicodeString;
FDeprecatedMessage : UnicodeString;
FImplicitUse : Boolean;
function GetDependencies: TStrings;
procedure SetDependencies(const Value: TStrings);
procedure SetScript(const Value: TDelphiWebScript);
procedure SetUnitName(const Value: UnicodeString);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetUnitName: UnicodeString; virtual;
function GetUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; rootTable : TSymbolTable) : TUnitSymbolTable; virtual; abstract;
function GetUnitFlags : TIdwsUnitFlags;
function GetDeprecatedMessage : UnicodeString;
property Dependencies: TStrings read FDependencies write SetDependencies;
{$WARNINGS OFF}
property UnitName: UnicodeString read GetUnitName write SetUnitName;
{$WARNINGS ON}
property DeprecatedMessage : UnicodeString read FDeprecatedMessage write FDeprecatedMessage;
property ImplicitUse : Boolean read FImplicitUse write FImplicitUse;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Script: TDelphiWebScript read FScript write SetScript;
end;
TSymbolTableType = (sttDefault, sttStatic, sttLinked);
// TdwsAbstractStaticUnit
//
TdwsAbstractStaticUnit = class(TdwsAbstractUnit)
private
FStaticSymbols : Boolean;
FStaticTable : IStaticSymbolTable;
protected
function GetUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; rootTable : TSymbolTable) : TUnitSymbolTable; override;
function CreateUnitTable(parent, rootTable: TSymbolTable; tableType: TSymbolTableType): TUnitSymbolTable; virtual;
procedure SetStaticSymbols(const Value: Boolean); // static symbols
procedure InitUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; UnitTable: TUnitSymbolTable); virtual;
procedure AddUnitSymbols(systemTable : TSystemSymbolTable; table : TSymbolTable; operators : TOperators); virtual; abstract;
property StaticSymbols : Boolean read FStaticSymbols write SetStaticSymbols;
property StaticTable : IStaticSymbolTable read FStaticTable;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeforeDestruction; override;
function InitStaticSymbols(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols; operators : TOperators): Boolean;
procedure ReleaseStaticSymbols;
end;
TDataType = UnicodeString;
TdwsUnit = class;
TdwsGlobal = class;
TdwsSymbol = class(TCollectionItem)
private
FName: UnicodeString;
FIsGenerating: Boolean;
FUnit: TdwsUnit;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure CheckName(aTable : TSymbolTable; const aName : UnicodeString; overloaded : Boolean = False);
function GetDataType(systemTable : TSystemSymbolTable; aTable : TSymbolTable; const aName : UnicodeString) : TTypeSymbol;
procedure Reset;
procedure SetName(const val : UnicodeString);
function Parse(const Value : UnicodeString): UnicodeString; virtual;
property IsGenerating: Boolean read FIsGenerating write FIsGenerating;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
function Generate(systemTable : TSystemSymbolTable; table: TSymbolTable; parentSym: TSymbol = nil): TSymbol;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol; virtual; abstract;
function GetNamePath: String; override;
function GetUnit: TdwsUnit;
published
property Name: UnicodeString read FName write SetName;
end;
TdwsSymbolArray = array of TdwsSymbol;
TdwsSymbolClass = class of TdwsSymbol;
TdwsCollection = class(TOwnedCollection)
private
FUnit: TdwsUnit;
protected
class function GetSymbolClass : TdwsSymbolClass; virtual; abstract;
function GetSymbols(const Name: UnicodeString): TdwsSymbol;
function GetItem(Index: Integer): TdwsSymbol;
procedure SetItem(Index: Integer; Value: TdwsSymbol);
procedure Reset;
public
constructor Create(AOwner: TPersistent);
function GetOwner: TPersistent; override;
function GetUnit: TdwsUnit;
function IndexOf(const Name: UnicodeString): Integer;
property Symbols[const Name: UnicodeString]: TdwsSymbol read GetSymbols;
property Items[Index: Integer]: TdwsSymbol read GetItem write SetItem;
end;
TdwsVariable = class(TdwsSymbol)
private
FDataType: TDataType;
protected
function GetDisplayName: String; override;
public
procedure Assign(Source: TPersistent); override;
published
property DataType: TDataType read FDataType write FDataType;
end;
TdwsVariables = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
function GetDisplayName: String;
public
function Add : TdwsGlobal; overload;
function Add(const name, typName : UnicodeString) : TdwsGlobal; overload;
end;
TdwsVariablesClass = class of TdwsVariables;
// TdwsParameter
//
TdwsParameter = class(TdwsVariable)
private
FIsVarParam : Boolean;
FIsLazy : Boolean;
FIsWritable : Boolean;
FDefaultValue : Variant;
FHasDefaultValue : Boolean;
protected
procedure SetIsVarParam(const Value: Boolean);
procedure SetHasDefaultValue(const Value: Boolean);
procedure SetIsWritable(const Value: Boolean);
procedure SetIsLazy(const val : Boolean);
procedure SetDefaultValue(const Value: Variant);
function GetDisplayName: String; override;
function Parse(const Value : UnicodeString): UnicodeString; override;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol; override;
// not supported here yet, experimental
property IsLazy : Boolean read FIsLazy write SetIsLazy default False;
published
property IsVarParam : Boolean read FIsVarParam write SetIsVarParam default False;
property IsWritable : Boolean read FIsWritable write SetIsWritable default True;
property HasDefaultValue : Boolean read FHasDefaultValue write SetHasDefaultValue default False;
property DefaultValue: Variant read FDefaultValue write SetDefaultValue;
end;
TdwsParameters = class(TdwsVariables)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsParameter; overload; inline;
function Add(const name, typeName : UnicodeString) : TdwsParameter; overload;
end;
TFuncEvalEvent = procedure(info : TProgramInfo) of object;
TFuncFastEvalEvent = function(const args : TExprBaseListExec) : Variant of object;
TInitSymbolEvent = procedure(sender : TObject; symbol : TSymbol) of object;
TInitExprEvent = procedure(sender : TObject; expr : TExprBase) of object;
TdwsCallable = class(TInterfacedSelfObject, IExecutable, ICallable)
private
FOwner : TObject;
FOnInitSymbol : TInitSymbolEvent;
FOnInitExpr : TInitExprEvent;
protected
procedure Call(exec : TdwsProgramExecution; func : TFuncSymbol); virtual; abstract;
procedure InitSymbol(symbol : TSymbol; const msgs : TdwsCompileMessageList);
procedure InitExpression(expr : TExprBase);
function SubExpr(i : Integer) : TExprBase;
function SubExprCount : Integer;
public
constructor Create(owner : TObject);
property OnInitSymbol : TInitSymbolEvent read FOnInitSymbol write FOnInitSymbol;
property OnInitExpr : TInitExprEvent read FOnInitExpr write FOnInitExpr;
end;
TdwsFunctionCallable = class(TdwsCallable)
private
FOnEval : TFuncEvalEvent;
protected
procedure Call(exec : TdwsProgramExecution; func : TFuncSymbol); override;
public
property OnEval : TFuncEvalEvent read FOnEval write FOnEval;
end;
TdwsFunctionSymbol = class(TdwsSymbol)
private
FResultType : TDataType;
FParameters : TdwsParameters;
FDeprecated : UnicodeString;
FCallable : TdwsCallable;
FOverloaded : Boolean;
protected
function GetDisplayName: String; override;
procedure SetResultType(const val : TDataType); virtual;
procedure SetParameters(const Value: TdwsParameters);
function GetOnInitExpr : TInitExprEvent;
procedure SetOnInitExpr(const val : TInitExprEvent);
function GetOnInitSymbol : TInitSymbolEvent;
procedure SetOnInitSymbol(const val : TInitSymbolEvent);
function StoreParameters : Boolean;
function Parse(const Value : UnicodeString): UnicodeString; override;
procedure SetMethodType(const value: TTokenType); virtual;
public
constructor Create(collection : TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
function GetParameters(systemTable : TSystemSymbolTable; Table: TSymbolTable): TParamArray;
published
property Parameters : TdwsParameters read FParameters write SetParameters stored StoreParameters;
property ResultType : TDataType read FResultType write SetResultType;
property OnInitSymbol : TInitSymbolEvent read GetOnInitSymbol write SetOnInitSymbol;
property OnInitExpr : TInitExprEvent read GetOnInitExpr write SetOnInitExpr;
property Deprecated : UnicodeString read FDeprecated write FDeprecated;
property Overloaded : Boolean read FOverloaded write FOverloaded default False;
end;
TdwsFunction = class(TdwsFunctionSymbol)
private
FOnFastEval : TFuncFastEvalEvent;
protected
function GetOnEval : TFuncEvalEvent;
procedure SetOnEval(const val : TFuncEvalEvent);
public
constructor Create(collection : TCollection); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol; override;
published
property OnEval : TFuncEvalEvent read GetOnEval write SetOnEval;
property OnFastEval : TFuncFastEvalEvent read FOnFastEval write FOnFastEval;
end;
TdwsFunctions = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsFunction; overload; inline;
function Add(const name : UnicodeString; const resultType : UnicodeString = '') : TdwsFunction; overload;
end;
TdwsFunctionsClass = class of TdwsFunctions;
// It would have better sense to derive both TdwsFunctionSymbol and TdwsDelegate
// from a common ancestor.
TdwsDelegate = class(TdwsSymbol)
private
FResultType : TDataType;
FParameters : TdwsParameters;
FDeprecated : UnicodeString;
protected
function GetDisplayName: String; override;
procedure SetResultType(const Value: TDataType); virtual;
procedure SetParameters(const Value: TdwsParameters);
function StoreParameters : Boolean;
function Parse(const Value : UnicodeString): UnicodeString; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol; override;
function GetParameters(systemTable : TSystemSymbolTable; Table: TSymbolTable): TParamArray;
published
property Parameters : TdwsParameters read FParameters write SetParameters stored StoreParameters;
property ResultType : TDataType read FResultType write SetResultType;
property Deprecated : UnicodeString read FDeprecated write FDeprecated;
end;
TdwsDelegates = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add: TdwsDelegate; overload; inline;
function Add(const Name: UnicodeString; const ResultType: UnicodeString = '') : TdwsDelegate; overload;
end;
TdwsDelegatesClass = class of TdwsDelegates;
TdwsArray = class(TdwsSymbol)
private
FDataType: TDataType;
FLowBound: Integer;
FHighBound: Integer;
protected
procedure SetIsDynamic(const Value: Boolean);
function GetIsDynamic: Boolean;
function GetDisplayName: String; override;
function GetBoundStored: Boolean;
public
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
override;
procedure Assign(Source: TPersistent); override;
published
property DataType: TDataType read FDataType write FDataType;
property LowBound: Integer read FLowBound write FLowBound stored GetBoundStored;
property HighBound: Integer read FHighBound write FHighBound stored GetBoundStored;
property IsDynamic: Boolean read GetIsDynamic write SetIsDynamic default False;
end;
TdwsArrays = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsArray;
end;
TdwsArraysClass = class of TdwsArrays;
TdwsConstant = class(TdwsVariable)
protected
FValue: Variant;
function GetDisplayName: String; override;
public
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Value: Variant read FValue write FValue;
end;
TdwsConstants = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsConstant; inline;
end;
TdwsConstantsClass = class of TdwsConstants;
TdwsForward = class(TdwsSymbol)
protected
function GetDisplayName: String; override;
public
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
end;
TdwsForwards = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsForward; inline;
end;
TdwsForwardsClass = class of TdwsForwards;
TdwsField = class(TdwsVariable)
private
FVisibility : TdwsVisibility;
FDefaultValue : Variant;
FHasDefaultValue : Boolean;
protected
function GetDisplayName: String; override;
procedure SetDefaultValue(const Value: Variant);
function GetHasDefaultValue : Boolean;
function Parse(const Value : UnicodeString): UnicodeString; override;
public
constructor Create(Collection: TCollection); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Visibility : TdwsVisibility read FVisibility write FVisibility default cvPublic;
property DefaultValue : Variant read FDefaultValue write SetDefaultValue stored GetHasDefaultValue;
property HasDefaultValue : Boolean read FHasDefaultValue write FHasDefaultValue default False;
end;
TdwsFields = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsField;
end;
TdwsProperty = class(TdwsSymbol)
private
FDataType: TDataType;
FReadAccess: UnicodeString;
FWriteAccess: UnicodeString;
FParameters: TdwsParameters;
FDeprecated : UnicodeString;
FIndexValue: Variant;
FIsDefault: Boolean;
FIndexType: TDataType;
FVisibility : TdwsVisibility;
procedure SetReadAccess(const Value: UnicodeString);
procedure SetWriteAccess(const Value: UnicodeString);
protected
function GetDisplayName: String; override;
function GetIsDefault: Boolean;
procedure SetIsDefault(Value: Boolean);
procedure SetParameters(const Value: TdwsParameters);
function StoreParameters : Boolean;
function Parse(const Value : UnicodeString): UnicodeString; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property DataType: TDataType read FDataType write FDataType;
property Deprecated : UnicodeString read FDeprecated write FDeprecated;
property Visibility : TdwsVisibility read FVisibility write FVisibility default cvPublic;
property ReadAccess: UnicodeString read FReadAccess write SetReadAccess;
property WriteAccess: UnicodeString read FWriteAccess write SetWriteAccess;
property Parameters: TdwsParameters read FParameters write SetParameters stored StoreParameters;
property IsDefault: Boolean read GetIsDefault write SetIsDefault default False;
property IndexType: TDataType read FIndexType write FIndexType;
property IndexValue: Variant read FIndexValue write FIndexValue;
end;
TdwsProperties = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsProperty;
end;
TdwsClassOperator = class(TdwsSymbol)
private
FOperator: TTokenType;
FDataType: TDataType;
FUsesAccess: UnicodeString;
protected
function GetDisplayName: String; override;
public
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property DataType: TDataType read FDataType write FDataType;
property &Operator : TTokenType read FOperator write FOperator;
property UsesAccess : UnicodeString read FUsesAccess write FUsesAccess;
end;
TdwsClassOperators = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
end;
TdwsTypeSymbol = class(TCollectionItem)
private
FName: UnicodeString;
protected
function GetDisplayName: String; override;
public
procedure Assign(Source: TPersistent); override;
published
property Name : UnicodeString read FName write FName;
end;
TdwsTypeSymbols = class(TOwnedCollection)
public
constructor Create(AOwner: TPersistent);
function Add : TdwsTypeSymbol;
end;
TdwsOperator = class(TdwsSymbol)
private
FOperator: TTokenType;
FResultType: TDataType;
FParams : TdwsTypeSymbols;
FUsesAccess: UnicodeString;
protected
function GetDisplayName: String; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property ResultType : TDataType read FResultType write FResultType;
property Params : TdwsTypeSymbols read FParams write FParams;
property &Operator : TTokenType read FOperator write FOperator;
property UsesAccess : UnicodeString read FUsesAccess write FUsesAccess;
end;
TdwsOperators = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsOperator;
end;
TdwsOperatorsClass = class of TdwsOperators;
TAssignExternalObjectEvent = procedure(Info: TProgramInfo; var ExtObject: TObject) of object;
TMethodEvalEvent = procedure(Info: TProgramInfo; ExtObject: TObject) of object;
TdwsMethodCallable = class(TdwsCallable)
private
FOnEval : TMethodEvalEvent;
protected
procedure Call(exec : TdwsProgramExecution; func : TFuncSymbol); override;
public
property OnEval : TMethodEvalEvent read FOnEval write FOnEval;
end;
TdwsMethod = class(TdwsFunctionSymbol)
private
FAttributes : TMethodAttributes;
FKind : TMethodKind;
FVisibility : TdwsVisibility;
protected
function GetDisplayName: String; override;
function GetOnEval : TMethodEvalEvent;
procedure SetOnEval(const val : TMethodEvalEvent);
procedure SetResultType(const val : TDataType); override;
procedure SetAttributes(const attribs : TMethodAttributes);
procedure SetMethodType(const value: TTokenType); override;
public
constructor Create(collection : TCollection); override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Attributes: TMethodAttributes read FAttributes write SetAttributes default [];
property OnEval : TMethodEvalEvent read GetOnEval write SetOnEval;
property Visibility : TdwsVisibility read FVisibility write FVisibility default cvPublic;
property Kind: TMethodKind read FKind write FKind;
end;
TdwsMethods = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsMethod; overload; inline;
function Add(const name : UnicodeString; const resultType : UnicodeString = '') : TdwsMethod; overload;
end;
TdwsConstructorCallable = class(TdwsCallable)
private
FOnEval : TAssignExternalObjectEvent;
protected
procedure Call(exec : TdwsProgramExecution; func : TFuncSymbol); override;
public
property OnEval : TAssignExternalObjectEvent read FOnEval write FOnEval;
end;
TdwsConstructor = class(TdwsFunctionSymbol)
private
FAttributes: TMethodAttributes;
FVisibility : TdwsVisibility;
protected
function GetResultType: UnicodeString;
function GetDisplayName: String; override;
function GetOnEval : TAssignExternalObjectEvent;
procedure SetOnEval(const val : TAssignExternalObjectEvent);
procedure SetAttributes(const attribs : TMethodAttributes);
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Visibility : TdwsVisibility read FVisibility write FVisibility default cvPublic;
property OnEval : TAssignExternalObjectEvent read GetOnEval write SetOnEval;
property Attributes: TMethodAttributes read FAttributes write SetAttributes default [];
property ResultType: UnicodeString read GetResultType;
end;
TdwsConstructors = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsConstructor;
end;
TdwsClassConstant = class(TdwsConstant)
private
FVisibility : TdwsVisibility;
protected
function GetDisplayName: String; override;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Visibility : TdwsVisibility read FVisibility write FVisibility default cvPublic;
end;
TdwsClassConstants = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsClassConstant;
end;
// TdwsClass
//
TdwsClass = class(TdwsSymbol)
private
FAncestor : UnicodeString;
FConstructors : TdwsConstructors;
FFields : TdwsFields;
FMethods : TdwsMethods;
FOnObjectDestroy : TObjectDestroyEvent;
FProperties : TdwsProperties;
FOperators : TdwsClassOperators;
FConstants : TdwsClassConstants;
FHelperObject : TObject;
FIsSealed : Boolean;
FIsAbstract : Boolean;
FIsStatic : Boolean;
FDeprecated : String;
protected
function GetDisplayName : String; override;
function StoreConstructors : Boolean;
function StoreFields : Boolean;
function StoreMethods : Boolean;
function StoreOperators : Boolean;
function StoreConstants : Boolean;
function StoreProperties : Boolean;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
{: User-side helper object, freed by the TdwsClass. }
property HelperObject : TObject read FHelperObject write FHelperObject;
published
property Ancestor : UnicodeString read FAncestor write FAncestor;
property IsSealed : Boolean read FIsSealed write FIsSealed default False;
property IsAbstract : Boolean read FIsAbstract write FIsAbstract default False;
property IsStatic : Boolean read FIsStatic write FIsStatic default False;
property Deprecated : String read FDeprecated write FDeprecated;
property Constructors : TdwsConstructors read FConstructors write FConstructors stored StoreConstructors;
property Fields : TdwsFields read FFields write FFields stored StoreFields;
property Methods : TdwsMethods read FMethods write FMethods stored StoreMethods;
property Operators : TdwsClassOperators read FOperators write FOperators stored StoreOperators;
property Constants : TdwsClassConstants read FConstants write FConstants stored StoreConstants;
property Properties: TdwsProperties read FProperties write FProperties stored StoreProperties;
property OnCleanUp : TObjectDestroyEvent read FOnObjectDestroy write FOnObjectDestroy;
end;
TdwsClasses = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsClass;
end;
TdwsClassesClass = class of TdwsClasses;
// TdwsInterface
//
TdwsInterface = class(TdwsSymbol)
private
FAncestor : UnicodeString;
FMethods : TdwsMethods;
FProperties : TdwsProperties;
protected
function GetDisplayName : String; override;
function StoreMethods : Boolean;
function StoreProperties : Boolean;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Ancestor : UnicodeString read FAncestor write FAncestor;
property Methods : TdwsMethods read FMethods write FMethods stored StoreMethods;
property Properties: TdwsProperties read FProperties write FProperties stored StoreProperties;
end;
TdwsInterfaces = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsInterface;
end;
TdwsInterfacesClass = class of TdwsInterfaces;
TdwsMember = class(TdwsVariable)
private
FVisibility : TdwsVisibility;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Visibility : TdwsVisibility read FVisibility write FVisibility default cvPublic;
end;
TdwsMembers = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsMember; inline;
end;
TdwsRecord = class(TdwsSymbol)
private
FMembers : TdwsMembers;
FProperties : TdwsProperties;
protected
function GetDisplayName: String; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Members : TdwsMembers read FMembers write FMembers;
property Properties : TdwsProperties read FProperties write FProperties;
end;
TdwsRecords = class(TdwsCollection)
protected
class function GetSymbolClass: TdwsSymbolClass; override;
public
function Add : TdwsRecord; inline;
end;
TdwsRecordsClass = class of TdwsRecords;
TdwsElement = class(TdwsSymbol)
private
FIsUserDef: Boolean;
FUserDefValue: Integer;
procedure SetUserDefValue(const Value: Integer);
procedure SetIsUserDef(const Value: Boolean);
protected
function GetDisplayName: String; override;
public
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property UserDefValue : Integer read FUserDefValue write SetUserDefValue default 0;
property IsUserDef : Boolean read FIsUserDef write SetIsUserDef default False;
end;
TdwsElements = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsElement; inline;
end;
TdwsEnumeration = class(TdwsSymbol)
private
FElements: TdwsElements;
FStyle : TEnumerationSymbolStyle;
protected
function GetDisplayName: String; override;
function Parse(const Value : UnicodeString): UnicodeString; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property Elements: TdwsElements read FElements write FElements;
property Style : TEnumerationSymbolStyle read FStyle write FStyle default enumClassic;
end;
TdwsEnumerations = class(TdwsCollection)
protected
class function GetSymbolClass: TdwsSymbolClass; override;
public
function Add : TdwsEnumeration;
end;
TdwsEnumerationsClass = class of TdwsEnumerations;
TdwsSet = class(TdwsSymbol)
private
FBaseType : TDataType;
protected
function GetDisplayName: String; override;
function Parse(const Value : UnicodeString): UnicodeString; override;
public
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
published
property BaseType : TDataType read FBaseType write FBaseType;
end;
TdwsSets = class(TdwsCollection)
protected
class function GetSymbolClass: TdwsSymbolClass; override;
public
function Add : TdwsSet;
end;
TdwsSetsClass = class of TdwsSets;
TdwsCustomInstance = class;
TReadVarEvent = procedure (info: TProgramInfo; var value : Variant) of object;
TWriteVarEvent = procedure (info: TProgramInfo; const value : Variant) of object;
TInstantiateEvent = procedure (info: TProgramInfo; var ExtObject: TObject) of object;
TdwsGlobal = class(TdwsVariable)
private
FOnReadVar: TReadVarEvent;
FOnWriteVar: TWriteVarEvent;
protected
function Parse(const Value : UnicodeString): UnicodeString; override;
public
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
procedure Assign(Source: TPersistent); override;
published
property OnReadVar: TReadVarEvent read FOnReadVar write FOnReadVar;
property OnWriteVar: TWriteVarEvent read FOnWriteVar write FOnWriteVar;
end;
TdwsInstance = class;
TdwsInstances = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsInstance;
end;
TdwsInstancesClass = class of TdwsInstances;
TdwsCustomInstance = class(TdwsVariable)
private
FOnObjectDestroy: TObjectDestroyEvent;
FOnInstantiate: TInstantiateEvent;
FAutoDestroyExternalObject: Boolean;
FOnInitSymbol: TInitSymbolEvent;
FOnInitExpr: TInitExprEvent;
protected
procedure DoDestroy(ExternalObject: TObject); virtual;
procedure DoInstantiate(info : TProgramInfo; var ExternalObject: TObject); virtual;
procedure DoInitSymbol(Sender: TObject; Symbol: TSymbol); virtual;
procedure DoInitExpr(Sender: TObject; Expr: TExprBase); virtual;
public
constructor Create(Collection: TCollection); override;
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
procedure Assign(Source: TPersistent); override;
property AutoDestroyExternalObject: Boolean read FAutoDestroyExternalObject
write FAutoDestroyExternalObject default False;
property OnObjectDestroy: TObjectDestroyEvent read FOnObjectDestroy
write FOnObjectDestroy;
property OnInstantiate: TInstantiateEvent read FOnInstantiate write
FOnInstantiate;
property OnInitSymbol: TInitSymbolEvent read FOnInitSymbol
write FOnInitSymbol;
property OnInitExpr: TInitExprEvent read FOnInitExpr write FOnInitExpr;
end;
TdwsInstance = class(TdwsCustomInstance)
published
property AutoDestroyExternalObject;
property OnObjectDestroy;
property OnInstantiate;
property OnInitSymbol;
property OnInitExpr;
end;
TdwsSynonym = class(TdwsVariable)
public
function DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil): TSymbol; override;
end;
TdwsSynonyms = class(TdwsCollection)
protected
class function GetSymbolClass : TdwsSymbolClass; override;
public
function Add : TdwsSynonym;
end;
TdwsSynonymsClass = class of TdwsSynonyms;
TdwsParseName = (pnAtDesignTimeOnly, pnAlways, pnNever);
// TdwsUnit
//
TdwsUnit = class(TdwsAbstractStaticUnit)
private
FArrays: TdwsArrays;
FClasses: TdwsClasses;
FConstants: TdwsConstants;
FEnumerations: TdwsEnumerations;
FSets: TdwsSets;
FForwards: TdwsForwards;
FFunctions: TdwsFunctions;
FDelegates: TdwsDelegates;
FInstances: TdwsInstances;
FRecords: TdwsRecords;
FInterfaces : TdwsInterfaces;
FSynonyms: TdwsSynonyms;
FVariables: TdwsVariables;
FOperators : TdwsOperators;
FTable: TUnitSymbolTable;
FOnAfterInitUnitTable : TNotifyEvent;
FParseName : TdwsParseName;
protected
FCollections : array[0..13] of TdwsCollection;
class function GetArraysClass : TdwsArraysClass; virtual;
class function GetClassesClass : TdwsClassesClass; virtual;
class function GetConstantsClass : TdwsConstantsClass; virtual;
class function GetEnumerationsClass : TdwsEnumerationsClass; virtual;
class function GetSetsClass : TdwsSetsClass; virtual;
class function GetForwardsClass : TdwsForwardsClass; virtual;
class function GetFunctionsClass : TdwsFunctionsClass; virtual;
class function GetDelegatesClass : TdwsDelegatesClass; virtual;
class function GetInstancesClass : TdwsInstancesClass; virtual;
class function GetRecordsClass : TdwsRecordsClass; virtual;
class function GetInterfacesClass : TdwsInterfacesClass; virtual;
class function GetVariablesClass : TdwsVariablesClass; virtual;
class function GetSynonymsClass : TdwsSynonymsClass; virtual;
class function GetOperatorsClass : TdwsOperatorsClass; virtual;
procedure SetArrays(const Value: TdwsArrays);
procedure SetClasses(const Value: TdwsClasses);
procedure SetConstants(const Value: TdwsConstants);
procedure SetEnumerations(const Value: TdwsEnumerations);
procedure SetSets(const Value: TdwsSets);
procedure SetForwards(const Value: TdwsForwards);
procedure SetFunctions(const Value: TdwsFunctions);
procedure SetDelegates(const Value: TdwsDelegates);
procedure SetRecords(const Value: TdwsRecords);
procedure SetInterfaces(const value : TdwsInterfaces);
procedure SetVariables(const Value: TdwsVariables);
procedure SetInstances(const Value: TdwsInstances);
procedure SetSynonyms(const Value: TdwsSynonyms);
procedure SetOperators(const Value: TdwsOperators);
function StoreArrays : Boolean;
function StoreClasses : Boolean;
function StoreConstants : Boolean;
function StoreEnumerations : Boolean;
function StoreSets : Boolean;
function StoreForwards : Boolean;
function StoreFunctions : Boolean;
function StoreDelegates : Boolean;
function StoreRecords : Boolean;
function StoreInterfaces : Boolean;
function StoreVariables : Boolean;
function StoreInstances : Boolean;
function StoreSynonyms : Boolean;
function StoreOperators : Boolean;
function StoreImplicitUse : Boolean;
function InternalTypeDefined(const name : UnicodeString; visited: TStringList): Boolean;
protected
function GetSymbol(systemTable : TSystemSymbolTable; Table: TSymbolTable; const Name: UnicodeString): TSymbol;
procedure AddCollectionSymbols(aCollection: TdwsCollection;
systemTable : TSystemSymbolTable; Table: TSymbolTable;
operators : TOperators); virtual;
procedure AddUnitSymbols(systemTable : TSystemSymbolTable; Table: TSymbolTable; operators : TOperators); override;
procedure InitUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; UnitTable: TUnitSymbolTable); override;
// Method to support get/set property values for dynamicly registered classes
procedure HandleDynamicCreate(Info: TProgramInfo; var ExtObject: TObject);
procedure HandleDynamicProperty(Info: TProgramInfo; ExtObject: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ShouldParseName(const val : UnicodeString) : Boolean;
function TypeDefined(const name : UnicodeString) : Boolean;
procedure GetDataTypes(List: TStrings);
procedure GetClassTypes(List: TStrings);
procedure ExposeClassToUnit(AClass, AAncestor: TClass; ASearchProgram: TdwsProgram=nil; const ScriptAncestorType: UnicodeString='');
procedure ExposeInstanceToUnit(const AName, AClassType: UnicodeString; AInstance: TObject);
property Table: TUnitSymbolTable read FTable;
published
property Arrays: TdwsArrays read FArrays write SetArrays stored StoreArrays;
property Classes: TdwsClasses read FClasses write SetClasses stored StoreClasses;
property Constants: TdwsConstants read FConstants write SetConstants stored StoreConstants;
property Dependencies;
property Enumerations: TdwsEnumerations read FEnumerations write SetEnumerations stored StoreEnumerations;
property Sets: TdwsSets read FSets write SetSets stored StoreSets;
property Forwards: TdwsForwards read FForwards write SetForwards stored StoreForwards;
property Functions: TdwsFunctions read FFunctions write SetFunctions stored StoreFunctions;
property Delegates: TdwsDelegates read FDelegates write SetDelegates stored StoreDelegates;
property Instances: TdwsInstances read FInstances write SetInstances stored StoreInstances;
property Operators : TdwsOperators read FOperators write SetOperators stored StoreOperators;
property Records : TdwsRecords read FRecords write SetRecords stored StoreRecords;
property Interfaces : TdwsInterfaces read FInterfaces write SetInterfaces stored StoreInterfaces;
property Synonyms: TdwsSynonyms read FSynonyms write SetSynonyms stored StoreSynonyms;
property ParseName : TdwsParseName read FParseName write FParseName default pnAtDesignTimeOnly;
property UnitName;
property DeprecatedMessage;
property ImplicitUse stored StoreImplicitUse;
property Variables : TdwsVariables read FVariables write SetVariables stored StoreVariables;
property StaticSymbols;
property OnAfterInitUnitTable : TNotifyEvent read FOnAfterInitUnitTable write FOnAfterInitUnitTable;
end;
TCustomInstantiateFunc = class (TFunctionPrototype, IUnknown, ICallable)
protected
FClassSym : TClassSymbol;
FDataSym : TDataSymbol;
public
property ClassSym : TClassSymbol read FClassSym write FClassSym;
property DataSym : TDataSymbol read FDataSym write FDataSym;
end;
TDynamicInstantiateFunc = class(TCustomInstantiateFunc)
protected
FExternalObject : TObject;
public
constructor Create(FuncSym: TFuncSymbol; AExternalObject: TObject); virtual;
procedure Call(exec: TdwsProgramExecution; func: TFuncSymbol); override;
end;
TInstantiateFunc = class(TCustomInstantiateFunc)
private
FOnInstantiate : TInstantiateEvent;
FOnObjectDestroy : TObjectDestroyEvent;
FOnInitSymbol : TInitSymbolEvent;
FOnInitExpr : TInitExprEvent;
public
constructor Create(FuncSym: TFuncSymbol);
procedure Call(exec: TdwsProgramExecution; func: TFuncSymbol); override;
procedure InitSymbol(symbol : TSymbol; const msgs : TdwsCompileMessageList); override;
procedure InitExpression(expr : TExprBase); override;
property OnInstantiate : TInstantiateEvent read FOnInstantiate write FOnInstantiate;
property OnObjectDestroy : TObjectDestroyEvent read FOnObjectDestroy write FOnObjectDestroy;
property OnInitSymbol : TInitSymbolEvent read FOnInitSymbol write FOnInitSymbol;
property OnInitExpr : TInitExprEvent read FOnInitExpr write FOnInitExpr;
end;
TReadVarEventFunc = class(TAnonymousFunction)
private
FOnReadVar: TReadVarEvent;
public
procedure Execute(info : TProgramInfo); override;
property OnReadVar: TReadVarEvent read FOnReadVar write FOnReadVar;
end;
TWriteVarEventFunc = class(TAnonymousFunction)
private
FOnWriteVar: TWriteVarEvent;
public
procedure Execute(info : TProgramInfo); override;
property OnWriteVar: TWriteVarEvent read FOnWriteVar write FOnWriteVar;
end;
TReadVarFunc = class(TAnonymousFunction)
private
FData : TData;
FTyp : TTypeSymbol;
public
constructor Create(FuncSym: TFuncSymbol);
procedure Execute(info : TProgramInfo); override;
procedure SetValue(const data : TData; offset : Integer);
end;
TWriteVarFunc = class(TAnonymousFunction)
private
FReadVarFunc : TReadVarFunc;
public
constructor Create(FuncSym: TFuncSymbol; ReadVarFunc: TReadVarFunc);
procedure Execute(info : TProgramInfo); override;
end;
TCustomInternalMagicProcedure = class(TInternalMagicProcedure)
private
FOnFastEval : TFuncFastEvalEvent;
public
procedure DoEvalProc(const args : TExprBaseListExec); override;
end;
TCustomInternalMagicFunction = class(TInternalMagicVariantFunction)
private
FOnFastEval : TFuncFastEvalEvent;
public
function DoEvalAsVariant(const args : TExprBaseListExec) : Variant; override;
end;
TCustomInternalMagicDataFunction = class(TInternalMagicDataFunction)
private
FOnFastEval : TFuncFastEvalEvent;
FSize : Integer;
public
procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override;
end;
// Return the external object for a variable name.
function GetExternalObjForID(Info: TProgramInfo; const AVarName: UnicodeString): TObject;
// Get or create the DWS object ID (like a pointer) for a Delphi object instance.
//function GetOrCreateObjectID(Info: TProgramInfo; AObject: TObject; AClassName: UnicodeString = ''): Integer;
function GetParameters(Symbol: TdwsSymbol; Parameters: TdwsParameters;
systemTable : TSystemSymbolTable; Table: TSymbolTable): TParamArray;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
dwsPascalTokenizer;
type
EGenerationError = class(Exception);
EHandledGenerationError = class(Exception);
// ValueToString
//
function ValueToString(const value : Variant) : UnicodeString;
begin
case VarType(value) of
varEmpty :
Result := 'Unassigned';
varNull :
Result := 'Null';
varString, varUString, varOleStr, varStrArg :
Result := UnicodeFormat('''%s''', [VarToStr(value)]);
varDate :
Result := UnicodeFormat('DateTime(%f)', [TVarData(value).VDate]);
else
VariantToString(value, Result);
end;
end;
function GetExternalObjForID(Info: TProgramInfo; const AVarName: UnicodeString): TObject;
begin
// Get param "Source" as object in Source_Obj
Result := IScriptObj(IUnknown(Info.ValueAsVariant[AVarName])).ExternalObject;
end;
// DoEvalProc
//
procedure TCustomInternalMagicProcedure.DoEvalProc(const args : TExprBaseListExec);
begin
FOnFastEval(args);
end;
// DoEvalAsVariant
//
function TCustomInternalMagicFunction.DoEvalAsVariant(const args : TExprBaseListExec) : Variant;
begin
Result:=FOnFastEval(args);
end;
// DoEval
//
procedure TCustomInternalMagicDataFunction.DoEval(const args : TExprBaseListExec; var result : IDataContext);
var
tmp : Variant;
pvd : PVarData;
begin
tmp:=FOnFastEval(args);
pvd:=@tmp;
Assert(pvd.VType=varUnknown);
result.WriteData(IDataContext(IUnknown(pvd.VUnknown)), FSize);
end;
{ TDelphiWebScript }
// Create
//
constructor TDelphiWebScript.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FUnitName:=SYS_DEFAULT;
FCompiler:=TdwsCompiler.Create;
FConfig:=TdwsConfiguration.Create(Self);
AddUnit(Self);
FExtensions:=TdwsLanguageExtensionAggregator.Create;
FLock:=TFixedCriticalSection.Create;
end;
// Destroy
//
destructor TDelphiWebScript.Destroy;
begin
inherited;
FCompiler:=nil;
FConfig.Free;
FExtensions.Free;
FLock.Free;
end;
function TDelphiWebScript.GetVersion: UnicodeString;
begin
Result := '2.3';
end;
procedure TDelphiWebScript.SetVersion(const Value: UnicodeString);
begin
// This method is needed to make the IDE show the version in
// the object inspector
end;
// GetOnNeedUnit
//
function TDelphiWebScript.GetOnNeedUnit : TdwsOnNeedUnitEvent;
begin
Result:=Config.OnNeedUnit;
end;
// SetOnNeedUnit
//
procedure TDelphiWebScript.SetOnNeedUnit(const val : TdwsOnNeedUnitEvent);
begin
Config.OnNeedUnit:=val;
end;
// GetOnResource
//
function TDelphiWebScript.GetOnResource : TdwsResourceEvent;
begin
Result:=Config.OnResource;
end;
// SetOnResource
//
procedure TDelphiWebScript.SetOnResource(const val : TdwsResourceEvent);
begin
Config.OnResource:=val;
end;
// SetupExtensions
//
procedure TDelphiWebScript.SetupExtensions;
var
c : TdwsCompiler;
begin
c:=FCompiler.Compiler;
if FExtensions.Count>0 then begin
c.StaticExtensionSymbols:=FExtensions.StaticSymbols;
c.OnCreateBaseVariantSymbol:=FExtensions.CreateBaseVariantSymbol;
c.OnCreateSystemSymbols:=FExtensions.CreateSystemSymbols;
c.OnReadInstr:=FExtensions.ReadInstr;
c.OnReadInstrSwitch:=FExtensions.ReadInstrSwitch;
c.OnFindUnknownName:=FExtensions.FindUnknownName;
c.OnReadUnknownName:=FExtensions.ReadUnknownName;
c.OnSectionChanged:=FExtensions.SectionChanged;
c.OnReadScript:=FExtensions.ReadScript;
c.OnGetDefaultEnvironment:=FExtensions.DefaultEnvironment;
c.OnRootExternalClass:=FExtensions.RootExternalClass;
end else begin
c.StaticExtensionSymbols:=True;
c.OnCreateBaseVariantSymbol:=nil;
c.OnCreateSystemSymbols:=nil;
c.OnReadInstr:=nil;
c.OnReadInstrSwitch:=nil;
c.OnFindUnknownName:=nil;
c.OnReadUnknownName:=nil;
c.OnSectionChanged:=nil;
c.OnReadScript:=nil;
c.OnGetDefaultEnvironment:=nil;
c.OnRootExternalClass:=nil;
end;
end;
// Compile
//
function TDelphiWebScript.Compile(const Text: UnicodeString): IdwsProgram;
begin
Lock;
try
SetupExtensions;
Result:=FCompiler.Compile(Text, FConfig);
finally
UnLock;
end;
end;
// RecompileInContext
//
procedure TDelphiWebScript.RecompileInContext(const prog : IdwsProgram; const text : UnicodeString);
begin
Lock;
try
SetupExtensions;
FCompiler.RecompileInContext(prog, text, FConfig);
finally
UnLock;
end;
end;
// AbortCompilation
//
procedure TDelphiWebScript.AbortCompilation;
begin
FCompiler.AbortCompilation;
end;
// AddUnit
//
procedure TDelphiWebScript.AddUnit(const Un: IdwsUnit);
begin
RemoveUnit(Un);
if Assigned(Un) then
FConfig.Units.Add(Un);
end;
// RemoveUnit
//
function TDelphiWebScript.RemoveUnit(const Un: IdwsUnit): Boolean;
var
i : Integer;
begin
i := FConfig.Units.IndexOf(Un);
if i >= 0 then begin
FConfig.Units[i]:=nil;
FConfig.Units.Extract(i);
end;
Result := i >= 0;
end;
// Lock
//
procedure TDelphiWebScript.Lock;
begin
FLock.Enter;
end;
// UnLock
//
procedure TDelphiWebScript.UnLock;
begin
FLock.Leave;
end;
procedure TDelphiWebScript.SetConfig(const Value: TdwsConfiguration);
begin
FConfig.Assign(Value);
end;
// Implementation of TdwsEmptyUnit.AddUnitSymbols
procedure TDelphiWebScript.AddUnitSymbols(SymbolTable: TSymbolTable);
begin
// The TDelphiWebScript component is the unit "Default"
Config.ResultType.AddResultSymbols(SymbolTable);
end;
procedure TDelphiWebScript.SetOnInclude(const Value: TIncludeEvent);
begin
Config.OnInclude := Value;
end;
// GetOnExecutionStarted
//
function TDelphiWebScript.GetOnExecutionStarted : TdwsExecutionEvent;
begin
Result:=Config.OnExecutionStarted;
end;
// SetOnExecutionStarted
//
procedure TDelphiWebScript.SetOnExecutionStarted(const val : TdwsExecutionEvent);
begin
Config.OnExecutionStarted:=val;
end;
// GetOnExecutionEnded
//
function TDelphiWebScript.GetOnExecutionEnded : TdwsExecutionEvent;
begin
Result:=Config.OnExecutionEnded;
end;
// SetOnExecutionEnded
//
procedure TDelphiWebScript.SetOnExecutionEnded(const val : TdwsExecutionEvent);
begin
Config.OnExecutionEnded:=val;
end;
function TDelphiWebScript.GetOnInclude: TIncludeEvent;
begin
Result := Config.OnInclude;
end;
procedure TDelphiWebScript.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
Config.Notification(AComponent, Operation);
if Operation = opRemove then begin
if AComponent is TdwsUnitComponent then
Self.RemoveUnit(TdwsUnitComponent(AComponent))
else if AComponent is TdwsAbstractUnit then
Self.RemoveUnit(TdwsAbstractUnit(AComponent));
end;
end;
{ TdwsCollection }
constructor TdwsCollection.Create;
begin
inherited Create(AOwner, GetSymbolClass);
if AOwner is TdwsUnit then
FUnit := TdwsUnit(AOwner)
else if AOwner is TdwsSymbol then
FUnit := TdwsSymbol(AOwner).GetUnit
else
FUnit := nil;
end;
function TdwsCollection.GetOwner: TPersistent;
begin
Result := inherited GetOwner;
end;
function TdwsCollection.GetUnit: TdwsUnit;
begin
Result := FUnit;
end;
function TdwsCollection.GetItem(Index: Integer): TdwsSymbol;
begin
Result := TdwsSymbol(inherited Items[Index]);
end;
procedure TdwsCollection.Reset;
var
x: Integer;
begin
for x := 0 to Count - 1 do
Items[x].Reset;
end;
procedure TdwsCollection.SetItem(Index: Integer; Value: TdwsSymbol);
begin
Items[Index].Assign(Value);
end;
function TdwsCollection.GetSymbols(const Name: UnicodeString): TdwsSymbol;
var
x: Integer;
begin
for x := 0 to Count - 1 do
begin
Result := Items[x];
if UnicodeSameText(Result.Name,Name) then
Exit;
end;
Result := nil;
end;
function TdwsCollection.IndexOf(const Name: UnicodeString): Integer;
var
x: Integer;
begin
Result := -1;
for x := 0 to Self.Count - 1 do
if UnicodeSameText(Name, Items[x].Name) then
begin
Result := x;
Break;
end;
end;
{ TdwsUnit }
constructor TdwsUnit.Create(AOwner: TComponent);
begin
inherited;
FArrays := GetArraysClass.Create(Self);
FClasses := GetClassesClass.Create(Self);
FConstants := GetConstantsClass.Create(Self);
FEnumerations := GetEnumerationsClass.Create(Self);
FSets := GetSetsClass.Create(Self);
FForwards := GetForwardsClass.Create(Self);
FFunctions := GetFunctionsClass.Create(Self);
FDelegates := GetDelegatesClass.Create(Self);
FRecords := GetRecordsClass.Create(Self);
FInterfaces := GetInterfacesClass.Create(Self);
FVariables := GetVariablesClass.Create(Self);
FInstances := GetInstancesClass.Create(Self);
FSynonyms := GetSynonymsClass.Create(Self);
FOperators := TdwsOperators.Create(Self);
FCollections[0] := FForwards;
FCollections[1] := FEnumerations;
FCollections[2] := FArrays;
FCollections[3] := FRecords;
FCollections[4] := FInterfaces;
FCollections[5] := FClasses;
FCollections[6] := FSynonyms;
FCollections[7] := FFunctions;
FCollections[8] := FVariables;
FCollections[9] := FConstants;
FCollections[10] := FInstances;
FCollections[11] := FOperators;
FCollections[12] := FSets;
FCollections[13] := FDelegates;
FParseName := pnAtDesignTimeOnly;
end;
destructor TdwsUnit.Destroy;
var
i : Integer;
begin
for i:=Low(FCollections) to High(FCollections) do
FCollections[i].Free;
inherited;
end;
// ShouldParseName
//
function TdwsUnit.ShouldParseName(const val : UnicodeString) : Boolean;
var
i : Integer;
begin
if csLoading in ComponentState then Exit(False);
case ParseName of
pnAlways : Result:=True;
pnAtDesignTimeOnly : Result:=csDesigning in ComponentState;
else
Exit(False);
end;
if Result then begin
for i:=1 to Length(val) do begin
case val[i] of
':', '(', '=' : Exit;
end;
end;
Result:=False;
end;
end;
procedure TdwsUnit.AddCollectionSymbols(aCollection: TdwsCollection;
systemTable : TSystemSymbolTable; Table: TSymbolTable; operators : TOperators);
var
y: Integer;
clsName : UnicodeString;
collSym : TdwsSymbol;
sym : TSymbol;
begin
// add all classes as forwards automatically if they aren't there already
for y:=0 to FClasses.Count-1 do begin
clsName:=FClasses.Items[y].Name;
if FForwards.IndexOf(clsName)<0 then
Forwards.Add.Name:=clsName;
end;
for y := 0 to aCollection.Count - 1 do begin
collSym:=TdwsSymbol(aCollection.Items[y]);
if not collSym.IsGenerating then begin
try
sym:=collSym.Generate(systemTable, Table);
if sym is TOperatorSymbol then
operators.RegisterOperator(TOperatorSymbol(sym));
except
on e: Exception do
raise EGenerationError.CreateFmt(UNT_UnitGenerationError,
[UnitName, e.Message]);
end;
end;
end;
end;
procedure TdwsUnit.AddUnitSymbols(systemTable : TSystemSymbolTable; Table: TSymbolTable; operators : TOperators);
var
x: Integer;
begin
for x := Low(FCollections) to High(FCollections) do
FCollections[x].Reset;
for x := Low(FCollections) to High(FCollections) do
AddCollectionSymbols(FCollections[x], systemTable, Table, operators);
end;
procedure TdwsUnit.GetClassTypes(List: TStrings);
var
x : Integer;
sysTable : TSystemSymbolTable;
begin
if not Assigned(List) then
Exit;
if Assigned(FScript) then begin
sysTable:=FScript.Config.SystemSymbols.SymbolTable;
for x:=0 to sysTable.Count - 1 do begin
if sysTable[x] is TClassSymbol then
List.Add(sysTable[x].Name);
end;
end;
for x := 0 to FClasses.Count - 1 do
List.Add(FClasses.Items[x].Name);
end;
procedure TdwsUnit.GetDataTypes(List: TStrings);
var
x, y: Integer;
coll: TdwsCollection;
sysTable : TSystemSymbolTable;
begin
if not Assigned(List) then
Exit;
if Assigned(FScript) then begin
// Add all type symbols from the systemtable
sysTable:=FScript.Config.SystemSymbols.SymbolTable;
for x := 0 to sysTable.Count - 1 do
begin
if sysTable[x] is TTypeSymbol then
List.Add(sysTable[x].Name);
end;
end;
// Only return array-, record- and class symbols, synonyms and enums
for x := 1 to 6 do
begin
coll := FCollections[x];
for y := 0 to coll.Count - 1 do
List.Add(coll.Items[y].Name);
end;
// ...and sets and delegates
for x := 12 to 13 do
begin
coll := FCollections[x];
for y := 0 to coll.Count - 1 do
List.Add(coll.Items[y].Name);
end;
end;
class function TdwsUnit.GetDelegatesClass: TdwsDelegatesClass;
begin
Result := TdwsDelegates;
end;
function TdwsUnit.GetSymbol(systemTable : TSystemSymbolTable; Table: TSymbolTable; const Name: UnicodeString): TSymbol;
procedure RaiseCircularReference(item : TdwsSymbol);
begin
raise Exception.CreateFmt(UNT_CircularReference, [item.ClassName+':'+Name]);
end;
var
x, y: Integer;
item: TdwsSymbol;
coll: TdwsCollection;
begin
Result:=Table.FindSymbol(Name, cvMagic);
if Assigned(Result) then Exit;
for x := Low(FCollections) to High(FCollections) do begin
// Check if the symbol is defined but not yet generated
coll := FCollections[x];
for y := 0 to coll.Count - 1 do begin
item := coll.Items[y];
if UnicodeSameText(item.Name, Name) then begin
// Check for circular references
if item.IsGenerating then
RaiseCircularReference(item);
// Generate the symbol now
try
Result := item.Generate(systemTable, Table);
except
on e: Exception do
raise EHandledGenerationError.Create(e.Message);
end;
Exit;
end;
end;
end;
end;
procedure TdwsUnit.SetArrays(const Value: TdwsArrays);
begin
FArrays.Assign(Value);
end;
procedure TdwsUnit.SetClasses(const Value: TdwsClasses);
begin
FClasses.Assign(Value);
end;
procedure TdwsUnit.SetConstants(const Value: TdwsConstants);
begin
FConstants.Assign(Value);
end;
procedure TdwsUnit.SetDelegates(const Value: TdwsDelegates);
begin
FDelegates.Assign(Value);
end;
procedure TdwsUnit.SetForwards(const Value: TdwsForwards);
begin
FForwards.Assign(Value);
end;
procedure TdwsUnit.SetFunctions(const Value: TdwsFunctions);
begin
FFunctions.Assign(Value);
end;
procedure TdwsUnit.SetRecords(const Value: TdwsRecords);
begin
FRecords.Assign(Value);
end;
// SetInterfaces
//
procedure TdwsUnit.SetInterfaces(const value : TdwsInterfaces);
begin
FInterfaces.Assign(value);
end;
procedure TdwsUnit.SetVariables(const Value: TdwsVariables);
begin
FVariables.Assign(Value);
end;
procedure TdwsUnit.SetEnumerations(const Value: TdwsEnumerations);
begin
FEnumerations.Assign(Value);
end;
procedure TdwsUnit.SetSets(const Value: TdwsSets);
begin
FSets.Assign(Value);
end;
procedure TdwsUnit.SetInstances(const Value: TdwsInstances);
begin
FInstances.Assign(Value);
end;
class function TdwsUnit.GetFunctionsClass: TdwsFunctionsClass;
begin
Result := TdwsFunctions;
end;
class function TdwsUnit.GetArraysClass: TdwsArraysClass;
begin
Result := TdwsArrays;
end;
class function TdwsUnit.GetClassesClass: TdwsClassesClass;
begin
Result := TdwsClasses;
end;
class function TdwsUnit.GetConstantsClass: TdwsConstantsClass;
begin
Result := TdwsConstants;
end;
class function TdwsUnit.GetEnumerationsClass: TdwsEnumerationsClass;
begin
Result := TdwsEnumerations;
end;
class function TdwsUnit.GetSetsClass: TdwsSetsClass;
begin
Result := TdwsSets;
end;
class function TdwsUnit.GetForwardsClass: TdwsForwardsClass;
begin
Result := TdwsForwards;
end;
class function TdwsUnit.GetInstancesClass: TdwsInstancesClass;
begin
Result := TdwsInstances;
end;
class function TdwsUnit.GetRecordsClass: TdwsRecordsClass;
begin
Result := TdwsRecords;
end;
// GetInterfacesClass
//
class function TdwsUnit.GetInterfacesClass : TdwsInterfacesClass;
begin
Result:=TdwsInterfaces;
end;
class function TdwsUnit.GetVariablesClass: TdwsVariablesClass;
begin
Result := TdwsVariables;
end;
class function TdwsUnit.GetSynonymsClass: TdwsSynonymsClass;
begin
Result := TdwsSynonyms;
end;
// GetOperatorsClass
//
class function TdwsUnit.GetOperatorsClass: TdwsOperatorsClass;
begin
Result:=TdwsOperators;
end;
procedure TdwsUnit.SetSynonyms(const Value: TdwsSynonyms);
begin
FSynonyms.Assign(Value);
end;
// SetOperators
//
procedure TdwsUnit.SetOperators(const Value: TdwsOperators);
begin
FOperators.Assign(Value);
end;
// StoreArrays
//
function TdwsUnit.StoreArrays : Boolean;
begin
Result:=FArrays.Count>0;
end;
// StoreClasses
//
function TdwsUnit.StoreClasses : Boolean;
begin
Result:=FClasses.Count>0;
end;
// StoreConstants
//
function TdwsUnit.StoreConstants : Boolean;
begin
Result:=FConstants.Count>0;
end;
function TdwsUnit.StoreDelegates: Boolean;
begin
Result := (FDelegates.Count > 0);
end;
// StoreEnumerations
//
function TdwsUnit.StoreEnumerations : Boolean;
begin
Result:=FEnumerations.Count>0;
end;
// StoreSets
//
function TdwsUnit.StoreSets : Boolean;
begin
Result:=FSets.Count>0;
end;
// StoreForwards
//
function TdwsUnit.StoreForwards : Boolean;
begin
Result:=FForwards.Count>0;
end;
// StoreFunctions
//
function TdwsUnit.StoreFunctions : Boolean;
begin
Result:=FFunctions.Count>0;
end;
// StoreRecords
//
function TdwsUnit.StoreRecords : Boolean;
begin
Result:=FRecords.Count>0;
end;
// StoreInterfaces
//
function TdwsUnit.StoreInterfaces : Boolean;
begin
Result:=(FInterfaces.Count>0);
end;
// StoreVariables
//
function TdwsUnit.StoreVariables : Boolean;
begin
Result:=FVariables.Count>0;
end;
function TdwsUnit.InternalTypeDefined(const name: UnicodeString; visited: TStringList): Boolean;
var
dep: string;
depIdx: integer;
list: TStringList;
begin
visited.Add(self.UnitName);
list := TStringList.Create;
try
self.GetDataTypes(list);
result := list.IndexOf(name) > -1;
finally
list.Free;
end;
for dep in self.Dependencies do
begin
if visited.IndexOf(dep) > -1 then
continue;
depIdx := FScript.FConfig.Units.IndexOfName(dep);
if depIdx > -1 then
result := TdwsUnit(FScript.FConfig.Units.Items[depIdx]).InternalTypeDefined(name, visited);
if result then
exit;
end;
end;
function TdwsUnit.TypeDefined(const name: UnicodeString): Boolean;
var
list: TStringList;
begin
list := TStringList.Create;
try
result := InternalTypeDefined(name, list);
finally
list.Free;
end;
end;
// StoreInstances
//
function TdwsUnit.StoreInstances : Boolean;
begin
Result:=FInstances.Count>0;
end;
// StoreSynonyms
//
function TdwsUnit.StoreSynonyms : Boolean;
begin
Result:=FSynonyms.Count>0;
end;
// StoreOperators
//
function TdwsUnit.StoreOperators : Boolean;
begin
Result:=FOperators.Count>0;
end;
// StoreImplicitUse
//
function TdwsUnit.StoreImplicitUse : Boolean;
begin
Result:=ImplicitUse;
end;
procedure TdwsUnit.HandleDynamicProperty(Info: TProgramInfo; ExtObject: TObject);
var
propName: UnicodeString;
param: TParamSymbol;
setValue: Variant;
begin
{ NOTE: Special handling is required for Boolean types. At least with Delphi 5 }
if (Info.FuncSym is TMethodSymbol) and Assigned(ExtObject) then
begin
propName := StrDeleteLeft(Info.FuncSym.Name, 3); // get property name. Trim off Get/Set prefix
case TMethodSymbol(Info.FuncSym).Kind of
fkFunction : // function is a "Get" method
begin
{ Return property value for property GetXXX function }
// Class
if Info.FuncSym.Typ is TClassSymbol then // don't free the object instance returned
Info.ResultAsVariant := Info.RegisterExternalObject(GetObjectProp(ExtObject, propName), False, False) // wrap as best we can (find a match)
// Boolean
else if ASCIISameText(Info.FuncSym.Typ.Name, SYS_BOOLEAN) then
Info.ResultAsBoolean := Boolean(GetOrdProp(ExtObject, propName))
// All others
else
Info.ResultAsVariant := GetPropValue(ExtObject, propName);
end;
fkProcedure : // procedure is a "Set" method
begin
// Set property value for property SetXXX function
if Info.FuncSym.Params.Count > 0 then
begin
param := Info.FuncSym.Params.Symbols[0] as TParamSymbol;
// fetch param value by name
VarCopy(setValue, Info.Data[ param.Name ][0]);
// Class
if param.Typ is TClassSymbol then
SetObjectProp(ExtObject, propName, Info.GetExternalObjForVar(param.Name))
// Boolean
else if VarType(setValue) = varBoolean then
SetOrdProp(ExtObject, propName, Integer(setValue))
// All others
else
SetPropValue(ExtObject, propName, setValue);
end;
end;
end;
end;
end;
{ AClass is the class to expose to the unit. All published properties of standard
simple datatypes that are supported in DWS will be exposed that were introduced
between AAncestor and AClass. The ScriptAncestorType is the type that will be
used for the new Script class inherited class type. If none is provided then
AAncestor.ClassName is used. }
procedure TdwsUnit.ExposeClassToUnit(AClass, AAncestor: TClass; ASearchProgram: TdwsProgram; const ScriptAncestorType: UnicodeString);
{ Determine if the type is available to the program. If so, add the owning
unit as a dependency. }
function IsTypeSupported(const ATypeName: UnicodeString): Boolean;
var
x: Integer;
list: TStringList;
begin
Result := False;
// if given a compiled program to search through for type declarations
if Assigned(ASearchProgram) then
begin
for x := 0 to ASearchProgram.Table.Count - 1 do
begin
if ASearchProgram.Table.Symbols[x].ClassType=TUnitSymbol then
// unit has the type declared
if TUnitSymbol(ASearchProgram.Table.Symbols[x]).Table.FindLocal(ATypeName) <> nil then
begin
Result := True;
// add the declaring unit as a dependency
if Self.Dependencies.IndexOf(ASearchProgram.Table.Symbols[x].Name) < 0 then
Self.Dependencies.Add(ASearchProgram.Table.Symbols[x].Name);
end;
end;
end
// No compiled program provided. Look up type locally
else
begin
list := TStringList.Create;
try
Self.GetDataTypes(list);
Result := list.IndexOf(ATypeName) >= 0;
finally
list.Free;
end;
end;
end;
var
newForward: TdwsForward;
useClass: TdwsClass;
newCreate: TdwsConstructor;
newMeth: TdwsMethod;
TypeData: PTypeData;
propTypeData: PTypeData;
PropList: PPropList;
PropertyName, PropertyType: UnicodeString;
i: Integer;
Include: Boolean;
getMethName, setMethName: UnicodeString;
propIsDefault: Boolean;
begin
if not Assigned(AClass) then
EXIT;
// Look for the class. If found use it, otherwise create new.
useClass := TdwsClass(Classes.Symbols[AClass.ClassName]);
if not Assigned(useClass) then
begin
// Create the class declaration
useClass := Classes.Add;
if ScriptAncestorType <> '' then
useClass.Ancestor := ScriptAncestorType
else
useClass.Ancestor := AAncestor.ClassName;
useClass.Name := AClass.ClassName;
newCreate := TdwsConstructor(useClass.Constructors.Add);
newCreate.Name := 'Create';
newCreate.OnEval := HandleDynamicCreate;
// Create a forward for the class. Handles all issues with class nestings and orderings
newForward := TdwsForward(Forwards.Add);
newForward.Name := useClass.Name;
end;
{ Adds the published property names in AClass which are declared from AAncestor }
TypeData := GetTypeData(AClass.ClassInfo);
New(PropList);
try
GetPropInfos(AClass.ClassInfo, PropList);
for i := 0 to Pred(TypeData^.PropCount) do
begin
PropertyName := UnicodeString(PropList^[i]^.Name);
propIsDefault := WordBool(PropList^[i]^.Default);
{$ifdef FPC}
propTypeData := GetTypeData(PropList^[i]^.PropType);
{$else}
propTypeData := GetTypeData(PropList^[i]^.PropType^);
{$endif}
Include := True;
if IsTypeSupported(UnicodeString(PropList^[i]^.PropType^.Name)) then
PropertyType := UnicodeString(PropList^[i]^.PropType^.Name)
else
begin
{ NOTE: Could attempt to use the actual type name (ex: TComponentName is a UnicodeString).
This would require trying to find the type when it is not yet compiled
or risking using the type name without the alias being declared.
It is easiest and safest to just support the standard native types. }
case PropList^[i]^.PropType^.Kind of
tkInteger : PropertyType := SYS_INTEGER;
tkFloat : PropertyType := SYS_FLOAT;
tkString, tkLString, tkWString : PropertyType := SYS_STRING;
tkVariant : PropertyType := SYS_VARIANT;
tkEnumeration : // Booleans are reported as enumerations. Only support booleans
begin
{$ifdef FPC}
if propTypeData^.BaseType = TypeInfo(Boolean) then
{$else}
if propTypeData^.BaseType^ = TypeInfo(Boolean) then
{$endif}
PropertyType := SYS_BOOLEAN
else
Include := False;
end;
{ TODO : How to support TDateTime? }
// CreateGetSetMethodsForType(newClass, SYS_DATETIME);
else
Include := False;
end;
end;
{ Include property if it does not exist in AAncestor class. }
// NOTE: In D5, TObject.ClassInfo = nil... would cause AV errors. First test for a valid pointer
if Include and (AAncestor.ClassInfo <> nil) then
Include := (GetPropInfo(AAncestor, PropertyName) = nil);
// if set to include and property not already added
if Include then
begin
getMethName := 'Get'+PropertyName;
setMethName := 'Set'+PropertyName;
// Don't add if already present
if useClass.Methods.Symbols[getMethName] = nil then
begin
// read value
newMeth := (useClass.Methods.Add as TdwsMethod);
newMeth.Name := getMethName;
newMeth.ResultType := PropertyType;
newMeth.OnEval := HandleDynamicProperty;
// write value
newMeth := (useClass.Methods.Add as TdwsMethod);
newMeth.Name := setMethName;
newMeth.OnEval := HandleDynamicProperty;
with newMeth.Parameters.Add do
begin
Name := 'Value';
DataType := PropertyType;
end;
end;
// Create the property that uses the methods
with useClass.Properties.Add as TdwsProperty do
begin
Name := PropertyName;
DataType := PropertyType;
ReadAccess := getMethName;
WriteAccess := setMethName;
IsDefault := propIsDefault;
end;
end;{if Include}
end;{for i}
finally
Dispose(PropList);
end;
end;
procedure TdwsUnit.ExposeInstanceToUnit(const AName, AClassType: UnicodeString;
AInstance: TObject);
var
typSym: TTypeSymbol;
instFunc: TDynamicInstantiateFunc;
externalVar: TExternalVarSymbol;
funcSym: TFuncSymbol;
begin
{ CheckName }
if AName = '' then
raise Exception.Create(UNT_NameIsEmpty);
if Assigned(Table.FindLocal(AName)) then
raise Exception.CreateFmt(UNT_NameAlreadyExists, [AName]);
typSym := Table.FindTypeLocal(AClassType);
// Get the type symbol of this variable
if not (typSym is TTypeSymbol) then
raise Exception.CreateFmt(UNT_DatatypeUnknown, [AClassType]);
if typSym is TClassSymbol then
begin
funcSym := TFuncSymbol.Create('', fkFunction, 1);
funcSym.Typ := typSym;
instFunc := TDynamicInstantiateFunc.Create(funcSym, AInstance);
instFunc.ClassSym := TClassSymbol(typSym);
instFunc.DataSym := TDataSymbol.Create('', typSym);
Table.AddSymbol(instFunc.DataSym);
funcSym.Executable := ICallable(instFunc);
externalVar := TExternalVarSymbol.Create(AName, typSym);
externalVar.ReadFunc := funcSym;
Table.AddSymbol(externalVar);
end
else
raise Exception.CreateFmt(UNT_AutoInstantiateWithoutClass, [AClassType]);
end;
procedure TdwsUnit.InitUnitTable(SystemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols; operators : TOperators; UnitTable: TUnitSymbolTable);
begin
FTable := UnitTable;
try
inherited InitUnitTable(SystemTable, UnitSyms, operators, UnitTable);
if Assigned(FOnAfterInitUnitTable) then
FOnAfterInitUnitTable(Self);
finally
FTable := nil;
end;
end;
procedure TdwsUnit.HandleDynamicCreate(Info: TProgramInfo; var ExtObject: TObject);
begin
{ TODO : If accepted, create a UnicodeString declaration in appropriate unit. }
raise Exception.CreateFmt('Cannot create dynamic class "%s". Must be obtained from supported objects.', [Info.ScriptObj.GetClassSym.Name]);
end;
{ TdwsConstant }
procedure TdwsConstant.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsConstant then
FValue := TdwsConstant(Source).Value;
end;
// DoGenerate
//
function TdwsConstant.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol): TSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
Result:=TConstSymbol.CreateValue(Name, GetDataType(systemTable, Table, DataType), Value);
GetUnit.Table.AddSymbol(Result);
end;
// GetDisplayName
//
function TdwsConstant.GetDisplayName: String;
var
valAsString : UnicodeString;
begin
valAsString:=VarToStr(Value);
if ASCIISameText(DataType, SYS_STRING) then // just for show
valAsString:=''''+valAsString+'''';
Result := Format('const %s: %s = %s;', [Name, DataType, valAsString]);
end;
{ TdwsVariable }
procedure TdwsVariable.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsVariable then
FDataType := TdwsVariable(Source).DataType;
end;
function TdwsVariable.GetDisplayName: String;
begin
Result := Name + ' : ' + DataType;
end;
{ TdwsVariables }
function TdwsVariables.GetDisplayName: String;
var
i: Integer;
begin
if Count > 0 then
begin
Result := Items[0].GetDisplayName;
for i := 1 to Count - 1 do
Result := Result + '; ' + Items[i].GetDisplayName;
end
else
Result := '';
end;
// Add
//
function TdwsVariables.Add : TdwsGlobal;
begin
Result:=TdwsGlobal(inherited Add);
end;
// Add
//
function TdwsVariables.Add(const name, typName : UnicodeString) : TdwsGlobal;
begin
Result:=Add;
Result.Name:=name;
Result.DataType:=typName;
end;
class function TdwsVariables.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsGlobal;
end;
{ TdwsGlobal }
function TdwsGlobal.Parse(const Value : UnicodeString): UnicodeString;
var
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
sourceFile : TSourceFile;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
if tok.TestName then begin
Result := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('name expected');
// check whether data type is present. Otherwise skip parsing
if not tok.TestDelete(ttCOLON) then
Exit;
// set data type
if tok.TestName then begin
DataType := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Data type expected');
tok.EndSourceFile;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
function TdwsGlobal.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol = nil) : TSymbol;
var
typSym: TTypeSymbol;
readEventFunc: TReadVarEventFunc;
writeEventFunc: TWriteVarEventFunc;
readFunc: TReadVarFunc;
funcSym: TFuncSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
// Get the type symbol of this variable
typSym := GetDataType(systemTable, Table, DataType);
if typSym is TArraySymbol then
raise EHandledGenerationError.CreateFmt('Globals of array type not supported: %s in %s', [Name, FUnit.Name]);
if typSym is TRecordSymbol then
raise EHandledGenerationError.CreateFmt('Globals of record type not supported: %s in %s', [Name, FUnit.Name]);
if (Assigned(FOnReadVar) or Assigned(FOnWriteVar)) then begin
Result := TExternalVarSymbol.Create(Name, typSym);
if Assigned(FOnReadVar) then begin
funcSym := TFuncSymbol.Create('', fkFunction, 1);
funcSym.Typ := typSym;
readEventFunc := TReadVarEventFunc.Create(funcSym);
readEventFunc.OnReadVar := FOnReadVar;
funcSym.Executable := ICallable(readEventFunc);
TExternalVarSymbol(Result).ReadFunc := funcSym;
end;
if Assigned(FOnWriteVar) then begin
funcSym := TFuncSymbol.Create('', fkProcedure, 1);
funcSym.AddParam(TParamSymbol.Create('Value', typSym));
writeEventFunc := TWriteVarEventFunc.Create(funcSym);
writeEventFunc.OnWriteVar := FOnWriteVar;
funcSym.Executable := ICallable(writeEventFunc);
TExternalVarSymbol(Result).WriteFunc := funcSym;
end;
end else begin
Result := TExternalVarSymbol.Create(Name, typSym);
funcSym := TFuncSymbol.Create('', fkFunction, 1);
funcSym.Typ := typSym;
readFunc := TReadVarFunc.Create(funcSym);
TExternalVarSymbol(Result).ReadFunc := funcSym;
funcSym := TFuncSymbol.Create('', fkProcedure, 1);
funcSym.AddParam(TParamSymbol.Create('Value', typSym));
TWriteVarFunc.Create(funcSym, readFunc);
TExternalVarSymbol(Result).WriteFunc := funcSym;
end;
GetUnit.Table.AddSymbol(Result);
end;
procedure TdwsGlobal.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsGlobal then
begin
FOnReadVar := TdwsGlobal(Source).OnReadVar;
FOnWriteVar := TdwsGlobal(Source).OnWriteVar;
end;
end;
// ------------------
// ------------------ TDynamicInstantiateFunc ------------------
// ------------------
constructor TDynamicInstantiateFunc.Create(FuncSym: TFuncSymbol;
AExternalObject: TObject);
begin
inherited Create;
FuncSym.Executable := ICallable(Self);
FExternalObject := AExternalObject;
end;
// Call
//
procedure TDynamicInstantiateFunc.Call(exec: TdwsProgramExecution; func: TFuncSymbol);
var
v : Variant;
scriptObj : TScriptObjInstance;
begin
exec.Stack.ReadValue(DataSym.StackAddr, v);
if VarIsEmpty(v) then begin
// First access to this variable. Create object instance!
scriptObj := TScriptObjInstance.Create(FClassSym);
scriptObj.ExternalObject := FExternalObject;
v := IScriptObj(scriptObj);
exec.Stack.WriteValue(DataSym.StackAddr, v);
end;
exec.Stack.WriteValue(exec.Stack.StackPointer+func.Result.StackAddr, v)
end;
// ------------------
// ------------------ TInstantiateFunc ------------------
// ------------------
// Create
//
constructor TInstantiateFunc.Create(FuncSym: TFuncSymbol);
begin
inherited Create;
FuncSym.Executable := ICallable(Self);
end;
procedure TInstantiateFunc.InitSymbol(Symbol: TSymbol; const msgs : TdwsCompileMessageList);
begin
inherited;
if Assigned(FOnInitSymbol) then
FOnInitSymbol(Self,Symbol);
end;
procedure TInstantiateFunc.InitExpression(Expr: TExprBase);
begin
inherited;
if Assigned(FOnInitExpr) then
FOnInitExpr(Self,Expr);
end;
// Call
//
procedure TInstantiateFunc.Call(exec: TdwsProgramExecution; func: TFuncSymbol);
var
p : PVariant;
procedure DoInstantiate;
var
scriptObj : TScriptObjInstance;
extObj : TObject;
info : TProgramInfo;
begin
extObj:=nil;
if Assigned(FOnInstantiate) then begin
info:=exec.AcquireProgramInfo(func);
try
FOnInstantiate(info, extObj);
finally
exec.ReleaseProgramInfo(info);
end;
if extObj=nil then begin
p^ := IUnknown(nil);
exec.Stack.WriteValue(DataSym.StackAddr, p^);
Exit;
end;
end;
scriptObj := TScriptObjInstance.Create(ClassSym);
scriptObj.OnObjectDestroy := OnObjectDestroy;
scriptObj.ExternalObject := extObj;
p^ := IScriptObj(scriptObj);
exec.Stack.WriteValue(DataSym.StackAddr, p^);
end;
begin
p:=@exec.Stack.Data[DataSym.StackAddr];
if VarIsEmpty(p^) then begin
// First access to this variable. Create object instance!
DoInstantiate;
end;
exec.Stack.WriteValue(exec.Stack.StackPointer+func.Result.StackAddr, p^)
end;
// ------------------
// ------------------ TdwsParameter ------------------
// ------------------
procedure TdwsParameter.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsParameter then
begin
FIsVarParam := TdwsParameter(Source).IsVarParam;
FIsWritable := TdwsParameter(Source).IsWritable;
end;
end;
constructor TdwsParameter.Create(Collection: TCollection);
begin
inherited;
FIsWritable := True;
FIsVarParam := False;
FDefaultValue := Unassigned;
FHasDefaultValue := False;
end;
function TdwsParameter.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
//var
// paramSym : TParamSymbol;
// paramType : TTypeSymbol;
// elemSym : TSymbol;
// elemValue : Integer;
begin
Result:=nil;
Assert(False); // shouldn't be used anymore (not sure yet)
// FIsGenerating := True;
// paramType := GetDataType(Table, DataType);
// if IsLazy then
// paramSym:=TLazyParamSymbol.Create(Name, paramType)
// else if IsVarParam then begin
// if IsWritable then
// paramSym := TVarParamSymbol.Create(Name, paramType)
// else paramSym := TConstParamSymbol.Create(Name, paramType)
// end else if HasDefaultValue then begin
// paramSym := TParamSymbolWithDefaultValue.Create(Name, paramType);
// if paramType is TEnumerationSymbol then begin
// elemSym:=TEnumerationSymbol(paramType).Elements.FindLocal(DefaultValue);
// if elemSym=nil then
// elemValue:=DefaultValue
// else elemValue:=TElementSymbol(elemSym).UserDefValue;
// TParamSymbolWithDefaultValue(paramSym).SetDefaultValue(elemValue);
// end else TParamSymbolWithDefaultValue(paramSym).SetDefaultValue(DefaultValue);
// end else begin
// paramSym := TParamSymbol.Create(Name, paramType);
// end;
// Result := paramSym;
end;
function TdwsParameter.GetDisplayName: String;
begin
Result:=inherited GetDisplayName;
if IsVarParam then
if IsWritable then
Result:='var '+Result
else Result:='const '+Result
else if IsLazy then
Result:='lazy '+Result;
if HasDefaultValue then
Result:=Result+Format(' = %s', [ValueToString(DefaultValue)]);
end;
procedure TdwsParameter.SetDefaultValue(const Value: Variant);
begin
FDefaultValue := Value;
FHasDefaultValue := not (FIsVarParam and FIsWritable);
end;
procedure TdwsParameter.SetHasDefaultValue(const Value: Boolean);
begin
FHasDefaultValue := Value and not (FIsVarParam and FIsWritable);
end;
// SetIsVarParam
//
procedure TdwsParameter.SetIsVarParam(const Value: Boolean);
begin
FIsVarParam := Value;
if FIsVarParam and FIsWritable then
FHasDefaultValue := False;
if FIsVarParam then
FIsLazy:=False;
end;
// SetIsWritable
//
procedure TdwsParameter.SetIsWritable(const Value: Boolean);
begin
FIsWritable := Value;
if FIsVarParam and FIsWritable then
FHasDefaultValue := False;
if FIsWritable then
FIsLazy:=False;
end;
// SetIsLazy
//
procedure TdwsParameter.SetIsLazy(const val : Boolean);
begin
FIsLazy:=val;
if FIsLazy then begin
IsVarParam:=False;
IsWritable:=False;
end;
end;
// Parse
//
function TdwsParameter.Parse(const Value : UnicodeString): UnicodeString;
var
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
sourceFile : TSourceFile;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
case tok.TestDeleteAny([ttVAR, ttCONST, ttLAZY]) of
ttVAR : begin
IsVarParam := True;
IsWritable := True;
end;
ttCONST : begin
IsVarParam := True;
IsWritable := False;
end;
ttLAZY : begin
IsLazy := True;
IsWritable := False;
end;
end;
if tok.TestName then begin
Result := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Parameter name expected');
// check whether data type is present. Otherwise skip parsing
if not tok.TestDelete(ttCOLON) then
Exit;
// set data type
if tok.TestName then begin
DataType := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Data type expected');
// check for default value
if tok.TestDelete(ttEQ) then begin
case tok.TestAny([ttStrVal, ttIntVal, ttFloatVal]) of
ttStrVal : begin
DefaultValue := tok.GetToken.AsString;
tok.KillToken;
end;
ttIntVal : begin
DefaultValue := tok.GetToken.FInteger;
tok.KillToken;
end;
ttFloatVal : begin
DefaultValue := tok.GetToken.FFloat;
tok.KillToken;
end;
else
if tok.TestName then begin
DefaultValue := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Default value expected');
end;
end;
tok.EndSourceFile;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
// ------------------
// ------------------ TdwsCallable ------------------
// ------------------
// Create
//
constructor TdwsCallable.Create(owner : TObject);
begin
FOwner:=owner;
_AddRef;
end;
// InitSymbol
//
procedure TdwsCallable.InitSymbol(symbol : TSymbol; const msgs : TdwsCompileMessageList);
begin
if Assigned(FOnInitSymbol) then
FOnInitSymbol(FOwner, symbol);
end;
// InitExpression
//
procedure TdwsCallable.InitExpression(expr : TExprBase);
begin
if Assigned(FOnInitExpr) then
FOnInitExpr(FOwner, expr);
end;
// SubExpr
//
function TdwsCallable.SubExpr(i : Integer) : TExprBase;
begin
Result:=nil;
end;
// SubExprCount
//
function TdwsCallable.SubExprCount : Integer;
begin
Result:=0;
end;
// ------------------
// ------------------ TdwsFunctionCallable ------------------
// ------------------
// Call
//
procedure TdwsFunctionCallable.Call(exec : TdwsProgramExecution; func : TFuncSymbol);
var
info : TProgramInfo;
begin
if Assigned(FOnEval) then begin
info:=exec.AcquireProgramInfo(Func);
try
FOnEval(info);
finally
exec.ReleaseProgramInfo(info);
end;
end;
end;
// ------------------
// ------------------ TdwsFunctionSymbol ------------------
// ------------------
// Create
//
constructor TdwsFunctionSymbol.Create;
begin
inherited;
FParameters:=TdwsParameters.Create(Self);
end;
// Destroy
//
destructor TdwsFunctionSymbol.Destroy;
begin
FCallable._Release;
FCallable:=nil;
FParameters.Free;
inherited;
end;
// SetParameters
//
procedure TdwsFunctionSymbol.SetParameters(const Value: TdwsParameters);
begin
FParameters.Assign(Value);
end;
// GetOnInitExpr
//
function TdwsFunctionSymbol.GetOnInitExpr : TInitExprEvent;
begin
Result:=FCallable.OnInitExpr;
end;
// SetOnInitExpr
//
procedure TdwsFunctionSymbol.SetOnInitExpr(const val : TInitExprEvent);
begin
FCallable.OnInitExpr:=val;
end;
// GetOnInitSymbol
//
function TdwsFunctionSymbol.GetOnInitSymbol : TInitSymbolEvent;
begin
Result:=FCallable.OnInitSymbol;
end;
// SetOnInitSymbol
//
procedure TdwsFunctionSymbol.SetOnInitSymbol(const val : TInitSymbolEvent);
begin
FCallable.OnInitSymbol:=val;
end;
// StoreParameters
//
function TdwsFunctionSymbol.StoreParameters : Boolean;
begin
Result:=(FParameters.Count>0);
end;
// DoGenerate
//
function TdwsFunctionSymbol.DoGenerate(systemTable : TSystemSymbolTable; table : TSymbolTable; parentSym : TSymbol = nil) : TSymbol;
var
funcSym : TFuncSymbol;
begin
FIsGenerating:=True;
CheckName(Table, Name, Overloaded);
if ResultType<>'' then
GetDataType(systemTable, Table, ResultType);
funcSym:=TFuncSymbol.Generate(table, Name, GetParameters(systemTable, table), ResultType);
try
funcSym.Params.AddParent(table);
funcSym.Executable:=FCallable;
funcSym.DeprecatedMessage:=Deprecated;
funcSym.IsOverloaded:=Overloaded;
GetUnit.Table.AddSymbol(funcSym);
except
funcSym.Free;
raise;
end;
Result:=funcSym;
end;
// GetParameters
//
function GetParameters(Symbol: TdwsSymbol; Parameters: TdwsParameters;
systemTable : TSystemSymbolTable; Table: TSymbolTable): TParamArray;
var
i, j, elemValue: Integer;
name, enumValue : UnicodeString;
paramSym, elemSym : TSymbol;
param : TdwsParameter;
begin
SetLength(Result, Parameters.Count);
for i := 0 to Parameters.Count - 1 do begin
param:=TdwsParameter(Parameters.Items[i]);
name := param.Name;
// Check whether parameter name is unique
for j := i - 1 downto 0 do begin
if UnicodeSameText(Result[j].ParamName, name) then
raise Exception.CreateFmt(UNT_ParameterNameAlreadyExists, [name]);
end;
Result[i].IsVarParam := param.IsVarParam and param.IsWritable;
Result[i].IsConstParam := param.IsVarParam and not param.IsWritable;
Result[i].ParamName := name;
Result[i].ParamType := param.DataType;
Result[i].HasDefaultValue := param.HasDefaultValue;
if Result[i].HasDefaultValue then begin
SetLength(Result[i].DefaultValue, 1);
paramSym:=Symbol.GetDataType(systemTable, Table, Result[i].ParamType);
if paramSym is TEnumerationSymbol then begin
enumValue:=param.DefaultValue;
if UnicodeSameText(StrBeforeChar(enumValue, '.'), paramSym.Name) then
enumValue:=StrAfterChar(enumValue, '.');
elemSym:=TEnumerationSymbol(paramSym).Elements.FindLocal(enumValue);
if elemSym=nil then
elemValue:=param.DefaultValue
else elemValue:=TElementSymbol(elemSym).Value;
Result[i].DefaultValue[0] := elemValue;
end else Result[i].DefaultValue[0] := param.DefaultValue;
end else Result[i].DefaultValue := nil;
Symbol.GetUnit.GetSymbol(systemTable, Table, Result[i].ParamType);
end;
end;
function TdwsFunctionSymbol.GetParameters(systemTable : TSystemSymbolTable; Table: TSymbolTable): TParamArray;
begin
Result := dwsComp.GetParameters(Self,Parameters, systemTable, Table);
end;
// GetDisplayName
//
function TdwsFunctionSymbol.GetDisplayName: String;
begin
Result:=Parameters.GetDisplayName;
if Result<>'' then
Result:='('+Result+')';
if ResultType='' then
Result:=Format('procedure %s%s;', [Name, Result])
else Result:=Format('function %s%s : %s;', [Name, Result, ResultType]);
if Overloaded then
Result:=Result+' overloaded;';
if Deprecated<>'' then
Result:=Result+' deprecated;';
end;
// SetResultType
//
procedure TdwsFunctionSymbol.SetResultType(const val : TDataType);
begin
FResultType:=val;
end;
procedure TdwsFunctionSymbol.SetMethodType(const value : TTokenType);
begin
raise Exception.Create('Only methods of a class can be constructors or destructors');
end;
// ParseFunctionName
//
function TdwsFunctionSymbol.Parse(const Value : UnicodeString): UnicodeString;
var
param : TdwsParameter;
params : array of TdwsParameter;
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
tokenType: TTokenType;
methodType: TTokenType;
sourceFile : TSourceFile;
hasName: boolean;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
// check whether tokens are available at all
if not tok.HasTokens then
raise Exception.Create('Token expected');
methodType := tok.TestDeleteAny([ttFUNCTION, ttPROCEDURE, ttMETHOD, ttCONSTRUCTOR, ttDESTRUCTOR]);
if methodType in [ttCONSTRUCTOR, ttDestructor] then
self.SetMethodType(methodType);
hasName := tok.TestName;
tokenType := tok.GetToken.FTyp;
// check for name
if not (hasName or (tokenType <> ttNone)) then
raise Exception.Create('Name expected');
// get name and kill token
Result := tok.GetToken.AsString;
tok.KillToken;
// kill token and eventually ignore additional procedure / function
if tokenType <> ttNone then begin
// check if further tokens are available, if not accept name
if not tok.HasTokens then begin
Result := Value;
Exit;
end;
end;
// check for parameters
if tok.TestDelete(ttBLEFT) then begin
while not tok.TestDelete(ttBRIGHT) do begin
param := Parameters.Add;
case tok.TestDeleteAny([ttVAR, ttCONST, ttLAZY]) of
ttVAR: begin
param.IsVarParam := True;
param.IsWritable := True;
end;
ttCONST: begin
param.IsVarParam := True;
param.IsWritable := False;
end;
ttLAZY: begin
param.IsLazy := True;
param.IsWritable := False;
end;
end;
if tok.TestName then begin
param.Name := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Parameter name expected');
SetLength(params, 1);
Params[0] := param;
while tok.TestDelete(ttCOMMA) do
begin
SetLength(params, length(params) + 1);
param := Parameters.Add;
param.Assign(params[0]);
if tok.TestName then begin
param.Name := tok.GetToken.AsString;
tok.KillToken;
params[high(params)] := param;
end else raise Exception.Create('Parameter name expected');
end;
if not tok.TestDelete(ttCOLON) then
raise Exception.Create('Colon expected');
if tok.TestName then begin
for param in params do
param.DataType := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Data type expected');
// check for default value
if tok.TestDelete(ttEQ) then begin
if length(params) > 1 then
raise Exception.Create('Default value not allowed for a list of more than 1 parameter');
case tok.TestAny([ttStrVal, ttIntVal, ttFloatVal]) of
ttStrVal: begin
params[0].DefaultValue := tok.GetToken.AsString;
tok.KillToken;
end;
ttIntVal: begin
params[0].DefaultValue := tok.GetToken.FInteger;
tok.KillToken;
end;
ttFloatVal: begin
params[0].DefaultValue := tok.GetToken.FFloat;
tok.KillToken;
end;
else
if tok.TestName then begin
params[0].DefaultValue := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Default value expected');
end;
end;
// eventually head over to next parameter
if tok.TestDelete(ttSEMI) then
Continue;
end;
end;
// check for return type
if tok.TestDelete(ttCOLON) then begin
if tok.TestName then begin
ResultType := tok.GetToken.AsString;
tok.KillToken;
end;
end;
tok.EndSourceFile;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
// Assign
//
procedure TdwsFunctionSymbol.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsFunctionSymbol then begin
FResultType := TdwsFunctionSymbol(Source).ResultType;
FParameters.Assign(TdwsFunctionSymbol(Source).Parameters);
FDeprecated:=TdwsFunctionSymbol(Source).Deprecated;
FOverloaded:=TdwsFunctionSymbol(Source).Overloaded;
end;
end;
// ------------------
// ------------------ TdwsFunction ------------------
// ------------------
// Create
//
constructor TdwsFunction.Create;
begin
inherited;
FCallable:=TdwsFunctionCallable.Create(Self);
end;
// DoGenerate
//
function TdwsFunction.DoGenerate(systemTable : TSystemSymbolTable; table : TSymbolTable; parentSym : TSymbol = nil): TSymbol;
var
func : TInternalMagicFunction;
flags : TInternalFunctionFlags;
resType : TTypeSymbol;
begin
if not Assigned(FOnFastEval) then
Exit(inherited DoGenerate(systemTable, Table, parentSym));
FIsGenerating:=True;
CheckName(table, Name);
flags:=[];
if Deprecated<>'' then
Include(flags, iffDeprecated);
if ResultType='' then begin
func:=TCustomInternalMagicProcedure.Create(table, Name, GetParameters(systemTable, table),
ResultType, flags, nil, '');
TCustomInternalMagicProcedure(func).FOnFastEval:=FOnFastEval;
end else begin
resType:=GetDataType(systemTable, table, ResultType);
if resType.Size<>1 then begin
func:=TCustomInternalMagicDataFunction.Create(table, Name, GetParameters(systemTable, table),
ResultType, flags, nil, '');
TCustomInternalMagicDataFunction(func).FOnFastEval:=FOnFastEval;
TCustomInternalMagicDataFunction(func).FSize:=resType.Size;
end else begin
func:=TCustomInternalMagicFunction.Create(table, Name, GetParameters(systemTable, table),
ResultType, flags, nil, '');
TCustomInternalMagicFunction(func).FOnFastEval:=FOnFastEval;
end;
end;
Result:=table.FindLocal(Name) as TMagicFuncSymbol;
end;
//
// GetOnEval
//
function TdwsFunction.GetOnEval : TFuncEvalEvent;
begin
Result:=TdwsFunctionCallable(FCallable).OnEval;
end;
// SetOnEval
//
procedure TdwsFunction.SetOnEval(const val : TFuncEvalEvent);
begin
TdwsFunctionCallable(FCallable).OnEval:=val;
end;
// ------------------
// ------------------ TdwsField ------------------
// ------------------
// Create
//
constructor TdwsField.Create(Collection: TCollection);
begin
inherited;
FVisibility:=cvPublic;
end;
function TdwsField.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
var
data : TData;
begin
FIsGenerating := True;
CheckName(TClassSymbol(ParentSym).Members, Name);
Result := TFieldSymbol.Create(Name, GetDataType(systemTable, Table, DataType), Visibility);
if FHasDefaultValue then begin
SetLength(data, 1);
data[0]:=FDefaultValue;
TFieldSymbol(Result).DefaultValue:=data;
end;
end;
// GetDisplayName
//
function TdwsField.GetDisplayName: String;
begin
Result:=TClassSymbol.VisibilityToString(Visibility)+' '+inherited GetDisplayName;
end;
// SetDefaultValue
//
procedure TdwsField.SetDefaultValue(const Value: Variant);
begin
FDefaultValue:=Value;
FHasDefaultValue:=True;
end;
// GetHasDefaultValue
//
function TdwsField.GetHasDefaultValue : Boolean;
begin
Result:=FHasDefaultValue;
end;
function TdwsField.Parse(const Value : UnicodeString): UnicodeString;
var
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
sourceFile : TSourceFile;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
// check for visibility
case tok.TestDeleteAny([ttPRIVATE, ttPROTECTED, ttPUBLIC, ttPUBLISHED]) of
ttPRIVATE:
Visibility := cvPrivate;
ttPROTECTED:
Visibility := cvProtected;
ttPUBLIC:
Visibility := cvPublic;
ttPUBLISHED:
Visibility := cvPublished;
end;
if tok.TestName then
begin
Result := tok.GetToken.AsString;
tok.KillToken;
end;
// check for return type
if tok.TestDelete(ttCOLON) then begin
if tok.TestName then
begin
DataType := tok.GetToken.AsString;
tok.KillToken;
end;
end;
// check for default value
if tok.TestDelete(ttEQ) then begin
case tok.TestAny([ttStrVal, ttIntVal, ttFloatVal]) of
ttStrVal: begin
DefaultValue := tok.GetToken.AsString;
tok.KillToken;
end;
ttIntVal: begin
DefaultValue := tok.GetToken.FInteger;
tok.KillToken;
end;
ttFloatVal: begin
DefaultValue := tok.GetToken.FFloat;
tok.KillToken;
end;
else
if tok.TestName then begin
DefaultValue := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Default value expected');
end;
end;
tok.EndSourceFile;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
// ------------------
// ------------------ TdwsMethodCallable ------------------
// ------------------
// Call
//
procedure TdwsMethodCallable.Call(exec : TdwsProgramExecution; func : TFuncSymbol);
var
info : TProgramInfo;
isClassMethod : Boolean;
methodSymbol : TMethodSymbol;
begin
if Assigned(FOnEval) then begin
info:=exec.AcquireProgramInfo(func);
try
methodSymbol:=(Func as TMethodSymbol);
isClassMethod:=methodSymbol.IsClassMethod;
if not isClassMethod then
info.PrepareScriptObj;
if Assigned(info.ScriptObj) then begin
FOnEval(info, info.ScriptObj.ExternalObject);
end else if isClassMethod then
FOnEval(info, nil)
else raise Exception.Create('Object not instantiated');
finally
exec.ReleaseProgramInfo(info);
end;
end;
end;
// ------------------
// ------------------ TdwsMethod ------------------
// ------------------
// Create
//
constructor TdwsMethod.Create(Collection: TCollection);
begin
inherited;
FVisibility:=cvPublic;
FCallable:=TdwsMethodCallable.Create(Self);
end;
// DoGenerate
//
function TdwsMethod.DoGenerate(systemTable : TSystemSymbolTable; table : TSymbolTable; parentSym : TSymbol = nil) : TSymbol;
var
methSymbol : TMethodSymbol;
begin
FIsGenerating := True;
CheckName(TClassSymbol(parentSym).Members, Name, Overloaded);
if ResultType <> '' then
GetUnit.GetSymbol(systemTable, table, ResultType);
methSymbol:=TMethodSymbol.Generate(table, Kind, Attributes, Name,
GetParameters(systemTable, table), ResultType,
TClassSymbol(parentSym), Visibility, Overloaded);
try
methSymbol.Params.AddParent(table);
methSymbol.DeprecatedMessage:=Deprecated;
methSymbol.IsOverloaded:=Overloaded;
methSymbol.Executable:=FCallable;
except
methSymbol.Free;
raise;
end;
Result:=methSymbol;
end;
// GetDisplayName
//
function TdwsMethod.GetDisplayName: String;
begin
Result:=Parameters.GetDisplayName;
if Result<>'' then
Result:='('+Result+')';
case FKind of
mkProcedure:
Result:=Format('procedure %s%s;', [Name, Result]);
mkFunction:
Result:=Format('function %s%s : %s;', [Name, Result, ResultType]);
mkMethod:
Result:=Format('method %s%s : %s;', [Name, Result, ResultType]);
mkConstructor:
Result:=Format('constructor %s%s;', [Name, Result]);
mkDestructor:
Result:=Format('destructor %s%s;', [Name, Result]);
mkClassProcedure:
Result:=Format('class procedure %s%s;', [Name, Result]);
mkClassFunction:
Result:=Format('class function %s%s : %s;', [Name, Result, ResultType]);
mkClassMethod:
Result:=Format('class method %s%s : %s;', [Name, Result, ResultType]);
else
Assert(false); // if triggered, this func needs upgrade !
end;
if maStatic in Attributes then
Result:=Result+' static;';
if Deprecated<>'' then
Result:=Result+' deprecated;';
Result:=TClassSymbol.VisibilityToString(Visibility)+' '+Result;
end;
// GetOnEval
//
function TdwsMethod.GetOnEval : TMethodEvalEvent;
begin
Result:=TdwsMethodCallable(FCallable).OnEval;
end;
// SetOnEval
//
procedure TdwsMethod.SetOnEval(const val : TMethodEvalEvent);
begin
TdwsMethodCallable(FCallable).OnEval:=val;
end;
// SetResultType
//
procedure TdwsMethod.SetResultType(const val: TDataType);
begin
inherited;
if val <> '' then begin
case FKind of
mkProcedure:
FKind := mkFunction;
mkClassProcedure:
FKind := mkClassFunction;
end
end else begin
case FKind of
mkFunction:
FKind := mkProcedure;
mkClassFunction:
FKind := mkClassProcedure;
end;
end;
end;
// SetAttributes
//
procedure TdwsMethod.SetAttributes(const attribs : TMethodAttributes);
begin
FAttributes:=attribs;
// normalize attributes
if maOverride in attribs then
Include(FAttributes, maVirtual);
end;
procedure TdwsMethod.SetMethodType(const value: TTokenType);
begin
case value of
ttCONSTRUCTOR: FKind := mkConstructor;
ttDESTRUCTOR: FKind := mkDestructor;
end;
end;
procedure TdwsMethod.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsMethod then
begin
FAttributes := TdwsMethod(Source).Attributes;
FKind := TdwsMethod(Source).Kind;
FResultType := TdwsMethod(Source).ResultType;
FVisibility := TdwsMethod(Source).Visibility;
end;
end;
// ------------------
// ------------------ TdwsConstructorCallable ------------------
// ------------------
// Call
//
procedure TdwsConstructorCallable.Call(exec : TdwsProgramExecution; func : TFuncSymbol);
var
info : TProgramInfo;
extObj : TObject;
begin
info:=exec.AcquireProgramInfo(Func);
try
info.PrepareScriptObj;
if Assigned(FOnEval) then begin
if Assigned(info.ScriptObj) then begin
extObj:=info.ScriptObj.ExternalObject; // may assigned by Info.GetConstructor()
FOnEval(info, extObj);
info.ScriptObj.ExternalObject:=extObj;
end;
end;
finally
exec.ReleaseProgramInfo(info);
end;
end;
// ------------------
// ------------------ TdwsConstructor ------------------
// ------------------
// Create
//
constructor TdwsConstructor.Create(collection : TCollection);
begin
inherited;
// Name the first constructor "Create" by default
if Collection.Count = 1 then
FName := 'Create';
FVisibility:=cvPublic;
FCallable:=TdwsConstructorCallable.Create(Self);
end;
procedure TdwsConstructor.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsMethod then begin
FAttributes := TdwsMethod(Source).Attributes;
FVisibility := TdwsMethod(Source).Visibility;
end;
end;
// DoGenerate
//
function TdwsConstructor.DoGenerate(systemTable : TSystemSymbolTable; table : TSymbolTable; parentSym : TSymbol) : TSymbol;
var
methSymbol : TMethodSymbol;
begin
FIsGenerating := True;
CheckName(TClassSymbol(ParentSym).Members, Name, Overloaded);
methSymbol := TMethodSymbol.Generate(Table, mkConstructor, Attributes, Name,
GetParameters(systemTable, Table), '', TClassSymbol(ParentSym),
Visibility, Overloaded);
try
methSymbol.Params.AddParent(Table);
methSymbol.Executable := FCallable;
except
methSymbol.Free;
raise;
end;
Result:=methSymbol;
end;
function TdwsConstructor.GetDisplayName: String;
begin
Result := Parameters.GetDisplayName;
if Result <> '' then
Result := '(' + Result + ')';
Result:=TClassSymbol.VisibilityToString(Visibility)+Format(' constructor %s%s;', [Name, Result]);
end;
// GetOnEval
//
function TdwsConstructor.GetOnEval : TAssignExternalObjectEvent;
begin
Result:=TdwsConstructorCallable(FCallable).OnEval;
end;
// SetOnEval
//
procedure TdwsConstructor.SetOnEval(const val : TAssignExternalObjectEvent);
begin
TdwsConstructorCallable(FCallable).OnEval:=val;
end;
// SetAttributes
//
procedure TdwsConstructor.SetAttributes(const attribs : TMethodAttributes);
begin
FAttributes:=attribs;
// normalize attributes
if maOverride in attribs then
Include(FAttributes, maVirtual);
end;
function TdwsConstructor.GetResultType: UnicodeString;
begin
// Hides the property "ResultType" in the object inspector
Result := '';
end;
// ------------------
// ------------------ TdwsClassConstant ------------------
// ------------------
// Create
//
constructor TdwsClassConstant.Create(Collection: TCollection);
begin
inherited;
FVisibility:=cvPublic;
end;
// Assign
//
procedure TdwsClassConstant.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsClassConstant then
FVisibility:=TdwsClassConstant(Source).Visibility;
end;
// DoGenerate
//
function TdwsClassConstant.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
Result:=TClassConstSymbol.CreateValue(Name, GetDataType(systemTable, Table, DataType), Value);
TClassConstSymbol(Result).Visibility:=Visibility;
end;
// GetDisplayName
//
function TdwsClassConstant.GetDisplayName: String;
begin
Result:=TClassSymbol.VisibilityToString(Visibility)+' '+inherited GetDisplayName;
end;
// ------------------
// ------------------ TdwsClassConstants ------------------
// ------------------
// GetSymbolClass
//
class function TdwsClassConstants.GetSymbolClass : TdwsSymbolClass;
begin
Result:=TdwsClassConstant;
end;
// Add
//
function TdwsClassConstants.Add : TdwsClassConstant;
begin
Result:=TdwsClassConstant(inherited Add);
end;
// ------------------
// ------------------ TdwsClass ------------------
// ------------------
// Create
//
constructor TdwsClass.Create(Collection: TCollection);
begin
inherited;
FFields := TdwsFields.Create(Self);
FConstructors := TdwsConstructors.Create(Self);
FMethods := TdwsMethods.Create(Self);
FProperties := TdwsProperties.Create(Self);
FOperators := TdwsClassOperators.Create(Self);
FConstants := TdwsClassConstants.Create(Self);
end;
// Destroy
//
destructor TdwsClass.Destroy;
begin
FFields.Free;
FConstructors.Free;
FMethods.Free;
FProperties.Free;
FOperators.Free;
FConstants.Free;
FHelperObject.Free;
inherited;
end;
// Assign
//
procedure TdwsClass.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsClass then begin
FAncestor := TdwsClass(Source).Ancestor;
FFields.Assign(TdwsClass(Source).Fields);
FMethods.Assign(TdwsClass(Source).Methods);
FProperties.Assign(TdwsClass(Source).Properties);
FOperators.Assign(TdwsClass(Source).Operators);
FConstants.Assign(TdwsClass(Source).Constants);
end;
end;
// DoGenerate
//
function TdwsClass.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
var
x : Integer;
sym : TSymbol;
ancestorSym, classSym : TClassSymbol;
begin
FIsGenerating := True;
classSym := nil;
sym := GetUnit.Table.FindSymbol(Name, cvMagic);
if Assigned(sym) then begin
if sym is TClassSymbol then begin
classSym:=TClassSymbol(sym);
if not classSym.IsForwarded then
raise Exception.Create(UNT_ClassAlreadyDefined);
end else begin
raise Exception.CreateFmt(UNT_ClassNameAlreadyDefined,
[Name, sym.Caption]);
end;
end;
if not Assigned(classSym) then
classSym := TClassSymbol.Create(Name, nil);
try
classSym.OnObjectDestroy := FOnObjectDestroy;
if FAncestor = '' then
FAncestor := SYS_TOBJECT;
classSym.IsStatic:=IsStatic;
ancestorSym := TClassSymbol(GetUnit.GetSymbol(systemTable, Table, FAncestor));
if ancestorSym = nil then
raise Exception.CreateFmt(UNT_SuperClassUnknwon, [FAncestor]);
if ancestorSym.IsSealed then
raise Exception.CreateFmt(CPE_ClassIsSealed, [FAncestor]);
classSym.InheritFrom(ancestorSym);
classSym.IsSealed:=IsSealed;
classSym.IsExplicitAbstract:=IsAbstract;
classSym.DeprecatedMessage:=Self.Deprecated;
for x := 0 to FFields.Count - 1 do
classSym.AddField(TFieldSymbol(TdwsField(FFields.Items[x]).Generate(systemTable, Table, classSym)));
for x := 0 to FConstructors.Count - 1 do
classSym.AddMethod(TMethodSymbol(TdwsConstructor(FConstructors.Items[x]).Generate(systemTable, Table, classSym)));
for x := 0 to FMethods.Count - 1 do
classSym.AddMethod(TMethodSymbol(TdwsMethod(FMethods.Items[x]).Generate(systemTable, Table, classSym)));
for x := 0 to FProperties.Count - 1 do
classSym.AddProperty(TPropertySymbol(TdwsProperty(FProperties.Items[x]).Generate(systemTable, Table, classSym)));
for x := 0 to FOperators.Count - 1 do
classSym.AddOperator(TClassOperatorSymbol(TdwsClassOperator(FOperators.Items[x]).Generate(systemTable, Table, classSym)));
for x := 0 to FConstants.Count - 1 do
classSym.AddConst(TClassConstSymbol(TdwsConstant(FConstants.Items[x]).Generate(systemTable, Table, classSym)));
except
if not classSym.IsForwarded then
classSym.Free;
raise;
end;
if classSym.IsForwarded then
classSym.ClearIsForwarded;
Result:=classSym;
end;
function TdwsClass.GetDisplayName: String;
begin
Result:=Name;
if IsAbstract then
Result:=Result+' abstract';
if IsSealed then
Result:=Result+' sealed';
if IsStatic then
Result:=Result+' static';
if Ancestor<>'' then
Result:=Result+' ('+Ancestor+')'
else Result:=Result+' (TObject)';
end;
// StoreConstructors
//
function TdwsClass.StoreConstructors : Boolean;
begin
Result:=(Constructors.Count>0);
end;
// StoreFields
//
function TdwsClass.StoreFields : Boolean;
begin
Result:=(Fields.Count>0);
end;
// StoreMethods
//
function TdwsClass.StoreMethods : Boolean;
begin
Result:=(Methods.Count>0);
end;
// StoreOperators
//
function TdwsClass.StoreOperators : Boolean;
begin
Result:=(Operators.Count>0);
end;
// StoreConstants
//
function TdwsClass.StoreConstants : Boolean;
begin
Result:=(Constants.Count>0);
end;
// StoreProperties
//
function TdwsClass.StoreProperties : Boolean;
begin
Result:=(Properties.Count>0);
end;
{ TdwsMember }
// Create
//
constructor TdwsMember.Create(Collection: TCollection);
begin
inherited;
FVisibility:=cvPublic;
end;
function TdwsMember.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
begin
FIsGenerating := True;
CheckName(TRecordSymbol(ParentSym).Members, Name);
Result := TFieldSymbol.Create(Name, GetDataType(systemTable, Table, DataType), Visibility);
end;
// Assign
//
procedure TdwsMember.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsMember then
FVisibility := TdwsMember(Source).Visibility;
end;
// ------------------
// ------------------ TdwsRecord ------------------
// ------------------
constructor TdwsRecord.Create;
begin
inherited;
FMembers:=TdwsMembers.Create(Self);
FProperties:=TdwsProperties.Create(Self);
end;
destructor TdwsRecord.Destroy;
begin
FProperties.Free;
FMembers.Free;
inherited;
end;
procedure TdwsRecord.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsRecord then begin
FMembers.Assign(TdwsRecord(Source).Members);
FProperties.Assign(TdwsRecord(Source).Properties);
end;
end;
function TdwsRecord.DoGenerate;
var
x : Integer;
begin
FIsGenerating := True;
CheckName(Table, Name);
Result := TRecordSymbol.Create(Name, nil);
try
for x := 0 to FMembers.Count - 1 do
TRecordSymbol(Result).AddField(TFieldSymbol(TdwsMember(FMembers.Items[x]).Generate(systemTable, Table, Result)));
for x := 0 to FProperties.Count - 1 do
TRecordSymbol(Result).AddProperty(TPropertySymbol(TdwsProperty(FProperties.Items[x]).Generate(systemTable, Table, Result)));
GetUnit.Table.AddSymbol(Result);
except
Result.Free;
raise;
end;
end;
function TdwsRecord.GetDisplayName: String;
begin
Result := 'Record ' + Name;
end;
// ------------------
// ------------------ TdwsInterface ------------------
// ------------------
// Create
//
constructor TdwsInterface.Create(Collection: TCollection);
begin
inherited;
FMethods:=TdwsMethods.Create(Self);
FProperties:=TdwsProperties.Create(Self);
end;
// Destroy
//
destructor TdwsInterface.Destroy;
begin
FMethods.Free;
FProperties.Free;
inherited;
end;
// Assign
//
procedure TdwsInterface.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsInterface then begin
FMethods.Assign(TdwsInterface(Source).Methods);
FProperties.Assign(TdwsInterface(Source).Properties);
end;
end;
// DoGenerate
//
function TdwsInterface.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
var
x : Integer;
sym : TSymbol;
intfSym, ancestorSym : TInterfaceSymbol;
begin
FIsGenerating := True;
intfSym := nil;
sym := GetUnit.Table.FindSymbol(Name, cvMagic);
if Assigned(sym) then begin
if sym is TInterfaceSymbol then begin
intfSym:=TInterfaceSymbol(sym);
if not intfSym.IsForwarded then
raise Exception.Create(UNT_InterfaceAlreadyDefined);
end else begin
raise Exception.CreateFmt(UNT_InterfaceNameAlreadyDefined,
[Name, sym.Caption]);
end;
end;
if not Assigned(intfSym) then
intfSym := TInterfaceSymbol.Create(Name, nil);
try
ancestorSym := (GetUnit.GetSymbol(systemTable, Table, FAncestor) as TInterfaceSymbol);
if ancestorSym <> nil then
intfSym.InheritFrom(ancestorSym);
for x := 0 to FMethods.Count - 1 do
intfSym.AddMethod(TMethodSymbol(TdwsMethod(FMethods.Items[x]).Generate(systemTable, Table, intfSym)));
for x := 0 to FProperties.Count - 1 do
intfSym.AddProperty(TPropertySymbol(TdwsProperty(FProperties.Items[x]).Generate(systemTable, Table, intfSym)));
GetUnit.Table.AddSymbol(intfSym);
except
if not intfSym.IsForwarded then
intfSym.Free;
raise;
end;
if intfSym.IsForwarded then
intfSym.ClearIsForwarded;
Result:=intfSym;
end;
// GetDisplayName
//
function TdwsInterface.GetDisplayName : String;
begin
Result:='Interface '+Name;
end;
// StoreMethods
//
function TdwsInterface.StoreMethods : Boolean;
begin
Result:=(FMethods.Count>0);
end;
// StoreProperties
//
function TdwsInterface.StoreProperties : Boolean;
begin
Result:=(FProperties.Count>0);
end;
// ------------------
// ------------------ TdwsInterfaces ------------------
// ------------------
// GetSymbolClass
//
class function TdwsInterfaces.GetSymbolClass : TdwsSymbolClass;
begin
Result:=TdwsInterface;
end;
// Add
//
function TdwsInterfaces.Add : TdwsInterface;
begin
Result:=TdwsInterface(inherited Add);
end;
// ------------------
// ------------------ TdwsArray ------------------
// ------------------
procedure TdwsArray.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsArray then
begin
FDataType := TdwsArray(Source).DataType;
FLowBound := TdwsArray(Source).LowBound;
FHighBound := TdwsArray(Source).HighBound;
end;
end;
function TdwsArray.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
if (LowBound = 0) and (HighBound = -1) then
Result := TDynamicArraySymbol.Create(Name, GetDataType(systemTable, Table, DataType), systemTable.TypInteger)
else
begin
if LowBound > HighBound then
raise Exception.Create(UNT_InvalidArrayBounds);
Result := TStaticArraySymbol.Create(Name, GetDataType(systemTable, Table, DataType),
systemTable.TypInteger,
LowBound, HighBound);
end;
GetUnit.Table.AddSymbol(Result);
end;
function TdwsArray.GetBoundStored: Boolean;
begin
Result := not IsDynamic;
end;
function TdwsArray.GetDisplayName: String;
begin
if IsDynamic then
Result := Format('%s = array of %s', [Name, DataType])
else
Result := Format('%s = array [%d .. %d] of %s', [Name, LowBound, HighBound,
DataType]);
end;
function TdwsArray.GetIsDynamic: Boolean;
begin
Result := (FLowBound = 0) and (FHighBound = -1);
end;
procedure TdwsArray.SetIsDynamic(const Value: Boolean);
begin
if Value then
begin
FLowBound := 0;
FHighBound := -1;
end
else if IsDynamic then
FHighBound := 0;
end;
{ TdwsProperty }
procedure TdwsProperty.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsProperty then
begin
FDataType := TdwsProperty(Source).DataType;
FReadAccess := TdwsProperty(Source).ReadAccess;
FWriteAccess := TdwsProperty(Source).WriteAccess;
FParameters.Assign(TdwsProperty(Source).Parameters);
FIsDefault := TdwsProperty(Source).IsDefault;
FVisibility:=TdwsProperty(Source).Visibility;
end;
end;
constructor TdwsProperty.Create(Collection: TCollection);
begin
inherited;
FParameters := TdwsParameters.Create(Self);
FVisibility:=cvPublic;
end;
destructor TdwsProperty.Destroy;
begin
FParameters.Free;
inherited;
end;
// DoGenerate
//
function TdwsProperty.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil) : TSymbol;
var
sym : TSymbol;
propSym : TPropertySymbol;
indexData : TData;
parent : TCompositeTypeSymbol;
begin
FIsGenerating := True;
if DataType='' then
raise Exception.CreateFmt(UNT_DatatypeNotSpecified, [Name, ParentSym.Name]);
propSym:=TPropertySymbol.Create(Name, GetDataType(systemTable, Table, DataType), Visibility, nil);
Result:=propSym;
propSym.GenerateParams(Table, GetParameters(Self, Parameters, systemTable, Table));
parent:=(ParentSym as TCompositeTypeSymbol);
if FReadAccess <> '' then begin
sym := parent.Members.FindLocal(FReadAccess);
if not Assigned(sym) then
raise Exception.CreateFmt(UNT_ReadAccessNotFound, [ReadAccess]);
propSym.ReadSym := sym;
end;
if FWriteAccess <> '' then begin
sym := parent.Members.FindLocal(FWriteAccess);
if not Assigned(sym) then
raise Exception.CreateFmt(UNT_WriteAccessNotFound, [WriteAccess]);
propSym.WriteSym := sym;
end;
if FIndexType <> '' then begin
SetLength(indexData,1);
indexData[0] := FIndexValue;
propSym.SetIndex(indexData, GetDataType(systemTable, Table, IndexType));
end;
if IsDefault then
parent.DefaultProperty := propSym;
propSym.DeprecatedMessage:=Deprecated;
end;
// GetDisplayName
//
function TdwsProperty.GetDisplayName: String;
begin
Result:=TClassSymbol.VisibilityToString(Visibility)+' property '+Name;
if FParameters.Count>0 then
Result:=Result+'['+FParameters.GetDisplayName+']';
Result:=Result+': '+DataType;
if IndexType<>'' then
Result:=Result+' index '+ValueToString(IndexValue);
if ReadAccess<>'' then
Result:=Result+' read '+ReadAccess;
if WriteAccess<>'' then
Result:=Result+' write '+WriteAccess;
Result:=Result+';';
if IsDefault then
Result:=Result+' default;';
end;
// GetIsDefault
//
function TdwsProperty.GetIsDefault: Boolean;
begin
Result:=FIsDefault and (Parameters.Count>0);
end;
// SetIsDefault
//
procedure TdwsProperty.SetIsDefault(Value: Boolean);
var
i: Integer;
properties: TdwsProperties;
begin
Value := Value and (Parameters.Count > 0);
if IsDefault <> Value then
begin
FIsDefault := Value;
if FIsDefault then
begin
properties := TdwsClass(TdwsCollection(Collection).GetOwner).Properties;
for i := 0 to properties.Count - 1 do
if properties.Items[i] <> Self then
TdwsProperty(properties.Items[i]).FIsDefault := False;
end;
end;
end;
// Parse
//
function TdwsProperty.Parse(const Value : UnicodeString): UnicodeString;
var
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
param: TdwsParameter;
sourceFile : TSourceFile;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
// check for visibility
case tok.TestDeleteAny([ttPRIVATE, ttPROTECTED, ttPUBLIC, ttPUBLISHED]) of
ttPRIVATE:
Visibility := cvPrivate;
ttPROTECTED:
Visibility := cvProtected;
ttPUBLIC:
Visibility := cvPublic;
ttPUBLISHED:
Visibility := cvPublished;
else
if not tok.HasTokens then
Result := Value;
end;
// delete property or set name to 'property' if this is the only token
if tok.TestDelete(ttPROPERTY) then
begin
if not tok.HasTokens then
Result := Value;
end;
// get property name
if tok.TestName then begin
Result := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Property name expected');
if tok.TestDelete(ttALEFT) then
repeat
if not tok.TestName then
raise Exception.Create('Parameter name expected!');
param := Parameters.Add;
param.Name := tok.GetToken.AsString;
tok.KillToken;
if not tok.TestDelete(ttCOLON) then
raise Exception.Create(''':'' expected!');
if not tok.TestName then
raise Exception.Create('Parameter datatype expected!');
param.DataType := tok.GetToken.AsString;
tok.KillToken;
if not tok.HasTokens then
raise Exception.Create(''']'' expected!');
until tok.TestDelete(ttARIGHT);
// check for data type
if not tok.TestDelete(ttCOLON) then
Exit;
if tok.TestName then begin
DataType := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Data type expected');
if tok.TestDelete(ttINDEX) then
begin
case tok.TestAny([ttStrVal, ttIntVal, ttFloatVal]) of
ttStrVal : begin
IndexValue := tok.GetToken.AsString;
IndexType := 'String';
tok.KillToken;
end;
ttIntVal : begin
IndexValue := tok.GetToken.FInteger;
IndexType := 'Integer';
tok.KillToken;
end;
ttFloatVal : begin
IndexValue := tok.GetToken.FFloat;
IndexType := 'Float';
tok.KillToken;
end;
else
if tok.TestName then begin
IndexValue := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Index value expected');
end;
end;
if tok.TestDelete(ttREAD) then
begin
if tok.TestName then begin
ReadAccess := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('ReadAccess expected');
end;
if tok.TestDelete(ttWRITE) then
begin
if tok.TestName then begin
WriteAccess := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('WriteAccess expected');
end;
// eventually delete semicolon
tok.TestDelete(ttSEMI);
IsDefault := tok.TestDelete(ttDEFAULT);
tok.EndSourceFile;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
// SetReadAccess
//
procedure TdwsProperty.SetReadAccess(const Value: UnicodeString);
//var
// cs: TComponentState;
// Obj: TdwsClass;
// Meth: TdwsMethod;
begin
FReadAccess := Value;
// See SetWriteAccess comment for why this was deactivated
(*
cs := FUnit.ComponentState;
if (csDesigning in cs) and not (csLoading in cs) then
begin
Assert(Collection is TdwsProperties);
if TdwsProperties(Collection).Owner is TdwsClass then
begin
Obj := TdwsClass(TdwsProperties(Collection).Owner);
if Obj.FMethods.GetSymbols(FReadAccess) = nil then
begin
Meth := Obj.FMethods.Add;
Meth.FName := FReadAccess;
Meth.Visibility := cvProtected;
Meth.ResultType := DataType;
end;
end
end;
*)
end;
// SetWriteAccess
//
procedure TdwsProperty.SetWriteAccess(const Value: UnicodeString);
//var
// cs: TComponentState;
// Obj: TdwsClass;
// Meth: TdwsMethod;
// Param: TdwsParameter;
begin
FWriteAccess := Value;
// deactivated by EG because when editing the write access field manually
// at design-time, it will create all "intermediate" methods
// f.i. if you type "SetProp", it will create methods "S", "Se", "Set", "SetP", etc.
// if anyone has a solution for that, let me know
(*
cs := FUnit.ComponentState;
if (csDesigning in cs) and not (csLoading in cs) then
begin
Assert(Collection is TdwsProperties);
if TdwsProperties(Collection).Owner is TdwsClass then
begin
Obj := TdwsClass(TdwsProperties(Collection).Owner);
if Obj.FMethods.GetSymbols(FWriteAccess) = nil then
begin
Meth := Obj.FMethods.Add;
Meth.FName := FWriteAccess;
Meth.Visibility := cvPrivate;
Param := Meth.Parameters.Add;
Param.FName := 'value';
Param.DataType := DataType;
Param.IsVarParam := True;
Param.IsWritable := False;
end;
end
end;
*)
end;
// SetParameters
//
procedure TdwsProperty.SetParameters(const Value: TdwsParameters);
begin
FParameters.Assign(Value);
end;
// StoreParameters
//
function TdwsProperty.StoreParameters : Boolean;
begin
Result:=(FParameters.Count>0);
end;
{ TdwsClassOperator }
procedure TdwsClassOperator.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsClassOperator then
begin
FDataType := TdwsClassOperator(Source).DataType;
FUsesAccess := TdwsClassOperator(Source).UsesAccess;
FOperator := TdwsClassOperator(Source).&Operator;
end;
end;
function TdwsClassOperator.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
var
opSymbol : TClassOperatorSymbol;
sym : TSymbol;
begin
FIsGenerating := True;
opSymbol:=TClassOperatorSymbol.Create(FOperator);
Result:=opSymbol;
Result.Typ:=GetDataType(systemTable, Table, DataType);
sym:=TClassSymbol(ParentSym).Members.FindLocal(FUsesAccess);
if (sym=nil) or not (sym is TMethodSymbol) then
raise Exception.CreateFmt(UNT_UsesAccessNotFound, [FUsesAccess]);
opSymbol.UsesSym:=TMethodSymbol(sym);
if opSymbol.UsesSym.Params.Count<>1 then
raise Exception.Create(CPE_SingleParameterExpected);
if opSymbol.UsesSym.Params[0].Typ<>Result.Typ then
raise Exception.CreateFmt(CPE_InvalidParameterType, [opSymbol.UsesSym.Name]);
end;
function TdwsClassOperator.GetDisplayName: String;
begin
Result:=Format('operator %s %s uses %s;', [cTokenStrings[FOperator], DataType, UsesAccess])
end;
{ TdwsSymbol }
constructor TdwsSymbol.Create(Collection: TCollection);
begin
inherited;
FUnit := TdwsCollection(Collection).GetUnit;
end;
function TdwsSymbol.GetUnit: TdwsUnit;
begin
Result := FUnit;
end;
procedure TdwsSymbol.Reset;
begin
FIsGenerating := False;
end;
procedure TdwsSymbol.SetName(const val : UnicodeString);
begin
if FUnit.ShouldParseName(val) then
FName:=Parse(val)
else FName:=val;
end;
function TdwsSymbol.Parse(const Value: UnicodeString): UnicodeString;
begin
Result := Value;
end;
function TdwsSymbol.GetNamePath: String;
begin
if FName <> '' then
Result := Collection.GetNamePath + FName
else
Result := Collection.GetNamePath + IntToStr(Index);
end;
// Generate
//
function TdwsSymbol.Generate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
begin
try
Result := DoGenerate(systemTable, Table, ParentSym);
except
on e: EHandledGenerationError do
raise;
on e: Exception do
raise Exception.CreateFmt(UNT_SymbolGenerationError, [ClassName, Name, e.Message]);
end;
end;
// GetDataType
//
function TdwsSymbol.GetDataType(systemTable : TSystemSymbolTable; aTable : TSymbolTable; const aName : UnicodeString) : TTypeSymbol;
var
sym : TSymbol;
begin
sym := GetUnit.GetSymbol(systemTable, aTable, aName);
if not (sym is TTypeSymbol) then
raise Exception.CreateFmt(UNT_DatatypeUnknown, [aName]);
Result := TTypeSymbol(sym);
end;
// CheckName
//
procedure TdwsSymbol.CheckName(aTable : TSymbolTable; const aName : UnicodeString;
overloaded : Boolean = False);
var
sym : TSymbol;
funcSym : TFuncSymbol;
begin
if aName='' then
raise Exception.Create(UNT_NameIsEmpty);
sym:=aTable.FindLocal(aName);
if Assigned(sym) then begin
if overloaded then begin
funcSym:=sym.AsFuncSymbol;
if (funcSym=nil) or not funcSym.IsOverloaded then
raise Exception.CreateFmt(UNT_PreviousNotOverloaded, [aName]);
end else raise Exception.CreateFmt(UNT_NameAlreadyExists, [aName]);
end;
end;
procedure TdwsSymbol.Assign(Source: TPersistent);
begin
if Source is TdwsSymbol then
FName := TdwsSymbol(Source).Name
else
inherited;
end;
procedure TdwsSymbol.AssignTo(Dest: TPersistent);
begin
if Dest is TdwsSymbol then
TdwsSymbol(Dest).Name := Name
else
inherited;
end;
{ TdwsForward }
function TdwsForward.DoGenerate;
begin
FIsGenerating := True;
CheckName(Table, Name);
Result := TClassSymbol.Create(Name, nil);
TClassSymbol(Result).SetForwardedPos(cNullPos);
GetUnit.Table.AddSymbol(Result);
end;
function TdwsForward.GetDisplayName: String;
begin
Result := Format('type %s = class;', [Name]);
end;
{ TReadVarEventFunc }
procedure TReadVarEventFunc.Execute(info : TProgramInfo);
var
Value: Variant;
begin
VarClear(Value);
if Assigned(FOnReadVar) then
FOnReadVar(info, Value);
Info.ResultAsVariant := Value;
end;
{ TWriteVarEventFunc }
procedure TWriteVarEventFunc.Execute(info : TProgramInfo);
begin
if Assigned(FOnWriteVar) then
FOnWriteVar(Info, Info.ValueAsVariant['Value']);
end;
{ TReadVarFunc }
constructor TReadVarFunc.Create(FuncSym: TFuncSymbol);
begin
inherited;
FTyp := FuncSym.Typ;
SetLength(FData, FTyp.Size);
FTyp.InitData(FData, 0);
end;
procedure TReadVarFunc.Execute(info : TProgramInfo);
begin
Info.Data[SYS_RESULT] := FData;
end;
procedure TReadVarFunc.SetValue(const data : TData; offset : Integer);
begin
DWSCopyData(data, offset, FData, 0, FTyp.Size);
end;
{ TWriteVarFunc }
constructor TWriteVarFunc.Create(FuncSym: TFuncSymbol; ReadVarFunc: TReadVarFunc);
begin
inherited Create(FuncSym);
FReadVarFunc := ReadVarFunc;
end;
procedure TWriteVarFunc.Execute(info : TProgramInfo);
begin
FReadVarFunc.SetValue(info.Execution.Stack.Data, info.Execution.Stack.StackPointer-1);
end;
{ TdwsComponent }
constructor TdwsAbstractUnit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDependencies := TStringList.Create;
end;
destructor TdwsAbstractUnit.Destroy;
begin
Script := nil;
FDependencies.Free;
inherited;
end;
function TdwsAbstractUnit.GetDependencies: TStrings;
begin
Result := FDependencies;
end;
function TdwsAbstractUnit.GetUnitName: UnicodeString;
begin
Result := FUnitName;
end;
// Notification
//
procedure TdwsAbstractUnit.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and (AComponent=FScript) then
SetScript(nil);
end;
procedure TdwsAbstractUnit.SetDependencies(const Value: TStrings);
begin
FDependencies.Assign(Value);
end;
// SetScript
//
procedure TdwsAbstractUnit.SetScript(const Value: TDelphiWebScript);
begin
if Assigned(FScript) then begin
FScript.RemoveUnit(Self);
FScript.RemoveFreeNotification(Self);
end;
FScript := Value;
if Assigned(FScript) then begin
FScript.AddUnit(Self);
FScript.FreeNotification(Self);
end;
end;
procedure TdwsAbstractUnit.SetUnitName(const Value: UnicodeString);
begin
if not (csDesigning in ComponentState) and Assigned(FScript)
and not UnicodeSameText(Value, FUnitName) then
raise Exception.Create(UNT_CantChangeUnitName)
else
FUnitName := Value;
end;
// GetUnitFlags
//
function TdwsAbstractUnit.GetUnitFlags : TIdwsUnitFlags;
begin
if ImplicitUse then
Result:=[ufImplicitUse]
else Result:=[];
end;
// GetDeprecatedMessage
//
function TdwsAbstractUnit.GetDeprecatedMessage : UnicodeString;
begin
Result:=FDeprecatedMessage;
end;
{ TdwsEmptyUnit }
constructor TdwsEmptyUnit.Create(AOwner: TComponent);
begin
inherited;
FDependencies := TStringList.Create;
end;
destructor TdwsEmptyUnit.Destroy;
begin
inherited;
FDependencies.Free;
end;
function TdwsEmptyUnit.GetDependencies: TStrings;
begin
Result := FDependencies;
end;
function TdwsEmptyUnit.GetUnitName: UnicodeString;
begin
Result := FUnitName;
end;
function TdwsEmptyUnit.GetUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; rootTable : TSymbolTable) : TUnitSymbolTable;
var
x : Integer;
sym : TUnitMainSymbol;
begin
Result:=TUnitSymbolTable.Create(systemTable);
try
// insert links to units this unit depends of
for x:=0 to FDependencies.Count-1 do begin
sym:=unitSyms.Find(FDependencies[x]);
sym.ReferenceInSymbolTable(Result, False);
end;
// create the symbols of this unit
AddUnitSymbols(Result);
except
Result.Free;
raise;
end;
end;
// GetUnitFlags
//
function TdwsEmptyUnit.GetUnitFlags : TIdwsUnitFlags;
begin
Result:=[ufImplicitUse];
end;
// GetDeprecatedMessage
//
function TdwsEmptyUnit.GetDeprecatedMessage : UnicodeString;
begin
Result:='';
end;
{ TdwsEmptyUnit }
destructor TdwsUnitComponent.Destroy;
begin
Script := nil;
inherited;
end;
procedure TdwsUnitComponent.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FScript) then
FScript := nil;
end;
procedure TdwsUnitComponent.SetScript(const Value: TDelphiWebScript);
begin
if Assigned(FScript) then
begin
FScript.RemoveUnit(Self);
FScript.RemoveFreeNotification(Self);
end;
FScript := Value;
if Assigned(FScript) then
begin
FScript.AddUnit(Self);
FScript.FreeNotification(Self);
end;
end;
{ TdwsEnumeration }
procedure TdwsEnumeration.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsEnumeration then
FElements.Assign(TdwsEnumeration(Source).Elements);
end;
constructor TdwsEnumeration.Create(Collection: TCollection);
begin
inherited;
FElements := TdwsElements.Create(Self);
FStyle:=enumClassic;
end;
destructor TdwsEnumeration.Destroy;
begin
FElements.Free;
inherited;
end;
// DoGenerate
//
function TdwsEnumeration.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol): TSymbol;
var
i : Integer;
enumSymbol : TEnumerationSymbol;
element : TElementSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
enumSymbol:=TEnumerationSymbol.Create(Name, systemTable.TypInteger, Style);
try
for i:=0 to FElements.Count-1 do begin
element:=(Elements.Items[i] as TdwsElement).Generate(systemTable, table, enumSymbol) as TElementSymbol;
enumSymbol.AddElement(element);
if Style=enumClassic then begin
Table.AddSymbol(element);
element.IncRefCount;
end;
end;
except
enumSymbol.Free;
raise;
end;
Table.AddSymbol(enumSymbol);
Result:=enumSymbol;
end;
// GetDisplayName
//
function TdwsEnumeration.GetDisplayName: String;
var
i : Integer;
begin
Result:=Name+' =';
case Style of
enumScoped : Result:=Result+' enum';
enumFlags : Result:=Result+' flags';
end;
Result:=Result+' (';
for i:=0 to FElements.Count-1 do begin
if i<>0 then
Result:=Result + ', ';
Result:=Result+TdwsElement(FElements.Items[i]).GetDisplayName;
end;
Result:=Result+');';
end;
// Parse
//
function TdwsEnumeration.Parse(const Value : UnicodeString): UnicodeString;
var
element: TdwsElement;
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
tokenType: TTokenType;
sourceFile : TSourceFile;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
// check whether tokens are available at all
if not tok.HasTokens then
raise Exception.Create('Token expected');
tokenType := tok.GetToken.FTyp;
// check for name
if not (tok.TestName or (tokenType <> ttNone)) then
raise Exception.Create('Name expected');
// get name and kill token
Result := tok.GetToken.AsString;
tok.KillToken;
// kill token and eventually ignore additional procedure / function
if tokenType <> ttNone then begin
// check if further tokens are available, if not accept name
if not tok.HasTokens then begin
Result := Value;
Exit;
end;
end;
// check for elements
if tok.TestDelete(ttEQ) then
begin
FElements.Clear;
if tok.TestDelete(ttBLEFT) then
repeat
if tok.TestName then begin
element := FElements.Add;
element.Name := tok.GetToken.AsString;
tok.KillToken;
end else raise Exception.Create('Element name expected');
until not tok.TestDelete(ttCOMMA);
if not tok.TestDelete(ttBRIGHT) then
raise Exception.Create('")" expected');
end;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
{ TdwsElement }
function TdwsElement.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol): TSymbol;
var
enumInt: Integer;
enumSym: TEnumerationSymbol;
begin
FIsGenerating := True;
enumSym := TEnumerationSymbol(ParentSym);
CheckName(enumSym.Elements, Name);
if FIsUserDef then
enumInt := FUserDefValue
else if enumSym.Style=enumFlags then begin
if enumSym.Elements.Count > 0 then
enumInt := TElementSymbol(enumSym.Elements[enumSym.Elements.Count - 1]).Value * 2
else enumInt := 1;
end else begin
if enumSym.Elements.Count > 0 then
enumInt := TElementSymbol(enumSym.Elements[enumSym.Elements.Count - 1]).Value + 1
else enumInt := 0;
end;
Result := TElementSymbol.Create(Name, enumSym, enumInt, FIsUserDef);
end;
function TdwsElement.GetDisplayName: String;
begin
if FIsUserDef then
Result := Name + ' = ' + IntToStr(FUserDefValue)
else
Result := Name;
end;
procedure TdwsElement.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsElement then begin
FIsUserDef := TdwsElement(Source).IsUserDef;
FUserDefValue := TdwsElement(Source).UserDefValue;
end;
end;
procedure TdwsElement.SetIsUserDef(const Value: Boolean);
begin
FIsUserDef := Value;
if not Value then
FUserDefValue := 0;
end;
procedure TdwsElement.SetUserDefValue(const Value: Integer);
begin
FIsUserDef := True;
FUserDefValue := Value;
end;
// ------------------
// ------------------ TdwsCustomInstance ------------------
// ------------------
procedure TdwsCustomInstance.Assign(Source: TPersistent);
begin
inherited;
if Source is TdwsCustomInstance then
begin
FOnInstantiate := TdwsCustomInstance(Source).OnInstantiate;
FOnObjectDestroy := TdwsCustomInstance(Source).OnObjectDestroy;
FAutoDestroyExternalObject := TdwsCustomInstance(Source).AutoDestroyExternalObject;
end;
end;
constructor TdwsCustomInstance.Create(Collection: TCollection);
begin
inherited;
FAutoDestroyExternalObject := False;
end;
procedure TdwsCustomInstance.DoDestroy(ExternalObject: TObject);
begin
if Assigned(FOnObjectDestroy) then
FOnObjectDestroy(ExternalObject);
if FAutoDestroyExternalObject then
ExternalObject.Free;
end;
function TdwsCustomInstance.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable;
ParentSym: TSymbol): TSymbol;
var
typSym: TTypeSymbol;
instFunc: TInstantiateFunc;
funcSym: TFuncSymbol;
dataSym : TDataSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
if Table.AddrGenerator=nil then
raise Exception.Create(UNT_InstancesNotSupportedInStaticUnits);
// Get the type symbol of this variable
typSym := GetDataType(systemTable, Table, DataType);
if typSym is TClassSymbol then
begin
funcSym := TFuncSymbol.Create('', fkFunction, 1);
funcSym.Typ := typSym;
dataSym := TDataSymbol.Create('', typSym);
Table.AddSymbol(dataSym);
instFunc := TInstantiateFunc.Create(funcSym);
instFunc.DataSym := dataSym;
instFunc.FClassSym := TClassSymbol(typSym);
instFunc.OnInstantiate := DoInstantiate;
instFunc.OnObjectDestroy := DoDestroy;
instFunc.OnInitSymbol := DoInitSymbol;
instFunc.OnInitExpr := DoInitExpr;
funcSym.Executable := ICallable(instFunc);
Result := TExternalVarSymbol.Create(Name, typSym);
TExternalVarSymbol(Result).ReadFunc := funcSym;
end
else
raise Exception.CreateFmt(UNT_AutoInstantiateWithoutClass, [DataType]);
GetUnit.Table.AddSymbol(Result);
end;
procedure TdwsCustomInstance.DoInitSymbol(Sender: TObject; Symbol: TSymbol);
begin
if Assigned(FOnInitSymbol) then
FOnInitSymbol(Self,Symbol)
end;
procedure TdwsCustomInstance.DoInitExpr(Sender: TObject; Expr: TExprBase);
begin
if Assigned(FOnInitExpr) then
FOnInitExpr(Self,Expr)
end;
procedure TdwsCustomInstance.DoInstantiate(info : TProgramInfo; var ExternalObject: TObject);
begin
if Assigned(FOnInstantiate) then
FOnInstantiate(info, ExternalObject);
end;
{ TdwsFunctions }
class function TdwsFunctions.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsFunction;
end;
// Add
//
function TdwsFunctions.Add : TdwsFunction;
begin
Result:=TdwsFunction(inherited Add);
end;
// Add
//
function TdwsFunctions.Add(const name : UnicodeString; const resultType : UnicodeString = '') : TdwsFunction;
begin
Result:=Add;
Result.Name:=name;
Result.ResultType:=resultType;
end;
{ TdwsForwards }
class function TdwsForwards.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsForward;
end;
// Add
//
function TdwsForwards.Add : TdwsForward;
begin
Result:=TdwsForward(inherited Add);
end;
{ TdwsEnumerations }
class function TdwsEnumerations.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsEnumeration;
end;
// Add
//
function TdwsEnumerations.Add : TdwsEnumeration;
begin
Result:=TdwsEnumeration(inherited Add);
end;
// ------------------
// ------------------ TdwsSet ------------------
// ------------------
// DoGenerate
//
function TdwsSet.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
var
base: TTypeSymbol;
eBase: TEnumerationSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
base := GetDataType(systemTable, Table, FBaseType);
if not (base is TEnumerationSymbol) then
raise Exception.CreateFmt('Type "%s" is not an enumeration', [FBaseType]);
eBase := TEnumerationSymbol(base);
result := TSetOfSymbol.Create(self.Name, eBase, 0, eBase.HighBound);
Table.AddSymbol(result);
end;
// GetDisplayName
//
function TdwsSet.GetDisplayName: String;
begin
Result:=Name+' = set of '+BaseType;
end;
function TdwsSet.Parse(const Value : UnicodeString): UnicodeString;
var
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
tokenType: TTokenType;
sourceFile : TSourceFile;
begin
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
// check whether tokens are available at all
if not tok.HasTokens then
raise Exception.Create('Token expected');
tokenType := tok.GetToken.FTyp;
// check for name
if not (tok.TestName or (tokenType <> ttNone)) then
raise Exception.Create('Name expected');
// get name and kill token
Result := tok.GetToken.AsString;
tok.KillToken;
// kill token and eventually ignore additional procedure / function
if tokenType <> ttNone then begin
// check if further tokens are available, if not accept name
if not tok.HasTokens then begin
Result := Value;
Exit;
end;
end;
// check for base type
if tok.TestDelete(ttEQ) then
begin
if tok.TestDelete(ttSET) and tok.TestDelete(ttOF) then
begin
if tok.TestName then
FBaseType := tok.GetToken.AsString
else raise Exception.Create('Base type name expected');
end
else raise Exception.Create('"set of" expected');
end;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
// ------------------
// ------------------ TdwsSets ------------------
// ------------------
// GetSymbolClass
//
class function TdwsSets.GetSymbolClass: TdwsSymbolClass;
begin
result := TdwsSet;
end;
function TdwsSets.Add: TdwsSet;
begin
result := inherited Add as TdwsSet;
end;
{ TdwsConstants }
class function TdwsConstants.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsConstant;
end;
// Add
//
function TdwsConstants.Add : TdwsConstant;
begin
Result:=TdwsConstant(inherited Add);
end;
{ TdwsClasses }
class function TdwsClasses.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsClass;
end;
// Add
//
function TdwsClasses.Add : TdwsClass;
begin
Result:=TdwsClass(inherited Add);
end;
{ TdwsArrays }
class function TdwsArrays.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsArray;
end;
function TdwsArrays.Add : TdwsArray;
begin
Result := TdwsArray(inherited Add);
end;
{ TdwsRecords }
class function TdwsRecords.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsRecord;
end;
// Add
//
function TdwsRecords.Add : TdwsRecord;
begin
Result:=TdwsRecord(inherited Add);
end;
{ TdwsParameters }
class function TdwsParameters.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsParameter;
end;
// Add
//
function TdwsParameters.Add : TdwsParameter;
begin
Result:=TdwsParameter(inherited Add);
end;
// Add
//
function TdwsParameters.Add(const name, typeName : UnicodeString) : TdwsParameter;
begin
Result:=Add;
Result.Name:=name;
Result.DataType:=typeName;
end;
{ TdwsInstances }
class function TdwsInstances.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsInstance;
end;
// Add
//
function TdwsInstances.Add : TdwsInstance;
begin
Result:=TdwsInstance(inherited Add);
end;
{ TdwsFields }
class function TdwsFields.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsField;
end;
// Add
//
function TdwsFields.Add : TdwsField;
begin
Result:=TdwsField(inherited Add);
end;
{ TdwsConstructors }
class function TdwsConstructors.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsConstructor;
end;
// Add
//
function TdwsConstructors.Add : TdwsConstructor;
begin
Result:=TdwsConstructor(inherited Add);
end;
{ TdwsMethods }
class function TdwsMethods.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsMethod;
end;
// Add
//
function TdwsMethods.Add : TdwsMethod;
begin
Result:=TdwsMethod(inherited Add);
end;
// Add
//
function TdwsMethods.Add(const name : UnicodeString; const resultType : UnicodeString = '') : TdwsMethod;
begin
Result:=Add;
Result.Name:=name;
Result.ResultType:=resultType;
end;
{ TdwsProperties }
class function TdwsProperties.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsProperty;
end;
// Add
//
function TdwsProperties.Add : TdwsProperty;
begin
Result:=TdwsProperty(inherited Add);
end;
{ TdwsClassOperators }
class function TdwsClassOperators.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsClassOperator;
end;
{ TdwsMembers }
class function TdwsMembers.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsMember;
end;
// Add
//
function TdwsMembers.Add : TdwsMember;
begin
Result:=TdwsMember(inherited Add);
end;
{ TdwsElements }
class function TdwsElements.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsElement;
end;
// Add
//
function TdwsElements.Add : TdwsElement;
begin
Result:=TdwsElement(inherited Add);
end;
{ TdwsSynonyms }
class function TdwsSynonyms.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsSynonym;
end;
// Add
//
function TdwsSynonyms.Add : TdwsSynonym;
begin
Result := TdwsSynonym(inherited Add);
end;
{ TdwsSynonym }
function TdwsSynonym.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol): TSymbol;
begin
FIsGenerating := True;
CheckName(Table, Name);
Result := TAliasSymbol.Create(Name, GetDataType(systemTable, Table, DataType));
GetUnit.Table.AddSymbol(Result);
end;
{ TdwsAbstractStaticUnit }
constructor TdwsAbstractStaticUnit.Create(AOwner: TComponent);
begin
inherited;
FStaticTable := nil;
FStaticSymbols := False;
end;
function TdwsAbstractStaticUnit.CreateUnitTable(parent, rootTable: TSymbolTable; tableType: TSymbolTableType): TUnitSymbolTable;
begin
case tableType of
sttLinked :
Result := TLinkedSymbolTable.Create(Parent as TStaticSymbolTable);
sttStatic :
Result := TStaticSymbolTable.Create(Parent as TStaticSymbolTable);
else
if rootTable=nil then
Result := TUnitSymbolTable.Create(Parent)
else Result := TUnitSymbolTable.Create(Parent, rootTable.AddrGenerator);
end;
end;
procedure TdwsAbstractStaticUnit.BeforeDestruction;
begin
ReleaseStaticSymbols;
inherited;
end;
destructor TdwsAbstractStaticUnit.Destroy;
begin
inherited;
end;
function TdwsAbstractStaticUnit.GetUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; rootTable : TSymbolTable) : TUnitSymbolTable;
begin
if StaticSymbols and InitStaticSymbols(SystemTable, UnitSyms, operators) then
Result := CreateUnitTable(FStaticTable.SymbolTable, nil, sttLinked) as TLinkedSymbolTable // typecheck
else begin
Result := CreateUnitTable(SystemTable, rootTable, sttDefault);
try
InitUnitTable(SystemTable, UnitSyms, operators, Result);
except
Result.Free;
raise;
end;
end;
end;
function TdwsAbstractStaticUnit.InitStaticSymbols(systemTable : TSystemSymbolTable;
unitSyms : TUnitMainSymbols; operators : TOperators): Boolean;
var
staticParent: TStaticSymbolTable;
begin
if not Assigned(FStaticTable) then
begin
staticParent := (SystemTable as TStaticSymbolTable);
if Assigned(staticParent) then
begin
FStaticTable := CreateUnitTable(staticParent, nil, sttStatic) as TStaticSymbolTable;
try
InitUnitTable(SystemTable, UnitSyms, operators, FStaticTable.SymbolTable);
except
ReleaseStaticSymbols;
raise;
end;
end;
end; // else check FSymbolTable = StaticTable
Result := Assigned(FStaticTable);
end;
procedure TdwsAbstractStaticUnit.InitUnitTable(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols;
operators : TOperators; unitTable: TUnitSymbolTable);
var
x : Integer;
sym : TUnitMainSymbol;
begin
if UnitName = '' then
raise Exception.CreateFmt(UNT_UnitNameNotDefined, [Name]);
for x := 0 to FDependencies.Count - 1 do begin
sym := unitSyms.Find(FDependencies[x]);
sym.ReferenceInSymbolTable(unitTable, False);
end;
AddUnitSymbols(systemTable, unitTable, operators);
end;
// ReleaseStaticSymbols
//
procedure TdwsAbstractStaticUnit.ReleaseStaticSymbols;
begin
FStaticTable := nil;
end;
procedure TdwsAbstractStaticUnit.SetStaticSymbols(const Value: Boolean);
begin
FStaticSymbols := Value;
if not FStaticSymbols then
ReleaseStaticSymbols;
end;
// ------------------
// ------------------ TdwsCustomLangageExtension ------------------
// ------------------
// Create
//
constructor TdwsCustomLangageExtension.Create(AOwner: TComponent);
begin
inherited;
FExtension:=CreateExtension;
end;
// Destroy
//
destructor TdwsCustomLangageExtension.Destroy;
begin
inherited;
Script:=nil;
FExtension.Free;
end;
// SetScript
//
procedure TdwsCustomLangageExtension.SetScript(const val : TDelphiWebScript);
begin
if FScript<>nil then begin
FScript.FExtensions.Remove(FExtension);
FScript.RemoveFreeNotification(Self);
end;
FScript:=val;
if FScript<>nil then begin
FScript.FExtensions.Add(FExtension);
FScript.FreeNotification(Self);
end;
end;
// Notification
//
procedure TdwsCustomLangageExtension.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and (AComponent=FScript) then
Script:=nil;
end;
// ------------------
// ------------------ TdwsTypeSymbol ------------------
// ------------------
// GetDisplayName
//
function TdwsTypeSymbol.GetDisplayName: String;
begin
Result:=FName;
end;
// Assign
//
procedure TdwsTypeSymbol.Assign(Source: TPersistent);
begin
if Source is TdwsTypeSymbol then begin
FName := TdwsTypeSymbol(Source).FName;
end else inherited;
end;
// ------------------
// ------------------ TdwsTypeSymbols ------------------
// ------------------
// Create
//
constructor TdwsTypeSymbols.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TdwsTypeSymbol);
end;
// Add
//
function TdwsTypeSymbols.Add : TdwsTypeSymbol;
begin
Result:=TdwsTypeSymbol(inherited Add);
end;
// ------------------
// ------------------ TdwsOperator ------------------
// ------------------
// Create
//
constructor TdwsOperator.Create(Collection: TCollection);
begin
inherited;
FParams:=TdwsTypeSymbols.Create(Self);
end;
// Destroy
//
destructor TdwsOperator.Destroy;
begin
FParams.Free;
inherited;
end;
// GetDisplayName
//
function TdwsOperator.GetDisplayName: String;
var
i : Integer;
begin
Result:='operator '+cTokenStrings[Operator]+' (';
for i:=0 to Params.Count-1 do begin
if i>0 then
Result:=Result+', ';
Result:=Result+Params.Items[i].DisplayName;
end;
Result:=Result+') : '+ResultType+' uses '+UsesAccess;
end;
// Assign
//
procedure TdwsOperator.Assign(Source: TPersistent);
begin
if Source is TdwsOperator then begin
FOperator:=TdwsOperator(Source).FOperator;
FResultType:=TdwsOperator(Source).FResultType;
FUsesAccess:=TdwsOperator(Source).FUsesAccess;
FParams.Assign(TdwsOperator(Source).FParams);
end else inherited;
end;
// DoGenerate
//
function TdwsOperator.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol = nil): TSymbol;
procedure RaiseError;
begin
raise EGenerationError.CreateFmt(UNT_IncorrectOperatorOverload, [DisplayName]);
end;
var
op : TOperatorSymbol;
i : Integer;
typ : TTypeSymbol;
sym : TSymbol;
begin
op:=TOperatorSymbol.Create(Operator);
try
if Params.Count<>2 then
RaiseError;
for i:=0 to Params.Count-1 do begin
typ:=Table.FindTypeSymbol(Params.Items[i].DisplayName, cvMagic);
if (typ=nil) or not typ.IsType then
RaiseError;
op.AddParam(typ);
end;
typ:=Table.FindTypeSymbol(ResultType, cvMagic);
if (typ=nil) or not typ.IsType then
RaiseError;
op.Typ:=typ;
sym:=Table.FindTypeSymbol(UsesAccess, cvMagic);
if (sym=nil) or sym.IsType or (sym.AsFuncSymbol=nil) then
raise Exception.CreateFmt(UNT_UsesAccessNotFound, [UsesAccess]);
op.UsesSym:=sym.AsFuncSymbol;
Table.AddSymbol(op);
except
op.Free;
raise;
end;
Result:=op;
end;
// ------------------
// ------------------ TdwsOperators ------------------
// ------------------
// GetSymbolClass
//
class function TdwsOperators.GetSymbolClass : TdwsSymbolClass;
begin
Result:=TdwsOperator;
end;
// Add
//
function TdwsOperators.Add : TdwsOperator;
begin
Result:=TdwsOperator(inherited Add);
end;
// ------------------
// ------------------ TEventBasedLocalizer ------------------
// ------------------
// LocalizeSymbol
//
procedure TEventBasedLocalizer.LocalizeSymbol(aResSymbol : TResourceStringSymbol; var Result : UnicodeString);
begin
if Assigned(FOnLocalizeSymbol) then
FOnLocalizeSymbol(Sender, aResSymbol, Result)
else LocalizeString(aResSymbol.Value, Result);
end;
// LocalizeString
//
procedure TEventBasedLocalizer.LocalizeString(const aString : UnicodeString; var Result : UnicodeString);
begin
if Assigned(FOnLocalizeString) then
FOnLocalizeString(Sender, aString, Result)
else Result:=aString;
end;
// ------------------
// ------------------ TdwsCustomLocalizer ------------------
// ------------------
// GetLocalizer
//
function TdwsCustomLocalizer.GetLocalizer : IdwsLocalizer;
var
loc : TEventBasedLocalizer;
begin
loc:=TEventBasedLocalizer.Create;
loc.Sender:=Self;
loc.OnLocalizeSymbol:=OnLocalizeSymbol;
loc.OnLocalizeString:=OnLocalizeString;
Result:=loc;
if Assigned(FOnGetLocalizer) then
FOnGetLocalizer(Self, Result);
end;
// -----------------------------------------------------------------------------
//
// TdwsDelegate
//
// -----------------------------------------------------------------------------
procedure TdwsDelegate.Assign(Source: TPersistent);
begin
inherited;
if (Source is TdwsDelegate) then
begin
FResultType := TdwsDelegate(Source).ResultType;
FParameters.Assign(TdwsDelegate(Source).Parameters);
FDeprecated := TdwsDelegate(Source).Deprecated;
end;
end;
// -----------------------------------------------------------------------------
constructor TdwsDelegate.Create(Collection: TCollection);
begin
inherited;
FParameters := TdwsParameters.Create(Self);
end;
// -----------------------------------------------------------------------------
destructor TdwsDelegate.Destroy;
begin
FParameters.Free;
inherited;
end;
// -----------------------------------------------------------------------------
function TdwsDelegate.DoGenerate(systemTable : TSystemSymbolTable; Table: TSymbolTable; ParentSym: TSymbol): TSymbol;
var
FuncSym: TFuncSymbol;
FuncKind: TFuncKind;
Params: TParamArray;
begin
FIsGenerating := True;
CheckName(Table, Name);
if (ResultType <> '') then
begin
GetDataType(systemTable, Table, ResultType);
FuncKind := fkFunction;
end else
FuncKind := fkProcedure;
FuncSym := TFuncSymbol.Create('', FuncKind, -1);
// FuncSym := TFuncSymbol.Generate(Table, Name, GetParameters(Table), ResultType);
try
Params := GetParameters(systemTable, Table);
FuncSym.GenerateParams(Table, Params);
FuncSym.Params.AddParent(Table);
FuncSym.SetName(Name);
FuncSym.SetIsType;
FuncSym.DeprecatedMessage := Deprecated;
GetUnit.Table.AddSymbol(FuncSym);
except
FuncSym.Free;
raise;
end;
Result := FuncSym;
end;
// -----------------------------------------------------------------------------
function TdwsDelegate.GetDisplayName: String;
var
Params: string;
begin
Params := Parameters.GetDisplayName;
if (Params <> '') then
Params := '(' + Params + ')';
if (ResultType = '') then
Result := Format('%s = procedure%s;', [Name, Params])
else
Result := Format('%s = function%s: %s;', [Name, Params, ResultType]);
if (Deprecated <> '') then
Result := Result + ' deprecated;';
end;
// -----------------------------------------------------------------------------
function TdwsDelegate.GetParameters(systemTable : TSystemSymbolTable; Table: TSymbolTable): TParamArray;
begin
Result := dwsComp.GetParameters(Self, Parameters, systemTable, Table);
end;
// -----------------------------------------------------------------------------
function TdwsDelegate.Parse(const Value: UnicodeString): UnicodeString;
var
param : TdwsParameter;
params : array of TdwsParameter;
rules : TPascalTokenizerStateRules;
tok : TTokenizer;
tokenType: TTokenType;
sourceFile : TSourceFile;
begin
(*
** identifier ( parameters ) [: returntype]
*)
rules := TPascalTokenizerStateRules.Create;
tok := TTokenizer.Create(rules, nil);
sourceFile := TSourceFile.Create;
try
sourceFile.Code := Value;
tok.BeginSourceFile(sourceFile);
// check whether tokens are available at all
if not tok.HasTokens then
raise Exception.Create('Token expected');
tokenType := tok.GetToken.FTyp;
// check for name
if not (tok.TestName or (tokenType <> ttNone)) then
raise Exception.Create('Name expected');
// get name and kill token
Result := tok.GetToken.AsString;
tok.KillToken;
// kill token and eventually ignore additional procedure / function
if tokenType <> ttNone then
begin
// check if further tokens are available, if not accept name
if not tok.HasTokens then begin
Result := Value;
Exit;
end;
end;
// check for parameters
if tok.TestDelete(ttBLEFT) then
begin
while not tok.TestDelete(ttBRIGHT) do
begin
param := Parameters.Add;
case tok.TestDeleteAny([ttVAR, ttCONST, ttLAZY]) of
ttVAR:
begin
param.IsVarParam := True;
param.IsWritable := True;
end;
ttCONST:
begin
param.IsVarParam := True;
param.IsWritable := False;
end;
ttLAZY:
begin
param.IsLazy := True;
param.IsWritable := False;
end;
end;
if tok.TestName then
begin
param.Name := tok.GetToken.AsString;
tok.KillToken;
end else
raise Exception.Create('Parameter name expected');
SetLength(params, 1);
Params[0] := param;
while tok.TestDelete(ttCOMMA) do
begin
SetLength(params, length(params) + 1);
param := Parameters.Add;
param.Assign(params[0]);
if tok.TestName then
begin
param.Name := tok.GetToken.AsString;
tok.KillToken;
params[high(params)] := param;
end else
raise Exception.Create('Parameter name expected');
end;
if not tok.TestDelete(ttCOLON) then
raise Exception.Create('Colon expected');
if tok.TestName then
begin
for param in params do
param.DataType := tok.GetToken.AsString;
tok.KillToken;
end else
raise Exception.Create('Data type expected');
// eventually head over to next parameter
if tok.TestDelete(ttSEMI) then
Continue;
end;
end;
// check for return type
if tok.TestDelete(ttCOLON) then
begin
if tok.TestName then
begin
ResultType := tok.GetToken.AsString;
tok.KillToken;
end;
end;
tok.EndSourceFile;
finally
sourceFile.Free;
tok.Free;
rules.Free;
end;
end;
// -----------------------------------------------------------------------------
procedure TdwsDelegate.SetParameters(const Value: TdwsParameters);
begin
FParameters.Assign(Value);
end;
// -----------------------------------------------------------------------------
procedure TdwsDelegate.SetResultType(const Value: TDataType);
begin
FResultType := Value;
end;
// -----------------------------------------------------------------------------
function TdwsDelegate.StoreParameters: Boolean;
begin
Result := (FParameters.Count > 0);
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// TdwsDelegates
//
// -----------------------------------------------------------------------------
function TdwsDelegates.Add: TdwsDelegate;
begin
Result := TdwsDelegate(inherited Add);
end;
// -----------------------------------------------------------------------------
function TdwsDelegates.Add(const Name, ResultType: UnicodeString): TdwsDelegate;
begin
Result := Add;
Result.Name := Name;
Result.ResultType := ResultType;
end;
// -----------------------------------------------------------------------------
class function TdwsDelegates.GetSymbolClass: TdwsSymbolClass;
begin
Result := TdwsDelegate;
end;
end.
| 28.553794 | 150 | 0.675086 |
fc6deea01195e71289ab1518eefc0f1a3a025d61 | 32,409 | pas | Pascal | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/uSpell.pas | rjwinchester/VistA | 6ada05a153ff670adcb62e1c83e55044a2a0f254 | [
"Apache-2.0"
]
| 72 | 2015-02-03T02:30:45.000Z | 2020-01-30T17:20:52.000Z | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/uSpell.pas | rjwinchester/VistA | 6ada05a153ff670adcb62e1c83e55044a2a0f254 | [
"Apache-2.0"
]
| 80 | 2016-04-19T12:04:06.000Z | 2020-01-31T14:35:19.000Z | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/uSpell.pas | rjwinchester/VistA | 6ada05a153ff670adcb62e1c83e55044a2a0f254 | [
"Apache-2.0"
]
| 67 | 2015-01-27T16:47:56.000Z | 2020-02-12T21:23:56.000Z | unit uSpell;
// Word settings need to be restored to origional settings!
{$O-}
{$DEFINE CPRS}
{$UNDEF CPRS}
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, ComObj, StdCtrls, ComCtrls,
rCore, ORFn, Word2000, Variants, clipbrd, ActiveX, Contnrs, PSAPI, ExtCtrls;
type
TSpellCheckAvailable = record
Evaluated: boolean;
Available: boolean;
end;
function SpellCheckInProgress: Boolean;
procedure KillSpellCheck;
function SpellCheckAvailable: Boolean;
procedure SpellCheckForControl(AnEditControl: TCustomMemo);
procedure GrammarCheckForControl(AnEditControl: TCustomMemo);
// Do Not Call these routines - internal use only
procedure InternalSpellCheck(SpellCheck: boolean; EditControl: TCustomMemo);
procedure RefocusSpellCheckWindow;
const
SpellCheckerSettingName = 'SpellCheckerSettings';
var
SpellCheckerSettings: string = '';
implementation
uses VAUtils, fSpellNotify, uInit;
const
TX_ERROR_TITLE = 'Error';
TX_ERROR_INTRO = 'An error has occured.';
TX_TRY_AGAIN = 'Would you like to try again?';
TX_WINDOW_TITLE = 'CPRS-Chart Spell Checking #';
TX_NO_SPELL_CHECK = 'Spell checking is unavailable.';
TX_NO_GRAMMAR_CHECK = 'Grammar checking is unavailable.';
TX_SPELL_COMPLETE = 'The spelling check is complete.';
TX_GRAMMAR_COMPLETE = 'The grammar check is complete.';
TX_SPELL_ABORT = 'The spelling check terminated abnormally.';
TX_GRAMMAR_ABORT = 'The grammar check terminated abnormally.';
TX_SPELL_CANCELLED = 'Spelling check was cancelled before completion.';
TX_GRAMMAR_CANCELLED = 'Grammar check was cancelled before completion.';
TX_NO_DETAILS = 'No further details are available.';
TX_NO_CORRECTIONS = 'Corrections have NOT been applied.';
CRLF = #13#10;
// TABOO_STARTING_CHARS = '!"#$%&()*+,./:;<=>?@[\]^_`{|}';
VALID_STARTING_CHARS = '''-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
type
TMSWordThread = class(TThread)
private
FBeforeLines: TStringList;
FAfterLines: TStringList;
FWordSettings: TList;
FEditControl: TCustomMemo;
FShowingMessage: boolean;
// FEmptyVar: OleVariant;
FFalseVar: OleVariant;
// FTrueVar: OleVariant;
FNullStr: OleVariant;
FWord: WordApplication;
FDoc: WordDocument;
FWordVersion: single;
FDialog: OleVariant;
FDocDlg: OleVariant;
FText: string;
FSpellCheck: boolean;
FCanceled: boolean;
FTitle: string;
FDocWindowHandle: HWnd;
FOldFormChange: TNotifyEvent;
FOldOnActivate: TNotifyEvent;
FError: Exception;
FErrorText1: string;
FErrorText2: string;
FAllowErrorRetry: boolean;
FRetryResult: TShow508MessageResult;
FResultMessage: string;
FSpellChecking: boolean;
FLock: TRTLCriticalSection;
procedure OnFormChange(Sender: TObject);
procedure OnAppActivate(Sender: TObject);
procedure OnThreadTerminate(Sender: TObject);
procedure FindDocumentWindow;
procedure TransferText;
function RunWithErrorTrap(AMethod: TThreadMethod;
SpellCheckErrorMessage, GrammarCheckErrorMessage, AdditionalErrorMessage: string;
AllowRetry: boolean): boolean;
procedure WordError;
procedure StartWord;
procedure CreateDocument;
procedure DoCheck;
procedure ConfigWord;
procedure ConfigDoc;
procedure GetDialogs;
procedure SaveUserSettings;
procedure LoadUserSettings;
procedure ExitWord;
procedure ReportResults;
procedure SaveWordSettings;
procedure RestoreWordSettings;
function UserSetting(Index: integer): boolean;
procedure ThreadLock;
procedure ThreadUnlock;
protected
constructor CreateThread(SpellCheck: boolean; AEditControl: TCustomMemo);
procedure Execute; override;
public
procedure RefocusSpellCheckDialog;
property Text: string read FText;
property Canceled: boolean read FCanceled;
end;
var
MSWordThread: TMSWordThread = nil;
function ControlHasText(SpellCheck: boolean; AnEditControl: TCustomMemo): boolean;
var
i: integer;
begin
Result := FALSE;
if not assigned(AnEditControl) then
ShowMsg('Spell Check programming error')
else
begin
for i := 0 to AnEditControl.Lines.Count - 1 do
begin
if trim(AnEditControl.Lines[i]) <> '' then
begin
Result := TRUE;
break;
end;
end;
if not Result then
begin
if SpellCheck then
ShowMsg(TX_SPELL_COMPLETE)
else
ShowMsg(TX_GRAMMAR_COMPLETE)
end;
end;
end;
function SpellCheckInProgress: boolean;
begin
Result := assigned(MSWordThread);
end;
var
uSpellCheckAvailable: TSpellCheckAvailable;
procedure KillSpellCheck;
var
checking: boolean;
WordHandle: HWnd;
ProcessID: DWORD;
ProcessHandle: THandle;
begin
if assigned(MSWordThread) then
begin
with MSWordThread do
begin
ThreadLock;
try
checking := FSpellChecking;
WordHandle := FDocWindowHandle;
Terminate;
finally
ThreadUnlock;
end;
try
if checking then
begin
GetWindowThreadProcessId(WordHandle, ProcessID);
ProcessHandle := OpenProcess(PROCESS_TERMINATE, False, ProcessID);
try
TerminateProcess(ProcessHandle, 0);
finally
CloseHandle(ProcessHandle);
end;
end;
if assigned(MSWordThread) then
begin
WaitFor;
end;
except
end;
end;
end;
end;
{ Spell Checking using Visual Basic for Applications script }
function SpellCheckAvailable: Boolean;
//const
// WORD_VBA_CLSID = 'CLSID\{000209FF-0000-0000-C000-000000000046}';
begin
// CHANGED FOR PT. SAFETY ISSUE RELEASE 19.16, PATCH OR*3*155 - ADDED NEXT 2 LINES:
//result := false;
//exit;
// Reenabled in version 21.1, via parameter setting (RV)
// Result := (GetUserParam('ORWOR SPELL CHECK ENABLED?') = '1');
with uSpellCheckAvailable do // only want to call this once per session!!! v23.10+
begin
if not Evaluated then
begin
Available := (GetUserParam('ORWOR SPELL CHECK ENABLED?') = '1');
Evaluated := True;
end;
Result := Available;
end;
end;
procedure DoSpellCheck(SpellCheck: boolean; AnEditControl: TCustomMemo);
var
frmSpellNotify: TfrmSpellNotify;
begin
if assigned(MSWordThread) then exit;
if ControlHasText(SpellCheck, AnEditControl) then
begin
frmSpellNotify := TfrmSpellNotify.Create(Application);
try
SuspendTimeout;
try
frmSpellNotify.SpellCheck := SpellCheck;
frmSpellNotify.EditControl := AnEditControl;
frmSpellNotify.ShowModal;
finally
ResumeTimeout;
end;
finally
frmSpellNotify.Free;
end;
end;
end;
procedure InternalSpellCheck(SpellCheck: boolean; EditControl: TCustomMemo);
begin
MSWordThread := TMSWordThread.CreateThread(SpellCheck, EditControl);
while assigned(MSWordThread) do
begin
Application.ProcessMessages;
sleep(50);
end;
end;
procedure RefocusSpellCheckWindow;
begin
if assigned(MSWordThread) then
MSWordThread.RefocusSpellCheckDialog;
end;
procedure SpellCheckForControl(AnEditControl: TCustomMemo);
begin
DoSpellCheck(True, AnEditControl);
end;
procedure GrammarCheckForControl(AnEditControl: TCustomMemo);
begin
DoSpellCheck(False, AnEditControl);
end;
{ TMSWordThread }
const
RETRY_MAX = 3;
usCheckSpellingAsYouType = 1;
usCheckGrammarAsYouType = 2;
usIgnoreInternetAndFileAddresses = 3;
usIgnoreMixedDigits = 4;
usIgnoreUppercase = 5;
usCheckGrammarWithSpelling = 6;
usShowReadabilityStatistics = 7;
usSuggestFromMainDictionaryOnly = 8;
usSuggestSpellingCorrections = 9;
usHideSpellingErrors = 10;
usHideGrammarErrors = 11;
sTrueCode = 'T';
sFalseCode = 'F';
// AFAYT = AutoFormatAsYouType
wsAFAYTApplyBorders = 0;
wsAFAYTApplyBulletedLists = 1;
wsAFAYTApplyFirstIndents = 2;
wsAFAYTApplyHeadings = 3;
wsAFAYTApplyNumberedLists = 4;
wsAFAYTApplyTables = 5;
wsAFAYTAutoLetterWizard = 6;
wsAFAYTDefineStyles = 7;
wsAFAYTFormatListItemBeginning = 8;
wsAFAYTInsertClosings = 9;
wsAFAYTReplaceQuotes = 10;
wsAFAYTReplaceFractions = 11;
wsAFAYTReplaceHyperlinks = 12;
wsAFAYTReplaceOrdinals = 13;
wsAFAYTReplacePlainTextEmphasis = 14;
wsAFAYTReplaceSymbols = 15;
wsAutoFormatReplaceQuotes = 16;
wsTabIndentKey = 17;
wsWindowState = 18;
wsSaveInterval = 19;
wsTrackRevisions = 20;
wsShowRevisions = 21;
wsShowSummary = 22; // not used for Word 2010
procedure TMSWordThread.Execute;
var
ok: boolean;
procedure EnableAppActivation;
begin
FWord.Caption := FTitle;
Synchronize(FindDocumentWindow);
end;
procedure Run(AMethod: TThreadMethod; force: boolean = false);
begin
if terminated then exit;
if ok or force then
begin
ok := RunWithErrorTrap(AMethod, TX_SPELL_ABORT, TX_GRAMMAR_ABORT, '', FALSE);
end;
end;
procedure BuildResultMessage;
begin
FResultMessage := '';
if FCanceled then
begin
if FSpellCheck then
FResultMessage := TX_SPELL_CANCELLED
else
FResultMessage := TX_GRAMMAR_CANCELLED;
FResultMessage := FResultMessage + CRLF + TX_NO_CORRECTIONS;
end
else
begin
if FSpellCheck then
FResultMessage := TX_SPELL_COMPLETE
else
FResultMessage := TX_GRAMMAR_COMPLETE;
end;
end;
procedure SetStatus(value, force: boolean);
begin
if ok or force then
begin
ThreadLock;
FSpellChecking := value;
ThreadUnlock;
end;
end;
begin
CoInitialize(nil);
ok := true;
try
if RunWithErrorTrap(StartWord, TX_NO_SPELL_CHECK, TX_NO_GRAMMAR_CHECK, TX_TRY_AGAIN, TRUE) then
begin
try
if RunWithErrorTrap(CreateDocument, TX_SPELL_ABORT, TX_GRAMMAR_ABORT, '', FALSE) then
begin
try
EnableAppActivation;
Run(SaveWordSettings);
Run(ConfigWord);
Run(ConfigDoc);
Run(GetDialogs);
Run(LoadUserSettings);
SetStatus(True, False);
Run(DoCheck);
SetStatus(False, True);
Run(SaveUserSettings);
Run(RestoreWordSettings);
Run(ExitWord, True);
if ok and (not terminated) then
begin
Synchronize(TransferText);
BuildResultMessage;
Synchronize(ReportResults);
end;
finally
FDoc := nil;
end;
end;
finally
FWord := nil;
end;
end;
finally
CoUninitialize;
end;
end;
procedure TMSWordThread.ExitWord;
var
Save: OleVariant;
Doc: OleVariant;
begin
VarClear(FDialog);
VarClear(FDocDlg);
VariantInit(Save);
VariantInit(Doc);
try
Save := wdDoNotSaveChanges;
Doc := wdWordDocument;
FWord.Quit(Save, Doc, FFalseVar);
finally
VarClear(Save);
VarClear(Doc);
end;
end;
var
WindowTitle: string;
WindowHandle: HWnd;
function FindDocWindow(Handle: HWND; Info: Pointer): BOOL; stdcall;
var
title: string;
begin
title := GetWindowTitle(Handle);
if title = WindowTitle then
begin
WindowHandle := Handle;
Result := FALSE;
end
else
Result := True;
end;
procedure TMSWordThread.FindDocumentWindow;
begin
WindowTitle := FTitle;
WindowHandle := 0;
EnumWindows(@FindDocWindow, 0);
FDocWindowHandle := WindowHandle;
end;
procedure TMSWordThread.GetDialogs;
//var
// DispParams: TDispParams;
// OleArgs: array of OleVariant;
// ExcepInfo: TExcepInfo;
// Status: integer;
begin
// SetLength(OleArgs, 1);
// VariantInit(OleArgs[0]);
// try
VariantInit(FDialog);
FDialog := FWord.Dialogs.Item(wdDialogToolsOptionsSpellingAndGrammar);
VariantInit(FDocDlg);
FDocDlg := FWord.ActiveDocument;
(* OleArgs[0] := wdDialogToolsOptionsSpellingAndGrammar;
DispParams.rgvarg := @OleArgs[0];
DispParams.cArgs := 1;
DispParams.rgdispidNamedArgs := nil;
DispParams.cNamedArgs := 0;
// FDialog := FWord.Dialogs.Item(wdDialogToolsOptionsSpellingAndGrammar);
// dispid 0 is the Item method
Status := FWord.Dialogs.Invoke(0, GUID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_METHOD or DISPATCH_PROPERTYGET, DispParams, @FDialog, @ExcepInfo, nil);
if Status <> S_OK then
DispatchInvokeError(Status, ExcepInfo);
VariantInit(FDocDlg);
DispParams.rgvarg := nil;
DispParams.cArgs := 0;
Status := FWord.Invoke(3, GUID_NULL, LOCALE_USER_DEFAULT,
DISPATCH_METHOD or DISPATCH_PROPERTYGET, DispParams, @FDocDlg, @ExcepInfo, nil);
if Status <> S_OK then
DispatchInvokeError(Status, ExcepInfo);
finally
VarClear(OleArgs[0]);
SetLength(OleArgs, 0);
end; *)
end;
procedure TMSWordThread.LoadUserSettings;
begin
// load FUserSettings from server
// these are default values
(*
9 AlwaysSuggest,
8 SuggestFromMainDictOnly,
5 IgnoreAllCaps,
4 IgnoreMixedDigits,
ResetIgnoreAll,
Type, CustomDict1, CustomDict2, CustomDict3, CustomDict4, CustomDict5, CustomDict6,
CustomDict7, CustomDict8, CustomDict9, CustomDict10,
1 AutomaticSpellChecking,
3 FilenamesEmailAliases,
UserDict1,
2 AutomaticGrammarChecking,
6?? ForegroundGrammar,
7 ShowStatistics,
Options, RecheckDocument, IgnoreAuxFind, IgnoreMissDictSearch,
10 HideGrammarErrors,
CheckSpelling, GrLidUI, SpLidUI,
DictLang1, DictLang2, DictLang3,
DictLang4, DictLang5, DictLang6, DictLang7, DictLang8, DictLang9, DictLang10,
11 HideSpellingErrors,
HebSpellStart, InitialAlefHamza, FinalYaa, GermanPostReformSpell,
AraSpeller, ProcessCompoundNoun
*)
// FDialog.
ThreadLock;
try
FDialog.AutomaticSpellChecking := UserSetting(usCheckSpellingAsYouType);
FDialog.AutomaticGrammarChecking := UserSetting(usCheckGrammarAsYouType);
FDialog.FilenamesEmailAliases := UserSetting(usIgnoreInternetAndFileAddresses);
FDialog.IgnoreMixedDigits := UserSetting(usIgnoreMixedDigits);
FDialog.ForegroundGrammar := UserSetting(usCheckGrammarWithSpelling);
FDialog.ShowStatistics := UserSetting(usShowReadabilityStatistics);
FDialog.SuggestFromMainDictOnly := UserSetting(usSuggestFromMainDictionaryOnly);
FDialog.IgnoreAllCaps := UserSetting(usIgnoreUppercase);
FDialog.AlwaysSuggest := UserSetting(usSuggestSpellingCorrections);
FDialog.HideSpellingErrors := UserSetting(usHideSpellingErrors);
FDialog.HideGrammarErrors := UserSetting(usHideGrammarErrors);
FDialog.Execute;
finally
ThreadUnlock;
end;
// need list of custom dictionaries - default to CUSTOM.DIC (or query Word for it!!!)
// FWord.CustomDictionaries
end;
procedure TMSWordThread.OnAppActivate(Sender: TObject);
begin
if assigned(FOldOnActivate) then
FOldOnActivate(Sender);
RefocusSpellCheckDialog;
end;
procedure TMSWordThread.OnFormChange(Sender: TObject);
begin
if assigned(FOldFormChange) then
FOldFormChange(Sender);
RefocusSpellCheckDialog;
end;
procedure TMSWordThread.OnThreadTerminate(Sender: TObject);
begin
Application.OnActivate := FOldOnActivate;
Screen.OnActiveFormChange := FOldFormChange;
// VarClear(FEmptyVar);
VarClear(FFalseVar);
// VarClear(FTrueVar);
FWordSettings.Free;
FBeforeLines.Free;
FAfterLines.Free;
DeleteCriticalSection(FLock);
Screen.Cursor := crDefault;
MSWordThread := nil;
end;
procedure TMSWordThread.RefocusSpellCheckDialog;
begin
Application.ProcessMessages;
if Application.Active and (not FShowingMessage) and (FDocWindowHandle <> 0) then
begin
SetForegroundWindow(FDocWindowHandle);
SetFocus(FDocWindowHandle);
end;
end;
procedure TMSWordThread.ReportResults;
var
icon: TShow508MessageIcon;
begin
if not FCanceled then
icon := smiInfo
else
icon := smiWarning;
FShowingMessage := True;
try
ShowMsg(FResultMessage, icon, smbOK);
finally
FShowingMessage := False;
end;
end;
procedure TMSWordThread.RestoreWordSettings;
function Load(Index: integer): integer;
begin
if FWordSettings.Count > Index then
Result := Integer(FWordSettings[Index])
else
Result := 0
end;
begin
FWord.Options.AutoFormatAsYouTypeApplyBorders := boolean(Load(wsAFAYTApplyBorders));
FWord.Options.AutoFormatAsYouTypeApplyBulletedLists := boolean(Load(wsAFAYTApplyBulletedLists));
FWord.Options.AutoFormatAsYouTypeApplyFirstIndents := boolean(Load(wsAFAYTApplyFirstIndents));
FWord.Options.AutoFormatAsYouTypeApplyHeadings := boolean(Load(wsAFAYTApplyHeadings));
FWord.Options.AutoFormatAsYouTypeApplyNumberedLists := boolean(Load(wsAFAYTApplyNumberedLists));
FWord.Options.AutoFormatAsYouTypeApplyTables := boolean(Load(wsAFAYTApplyTables));
FWord.Options.AutoFormatAsYouTypeAutoLetterWizard := boolean(Load(wsAFAYTAutoLetterWizard));
FWord.Options.AutoFormatAsYouTypeDefineStyles := boolean(Load(wsAFAYTDefineStyles));
FWord.Options.AutoFormatAsYouTypeFormatListItemBeginning := boolean(Load(wsAFAYTFormatListItemBeginning));
FWord.Options.AutoFormatAsYouTypeInsertClosings := boolean(Load(wsAFAYTInsertClosings));
FWord.Options.AutoFormatAsYouTypeReplaceQuotes := boolean(Load(wsAFAYTReplaceQuotes));
FWord.Options.AutoFormatAsYouTypeReplaceFractions := boolean(Load(wsAFAYTReplaceFractions));
FWord.Options.AutoFormatAsYouTypeReplaceHyperlinks := boolean(Load(wsAFAYTReplaceHyperlinks));
FWord.Options.AutoFormatAsYouTypeReplaceOrdinals := boolean(Load(wsAFAYTReplaceOrdinals));
FWord.Options.AutoFormatAsYouTypeReplacePlainTextEmphasis := boolean(Load(wsAFAYTReplacePlainTextEmphasis));
FWord.Options.AutoFormatAsYouTypeReplaceSymbols := boolean(Load(wsAFAYTReplaceSymbols));
FWord.Options.AutoFormatReplaceQuotes := boolean(Load(wsAutoFormatReplaceQuotes));
FWord.Options.TabIndentKey := boolean(Load(wsTabIndentKey));
FWord.WindowState := Load(wsWindowState);
FWord.Options.SaveInterval := Load(wsSaveInterval);
FDoc.TrackRevisions := boolean(Load(wsTrackRevisions));
FDoc.ShowRevisions := boolean(Load(wsShowRevisions));
if (FWordVersion < 13) then // altered for Word 2010
FDoc.ShowSummary := boolean(Load(wsShowSummary));
end;
function TMSWordThread.RunWithErrorTrap(AMethod: TThreadMethod;
SpellCheckErrorMessage, GrammarCheckErrorMessage,
AdditionalErrorMessage: string; AllowRetry: boolean): boolean;
var
RetryCount: integer;
Done: boolean;
begin
RetryCount := 0;
Result := TRUE;
repeat
Done := TRUE;
try
AMethod;
except
on E: Exception do
begin
if not terminated then
begin
inc(RetryCount);
Done := FALSE;
if RetryCount >= RETRY_MAX then
begin
FError := E;
FAllowErrorRetry := AllowRetry;
if FSpellCheck then
FErrorText1 := SpellCheckErrorMessage
else
FErrorText1 := GrammarCheckErrorMessage;
FErrorText2 := AdditionalErrorMessage;
Synchronize(WordError);
if AllowRetry and (FRetryResult = smrRetry) then
RetryCount := 0
else
begin
Result := FALSE;
Done := TRUE;
end;
end;
end;
end;
end;
until Done;
end;
procedure TMSWordThread.DoCheck;
begin
FDoc.Content.Text := FText;
FDoc.Content.SpellingChecked := False;
FDoc.Content.GrammarChecked := False;
if FSpellCheck then
begin
FDocDlg.Content.CheckSpelling;
// FDoc.CheckSpelling(FNullStr, FEmptyVar, FEmptyVar, {Ignore, Suggest, }FNullStr, FNullStr,
// FNullStr, FNullStr, FNullStr, FNullStr, FNullStr, FNullStr, FNullStr);
// FSucceeded := FDoc.Content.SpellingChecked;
FText := FDoc.Content.Text;
end
else
begin
FDoc.Content.CheckGrammar;
// FSucceeded := FDoc.Content.GrammarChecked;
FText := FDoc.Content.Text;
end;
FCanceled := (FText = '');
end;
procedure TMSWordThread.SaveUserSettings;
procedure SaveSetting(Value: boolean; Index: integer);
begin
while length(SpellCheckerSettings) < Index do
SpellCheckerSettings := SpellCheckerSettings + ' ';
if Value then
SpellCheckerSettings[Index] := sTrueCode
else
SpellCheckerSettings[Index] := sFalseCode;
end;
begin
ThreadLock;
try
SpellCheckerSettings := '';
FDialog.Update;
SaveSetting(FDialog.AutomaticSpellChecking, usCheckSpellingAsYouType);
SaveSetting(FDialog.AutomaticGrammarChecking, usCheckGrammarAsYouType);
SaveSetting(FDialog.FilenamesEmailAliases, usIgnoreInternetAndFileAddresses);
SaveSetting(FDialog.IgnoreMixedDigits, usIgnoreMixedDigits);
SaveSetting(FDialog.IgnoreAllCaps, usIgnoreUppercase);
SaveSetting(FDialog.ForegroundGrammar, usCheckGrammarWithSpelling);
SaveSetting(FDialog.ShowStatistics, usShowReadabilityStatistics);
SaveSetting(FDialog.SuggestFromMainDictOnly, usSuggestFromMainDictionaryOnly);
SaveSetting(FDialog.AlwaysSuggest, usSuggestSpellingCorrections);
SaveSetting(FDialog.HideSpellingErrors, usHideSpellingErrors);
SaveSetting(FDialog.HideGrammarErrors, usHideGrammarErrors);
finally
ThreadUnlock;
end;
(*
9 AlwaysSuggest,
8 SuggestFromMainDictOnly,
5 IgnoreAllCaps,
4 IgnoreMixedDigits,
ResetIgnoreAll,
Type, CustomDict1, CustomDict2, CustomDict3, CustomDict4, CustomDict5, CustomDict6,
CustomDict7, CustomDict8, CustomDict9, CustomDict10,
1 AutomaticSpellChecking,
3 FilenamesEmailAliases,
UserDict1,
2 AutomaticGrammarChecking,
6?? ForegroundGrammar,
7 ShowStatistics,
Options, RecheckDocument, IgnoreAuxFind, IgnoreMissDictSearch,
10 HideGrammarErrors,
CheckSpelling, GrLidUI, SpLidUI,
DictLang1, DictLang2, DictLang3,
DictLang4, DictLang5, DictLang6, DictLang7, DictLang8, DictLang9, DictLang10,
11 HideSpellingErrors,
HebSpellStart, InitialAlefHamza, FinalYaa, GermanPostReformSpell,
AraSpeller, ProcessCompoundNoun
*)
end;
procedure TMSWordThread.SaveWordSettings;
procedure Save(Value, Index: integer);
begin
while FWordSettings.Count <= Index do
FWordSettings.Add(nil);
FWordSettings[Index] := Pointer(Value);
end;
begin
Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyBorders) , wsAFAYTApplyBorders);
Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyBulletedLists) , wsAFAYTApplyBulletedLists);
Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyFirstIndents) , wsAFAYTApplyFirstIndents);
Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyHeadings) , wsAFAYTApplyHeadings);
Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyNumberedLists) , wsAFAYTApplyNumberedLists);
Save(Ord(FWord.Options.AutoFormatAsYouTypeApplyTables) , wsAFAYTApplyTables);
Save(Ord(FWord.Options.AutoFormatAsYouTypeAutoLetterWizard) , wsAFAYTAutoLetterWizard);
Save(Ord(FWord.Options.AutoFormatAsYouTypeDefineStyles) , wsAFAYTDefineStyles);
Save(Ord(FWord.Options.AutoFormatAsYouTypeFormatListItemBeginning) , wsAFAYTFormatListItemBeginning);
Save(Ord(FWord.Options.AutoFormatAsYouTypeInsertClosings) , wsAFAYTInsertClosings);
Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceQuotes) , wsAFAYTReplaceQuotes);
Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceFractions) , wsAFAYTReplaceFractions);
Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceHyperlinks) , wsAFAYTReplaceHyperlinks);
Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceOrdinals) , wsAFAYTReplaceOrdinals);
Save(Ord(FWord.Options.AutoFormatAsYouTypeReplacePlainTextEmphasis) , wsAFAYTReplacePlainTextEmphasis);
Save(Ord(FWord.Options.AutoFormatAsYouTypeReplaceSymbols) , wsAFAYTReplaceSymbols);
Save(Ord(FWord.Options.AutoFormatReplaceQuotes) , wsAutoFormatReplaceQuotes);
Save(Ord(FWord.Options.TabIndentKey) , wsTabIndentKey);
Save(Ord(FWord.WindowState) , wsWindowState);
Save(Ord(FWord.Options.SaveInterval) , wsSaveInterval);
Save(Ord(FDoc.TrackRevisions) , wsTrackRevisions);
Save(Ord(FDoc.ShowRevisions) , wsShowRevisions);
if (FWordVersion < 13) then // altered for Word 2010
Save(Ord(FDoc.ShowSummary) , wsShowSummary);
end;
procedure TMSWordThread.StartWord;
begin
FWord := CoWordApplication.Create;
FWordVersion := StrToFloatDef(FWord.Version, 0.0);
end;
procedure TMSWordThread.ThreadLock;
begin
EnterCriticalSection(FLock);
end;
procedure TMSWordThread.ThreadUnlock;
begin
LeaveCriticalSection(FLock);
end;
procedure TMSWordThread.TransferText;
var
i: integer;
Lines: TStringList;
begin
if (not FCanceled) then
begin
Lines := TStringList.Create;
try
Lines.Text := FText;
// For some unknown reason spell check adds garbage lines to text
while (Lines.Count > 0) and (trim(Lines[Lines.Count-1]) = '') do
Lines.Delete(Lines.Count-1);
for i := 0 to FBeforeLines.Count-1 do
Lines.Insert(i, FBeforeLines[i]);
for i := 0 to FAfterLines.Count-1 do
Lines.Add(FAfterLines[i]);
FEditControl.Lines.Text := Lines.Text;
// FastAssign(Lines, FEditControl.Lines);
finally
Lines.Free;
end;
end;
end;
function TMSWordThread.UserSetting(Index: integer): boolean;
begin
if SpellCheckerSettings = '' then
begin
case Index of
usCheckSpellingAsYouType: Result := True;
usCheckGrammarAsYouType: Result := False;
usIgnoreInternetAndFileAddresses: Result := True;
usIgnoreMixedDigits: Result := True;
usIgnoreUppercase: Result := True;
usCheckGrammarWithSpelling: Result := False;
usShowReadabilityStatistics: Result := False;
usSuggestFromMainDictionaryOnly: Result := False;
usSuggestSpellingCorrections: Result := True;
usHideSpellingErrors: Result := False;
usHideGrammarErrors: Result := True;
else Result := False;
end;
end
else
Result := copy(SpellCheckerSettings,Index,1) = sTrueCode;
end;
procedure TMSWordThread.ConfigDoc;
begin
FDoc.TrackRevisions := False;
FDoc.ShowRevisions := False;
if (FWordVersion < 13) then // altered for Word 2010
FDoc.ShowSummary := False;
FWord.Height := 1000;
FWord.Width := 1000;
FWord.Top := -2000;
FWord.Left := -2000;
end;
procedure TMSWordThread.ConfigWord;
begin
// save all old values to FWord, restore when done.
FWord.Options.AutoFormatAsYouTypeApplyBorders := False;
FWord.Options.AutoFormatAsYouTypeApplyBulletedLists := False;
FWord.Options.AutoFormatAsYouTypeApplyFirstIndents := False;
FWord.Options.AutoFormatAsYouTypeApplyHeadings := False;
FWord.Options.AutoFormatAsYouTypeApplyNumberedLists := False;
FWord.Options.AutoFormatAsYouTypeApplyTables := False;
FWord.Options.AutoFormatAsYouTypeAutoLetterWizard := False;
FWord.Options.AutoFormatAsYouTypeDefineStyles := False;
FWord.Options.AutoFormatAsYouTypeFormatListItemBeginning := False;
FWord.Options.AutoFormatAsYouTypeInsertClosings := False;
FWord.Options.AutoFormatAsYouTypeReplaceQuotes := False;
FWord.Options.AutoFormatAsYouTypeReplaceFractions := False;
FWord.Options.AutoFormatAsYouTypeReplaceHyperlinks := False;
FWord.Options.AutoFormatAsYouTypeReplaceOrdinals := False;
FWord.Options.AutoFormatAsYouTypeReplacePlainTextEmphasis := False;
FWord.Options.AutoFormatAsYouTypeReplaceSymbols := False;
FWord.Options.AutoFormatReplaceQuotes := False;
FWord.Options.TabIndentKey := False;
FWord.WindowState := wdWindowStateNormal;
FWord.Options.SaveInterval := 0;
FWord.ResetIgnoreAll;
end;
procedure TMSWordThread.CreateDocument;
var
DocType: OleVariant;
begin
VariantInit(DocType);
try
DocType := wdNewBlankDocument;
FDoc := FWord.Documents.Add(FNullStr, FFalseVar, DocType, FFalseVar);
FDoc.Activate;
finally
VarClear(DocType);
end;
end;
constructor TMSWordThread.CreateThread(SpellCheck: boolean; AEditControl: TCustomMemo);
function WordDocTitle: string;
var
Guid: TGUID;
begin
if ActiveX.Succeeded(CreateGUID(Guid)) then
Result := GUIDToString(Guid)
else
Result := '';
Result := TX_WINDOW_TITLE + IntToStr(Application.Handle) + '/' + Result;
end;
function BeforeLineInvalid(Line: string): boolean;
var
i: integer;
begin
Result := (trim(Line) = '');
if not Result then
begin
for I := 1 to length(Line) do
if pos(Line[i], VALID_STARTING_CHARS) > 0 then exit;
Result := True;
end;
end;
procedure GetTextFromComponent;
var
Lines: TStrings;
begin
Lines := TStringList.Create;
try
Lines.Text := AEditControl.Lines.Text;
// FastAssign(AEditControl.Lines, Lines);
while (Lines.Count > 0) and (trim(Lines[Lines.Count-1]) = '') do
begin
FAfterLines.Insert(0, Lines[Lines.Count-1]);
Lines.Delete(Lines.Count-1);
end;
while (Lines.Count > 0) and (BeforeLineInvalid(Lines[0])) do
begin
FBeforeLines.Add(Lines[0]);
Lines.Delete(0);
end;
FText := Lines.Text;
finally
Lines.Free;
end;
end;
begin
inherited Create(TRUE);
Screen.Cursor := crHourGlass;
InitializeCriticalSection(FLock);
FBeforeLines := TStringList.Create;
FAfterLines := TStringList.Create;
FWordSettings := TList.Create;
FSpellChecking := False;
FEditControl := AEditControl;
// VariantInit(FEmptyVar);
VariantInit(FFalseVar);
// VariantInit(FTrueVar);
VariantInit(FNullStr);
// TVarData(FEmptyVar).VType := VT_EMPTY;
TVarData(FFalseVar).VType := VT_BOOL;
// TVarData(FTrueVar).VType := VT_BOOL;
TVarData(FNullStr).VType := VT_BSTR;
// FEmptyVar := 0;
FFalseVar := 0;
// FTrueVar := -1;
FNullStr := '';
FDocWindowHandle := 0;
FSpellCheck := SpellCheck;
GetTextFromComponent;
FCanceled := FALSE;
FTitle := WordDocTitle;
FreeOnTerminate := True;
OnTerminate := OnThreadTerminate;
FOldOnActivate := Application.OnActivate;
Application.OnActivate := OnAppActivate;
FOldFormChange := Screen.OnActiveFormChange;
Screen.OnActiveFormChange := OnFormChange;
{$WARN SYMBOL_DEPRECATED OFF}
Resume;
{$WARN SYMBOL_DEPRECATED ON}
end;
procedure TMSWordThread.WordError;
var
btn: TShow508MessageButton;
msg: string;
procedure Append(txt: string);
begin
if txt <> '' then
msg := msg + CRLF + txt;
end;
begin
if FAllowErrorRetry then
btn := smbRetryCancel
else
btn := smbOK;
msg := TX_ERROR_INTRO;
Append(FErrorText1);
if FError.Message <> '' then
Append(FError.Message)
else
Append(TX_NO_DETAILS);
Append(FErrorText2);
FShowingMessage := True;
try
FRetryResult := ShowMsg(Msg, TX_ERROR_TITLE, smiError, btn);
finally
FShowingMessage := False;
end;
end;
initialization
finalization
KillSpellCheck;
end.
| 31.102687 | 110 | 0.685396 |
47be5f5387a3487983a7ece1e7a43b5c2fc4f847 | 42,634 | pas | Pascal | src/xampp-control-panel/VersInfo.pas | mnikolop/Thesis_project_CyberDoc | 9a37fdd5a31de24cb902ee31ef19eb992faa1665 | [
"Apache-2.0"
]
| 4 | 2018-04-20T07:27:13.000Z | 2021-12-21T05:19:24.000Z | src/xampp-control-panel/VersInfo.pas | mnikolop/Thesis_project_CyberDoc | 9a37fdd5a31de24cb902ee31ef19eb992faa1665 | [
"Apache-2.0"
]
| 4 | 2020-06-22T12:31:31.000Z | 2021-05-11T15:32:59.000Z | src/xampp-control-panel/VersInfo.pas | mnikolop/Thesis_project_CyberDoc | 9a37fdd5a31de24cb902ee31ef19eb992faa1665 | [
"Apache-2.0"
]
| 1 | 2019-11-24T08:43:35.000Z | 2019-11-24T08:43:35.000Z | (* **************************************************************************** *)
(* Delphi Free Stuff Include File. This file is used for all my components *)
(* to create some standard defines. This will help reduce headaches when new *)
(* versions of Delphi and C++Builder are released, among other things. *)
(* **************************************************************************** *)
(* Brad Stowers: bstowers@pobox.com *)
(* Delphi Free Stuff: http://www.delphifreestuff.com/ *)
(* June 27, 2001 *)
(* **************************************************************************** *)
(* Usage: Add the following line to the top of your unit file: *)
(* {$I DFS.INC} *)
(* **************************************************************************** *)
(* *)
(* Complete Boolean Evaluation compiler directive is turned off by including *)
(* this file. *)
(* The $ObjExportAll directive is turned on if compiling with C++Builder 3 or *)
(* higher. This is required for Delphi components built in Builder with *)
(* run-time packages. *)
(* *)
(* Here is a brief explanation of what each of the defines mean: *)
(* DELPHI_FREE_STUFF : Always defined when DFS.INC is included *)
(* DFS_WIN16 : Compilation target is 16-bit Windows *)
(* DFS_WIN32 : Compilation target is 32-bit Windows *)
(* DFS_USEDEFSHLOBJ : The SHLOBJ.PAS version contains no none errors. *)
(* Delphi 2.0x and C++Builder 1.0x shipped with a *)
(* version of SHLOBJ.PAS that had many nasty errors. *)
(* See my web site in the Hints section for how to fix *)
(* DFS_NO_COM_CLEANUP : The version of the compiler being used does not *)
(* require COM objects to be released; it is done *)
(* automatically when they go "out of scope". *)
(* DFS_NO_DSGNINTF : Delphi 6 pretty much kills off the DsgnIntf unit *)
(* for good. Split into a couple of new units. *)
(* DFS_DESIGNERSELECTIONS: IDesignerSelections replaced TDesignerSelectionList *)
(* DFS_IPROPERTY : IProperty introduced for design-time stuff. *)
(* DFS_COMPILER_1 : Delphi 1.0 is the compiler. Note that C++B 1.0 *)
(* does NOT cause this to be defined. It is really *)
(* the 2.0 compiler. *)
(* DFS_COMPILER_1_UP : Delphi 1.0x or higher, or C++B 1.0x or higher is *)
(* the compiler. *)
(* DFS_COMPILER_2 : Delphi 2.0x or C++B 1.0x is the compiler. *)
(* DFS_COMPILER_2_UP : Delphi 2.0x or higher, or C++B 1.0x or higher is *)
(* the compiler. *)
(* DFS_COMPILER_3 : Delphi 3.0x or C++B 3.0x is the compiler. *)
(* DFS_COMPILER_3_UP : Delphi 3.0x or higher, or C++B 3.0x or higher is *)
(* the compiler. *)
(* DFS_COMPILER_4 : Delphi 4.0x or C++B 4.0x is the compiler. *)
(* DFS_COMPILER_4_UP : Delphi 4.0x or higher, or C++B 4.0x or higher is *)
(* the compiler. *)
(* DFS_COMPILER_5 : Delphi 5.0x or C++B 5.0x is the compiler. *)
(* DFS_COMPILER_5_UP : Delphi 5.0x or higher, or C++B 5.0x or higher is *)
(* the compiler. *)
(* DFS_COMPILER_6 : Delphi 6.0x or C++B 6.0x is the compiler. *)
(* DFS_COMPILER_6_UP : Delphi 6.0x or higher, or C++B 6.0x or higher is *)
(* the compiler. *)
(* DFS_UNKNOWN_COMPILER : No sense could be made of the compiliation *)
(* environment. *)
(* DFS_CPPB : Any version of C++B is being used. *)
(* DFS_CPPB_1 : C++B v1.0x is being used. *)
(* DFS_CPPB_3 : C++B v3.0x is being used. *)
(* DFS_CPPB_3_UP : C++B v3.0x or higher is being used. *)
(* DFS_CPPB_4 : C++B v4.0x is being used. *)
(* DFS_CPPB_4_UP : C++B v4.0x or higher is being used. *)
(* DFS_CPPB_5 : C++B v5.0x is being used. *)
(* DFS_CPPB_5_UP : C++B v5.0x or higher is being used. *)
(* DFS_DELPHI : Any version of Delphi is being used. *)
(* DFS_DELPHI_1 : Delphi v1.0x is being used. *)
(* DFS_DELPHI_2 : Delphi v2.0x is being used. *)
(* DFS_DELPHI_2_UP : Delphi v2.0x or higher is being used. *)
(* DFS_DELPHI_3 : Delphi v3.0x is being used. *)
(* DFS_DELPHI_3_UP : Delphi v3.0x or higher is being used. *)
(* DFS_DELPHI_4 : Delphi v4.0x is being used. *)
(* DFS_DELPHI_4_UP : Delphi v4.0x or higher is being used. *)
(* DFS_DELPHI_5 : Delphi v5.0x is being used. *)
(* DFS_DELPHI_5_UP : Delphi v5.0x or higher is being used. *)
(* DFS_DELPHI_6 : Delphi v6.0x is being used. *)
(* DFS_DELPHI_6_UP : Delphi v6.0x or higher is being used. *)
(* **************************************************************************** *)
{ All DFS components rely on complete boolean eval compiler directive set off. }
{$B-}
{$DEFINE DELPHI_FREE_STUFF}
{$IFDEF WIN32}
{$DEFINE DFS_WIN32}
{$ELSE}
{$DEFINE DFS_WIN16}
{$ENDIF}
{$IFDEF VER140}
{$DEFINE DFS_COMPILER_6}
{$DEFINE DFS_DELPHI}
{$DEFINE DFS_DELPHI_6}
{$ENDIF}
{$IFDEF VER130}
{$DEFINE DFS_COMPILER_5}
{$IFDEF BCB}
{$DEFINE DFS_CPPB}
{$DEFINE DFS_CPPB_5}
{$ELSE}
{$DEFINE DFS_DELPHI}
{$DEFINE DFS_DELPHI_5}
{$ENDIF}
{$ENDIF}
{$IFDEF VER125}
{$DEFINE DFS_COMPILER_4}
{$DEFINE DFS_CPPB}
{$DEFINE DFS_CPPB_4}
{$ENDIF}
{$IFDEF VER120}
{$DEFINE DFS_COMPILER_4}
{$DEFINE DFS_DELPHI}
{$DEFINE DFS_DELPHI_4}
{$ENDIF}
{$IFDEF VER110}
{$DEFINE DFS_COMPILER_3}
{$DEFINE DFS_CPPB}
{$DEFINE DFS_CPPB_3}
{$ENDIF}
{$IFDEF VER100}
{$DEFINE DFS_COMPILER_3}
{$DEFINE DFS_DELPHI}
{$DEFINE DFS_DELPHI_3}
{$ENDIF}
{$IFDEF VER93}
{$DEFINE DFS_COMPILER_2} { C++B v1 compiler is really v2 }
{$DEFINE DFS_CPPB}
{$DEFINE DFS_CPPB_1}
{ .$DEFINE DFS_USEDEFSHLOBJ } { C++B 1 has the correct SHLOBJ.H, but
SHLOBJ.PAS has errors so this isn't defined }
{$ENDIF}
{$IFDEF VER90}
{$DEFINE DFS_COMPILER_2}
{$DEFINE DFS_DELPHI}
{$DEFINE DFS_DELPHI_2}
{$ENDIF}
{$IFDEF VER80}
{$DEFINE DFS_COMPILER_1}
{$DEFINE DFS_DELPHI}
{$DEFINE DFS_DELPHI_1}
{$ENDIF}
{$IFNDEF DFS_CPPB}
{$IFNDEF DFS_DELPHI}
{ Don't know what the hell it is. Could be new version, or could be old BP. }
{$DEFINE DFS_UNKNOWN_COMPILER}
{$ENDIF}
{$ENDIF}
{$IFDEF DFS_COMPILER_1}
{$DEFINE DFS_COMPILER_1_UP}
{$ENDIF}
{$IFDEF DFS_COMPILER_2}
{$DEFINE DFS_COMPILER_1_UP}
{$DEFINE DFS_COMPILER_2_UP}
{$ENDIF}
{$IFDEF DFS_COMPILER_3}
{$DEFINE DFS_COMPILER_1_UP}
{$DEFINE DFS_COMPILER_2_UP}
{$DEFINE DFS_COMPILER_3_UP}
{$ENDIF}
{$IFDEF DFS_COMPILER_4}
{$DEFINE DFS_COMPILER_1_UP}
{$DEFINE DFS_COMPILER_2_UP}
{$DEFINE DFS_COMPILER_3_UP}
{$DEFINE DFS_COMPILER_4_UP}
{$ENDIF}
{$IFDEF DFS_COMPILER_5}
{$DEFINE DFS_COMPILER_1_UP}
{$DEFINE DFS_COMPILER_2_UP}
{$DEFINE DFS_COMPILER_3_UP}
{$DEFINE DFS_COMPILER_4_UP}
{$DEFINE DFS_COMPILER_5_UP}
{$ENDIF}
{$IFDEF DFS_COMPILER_6}
{$DEFINE DFS_COMPILER_1_UP}
{$DEFINE DFS_COMPILER_2_UP}
{$DEFINE DFS_COMPILER_3_UP}
{$DEFINE DFS_COMPILER_4_UP}
{$DEFINE DFS_COMPILER_5_UP}
{$DEFINE DFS_COMPILER_6_UP}
{$ENDIF}
{$IFDEF DFS_DELPHI_2}
{$DEFINE DFS_DELPHI_2_UP}
{$ENDIF}
{$IFDEF DFS_DELPHI_3}
{$DEFINE DFS_DELPHI_2_UP}
{$DEFINE DFS_DELPHI_3_UP}
{$ENDIF}
{$IFDEF DFS_DELPHI_4}
{$DEFINE DFS_DELPHI_2_UP}
{$DEFINE DFS_DELPHI_3_UP}
{$DEFINE DFS_DELPHI_4_UP}
{$ENDIF}
{$IFDEF DFS_DELPHI_5}
{$DEFINE DFS_DELPHI_2_UP}
{$DEFINE DFS_DELPHI_3_UP}
{$DEFINE DFS_DELPHI_4_UP}
{$DEFINE DFS_DELPHI_5_UP}
{$ENDIF}
{$IFDEF DFS_DELPHI_6}
{$DEFINE DFS_DELPHI_2_UP}
{$DEFINE DFS_DELPHI_3_UP}
{$DEFINE DFS_DELPHI_4_UP}
{$DEFINE DFS_DELPHI_5_UP}
{$DEFINE DFS_DELPHI_6_UP}
{$ENDIF}
{$IFDEF DFS_CPPB_3}
{$DEFINE DFS_CPPB_3_UP}
{$ENDIF}
{$IFDEF DFS_CPPB_4}
{$DEFINE DFS_CPPB_3_UP}
{$DEFINE DFS_CPPB_4_UP}
{$ENDIF}
{$IFDEF DFS_CPPB_5}
{$DEFINE DFS_CPPB_3_UP}
{$DEFINE DFS_CPPB_4_UP}
{$DEFINE DFS_CPPB_5_UP}
{$ENDIF}
{$IFDEF DFS_COMPILER_3_UP}
{$DEFINE DFS_NO_COM_CLEANUP}
{$DEFINE DFS_USEDEFSHLOBJ} { Only D3+ and C++B 3+ have no errors in SHLOBJ }
{$ENDIF}
{$IFDEF DFS_CPPB_3_UP}
// C++Builder requires this if you use Delphi components in run-time packages.
{$OBJEXPORTALL On}
{$ENDIF}
{$IFDEF DFS_COMPILER_6_UP}
// Delphi 6 pretty much kills off the DsgnIntf unit for good.
{$DEFINE DFS_NO_DSGNINTF}
{$DEFINE DFS_DESIGNERSELECTIONS}
{$DEFINE DFS_IPROPERTY}
{$ENDIF}
{ ------------------------------------------------------------------------------ }
{ TdfsVersionInfoResource v2.36 }
{ ------------------------------------------------------------------------------ }
{ A component to read version info resources. It is intended for Delphi 3, }
{ but should work with any file that contains a properly formatted resource. }
{ }
{ Copyright 2000-2001, Brad Stowers. All Rights Reserved. }
{ }
{ Copyright: }
{ All Delphi Free Stuff (hereafter "DFS") source code is copyrighted by }
{ Bradley D. Stowers (hereafter "author"), and shall remain the exclusive }
{ property of the author. }
{ }
{ Distribution Rights: }
{ You are granted a non-exlusive, royalty-free right to produce and distribute }
{ compiled binary files (executables, DLLs, etc.) that are built with any of }
{ the DFS source code unless specifically stated otherwise. }
{ You are further granted permission to redistribute any of the DFS source }
{ code in source code form, provided that the original archive as found on the }
{ DFS web site (http://www.delphifreestuff.com) is distributed unmodified. For }
{ example, if you create a descendant of TDFSColorButton, you must include in }
{ the distribution package the colorbtn.zip file in the exact form that you }
{ downloaded it from http://www.delphifreestuff.com/mine/files/colorbtn.zip. }
{ }
{ Restrictions: }
{ Without the express written consent of the author, you may not: }
{ * Distribute modified versions of any DFS source code by itself. You must }
{ include the original archive as you found it at the DFS site. }
{ * Sell or lease any portion of DFS source code. You are, of course, free }
{ to sell any of your own original code that works with, enhances, etc. }
{ DFS source code. }
{ * Distribute DFS source code for profit. }
{ }
{ Warranty: }
{ There is absolutely no warranty of any kind whatsoever with any of the DFS }
{ source code (hereafter "software"). The software is provided to you "AS-IS", }
{ and all risks and losses associated with it's use are assumed by you. In no }
{ event shall the author of the softare, Bradley D. Stowers, be held }
{ accountable for any damages or losses that may occur from use or misuse of }
{ the software. }
{ }
{ Support: }
{ Support is provided via the DFS Support Forum, which is a web-based message }
{ system. You can find it at http://www.delphifreestuff.com/discus/ }
{ All DFS source code is provided free of charge. As such, I can not guarantee }
{ any support whatsoever. While I do try to answer all questions that I }
{ receive, and address all problems that are reported to me, you must }
{ understand that I simply can not guarantee that this will always be so. }
{ }
{ Clarifications: }
{ If you need any further information, please feel free to contact me directly. }
{ This agreement can be found online at my site in the "Miscellaneous" section. }
{ ------------------------------------------------------------------------------ }
{ The lateset version of my components are always available on the web at: }
{ http://www.delphifreestuff.com/ }
{ See VersInfo.txt for notes, known issues, and revision history. }
{ ------------------------------------------------------------------------------ }
{ Date last modified: June 28, 2001 }
{ ------------------------------------------------------------------------------ }
{$DEFINE DFS_VERSION_INFO_AS_CLASS}
{$M+}
unit VersInfo;
interface
uses
{$IFDEF DFS_VERSION_INFO_AS_CLASS}
{$IFDEF DFS_WIN32}
Windows,
{$ELSE}
WinTypes, WinProcs, Ver,
{$ENDIF}
Classes, SysUtils; { I really hate Forms }
{$ELSE}
{$IFDEF DFS_WIN32}
Windows, ComCtrls,
{$ELSE}
WinTypes, WinProcs, Ver, Grids,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Forms, StdCtrls;
{$ENDIF}
const
{ This shuts up C++Builder 3 about the redefiniton being different. There
seems to be no equivalent in C1. Sorry. }
{$IFDEF DFS_CPPB_3_UP}
{$EXTERNALSYM DFS_COMPONENT_VERSION}
{$ENDIF}
DFS_COMPONENT_VERSION = 'TdfsVersionInfoResource v2.36';
DEFAULT_LANG_ID = $0409;
DEFAULT_CHAR_SET_ID = $04E4;
DEFAULT_LANG_CHAR_SET = '040904E4';
{$IFDEF DFS_COMPILER_3_UP}
resourcestring
{$ELSE}
const
{$ENDIF}
SFlagDebug = 'Debug';
SFlagInfoInferred = 'Info Inferred';
SFlagPatched = 'Patched';
SFlagPreRelease = 'Pre-Release';
SFlagPrivate = 'Private';
SFlagSpecial = 'Special';
SHeaderResource = 'Resource';
SHeaderValue = 'Value';
{ Predefined resource item captions. }
SResCapCompanyName = 'Company Name';
SResCapFileDescription = 'File Description';
SResCapFileVersion = 'File Version';
SResCapInternalName = 'Internal Name';
SResCapLegalCopyright = 'Legal Copyright';
SResCapLegalTrademarks = 'Legal Trademarks';
SResCapOriginalFilename = 'Original Filename';
SResCapProductName = 'Product Name';
SResCapProductVersion = 'Product Version';
SResCapComments = 'Comments';
SResCapBuildFlags = 'Build Flags';
{ set values to choose which resources are seen in the grid/listview }
type
TPreDef = (pdCompanyName, pdFileDescription, pdFileVersion, pdInternalName, pdLegalCopyright, pdLegalTrademarks, pdOriginalFilename, pdProductName,
pdProductVersion, pdComments, pdBuildFlags);
TPreDefs = set of TPreDef;
{ but to index properties we need integers }
const
IDX_COMPANYNAME = ord(pdCompanyName);
IDX_FILEDESCRIPTION = ord(pdFileDescription);
IDX_FILEVERSION = ord(pdFileVersion);
IDX_INTERNALNAME = ord(pdInternalName);
IDX_LEGALCOPYRIGHT = ord(pdLegalCopyright);
IDX_LEGALTRADEMARKS = ord(pdLegalTrademarks);
IDX_ORIGINALFILENAME = ord(pdOriginalFilename);
IDX_PRODUCTNAME = ord(pdProductName);
IDX_PRODUCTVERSION = ord(pdProductVersion);
IDX_COMMENTS = ord(pdComments);
IDX_BUILDFLAGS = ord(pdBuildFlags);
const
IDX_VER_MAJOR = 0;
IDX_VER_MINOR = 1;
IDX_VER_RELEASE = 2;
IDX_VER_BUILD = 3;
type
{$IFNDEF DFS_WIN32}
PVSFixedFileInfo = PVS_FixedFileInfo;
DWORD = longint;
UINT = word;
{$ENDIF}
TFixedFileInfoFlag = (ffDebug, ffInfoInferred, ffPatched, ffPreRelease, ffPrivateBuild, ffSpecialBuild);
TFixedFileInfoFlags = set of TFixedFileInfoFlag;
TVersionOperatingSystemFlag = (vosUnknown, vosDOS, vosOS2_16, vosOS2_32, vosNT, vosWindows16, vosPresentationManager16, vosPresentationManager32,
vosWindows32);
{ This is supposed to be one of the first line, and one of the second line. }
TVersionOperatingSystemFlags = set of TVersionOperatingSystemFlag;
TVersionFileType = (vftUnknown, vftApplication, vftDLL, vftDriver, vftFont, vftVXD, vftStaticLib);
TdfsVersionInfoResource = class; { forward declaration }
TFixedFileVersionInfo = class
private
FParent: TdfsVersionInfoResource;
FData: PVSFixedFileInfo;
function GetSignature: DWORD;
function GetStructureVersion: DWORD;
function GetFileVersionMS: DWORD;
function GetFileVersionLS: DWORD;
function GetProductVersionMS: DWORD;
function GetProductVersionLS: DWORD;
function GetValidFlags: TFixedFileInfoFlags;
function GetFlags: TFixedFileInfoFlags;
function GetFileOperatingSystem: TVersionOperatingSystemFlags;
function GetFileType: TVersionFileType;
function GetFileSubType: DWORD;
function GetCreationDate: TDateTime;
public
constructor Create(AParent: TdfsVersionInfoResource);
property Parent: TdfsVersionInfoResource read FParent write FParent;
property Data: PVSFixedFileInfo read FData write FData;
property Signature: DWORD read GetSignature;
property StructureVersion: DWORD read GetStructureVersion;
property FileVersionMS: DWORD read GetFileVersionMS;
property FileVersionLS: DWORD read GetFileVersionLS;
property ProductVersionMS: DWORD read GetProductVersionMS;
property ProductVersionLS: DWORD read GetProductVersionLS;
property ValidFlags: TFixedFileInfoFlags read GetValidFlags;
property Flags: TFixedFileInfoFlags read GetFlags;
property FileOperatingSystem: TVersionOperatingSystemFlags read GetFileOperatingSystem;
property FileType: TVersionFileType read GetFileType;
property FileSubType: DWORD read GetFileSubType;
property CreationDate: TDateTime read GetCreationDate;
end;
TVersionNumberInformation = class
private
FValid: boolean;
FMostSignificant: DWORD;
FLeastSignificant: DWORD;
FVersionNumberString: string;
function GetVersionNumber(Index: integer): word;
function GetVersionNumberString: string;
public
constructor Create(MSVer, LSVer: DWORD);
property Valid: boolean read FValid write FValid;
property Major: word index IDX_VER_MAJOR read GetVersionNumber;
property Minor: word index IDX_VER_MINOR read GetVersionNumber;
property Release: word index IDX_VER_RELEASE read GetVersionNumber;
property Build: word index IDX_VER_BUILD read GetVersionNumber;
property AsString: string read GetVersionNumberString;
end;
{$IFDEF DFS_DELPHI_1}
TVersionFilename = string;
{$ELSE}
TVersionFilename = type string;
{$ENDIF}
TdfsVersionInfoResource = class{$IFNDEF DFS_VERSION_INFO_AS_CLASS}(TComponent){$ENDIF}
private
FVersionInfo: PChar;
FVersionInfoSize: DWORD;
FFilename: TVersionFilename;
FTranslationIDs: TStringList;
FTranslationIDIndex: integer;
FFixedInfo: TFixedFileVersionInfo;
FForceEXE: boolean;
FFileVersion: TVersionNumberInformation;
FProductVersion: TVersionNumberInformation;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
FFileVersionLabel: TLabel;
FCopyrightLabel: TLabel;
{$IFDEF DFS_WIN32}
FVersionListView: TListView;
{$ELSE}
FVersionGrid: TStringGrid;
{$ENDIF}
FDescriptionLabel: TLabel;
FProductLabel: TLabel;
FShowResource: TPreDefs;
{$ENDIF}
protected
procedure SetFilename(const Val: TVersionFilename);
procedure SetTranslationIDIndex(Val: integer);
function GetTranslationIDs: TStrings;
procedure SetForceEXE(Val: boolean);
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
{$IFDEF DFS_WIN32}
procedure SetVersionListView(Value: TListView);
{$ELSE}
procedure SetVersionGrid(Value: TStringGrid);
{$ENDIF}
procedure SetShowResource(Value: TPreDefs);
procedure SetFileVersionLabel(Value: TLabel);
procedure SetCopyrightLabel(Value: TLabel);
procedure SetProductLabel(Value: TLabel);
procedure SetDescriptionLabel(Value: TLabel);
function GetVersion: string;
procedure SetVersion(const Val: string);
{$ENDIF}
function GetResourceFilename: string; virtual;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
procedure PopulateControls; virtual;
{$IFDEF DFS_WIN32}
procedure BuildListView; virtual;
{$ELSE}
procedure BuildGrid; virtual;
{$ENDIF}
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Loaded; override;
{$ENDIF}
function BuildFlags: string; virtual;
procedure ReadVersionInfoData; virtual;
function GetVersionInfoString(Index: integer): string;
function GetResourceStr(Index: string): string;
public
{$IFDEF DFS_VERSION_INFO_AS_CLASS}
constructor Create; virtual;
{$ELSE}
constructor Create(AOwner: TComponent); override;
{$ENDIF}
destructor Destroy; override;
property TranslationIDIndex: integer read FTranslationIDIndex write SetTranslationIDIndex;
property TranslationIDs: TStrings read GetTranslationIDs;
property FixedInfo: TFixedFileVersionInfo read FFixedInfo;
property UserResource[Index: string]: string read GetResourceStr;
property FileVersion: TVersionNumberInformation read FFileVersion;
property ProductVersion: TVersionNumberInformation read FProductVersion;
published
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
property Version: string read GetVersion write SetVersion stored FALSE;
{$ENDIF}
property Filename: TVersionFilename read FFilename write SetFilename;
property ForceEXE: boolean read FForceEXE write SetForceEXE default FALSE;
property CompanyName: string index IDX_COMPANYNAME read GetVersionInfoString;
property FileDescription: string index IDX_FILEDESCRIPTION read GetVersionInfoString;
property InternalName: string index IDX_INTERNALNAME read GetVersionInfoString;
property LegalCopyright: string index IDX_LEGALCOPYRIGHT read GetVersionInfoString;
property LegalTrademarks: string index IDX_LEGALTRADEMARKS read GetVersionInfoString;
property OriginalFilename: string index IDX_ORIGINALFILENAME read GetVersionInfoString;
property ProductName: string index IDX_PRODUCTNAME read GetVersionInfoString;
property Comments: string index IDX_COMMENTS read GetVersionInfoString;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
property VersionLabel: TLabel read FFileVersionLabel write SetFileVersionLabel;
{$IFDEF DFS_WIN32}
property VersionListView: TListView read FVersionListView write SetVersionListView;
{$ELSE}
property VersionGrid: TStringGrid read FVersionGrid write SetVersionGrid;
{$ENDIF}
property DescriptionLabel: TLabel read FDescriptionLabel write SetDescriptionLabel;
property CopyrightLabel: TLabel read FCopyrightLabel write SetCopyrightLabel;
property ProductLabel: TLabel read FProductLabel write SetProductLabel;
property ShowResource: TPreDefs read FShowResource write SetShowResource;
{$ENDIF}
end;
implementation
const
PREDEF_RESOURCES: array [IDX_COMPANYNAME .. IDX_BUILDFLAGS] of string = ('CompanyName', 'FileDescription', 'FileVersion', 'InternalName',
'LegalCopyright', 'LegalTrademarks', 'OriginalFilename', 'ProductName', 'ProductVersion', 'Comments', 'BuildFlags');
PREDEF_CAPTIONS: array [IDX_COMPANYNAME .. IDX_BUILDFLAGS] of string = (SResCapCompanyName, SResCapFileDescription, SResCapFileVersion,
SResCapInternalName, SResCapLegalCopyright, SResCapLegalTrademarks, SResCapOriginalFilename, SResCapProductName, SResCapProductVersion,
SResCapComments, SResCapBuildFlags);
{$IFDEF DFS_DELPHI_2}
{$DEFINE ST2DT_UNDEF}
{$ENDIF}
{$IFDEF DFS_CPPB_1}
{$DEFINE ST2DT_UNDEF}
{$ENDIF}
{$IFDEF ST2DT_UNDEF}
function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
begin
with SystemTime do
Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
end;
{$ENDIF}
{$IFNDEF DFS_WIN32}
function IsLibrary: boolean;
begin
Result := PrefixSeg = 0;
end;
{$ENDIF}
constructor TFixedFileVersionInfo.Create(AParent: TdfsVersionInfoResource);
begin
inherited Create;
FParent := AParent;
end;
function TFixedFileVersionInfo.GetSignature: DWORD;
begin
if FData = nil then
Result := 0
else
Result := FData^.dwSignature;
end;
function TFixedFileVersionInfo.GetStructureVersion: DWORD;
begin
if FData = nil then
Result := 0
else
Result := FData^.dwStrucVersion;
end;
function TFixedFileVersionInfo.GetFileVersionMS: DWORD;
begin
if FData = nil then
Result := 0
else
Result := FData^.dwFileVersionMS;
end;
function TFixedFileVersionInfo.GetFileVersionLS: DWORD;
begin
if FData = nil then
Result := 0
else
Result := FData^.dwFileVersionLS;
end;
function TFixedFileVersionInfo.GetProductVersionMS: DWORD;
begin
if FData = nil then
Result := 0
else
Result := FData^.dwProductVersionMS;
end;
function TFixedFileVersionInfo.GetProductVersionLS: DWORD;
begin
if FData = nil then
Result := 0
else
Result := FData^.dwProductVersionLS;
end;
function TFixedFileVersionInfo.GetValidFlags: TFixedFileInfoFlags;
begin
Result := [];
if FData <> nil then
begin
if (FData^.dwFileFlagsMask and VS_FF_DEBUG) <> 0 then
Include(Result, ffDebug);
if (FData^.dwFileFlagsMask and VS_FF_PRERELEASE) <> 0 then
Include(Result, ffPreRelease);
if (FData^.dwFileFlagsMask and VS_FF_PATCHED) <> 0 then
Include(Result, ffPatched);
if (FData^.dwFileFlagsMask and VS_FF_PRIVATEBUILD) <> 0 then
Include(Result, ffPrivateBuild);
if (FData^.dwFileFlagsMask and VS_FF_INFOINFERRED) <> 0 then
Include(Result, ffInfoInferred);
if (FData^.dwFileFlagsMask and VS_FF_SPECIALBUILD) <> 0 then
Include(Result, ffSpecialBuild);
end;
end;
function TFixedFileVersionInfo.GetFlags: TFixedFileInfoFlags;
begin
Result := [];
if FData <> nil then
begin
if (FData^.dwFileFlags and VS_FF_DEBUG) <> 0 then
Include(Result, ffDebug);
if (FData^.dwFileFlags and VS_FF_PRERELEASE) <> 0 then
Include(Result, ffPreRelease);
if (FData^.dwFileFlags and VS_FF_PATCHED) <> 0 then
Include(Result, ffPatched);
if (FData^.dwFileFlags and VS_FF_PRIVATEBUILD) <> 0 then
Include(Result, ffPrivateBuild);
if (FData^.dwFileFlags and VS_FF_INFOINFERRED) <> 0 then
Include(Result, ffInfoInferred);
if (FData^.dwFileFlags and VS_FF_SPECIALBUILD) <> 0 then
Include(Result, ffSpecialBuild);
end;
end;
function TFixedFileVersionInfo.GetFileOperatingSystem: TVersionOperatingSystemFlags;
{$IFNDEF DFS_WIN32}
var
FileOS: word;
{$ENDIF}
begin
Result := [];
if FData <> nil then
begin
case HiWord(FData^.dwFileOS) of
VOS_DOS shr 16:
Include(Result, vosDOS);
VOS_OS216 shr 16:
Include(Result, vosOS2_16);
VOS_OS232 shr 16:
Include(Result, vosOS2_32);
VOS_NT shr 16:
Include(Result, vosNT);
else
Include(Result, vosUnknown);
end;
{$IFDEF DFS_WIN32}
case LoWord(FData^.dwFileOS) of
LoWord(VOS__WINDOWS16):
Include(Result, vosWindows16);
LoWord(VOS__PM16):
Include(Result, vosPresentationManager16);
LoWord(VOS__PM32):
Include(Result, vosPresentationManager32);
LoWord(VOS__WINDOWS32):
Include(Result, vosWindows32);
else
Include(Result, vosUnknown);
end;
{$ELSE}
FileOS := LoWord(FData^.dwFileOS);
if FileOS = LoWord(VOS__WINDOWS16) then
Include(Result, vosWindows16)
else if FileOS = LoWord(VOS__PM16) then
Include(Result, vosPresentationManager16)
else if FileOS = LoWord(VOS__PM32) then
Include(Result, vosPresentationManager32)
else if FileOS = LoWord(VOS__WINDOWS32) then
Include(Result, vosWindows32)
else
Include(Result, vosUnknown);
{$ENDIF}
end;
end;
function TFixedFileVersionInfo.GetFileType: TVersionFileType;
begin
Result := vftUnknown;
if FData <> nil then
begin
case FData^.dwFileType of
VFT_APP:
Result := vftApplication;
VFT_DLL:
Result := vftDLL;
VFT_DRV:
Result := vftDriver;
VFT_FONT:
Result := vftFont;
VFT_VXD:
Result := vftVXD;
VFT_STATIC_LIB:
Result := vftStaticLib;
end;
end;
end;
function TFixedFileVersionInfo.GetFileSubType: DWORD;
begin
if FData = nil then
Result := 0
else
begin
Result := FData^.dwFileSubtype;
end;
end;
function TFixedFileVersionInfo.GetCreationDate: TDateTime;
{$IFDEF DFS_WIN32}
var
SysTime: TSystemTime;
FileTime: TFileTime;
begin
if FData = nil then
Result := 0
else
begin
FileTime.dwLowDateTime := FData^.dwFileDateLS;
FileTime.dwHighDateTime := FData^.dwFileDateMS;
if FileTimeToSystemTime(FileTime, SysTime) then
begin
Result := SystemTimeToDateTime(SysTime);
end
else
Result := 0;
end;
{$ELSE}
var
SR: TSearchRec;
begin
{ Fake it until I can figure out how to convert dwFileDateMS and LS }
Result := 0;
if assigned(FParent) then
begin
if FindFirst(FParent.GetResourceFilename, faAnyFile, SR) = 0 then
begin
Result := FileDateToDateTime(SR.Time);
FindClose(SR);
end;
end;
(*
var
BigNum: comp;
begin
if FData = nil then
Result := 0
else begin
BigNum := (FData^.dwFileDateMS * MaxLongInt) + FData^.dwFileDateLS;
BigNum := BigNum / 10000000;
{ LS and MS is the number of 100 nanosecond intervals since 1/1/1601 }
{ 10,000,000s of a second }
Result := EncodeDate(1601, 1, 1);
Result := BigNum.....
end;
*)
{$ENDIF}
end;
constructor TVersionNumberInformation.Create(MSVer, LSVer: DWORD);
begin
inherited Create;
FValid := FALSE;
FMostSignificant := MSVer;
FLeastSignificant := LSVer;
end;
function TVersionNumberInformation.GetVersionNumber(Index: integer): word;
begin
Result := 0;
if FValid then
case Index of
IDX_VER_MAJOR:
Result := HiWord(FMostSignificant);
IDX_VER_MINOR:
Result := LoWord(FMostSignificant);
IDX_VER_RELEASE:
Result := HiWord(FLeastSignificant);
IDX_VER_BUILD:
Result := LoWord(FLeastSignificant)
end
end;
function TVersionNumberInformation.GetVersionNumberString: string;
begin
if FValid then
begin
if FVersionNumberString = '' then
Result := Format('%d.%d.%d.%d', [Major, Minor, Release, Build])
else
Result := FVersionNumberString;
end
else
Result := ''
end;
{$IFDEF DFS_VERSION_INFO_AS_CLASS}
constructor TdfsVersionInfoResource.Create;
begin
inherited Create;
FVersionInfo := nil;
FVersionInfoSize := 0;
FFilename := '';
FTranslationIDIndex := 0;
FForceEXE := FALSE;
FTranslationIDs := TStringList.Create;
FFileVersion := TVersionNumberInformation.Create(0, 0);
FProductVersion := TVersionNumberInformation.Create(0, 0);
FFixedInfo := TFixedFileVersionInfo.Create(Self);
end;
{$ELSE}
constructor TdfsVersionInfoResource.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FVersionInfo := nil;
FVersionInfoSize := 0;
FFilename := '';
FTranslationIDIndex := 0;
FForceEXE := FALSE;
FTranslationIDs := TStringList.Create;
FFileVersion := TVersionNumberInformation.Create(0, 0);
FProductVersion := TVersionNumberInformation.Create(0, 0);
FFixedInfo := TFixedFileVersionInfo.Create(Self);
FShowResource := [Low(TPreDef) .. High(TPreDef)]
end;
{$ENDIF}
destructor TdfsVersionInfoResource.Destroy;
begin
FFileVersion.Free;
FProductVersion.Free;
FFixedInfo.Free;
FTranslationIDs.Free;
if FVersionInfo <> nil then
FreeMem(FVersionInfo, FVersionInfoSize);
inherited Destroy;
end;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
procedure TdfsVersionInfoResource.Loaded;
begin
inherited Loaded;
ReadVersionInfoData;
(*
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
PopulateControls;
{$ENDIF}
*)
end;
{$ENDIF}
procedure TdfsVersionInfoResource.SetFilename(const Val: TVersionFilename);
begin
FFilename := Val;
ReadVersionInfoData;
end;
procedure TdfsVersionInfoResource.ReadVersionInfoData;
const
TRANSLATION_INFO = '\VarFileInfo\Translation';
type
TTranslationPair = packed record
Lang, CharSet: word;
end;
PTranslationIDList = ^TTranslationIDList;
TTranslationIDList = array [0 .. MAXINT div SizeOf(TTranslationPair) - 1] of TTranslationPair;
var
QueryLen: UINT;
IDsLen: UINT;
Dummy: DWORD;
IDs: PTranslationIDList;
IDCount: integer;
FixedInfoData: PVSFixedFileInfo;
TempFilename: array [0 .. 255] of char;
begin
FTranslationIDs.Clear;
FFixedInfo.Data := nil;
if FVersionInfo <> nil then
FreeMem(FVersionInfo, FVersionInfoSize);
StrPCopy(TempFilename, GetResourceFilename);
{ Denis Kopprasch: added a try-Except because GetFileVersionInfoSize can fail
with an invalid pointer or something like that! }
try
FVersionInfoSize := GetFileVersionInfoSize(TempFilename, Dummy);
except
FVersionInfoSize := 0;
end;
if FVersionInfoSize = 0 then
begin
FVersionInfo := nil;
FFileVersion.Valid := FALSE;
FProductVersion.Valid := FALSE;
end
else
begin
GetMem(FVersionInfo, FVersionInfoSize);
GetFileVersionInfo(TempFilename, Dummy, FVersionInfoSize, FVersionInfo);
VerQueryValue(FVersionInfo, '\', pointer(FixedInfoData), QueryLen);
FFixedInfo.Data := FixedInfoData;
if VerQueryValue(FVersionInfo, TRANSLATION_INFO, pointer(IDs), IDsLen) then
begin
{ Denis Kopprasch: if IDCount = 0, the for .. to ...-Statement is executed
several times (maybe infinite until error) if range checking off }
IDCount := IDsLen div SizeOf(TTranslationPair);
if (IDCount > 0) then
begin
for Dummy := 0 to IDCount - 1 do
begin
{ !!! Potential problem. Some of MS's stuff does this, some does not. Need to
figure a way to make it work with both. }
(* if IDs^[Dummy].Lang = 0 then
IDs^[Dummy].Lang := DEFAULT_LANG_ID; { Some of Microsoft's stuff does this }
if IDs^[Dummy].CharSet = 0 then
IDs^[Dummy].CharSet := DEFAULT_CHAR_SET_ID; *)
FTranslationIDs.Add(Format('%.4x%.4x', [IDs^[Dummy].Lang, IDs^[Dummy].CharSet]));
end;
end
else if (IDCount = 0) and (IDsLen > 0) then
begin
{ There was translation info, but there was not a full set. What's
there is usually a char set, so we have to swap things around. }
FTranslationIDs.Add(Format('%.4x%.4x', [DEFAULT_LANG_ID, IDs^[Dummy].Lang]));
end;
end;
if FTranslationIDIndex >= FTranslationIDs.Count then
FTranslationIDIndex := 0;
FFileVersion.Valid := true;
FFileVersion.FMostSignificant := FFixedInfo.GetFileVersionMS;
FFileVersion.FLeastSignificant := FFixedInfo.GetFileVersionLS;
FFileVersion.FVersionNumberString := GetVersionInfoString(IDX_FILEVERSION);
FProductVersion.Valid := true;
FProductVersion.FMostSignificant := FFixedInfo.GetProductVersionMS;
FProductVersion.FLeastSignificant := FFixedInfo.GetProductVersionLS;
FProductVersion.FVersionNumberString := GetVersionInfoString(IDX_PRODUCTVERSION);
end;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
PopulateControls;
{$ENDIF}
end;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
procedure TdfsVersionInfoResource.PopulateControls;
begin
if [csDesigning, csLoading] * ComponentState <> [] then
exit;
if assigned(FFileVersionLabel) then
FFileVersionLabel.Caption := FileVersion.AsString;
if assigned(FCopyrightLabel) then
FCopyrightLabel.Caption := LegalCopyright;
if assigned(FProductLabel) then
FProductLabel.Caption := ProductName;
if assigned(FDescriptionLabel) then
FDescriptionLabel.Caption := FileDescription;
{$IFDEF DFS_WIN32}
if assigned(FVersionListView) then
BuildListView;
{$ELSE}
if assigned(FVersionGrid) then
BuildGrid;
{$ENDIF}
end;
{$ENDIF}
function TdfsVersionInfoResource.GetResourceFilename: string;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
var
TempFilename: array [0 .. 255] of char;
{$ENDIF}
begin
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
if FFilename = '' then
begin
if IsLibrary and (not FForceEXE) then
begin
GetModuleFileName(HInstance, TempFilename, SizeOf(TempFilename) - 1);
Result := StrPas(TempFilename);
end
else
Result := Application.EXEName;
end
else
{$ENDIF}
Result := FFilename;
end;
function TdfsVersionInfoResource.GetVersionInfoString(Index: integer): string;
begin
if (Index >= Low(PREDEF_RESOURCES)) and (Index <= High(PREDEF_RESOURCES)) then
Result := GetResourceStr(PREDEF_RESOURCES[Index])
else
Result := ''
end;
function TdfsVersionInfoResource.GetResourceStr(Index: string): string;
var
ResStr: PChar;
StrLen: UINT;
SubBlock: array [0 .. 255] of char;
LangCharSet: string;
begin
if FTranslationIDIndex < FTranslationIDs.Count then
LangCharSet := FTranslationIDs[FTranslationIDIndex]
else
LangCharSet := DEFAULT_LANG_CHAR_SET;
StrPCopy(SubBlock, '\StringFileInfo\' + LangCharSet + '\' + Index);
if (FVersionInfo <> nil) and VerQueryValue(FVersionInfo, SubBlock, pointer(ResStr), StrLen) then
Result := StrPas(ResStr)
else
Result := '';
end;
procedure TdfsVersionInfoResource.SetTranslationIDIndex(Val: integer);
begin
if (Val > 0) and (Val < FTranslationIDs.Count) then
FTranslationIDIndex := Val;
end;
function TdfsVersionInfoResource.GetTranslationIDs: TStrings;
begin
Result := FTranslationIDs;
end;
procedure TdfsVersionInfoResource.SetForceEXE(Val: boolean);
begin
if FForceEXE <> Val then
begin
FForceEXE := Val;
ReadVersionInfoData;
end;
end;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
procedure TdfsVersionInfoResource.SetFileVersionLabel(Value: TLabel);
begin
FFileVersionLabel := Value;
if assigned(FFileVersionLabel) then
begin
{$IFDEF DFS_WIN32}
FFileVersionLabel.FreeNotification(Self);
{$ENDIF}
FShowResource := FShowResource - [pdFileVersion];
PopulateControls;
end;
end;
procedure TdfsVersionInfoResource.SetCopyrightLabel(Value: TLabel);
begin
FCopyrightLabel := Value;
if assigned(FCopyrightLabel) then
begin
{$IFDEF DFS_WIN32}
FCopyrightLabel.FreeNotification(Self);
{$ENDIF}
FShowResource := FShowResource - [pdLegalCopyright];
PopulateControls;
end;
end;
procedure TdfsVersionInfoResource.SetProductLabel(Value: TLabel);
begin
FProductLabel := Value;
if assigned(FProductLabel) then
begin
{$IFDEF DFS_WIN32}
FProductLabel.FreeNotification(Self);
{$ENDIF}
FShowResource := FShowResource - [pdProductName];
PopulateControls;
end;
end;
procedure TdfsVersionInfoResource.SetDescriptionLabel(Value: TLabel);
begin
FDescriptionLabel := Value;
if assigned(FDescriptionLabel) then
begin
{$IFDEF DFS_WIN32}
FDescriptionLabel.FreeNotification(Self);
{$ENDIF}
FShowResource := FShowResource - [pdFileDescription];
PopulateControls;
end;
end;
procedure TdfsVersionInfoResource.SetShowResource(Value: TPreDefs);
begin
if Value <> FShowResource then
begin
FShowResource := Value;
PopulateControls;
end
end;
{$IFDEF DFS_WIN32}
procedure TdfsVersionInfoResource.SetVersionListView(Value: TListView);
begin
FVersionListView := Value;
if assigned(FVersionListView) then
begin
FVersionListView.FreeNotification(Self);
PopulateControls;
end;
end;
{$ELSE}
procedure TdfsVersionInfoResource.SetVersionGrid(Value: TStringGrid);
begin
FVersionGrid := Value;
if assigned(FVersionGrid) then
begin
{$IFDEF DFS_WIN32}
FVersionGrid.FreeNotification(Self);
{$ENDIF}
PopulateControls;
end;
end;
{$ENDIF}
procedure TdfsVersionInfoResource.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if (AComponent = FFileVersionLabel) then
FFileVersionLabel := nil
else if (AComponent = FCopyrightLabel) then
FCopyrightLabel := nil
else if (AComponent = FProductLabel) then
FProductLabel := nil
else if (AComponent = FDescriptionLabel) then
FDescriptionLabel := nil
{$IFDEF DFS_WIN32}
else if (AComponent = FVersionListView) then
FVersionListView := nil;
{$ELSE}
else if (AComponent = FVersionGrid) then
FVersionGrid := nil;
{$ENDIF}
end;
end;
{$ENDIF}
function TdfsVersionInfoResource.BuildFlags: string;
const
FLAG_STRING: array [TFixedFileInfoFlag] of string = (SFlagDebug, SFlagInfoInferred, SFlagPatched, SFlagPreRelease, SFlagPrivate, SFlagSpecial);
var
AFlag: TFixedFileInfoFlag;
begin
Result := '';
for AFlag := Low(TFixedFileInfoFlag) to High(TFixedFileInfoFlag) do
if AFlag in FixedInfo.Flags then
Result := Result + FLAG_STRING[AFlag] + ', ';
if Length(Result) > 0 then
Result := Copy(Result, 1, Length(Result) - 2);
end;
{$IFNDEF DFS_VERSION_INFO_AS_CLASS}
{$IFDEF DFS_WIN32}
procedure TdfsVersionInfoResource.BuildListView;
procedure Add_Item(StrId: integer; const Str: string);
var
NewItem: TListItem;
begin
if (Str <> '') and (TPreDef(StrId) in FShowResource) then
begin
NewItem := VersionListView.Items.Add;
NewItem.Caption := PREDEF_CAPTIONS[StrId];
NewItem.SubItems.Add(Str)
end
end;
procedure Add_Column(const Str: string);
var
NewColumn: TListColumn;
begin
NewColumn := VersionListView.Columns.Add;
NewColumn.Caption := Str;
NewColumn.Width := -2; { nifty! }
end;
begin
if assigned(VersionListView) then
with VersionListView do
begin
Columns.Clear;
Items.Clear;
{ only the minimum parameters in the listview are forced: }
ViewStyle := vsReport;
ReadOnly := true;
ColumnClick := FALSE;
Add_Column(SHeaderResource);
Add_Column(SHeaderValue);
Add_Item(IDX_PRODUCTNAME, ProductName);
Add_Item(IDX_PRODUCTVERSION, ProductVersion.AsString);
Add_Item(IDX_COMPANYNAME, CompanyName);
Add_Item(IDX_LEGALCOPYRIGHT, LegalCopyright);
Add_Item(IDX_LEGALTRADEMARKS, LegalTrademarks);
Add_Item(IDX_FILEDESCRIPTION, FileDescription);
Add_Item(IDX_FILEVERSION, FileVersion.AsString);
Add_Item(IDX_INTERNALNAME, InternalName);
Add_Item(IDX_ORIGINALFILENAME, OriginalFilename);
Add_Item(IDX_BUILDFLAGS, BuildFlags);
Add_Item(IDX_COMMENTS, Comments);
end
end;
{$ELSE}
procedure TdfsVersionInfoResource.BuildGrid;
const
FLAG_STRING: array [TFixedFileInfoFlag] of string = (SFlagDebug, SFlagInfoInferred, SFlagPatched, SFlagPreRelease, SFlagPrivate, SFlagSpecial);
procedure AddGridRow(var RowNum: integer; StrId: integer; Str: string);
var
i: integer;
begin
if (Str <> '') and (TPreDef(StrId) in FShowResource) then
begin
with VersionGrid do
begin
Cells[0, RowNum] := PREDEF_CAPTIONS[StrId];
Cells[1, RowNum] := Str;
i := Canvas.TextWidth(Str);
if i > ColWidths[1] then
ColWidths[1] := i + 4;
inc(RowNum);
end;
end;
end;
var
i, FRow: integer;
begin
With VersionGrid do
begin
{ Set Defaults }
FixedCols := 0;
FixedRows := 0;
ColCount := 2;
RowCount := 10;
Canvas.Font.Assign(Font);
DefaultRowHeight := Canvas.TextHeight(PREDEF_CAPTIONS[IDX_ORIGINALFILENAME]) + 2;
ColWidths[0] := Canvas.TextWidth(PREDEF_CAPTIONS[IDX_LEGALTRADEMARKS]) + 4;
ColWidths[1] := ClientWidth - ColWidths[0] - 1;
{ Clear }
for i := 0 to (ColCount - 1) do
Cols[i].Clear;
FRow := 0;
AddGridRow(FRow, IDX_PRODUCTNAME, ProductName);
AddGridRow(FRow, IDX_PRODUCTVERSION, ProductVersion.AsString);
AddGridRow(FRow, IDX_COMPANYNAME, CompanyName);
AddGridRow(FRow, IDX_LEGALCOPYRIGHT, LegalCopyright);
AddGridRow(FRow, IDX_LEGALTRADEMARKS, LegalTrademarks);
AddGridRow(FRow, IDX_FILEDESCRIPTION, FileDescription);
AddGridRow(FRow, IDX_FILEVERSION, FileVersion.AsString);
AddGridRow(FRow, IDX_INTERNALNAME, InternalName);
AddGridRow(FRow, IDX_ORIGINALFILENAME, OriginalFilename);
AddGridRow(FRow, IDX_BUILDFLAGS, BuildFlags);
AddGridRow(FRow, IDX_COMMENTS, Comments);
RowCount := FRow;
end;
end;
{$ENDIF}
function TdfsVersionInfoResource.GetVersion: string;
begin
Result := DFS_COMPONENT_VERSION;
end;
procedure TdfsVersionInfoResource.SetVersion(const Val: string);
begin
{ empty write method, just needed to get it to show up in Object Inspector }
end;
{$ENDIF}
end.
| 31.14244 | 149 | 0.714383 |
c375e6308909f4f984cbdf18ce28722b93f17899 | 2,189 | dpr | Pascal | src/convertxml.dpr | mrook/grendel | 428e2518868bcd459201e92e5338bae90b95fb59 | [
"BSD-3-Clause"
]
| null | null | null | src/convertxml.dpr | mrook/grendel | 428e2518868bcd459201e92e5338bae90b95fb59 | [
"BSD-3-Clause"
]
| null | null | null | src/convertxml.dpr | mrook/grendel | 428e2518868bcd459201e92e5338bae90b95fb59 | [
"BSD-3-Clause"
]
| null | null | null | program convertxml;
{$APPTYPE CONSOLE}
uses
Windows,
ActiveX,
xmldoc,
xmldom,
xmlintf,
SysUtils,
TypInfo,
skills,
console,
dtypes,
fsys,
race,
area;
var
are : GArea;
room : GRoom;
Count, Loop: Integer;
List: PPropList;
prop : PPropInfo;
iterator : GIterator;
doc : TXMLDocument;
child1, child2, node : IXMLNode;
begin
CoInitialize(nil);
try
doc := TXMLDocument.Create(nil);
doc.DOMVendor := DOMVendors[0];
doc.Active := true;
doc.Options := [doNodeAutoIndent];
doc.Encoding := 'iso-8859-1';
doc.Version := '1.0';
doc.NSPrefixBase := 'grendel';
node := doc.AddChild('area');
initRaces();
initSkills();
initAreas();
initConsole();
loadRaces();
are := GArea.Create();
are.load('roads.area');
Count := GetPropList(TypeInfo(GArea), tkAny, nil);
GetMem(List, Count * SizeOf(PPropInfo));
GetPropList(TypeInfo(GArea), tkAny, List);
for Loop := 0 to Pred(Count) do
begin
prop := List^[Loop];
child1 := node.addChild(prop^.Name);
case (prop.PropType^.Kind) of
tkInteger: child1.Text := IntToStr(GetOrdProp(are, prop));
tkFloat: child1.Text := FloatToStr(GetFloatProp(are, prop));
tkLString: child1.Text := GetStrProp(are, prop);
tkChar: child1.Text := char(GetOrdProp(are, prop));
end;
end;
FreeMem(List, Count * SizeOf(PPropInfo));
Count := GetPropList(TypeInfo(GRoom), tkAny, nil);
GetMem(List, Count * SizeOf(PPropInfo));
GetPropList(TypeInfo(GRoom), tkAny, List);
iterator := room_list.iterator();
while (iterator.hasNext()) do
begin
room := GRoom(iterator.next());
child1 := node.addChild('room');
for Loop := 0 to Pred(Count) do
begin
prop := List^[Loop];
child2 := child1.addChild(prop^.Name);
case (prop.PropType^.Kind) of
tkInteger: child2.Text := IntToStr(GetOrdProp(are, prop));
tkFloat: child2.Text := FloatToStr(GetFloatProp(are, prop));
tkLString: child2.Text := GetStrProp(are, prop);
tkChar: child2.Text := char(GetOrdProp(are, prop));
end;
end;
end;
FreeMem(List, Count * SizeOf(PPropInfo));
doc.SaveToFile('test.xml');
finally
CoUninitialize();
end;
end.
| 19.544643 | 65 | 0.64413 |
fcf2a7eb48ece948056848d9afbc67ba663cb6ea | 1,059 | pas | Pascal | Add prefix or suffix to Name.pas | Zebrina/FO4EditScripts | 64a35e6ff3cb168f0cacd011af0e5b8b0cd259e7 | [
"MIT"
]
| 4 | 2017-11-27T23:32:43.000Z | 2020-06-20T10:53:39.000Z | Add prefix or suffix to Name.pas | Zebrina/FO4EditScripts | 64a35e6ff3cb168f0cacd011af0e5b8b0cd259e7 | [
"MIT"
]
| null | null | null | Add prefix or suffix to Name.pas | Zebrina/FO4EditScripts | 64a35e6ff3cb168f0cacd011af0e5b8b0cd259e7 | [
"MIT"
]
| 1 | 2020-05-12T16:20:24.000Z | 2020-05-12T16:20:24.000Z | {
Just like 'Add prefix or suffix to Editor ID.pas' but with FULL - Name.
}
unit UserScript;
var
DoPrepend: boolean;
s: string;
function Initialize: integer;
var
i: integer;
begin
Result := 0;
// ask for prefix or suffix mode
i := MessageDlg('Prepend [YES] or append [NO] to Editor ID?', mtConfirmation, [mbYes, mbNo, mbCancel], 0);
if i = mrYes then DoPrepend := true else
if i = mrNo then DoPrepend := false else begin
Result := 1;
Exit;
end;
// ask for string
if not InputQuery('Enter', 'Prefix/suffix', s) then begin
Result := 2;
Exit;
end;
// empty string - do nothing
if s = '' then
Result := 3;
end;
function Process(e: IInterface): integer;
var
elEditorID: IInterface;
begin
Result := 0;
AddMessage('Processing: ' + Name(e));
elEditorID := ElementByName(e, 'FULL - Name');
if Assigned(elEditorID) then begin
if DoPrepend then
SetEditValue(elEditorID, s + GetEditValue(elEditorID))
else
SetEditValue(elEditorID, GetEditValue(elEditorID) + s);
end;
end;
end.
| 22.0625 | 108 | 0.653447 |
47cda0f4e05a3c4d053bf94531d3cfe7612ecd88 | 1,535 | pas | Pascal | samples/a8/graph/lines.pas | zbyti/Mad-Pascal | 546cae9724828f93047080109488be7d0d07d47e | [
"MIT"
]
| 1 | 2021-12-15T23:47:19.000Z | 2021-12-15T23:47:19.000Z | samples/a8/graph/lines.pas | michalkolodziejski/Mad-Pascal | 0a7a1e2f379e50b0a23878b0d881ff3407269ed6 | [
"MIT"
]
| null | null | null | samples/a8/graph/lines.pas | michalkolodziejski/Mad-Pascal | 0a7a1e2f379e50b0a23878b0d881ff3407269ed6 | [
"MIT"
]
| null | null | null | // 2829
uses crt, fastgraph;
const maxLines =16;
maxDrawLines =500;
type LineDescr = array [0..3] of smallint;
var Ball,
Vel,
max : LineDescr;
Lines : array [0..maxLines, 0..3] of smallint;
t : smallint;
count: word;
i, new, old: byte;
begin
randomize;
InitGraph(8 + 16);
max[0]:=ScreenWidth;
max[2]:=ScreenWidth;
max[3]:=ScreenHeight;
max[1]:=ScreenHeight;
for i := 3 downto 0 do begin
Vel[i] :=(random(0) and 7) shl 1 + 2;
Ball[i]:=random(smallint(max[i])) - 160;
end;
new := 0;
old := 0;
count := 0;
repeat
pause;
for i := 3 downto 0 do begin
t:=Ball[i]+Vel[i];
if t >= max[i] then begin
t := (max[i] shl 1) - Vel[i] - Ball[i];
Vel[i] := -Vel[i];
end;
if t<0 then begin
t := -t;
Vel[i] := -Vel[i];
end;
Ball[i] := t;
end;
if (count >= maxLines) then begin
SetColor(0);
Line (lines[old, 0], lines[old, 1], lines[old, 2], lines[old, 3]);
old:=byte(old+1) mod maxLines;
end;
Lines[new, 0] := Ball[0];
Lines[new, 1] := Ball[1];
Lines[new, 2] := Ball[2];
Lines[new, 3] := Ball[3];
new:=byte(new+1) mod maxLines;
SetColor(1);
Line (ball[0], ball[1], ball[2], ball[3]);
inc(count);
until (consol<>cn_none) or (count=MaxDrawLines);
repeat until consol<>cn_none;
end.
| 17.643678 | 75 | 0.477524 |
fc30853c90d5f6b4214b83e37d78241b6c2aaceb | 11,189 | pas | Pascal | EvilWorks.Vcl.ConsoleIO.pas | vedranvuk/EvilLibrary | 05b97e8689d47c2f97b3de510836f202130e2266 | [
"BSD-4-Clause"
]
| null | null | null | EvilWorks.Vcl.ConsoleIO.pas | vedranvuk/EvilLibrary | 05b97e8689d47c2f97b3de510836f202130e2266 | [
"BSD-4-Clause"
]
| null | null | null | EvilWorks.Vcl.ConsoleIO.pas | vedranvuk/EvilLibrary | 05b97e8689d47c2f97b3de510836f202130e2266 | [
"BSD-4-Clause"
]
| null | null | null | unit EvilWorks.Vcl.ConsoleIO;
interface
uses
WinApi.Windows,
WinApi.Messages,
System.Classes,
System.SysUtils,
Vcl.Forms;
const
MIO_OFFSET = $1911;
MIO_RECEIVE_OUTPUT = WM_USER + MIO_OFFSET + 0;
MIO_RECEIVE_ERROR = WM_USER + MIO_OFFSET + 1;
MIO_ERROR = WM_USER + MIO_OFFSET + 2;
MIO_PROCESS_TERMINATED = WM_USER + MIO_OFFSET + 3;
type
TReceiveEvent = procedure(Sender: TObject; const Cmd: string) of object;
TProcessStatusChangeEvent = procedure(Sender: TObject; IsRunning: Boolean) of object;
TSplitMode = (smNone, sm0D0A, smSplitchar);
{ TConsoleIO }
TConsoleIO = class(TComponent)
private
FWindowHandle : HWND;
InputReadPipe, InputWritePipe : THandle;
OutputReadPipe, OutputWritePipe: THandle;
ErrorReadPipe, ErrorWritePipe : THandle;
FProcessHandle : THandle;
FTerminateCommand : string;
FEnableKill : Boolean;
FWaitTimeout : Integer;
FStopProcessOnFree : Boolean;
FOutputBuffer : string;
FSplitReceive : Boolean;
FSplitSend : Boolean;
FSplitChar : Char;
FSplitMode : TSplitMode;
FOnReceiveError : TReceiveEvent;
FOnReceiveOutput : TReceiveEvent;
FOnError : TReceiveEvent;
FOnProcessStatusChange : TProcessStatusChangeEvent;
function GetIsRunning: Boolean;
procedure SetProcessHandle(const Value: THandle);
procedure ReceiveOutput(Buf: Pointer; Size: Integer);
procedure ReceiveError(Buf: Pointer; Size: Integer);
procedure Error(const Msg: string);
procedure ReaderProc(Handle: THandle; MessageCode: Integer);
procedure ProcessTerminated;
procedure CloseProcessHandle;
function SplitSendAvail: string;
property ProcessHandle: THandle read FProcessHandle write SetProcessHandle;
property OutputBuffer: string read FOutputBuffer write FOutputBuffer;
protected
procedure WndProc(var Msg: TMessage);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ClosePipes;
procedure SendInput(Msg: string);
procedure RunProcess(const CmdLine: string; CurrentDir: string = ''; ShowWindow: Boolean = False);
procedure StopProcess;
published
property EnableKill : Boolean read FEnableKill write FEnableKill default False;
property IsRunning : Boolean read GetIsRunning;
property SplitChar : Char read FSplitChar write FSplitChar default #10;
property SplitMode : TSplitMode read FSplitMode write FSplitMode default sm0D0A;
property SplitReceive : Boolean read FSplitReceive write FSplitReceive default True;
property SplitSend : Boolean read FSplitSend write FSplitSend default True;
property StopProcessOnFree: Boolean read FStopProcessOnFree write FStopProcessOnFree default True;
property TerminateCommand : string read FTerminateCommand write FTerminateCommand;
property WaitTimeout : Integer read FWaitTimeout write FWaitTimeout default 1000;
property OnError : TReceiveEvent read FOnError write FOnError;
property OnProcessStatusChange: TProcessStatusChangeEvent read FOnProcessStatusChange write FOnProcessStatusChange;
property OnReceiveError : TReceiveEvent read FOnReceiveError write FOnReceiveError;
property OnReceiveOutput : TReceiveEvent read FOnReceiveOutput write FOnReceiveOutput;
end;
implementation
{ Win API wrappers }
procedure WinCheck(Result: Boolean);
begin
if not Result then
RaiseLastOSError;
end;
procedure InprocessDuplicateHandle(Source: THandle; var Destination: THandle);
var
CurrentProcess: THandle;
begin
CurrentProcess := GetCurrentProcess;
WinCheck(DuplicateHandle(CurrentProcess, Source, CurrentProcess, @Destination, 0, False, DUPLICATE_SAME_ACCESS));
end;
procedure CloseAndZeroHandle(var Handle: THandle);
var
SaveHandle: THandle;
begin
SaveHandle := Handle;
Handle := 0;
WinCheck(CloseHandle(SaveHandle));
end;
function ToPChar(const St: string): PChar;
begin
if (St = EmptyStr) then
Result := nil
else
Result := PChar(St);
end;
{ Thread functions }
procedure IOReadOutput(Handler: TConsoleIO);
begin
Handler.ReaderProc(Handler.OutputReadPipe, MIO_RECEIVE_OUTPUT);
end;
procedure IOReadError(Handler: TConsoleIO);
begin
Handler.ReaderProc(Handler.ErrorReadPipe, MIO_RECEIVE_ERROR);
end;
procedure WaitProcess(Handler: TConsoleIO);
begin
if WaitForSingleObject(Handler.ProcessHandle, INFINITE) = WAIT_OBJECT_0 then
SendMessage(Handler.FWindowHandle, MIO_PROCESS_TERMINATED, 0, 0);
end;
{ TConsoleIO }
constructor TConsoleIO.Create(AOwner: TComponent);
begin
inherited;
FTerminateCommand := 'quit';
FSplitChar := #10;
FSplitMode := sm0D0A;
FSplitReceive := True;
FSplitSend := True;
FStopProcessOnFree := True;
FWaitTimeout := 1000;
FWindowHandle := AllocateHWnd(WndProc);
end;
destructor TConsoleIO.Destroy;
begin
if StopProcessOnFree then
StopProcess;
CloseProcessHandle;
DeallocateHWnd(FWindowHandle);
FWindowHandle := 0;
inherited;
end;
procedure TConsoleIO.ClosePipes;
begin
CloseAndZeroHandle(InputReadPipe);
CloseAndZeroHandle(OutputWritePipe);
CloseAndZeroHandle(ErrorWritePipe);
CloseAndZeroHandle(InputWritePipe);
CloseAndZeroHandle(OutputReadPipe);
CloseAndZeroHandle(ErrorReadPipe);
end;
procedure TConsoleIO.ReceiveOutput(Buf: Pointer; Size: Integer);
var
Cmd : string;
TastyStrPos: Integer;
begin
if (Size <= 0) then
Exit;
SetString(Cmd, PAnsiChar(Buf), Size);
OutputBuffer := OutputBuffer + Cmd;
if not Assigned(FOnReceiveOutput) then
Exit;
if not SplitReceive or (SplitMode = smNone) then
begin
FOnReceiveOutput(Self, OutputBuffer);
OutputBuffer := '';
end
else if SplitMode = sm0D0A then
repeat
TastyStrPos := Pos(#13#10, OutputBuffer);
if TastyStrPos = 0 then
Break;
FOnReceiveOutput(Self, Copy(OutputBuffer, 1, TastyStrPos - 1));
OutputBuffer := Copy(OutputBuffer, TastyStrPos + 2, Length(OutputBuffer));
until False
else if SplitMode = smSplitchar then
repeat
TastyStrPos := Pos(SplitChar, OutputBuffer);
if TastyStrPos = 0 then
Break;
FOnReceiveOutput(Self, Copy(OutputBuffer, 1, TastyStrPos - 1));
OutputBuffer := Copy(OutputBuffer, TastyStrPos + 1, Length(OutputBuffer));
until False;
end;
procedure TConsoleIO.ReceiveError(Buf: Pointer; Size: Integer);
var
Cmd: string;
begin
if (Size <= 0) then
Exit;
if not Assigned(FOnReceiveOutput) then
Exit;
SetString(Cmd, PAnsiChar(Buf), Size);
FOnReceiveError(Self, Cmd);
end;
procedure TConsoleIO.RunProcess(const CmdLine: string; CurrentDir: string = ''; ShowWindow: Boolean = False);
var
buffer: array [0 .. MAX_PATH] of Char;
SA : TSecurityAttributes;
SI : TStartupInfo;
PI : TProcessInformation;
InputWriteTmp: THandle;
OutputReadTmp: THandle;
ErrorReadTmp : THandle;
ThreadId: Cardinal;
begin
SA.nLength := SizeOf(SA);
SA.lpSecurityDescriptor := nil;
SA.bInheritHandle := True;
WinCheck(CreatePipe(InputReadPipe, InputWriteTmp, @SA, 0));
WinCheck(CreatePipe(OutputReadTmp, OutputWritePipe, @SA, 0));
WinCheck(CreatePipe(ErrorReadTmp, ErrorWritePipe, @SA, 0));
InprocessDuplicateHandle(InputWriteTmp, InputWritePipe);
InprocessDuplicateHandle(OutputReadTmp, OutputReadPipe);
InprocessDuplicateHandle(ErrorReadTmp, ErrorReadPipe);
CloseAndZeroHandle(InputWriteTmp);
CloseAndZeroHandle(OutputReadTmp);
CloseAndZeroHandle(ErrorReadTmp);
FillChar(SI, SizeOf(SI), $00);
SI.cb := SizeOf(SI);
SI.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
SI.hStdInput := InputReadPipe;
SI.hStdOutput := OutputWritePipe;
SI.hStdError := ErrorWritePipe;
if (ShowWindow) then
SI.wShowWindow := SW_SHOW
else
SI.wShowWindow := SW_HIDE;
ZeroMemory(@buffer, SizeOf(buffer));
CopyMemory(@buffer[0], @CmdLine[1], Length(CmdLine) * StringElementSize(CmdLine));
WinCheck(CreateProcess(nil, buffer, @SA, nil, True, CREATE_NEW_CONSOLE, nil, ToPChar(CurrentDir), SI, PI));
CloseAndZeroHandle(PI.hThread);
ProcessHandle := PI.hProcess;
WinCheck(BeginThread(nil, 0, @IOReadOutput, Self, 0, ThreadId) <> 0);
WinCheck(BeginThread(nil, 0, @IOReadError, Self, 0, ThreadId) <> 0);
WinCheck(BeginThread(nil, 0, @WaitProcess, Self, 0, ThreadId) <> 0);
end;
procedure TConsoleIO.SendInput(Msg: string);
var
BytesWritten: Cardinal;
bfr : ansistring;
begin
Msg := Msg + SplitSendAvail;
bfr := ansistring(Msg);
WinCheck(WriteFile(InputWritePipe, bfr[1], Length(Msg), BytesWritten, nil));
end;
procedure TConsoleIO.WndProc(var Msg: TMessage);
var
Unhandled: Boolean;
begin
with Msg do
begin
Unhandled := False;
try
case Msg of
MIO_RECEIVE_OUTPUT:
ReceiveOutput(Pointer(wParam), LParam);
MIO_RECEIVE_ERROR:
ReceiveError(Pointer(wParam), LParam);
MIO_PROCESS_TERMINATED:
ProcessTerminated;
MIO_ERROR:
Error(string(Pointer(wParam)))
else
Unhandled := True;
end;
except
Application.HandleException(Self);
end;
if Unhandled then
Result := DefWindowProc(FWindowHandle, Msg, wParam, LParam);
end;
end;
procedure TConsoleIO.Error(const Msg: string);
begin
if Assigned(FOnError) then
FOnError(Self, Msg);
end;
procedure TConsoleIO.ReaderProc(Handle: THandle; MessageCode: Integer);
var
Buf : array [0 .. 1024] of Char;
BytesRead: Cardinal;
Err : string;
begin
repeat
if not ReadFile(Handle, Buf, SizeOf(Buf), BytesRead, nil) then
try
if not IsRunning then
Exit;
RaiseLastOSError;
except
on E: Exception do
begin
Err := E.Message;
SendMessage(FWindowHandle, MIO_ERROR, Integer(PChar(Err)), Length(Err) + 1);
end;
end;
if BytesRead > 0 then
SendMessage(FWindowHandle, MessageCode, Integer(@Buf), BytesRead);
until False;
end;
procedure TConsoleIO.ProcessTerminated;
begin
if Assigned(FOnReceiveOutput) then
FOnReceiveOutput(Self, OutputBuffer);
OutputBuffer := '';
CloseProcessHandle;
ClosePipes;
end;
function TConsoleIO.GetIsRunning: Boolean;
begin
Result := ProcessHandle <> 0;
end;
procedure TConsoleIO.SetProcessHandle(const Value: THandle);
begin
if FProcessHandle = Value then
Exit;
Assert((ProcessHandle = 0) or (Value = 0));
FProcessHandle := Value;
if Assigned(FOnProcessStatusChange) then
FOnProcessStatusChange(Self, IsRunning);
end;
procedure TConsoleIO.CloseProcessHandle;
begin
if ProcessHandle = 0 then
Exit;
WinCheck(CloseHandle(ProcessHandle));
ProcessHandle := 0;
end;
procedure TConsoleIO.StopProcess;
begin
if not IsRunning then
Exit;
if TerminateCommand <> '' then
SendInput(TerminateCommand);
if not EnableKill then
Exit;
if TerminateCommand <> '' then
if WaitForSingleObject(ProcessHandle, WaitTimeout) = WAIT_OBJECT_0 then
Exit;
TerminateProcess(ProcessHandle, 4);
end;
function TConsoleIO.SplitSendAvail: string;
begin
Result := '';
if not SplitSend then
Exit;
if SplitMode = smNone then
Exit;
if SplitMode = sm0D0A
then
Result := #$0D#$0A
else
Result := SplitChar
end;
end.
| 28.113065 | 117 | 0.729645 |
83df0f6d789bd9b0a454464a9058080b08b0dfb3 | 90,509 | pas | Pascal | Lego/bricxcc/bricktools/backup/FantomSpirit.pas | jodosh/Personal | 92c943b95d3a07789d5f24faf60d4708040e22cb | [
"MIT"
]
| null | null | null | Lego/bricxcc/bricktools/backup/FantomSpirit.pas | jodosh/Personal | 92c943b95d3a07789d5f24faf60d4708040e22cb | [
"MIT"
]
| 1 | 2017-09-18T14:15:00.000Z | 2017-09-18T14:15:00.000Z | Lego/bricxcc/bricktools/backup/FantomSpirit.pas | jodosh/Personal | 92c943b95d3a07789d5f24faf60d4708040e22cb | [
"MIT"
]
| null | null | null | unit FantomSpirit;
interface
uses
Classes, SysUtils, rcx_cmd, uSpirit;
type
TFantomSpirit = class(TBrickComm)
private
fResPort : string;
fNXTHandle : Cardinal;
fResourceNames : TStrings;
// fNXTFileHandle : Cardinal;
// fNXTFileIteratorHandle : Cardinal;
dcResponse : array [0..63] of byte;
function TransferFirmware(aStream: TStream): boolean;
protected
function GetDownloadWaitTime: Integer; override;
function GetEEPROM(addr: Byte): Byte; override;
function GetEEPROMBlock(idx: Integer): EEPROMBlock; override;
function GetIsOpen: boolean; override;
function GetLSBlock(aPort: byte): NXTLSBlock; override;
function GetFullPortName: string; override;
function GetNicePortName: string; override;
function GetOmitHeader: Boolean; override;
function GetPortName: string; override;
function GetQuiet: Boolean; override;
function GetRCXFirmwareChunkSize: Integer; override;
function GetRxTimeout: Word; override;
function GetLinkLog: string; override;
function GetUseBT: Boolean; override;
procedure SetDownloadWaitTime(const Value: Integer); override;
procedure SetEEPROM(addr: Byte; const Value: Byte); override;
procedure SetLSBlock(aPort: byte; const Value: NXTLSBlock); override;
procedure SetOmitHeader(const Value: Boolean); override;
procedure SetPort(const Value: string); override;
procedure SetQuiet(const Value: Boolean); override;
procedure SetRCXFirmwareChunkSize(const Value: Integer); override;
procedure SetRxTimeout(const Value: Word); override;
protected
function dcBuffer: PByte;
function GetReplyByte(index: integer): Byte;
function GetReplyCardinal(index: integer): Cardinal;
function GetReplyWord(index: integer): Word;
procedure SetResourcePort(const name : string);
procedure LookupResourceName;
public
constructor Create(aType : TBrickType = 0; const aPort : string = 'COM1'); override;
destructor Destroy; override;
function Open : boolean; override;
function Close : boolean; override;
// PBrick sound commands
function PlayTone(aFreq, aTime : word) : boolean; override;
function PlaySystemSound(aSnd : byte) : boolean; override;
// PBrick output control commands
function MotorsOn(aMotorList : Byte) : boolean; override;
function MotorsOff(aMotorList : Byte) : boolean; override;
function MotorsFloat(aMotorList : Byte) : boolean; override;
function SetFwd(aMotorList : Byte) : boolean; override;
function SetRwd(aMotorList : Byte) : boolean; override;
function SwitchDirection(aMotorList : Byte) : boolean; override;
function SetMotorPower(aMotorList : Byte; aSrc, aNum : integer) : boolean; override;
// PBrick input control commands
function SetSensorType(aNum, aType : integer) : boolean; override;
function SetSensorMode(aNum, aMode, aSlope : integer) : boolean; override;
function ClearSensorValue(aNum : integer) : boolean; override;
// general
function TowerExists : boolean; override;
function Ping : boolean; override;
function PrepareBrick : boolean; override;
function UnlockFirmware : boolean; override;
function UnlockBrick : string; override;
function DownloadMemoryMap : TStrings; override;
function MonitorIR(aSeconds: integer): TStrings; override;
function PowerDownTime(aTime : integer) : boolean; override;
function BatteryLevel : integer; override;
function BrickAlive : boolean; override;
function Shutdown : boolean; override;
function Sleep(aVal : integer) : boolean; override;
function Version(var rom : Cardinal; var ram : Cardinal) : boolean; override;
function TransmitPower(aLevel : TTransmitLevel) : boolean; override;
function Poll(aSrc, aNum : integer) : integer; override;
function StartTask(aTask : integer) : boolean; override;
function StopTask(aTask : integer) : boolean; override;
function StopAllTasks : boolean; override;
function DeleteTask(aTask : integer) : boolean; override;
function DeleteAllTasks : boolean; override;
function DeleteSub(aSub : integer) : boolean; override;
function DeleteAllSubs : boolean; override;
function ClearTimer(aNum : integer) : boolean; override;
function ClearMemory : boolean; override;
function GetOutputStatus(aOut : integer) : integer; override;
function GetVariableValue(aVar: integer): integer; override;
function GetInputValue(aIn: integer): integer; override;
function GetMessageValue(aNum : integer) : integer; override;
function GetTimerValue(aNum : integer) : integer; override;
function GetCounterValue(aNum : integer) : integer; override;
// PBrick arithmetic/logical commands
function SetVar(aVar, aSrc, aNum : integer) : boolean; override;
function SumVar(aVar, aSrc, aNum : integer) : boolean; override;
function SubVar(aVar, aSrc, aNum : integer) : boolean; override;
function DivVar(aVar, aSrc, aNum : integer) : boolean; override;
function MulVar(aVar, aSrc, aNum : integer) : boolean; override;
function SgnVar(aVar, aSrc, aNum : integer) : boolean; override;
function AbsVar(aVar, aSrc, aNum : integer) : boolean; override;
function AndVar(aVar, aSrc, aNum : integer) : boolean; override;
function OrVar(aVar, aSrc, aNum : integer) : boolean; override;
// communication to brick
function SendRawCommand(aCmd : string; bRetry : boolean) : string; override;
function SendRemote(aEvent : string; aRepeat : integer = 1) : boolean; overload; override;
function SendRemote(aEvent : Word; aRepeat : integer = 1) : boolean; overload; override;
function SendMessage(aMsg : integer) : boolean; overload; override;
// RCX/2 only
function SelectProgram(aProg : integer) : boolean; override;
function SelectDisplay(aSrc, aNumber : integer) : boolean; override;
function SetWatch(aHrs, aMins : integer) : boolean; overload; override;
function SetWatch(aTime : string) : boolean; overload; override;
function DownloadFirmware(aFile : string; bFast, bComp, bUnlock : boolean) : boolean; override;
function SetDatalog(aSize : integer) : boolean; override;
function DatalogNext(aSrc, aNum : integer) : boolean; override;
function UploadDatalog(aFrom, aSize : integer) : TStrings; overload; override;
function UploadDatalog(bVerbose : boolean) : TStrings; overload; override;
// CM only methods
function Drive(aLeft, aRight : integer) : boolean; override;
function ClearTachoCounter(aMotorList : Byte) : boolean; override;
function OnWait(aMotorList : Byte; aNum : integer; aTime : Byte) : boolean; override;
function OnWaitDifferent(aMotorList : Byte; aNum0, aNum1, aNum2 : integer; aTime : Byte) : boolean; override;
// Scout only methods
function Scout(aVal : integer) : boolean; overload; override;
function Scout(bPower : boolean = true) : boolean; overload; override;
function CalibrateLightSensor : boolean; override;
function SetFeedback(src, val : integer) : boolean; override;
function SetLightSensorUpperThreshold(src : TLSSource; val : TThresholdValue) : boolean; override;
function SetLightSensorLowerThreshold(src : TLSSource; val : TThresholdValue) : boolean; override;
function SetLightSensorHysteresis(src : TLSSource; val : TThresholdValue) : boolean; override;
function SetLightSensorBlinkTime(src : TLSSource; val : TBlinkTimeValue) : boolean; override;
function SetTimerLimit(num : TTimerNumber; src : TTCSource; val : integer) : boolean; override;
function SetCounterLimit(num : TCounterNumber; src : TTCSource; val : integer) : boolean; override;
function ScoutRules(motion : TScoutMotion; touch : TScoutTouch;
light : TScoutLight; time : TScoutScale; fx : TScoutEffects) : boolean; override;
function ScoutSound(bSoundEnable : boolean; bSoundOff : boolean; aNum : TSoundSetNumber) : boolean; override;
// Scout & Spybot only methods
function SendVLL(aSrc, aNum : integer) : boolean; override;
function SetLight(bOn : boolean) : boolean; override;
// RCX2, Scout, & Spybot methods
function PollMemory(address : Integer; size : Integer = 128) : TStrings; override;
function SetGlobalOutput(motors : TMotorsNum; action : TGlobalOutAction) : boolean; override;
function SetGlobalDirection(motors : TMotorsNum; action : TGlobalDirAction) : boolean; override;
function SetMaxPower(motors : TMotorsNum; src, num : integer) : boolean; override;
function IncCounter(num : TCounterNumber) : boolean; override;
function DecCounter(num : TCounterNumber) : boolean; override;
function ClearCounter(num : TCounterNumber) : boolean; override;
// RCX2 & spybot only methods
function ClearSound : boolean; override;
function UnmuteSound : boolean; override;
function SendUARTData(start, size : integer) : boolean; override;
function SetEvent(enum, snum, etype : integer) : boolean; override;
function CalibrateEvent(enum, upper, lower, hysteresis : integer) : boolean; override;
function ClearAllEvents : boolean; override;
function SetSourceValue(aDestSrc, aDestVal, aOrigSrc: Byte; aOrigVal: Smallint): boolean; override;
// RCX2, Spy, & NXT
function MuteSound : boolean; override;
// RCX2 only methods
function ViewSourceValue(prec, src, value : integer) : boolean; override;
// Spybot only methods
function PollEEPROM(block : Integer = -1) : TStrings; override;
// NXT only methods
// NXT direct commands
function StartProgram(const filename : string) : boolean; override;
function StopProgram : boolean; override;
function PlaySoundFile(const filename : string; bLoop : boolean) : boolean; override;
function GetNXTOutputState(const aPort : byte; var power : integer;
var mode, regmode : byte; var turnratio : integer;
var runstate : byte; var tacholimit : cardinal; var tachocount,
blocktachocount, rotationcount : longint) : boolean; override;
function SetNXTOutputState(const aPort : byte; const power : integer;
const mode, regmode : byte; const turnratio : integer;
const runstate : byte; const tacholimit : cardinal) : boolean; override;
function GetNXTInputValues(const aPort : byte; var valid, calibrated : boolean;
var stype, smode : byte; var raw, normalized : word;
var scaled, calvalue : smallint) : boolean; override;
function SetNXTInputMode(const aPort, stype, smode : byte) : boolean; override;
function ResetInputScaledValue(const aPort : byte) : boolean; override;
function ResetOutputPosition(const aPort : byte; const Relative : boolean) : boolean; override;
function MessageWrite(const inbox : byte; const msg : string) : boolean; overload; override;
function KeepAlive(var time : cardinal; const chkResponse : boolean = true) : boolean; override;
function LSGetStatus(aPort : byte; var bytesReady : byte) : boolean; override;
function GetCurrentProgramName(var name : string) : boolean; override;
function GetButtonState(const idx : byte; const reset : boolean;
var pressed : boolean; var count : byte) : boolean; override;
function MessageRead(const remote, local : byte; const remove : boolean; var Msg : NXTMessage) : boolean; override;
// NXT system commands
function NXTOpenRead(const filename : string; var handle : cardinal;
var size : cardinal) : boolean; override;
function NXTOpenWrite(const filename : string; const size : cardinal;
var handle : cardinal) : boolean; override;
function NXTRead(var handle : cardinal; var count : word;
var buffer : NXTDataBuffer) : boolean; override;
function NXTWrite(var handle : cardinal; const buffer : NXTDataBuffer;
var count : word; const chkResponse : boolean = false) : boolean; override;
function NXTCloseFile(var handle : cardinal; const chkResponse: boolean = false) : boolean; override;
function NXTDeleteFile(var filename : string; const chkResponse: boolean = false) : boolean; override;
function NXTFindFirstFile(var filename : string; var handle : cardinal; var filesize : cardinal) : boolean; override;
function NXTFindNextFile(var handle : cardinal; var filename : string; var filesize : cardinal) : boolean; override;
function NXTGetVersions(var protmin, protmaj, firmmin, firmmaj : byte) : boolean; override;
function NXTOpenWriteLinear(const filename : string; const size : cardinal;
var handle : cardinal) : boolean; override;
function NXTOpenReadLinear(const filename : string; var handle : cardinal;
var size : cardinal) : boolean; override;
function NXTOpenWriteData(const filename : string; const size : cardinal;
var handle : cardinal) : boolean; override;
function NXTOpenAppendData(const filename : string; var size : cardinal;
var handle : cardinal) : boolean; override;
function NXTCloseModuleHandle(var handle : cardinal; const chkResponse: boolean = false) : boolean; override;
function NXTBootCommand(const chkResponse: boolean = false) : boolean; override;
function NXTSetBrickName(const name : string; const chkResponse: boolean = false) : boolean; override;
function NXTGetDeviceInfo(var name : string; BTAddress : PByte;
var BTSignal : Cardinal; var memFree : Cardinal) : boolean; override;
function NXTFreeMemory : integer; override;
function NXTDeleteUserFlash(const chkResponse: boolean = false) : boolean; override;
function NXTBTFactoryReset(const chkResponse: boolean = false) : boolean; override;
function NXTPollCommandLen(const bufNum : byte; var count : byte) : boolean; override;
function NXTPollCommand(const bufNum : byte; var count : byte;
var buffer : NXTDataBuffer) : boolean; override;
function NXTWriteIOMap(var ModID : Cardinal; const Offset : Word;
var count : Word; const buffer : NXTDataBuffer; chkResponse : Boolean = False) : boolean; override;
function NXTReadIOMap(var ModID : Cardinal; const Offset : Word;
var count : Word; var buffer : NXTDataBuffer) : boolean; override;
function NXTFindFirstModule(var ModName : string; var Handle : cardinal;
var ModID, ModSize : Cardinal; var IOMapSize : Word) : boolean; override;
function NXTFindNextModule(var Handle : cardinal; var ModName : string;
var ModID, ModSize : Cardinal; var IOMapSize : Word) : boolean; override;
function NXTRenameFile(const old, new : string; const chkResponse: boolean = false) : boolean; override;
{
kNXT_SCGetBTAddress = $9A;
}
// wrapper functions
function NXTDownloadFile(const filename : string; const filetype : TNXTFileType) : boolean; override;
function NXTDownloadStream(aStream : TStream; const dest : string; const filetype : TNXTFileType) : boolean; override;
function NXTUploadFile(const filename : string; const dir : string = '') : boolean; override;
function NXTListFiles(const searchPattern : string; Files : TStrings) : boolean; override;
function NXTListModules(const searchPattern : string; Modules : TStrings) : boolean; override;
function NXTListBricks(Bricks : TStrings) : boolean; override;
procedure NXTInitializeResourceNames; override;
end;
implementation
uses
rcx_constants, Contnrs, Math, uNXTConstants,
{$IFNDEF FPC}FANTOM{$ELSE}FANTOMFPC{$ENDIF};
function NXTModuleIDToName(const modID : cardinal) : string;
var
i : integer;
begin
Result := '*.*';
for i := Low(NXTModuleMap) to High(NXTModuleMap) do
begin
if NXTModuleMap[i].ID = modID then
begin
Result := NXTModuleMap[i].Name;
Break;
end;
end;
end;
{ TFantomSpirit }
constructor TFantomSpirit.Create(aType: TBrickType; const aPort: string);
begin
inherited Create(aType, aPort);
fResPort := '';
fResourceNames := TStringList.Create;
end;
destructor TFantomSpirit.Destroy;
begin
FreeAndNil(fResourceNames);
inherited Destroy;
end;
function TFantomSpirit.BatteryLevel: integer;
var
bopen : boolean;
cmd : TNINxtCmd;
status : integer;
begin
Result := -1;
bopen := IsOpen;
if bopen then
begin
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCGetBatteryLevel);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 4, status);
if status < kStatusNoError then
begin
result := kRCX_ReplyError;
Exit;
end;
Result := GetReplyWord(0);
finally
cmd.Free;
end;
end;
end;
function TFantomSpirit.Shutdown: boolean;
var
modID : Cardinal;
count : Word;
buffer : NXTDataBuffer;
begin
Result := IsOpen;
if not Result then Exit;
modID := kNXT_ModuleIOCtrl;
count := 2;
buffer.Data[0] := $0;
buffer.Data[1] := $5a;
Result := NXTWriteIOMap(modID, IOCtrlOffsetPowerOn, count, buffer);
end;
const
MotorBits : array[0..2] of byte = (1, 2, 4);
function TFantomSpirit.MotorsOn(aMotorList: Byte): boolean;
var
mode, regmode, runstate : byte;
oldpower, power, turnratio : integer;
tacholimit : cardinal;
tachocount, blocktachocount, rotationcount : integer;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorOn[i] := True;
Result := Result and GetNXTOutputState(i, oldpower, mode, regmode, turnratio,
runstate, tacholimit, tachocount, blocktachocount, rotationcount);
power := fMotorPower[i] * 14;
if not fMotorForward[i] then
power := power * -1;
if (oldpower <> power) or
((mode and OUT_MODE_MOTORON) <> OUT_MODE_MOTORON) or
((runstate and OUT_RUNSTATE_RUNNING) <> OUT_RUNSTATE_RUNNING) then
begin
mode := OUT_MODE_MOTORON+OUT_MODE_BRAKE;
runstate := OUT_RUNSTATE_RUNNING;
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
end;
if not Result then Break;
end;
end;
function TFantomSpirit.MotorsOff(aMotorList: Byte): boolean;
var
mode, regmode, runstate : byte;
power, turnratio : integer;
tacholimit : cardinal;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorOn[i] := False;
power := 0;
mode := OUT_MODE_MOTORON+OUT_MODE_BRAKE;
regmode := OUT_REGMODE_IDLE;
runstate := OUT_RUNSTATE_RUNNING;
turnratio := 0; // straight (side effect of stopping motors is to reset turn ratio)
tacholimit := 0; // no limit (side effect of stopping motors is to reset tacho limit)
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
if not Result then Break;
end;
end;
function TFantomSpirit.MotorsFloat(aMotorList: Byte): boolean;
var
mode, regmode, runstate : byte;
power, turnratio : integer;
tacholimit : cardinal;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorOn[i] := False;
power := 0;
mode := 0; // OUT_MODE_COAST;
regmode := 0; // OUT_REGMODE_IDLE;
runstate := 0; // OUT_RUNSTATE_IDLE;
turnratio := 0; // straight (side effect of stopping motors is to reset turn ratio)
tacholimit := 0; // no limit (side effect of stopping motors is to reset tacho limit)
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
if not Result then Break;
end;
end;
function TFantomSpirit.SetFwd(aMotorList: Byte): boolean;
var
mode, regmode, runstate : byte;
power, turnratio : integer;
tacholimit : cardinal;
tachocount, blocktachocount, rotationcount : integer;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorForward[i] := True;
Result := Result and GetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit, tachocount, blocktachocount, rotationcount);
if power < 0 then
begin
power := power * -1;
if not fMotorOn[i] then
begin
// make sure we are idle
mode := 0;
regmode := 0;
runstate := 0;
end;
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
end;
if not Result then Break;
end;
end;
function TFantomSpirit.SetRwd(aMotorList: Byte): boolean;
var
mode, regmode, runstate : byte;
power, turnratio : integer;
tacholimit : cardinal;
tachocount, blocktachocount, rotationcount : integer;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorForward[i] := False;
Result := Result and GetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit, tachocount, blocktachocount, rotationcount);
if power > 0 then
begin
power := power * -1;
if not fMotorOn[i] then
begin
// make sure we are idle
mode := 0;
regmode := 0;
runstate := 0;
end;
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
end;
if not Result then Break;
end;
end;
function TFantomSpirit.SwitchDirection(aMotorList: Byte): boolean;
var
mode, regmode, runstate : byte;
power, turnratio : integer;
tacholimit : cardinal;
tachocount, blocktachocount, rotationcount : integer;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorForward[i] := not fMotorForward[i];
Result := Result and GetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit, tachocount, blocktachocount, rotationcount);
power := power * -1;
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
if not Result then Break;
end;
end;
function TFantomSpirit.SetMotorPower(aMotorList: Byte; aSrc, aNum: integer): boolean;
var
mode, regmode, runstate : byte;
oldpower, power, turnratio : integer;
tacholimit : cardinal;
tachocount, blocktachocount, rotationcount : integer;
i : integer;
begin
Result := IsOpen;
if not Result then Exit;
if aSrc <> 2 then
begin
Result := False;
Exit;
end
else
begin
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
fMotorPower[i] := Abs(aNum) mod 8;
Result := Result and GetNXTOutputState(i, oldpower, mode, regmode, turnratio,
runstate, tacholimit, tachocount, blocktachocount, rotationcount);
power := fMotorPower[i] * 14;
if fMotorPower[i] = 7 then
power := 100;
if not fMotorForward[i] then
power := power * -1;
if oldpower <> power then
begin
if not fMotorOn[i] then
begin
// make sure we are idle
mode := 0;
regmode := 0;
runstate := 0;
end;
Result := Result and SetNXTOutputState(i, power, mode, regmode, turnratio,
runstate, tacholimit);
end;
end;
if not Result then Break;
end;
end;
end;
function TFantomSpirit.PlayTone(aFreq, aTime: word): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmdNoReply, kNXT_DCPlayTone, Lo(aFreq), Hi(aFreq), Lo(aTime), Hi(aTime));
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.SetSensorType(aNum, aType: integer): boolean;
begin
Result := IsOpen;
if not Result then Exit;
fSensorType[aNum] := aType;
Result := SetNXTInputMode(aNum, aType, fSensorMode[aNum]);
end;
function TFantomSpirit.SetSensorMode(aNum, aMode, aSlope: integer): boolean;
begin
Result := IsOpen;
if not Result then Exit;
fSensorMode[aNum] := ((aMode and $7) shl 5) or (aSlope and $F);
Result := SetNXTInputMode(aNum, fSensorType[aNum], fSensorMode[aNum]);
end;
function TFantomSpirit.ClearSensorValue(aNum: integer): boolean;
begin
Result := ResetInputScaledValue(aNum);
end;
function TFantomSpirit.Close: boolean;
var
status : integer;
begin
Result := True;
if IsOpen then
begin
fResPort := ''; // clear this so that it gets looked up again when opening
status := kStatusNoError;
destroyNXT(fNXTHandle, status);
fActive := False;
fNXTHandle := 0;
Result := status >= kStatusNoError;
end;
end;
function TFantomSpirit.Open: boolean;
var
nih : Cardinal;
status, status2 : integer;
resNamePC : array[0..54] of Char;
pairedResNamePC : array[0..54] of Char;
resName, pName, bName : string;
begin
Result := IsOpen;
if not FantomAPILoaded then Exit;
if not Result then begin
if fResPort = '' then
LookupResourceName;
if fResPort = '' then
fResPort := fPort;
resName := '';
pName := AnsiUpperCase(fResPort);
bName := AnsiUpperCase(BluetoothName);
if (Length(pName) > 4) and (Pos('::', pName) > 0) then
begin
// we think this is a resource string
// if we are using bluetooth then we need to make sure we are paired
// with the brick
status := kStatusNoError;
if UseBluetooth then // resource string starts with BTH == use bluetooth
begin
// unpairBluetooth(PChar(pName), status);
pairBluetooth(PChar(pName), '1234', pairedResNamePC, status);
pName := pairedResNamePC;
end;
if status >= kStatusNoError then
begin
status := kStatusNoError;
fNXTHandle := createNXT(PChar(pName), status, 0);
if status >= kStatusNoError then
begin
fActive := True;
Result := True;
end;
end;
end
else
begin
// use Fantom API to obtain a handle to an NXT on either USB or bluetooth
status := kStatusNoError;
nih := createNXTIterator(Ord(UseBluetooth), BluetoothSearchTimeout, status);
while status >= kStatusNoError do
begin
status2 := kStatusNoError;
iNXTIterator_getName(nih, resNamePC, status2);
resName := AnsiUpperCase(resNamePC);
if UseBluetooth then
begin
if bName = '' then
bName := 'BTH';
if Pos(bName, resName) > 0 then
Break;
end
else if Pos(pName, resName) > 0 then
Break;
iNXTIterator_advance(nih, status);
end;
// if we are using bluetooth then we need to make sure we are paired
// with the brick
if UseBluetooth then
begin
status := kStatusNoError;
pairBluetooth(resNamePC, '1234', pairedResNamePC, status);
resName := AnsiUpperCase(pairedResNamePC);
end;
if status >= kStatusNoError then
begin
fNXTHandle := iNXTIterator_getNXT(nih, status);
if status >= kStatusNoError then
begin
SetResourcePort(resName);
fActive := True;
Result := True;
end;
end;
status := kStatusNoError;
destroyNXTIterator(nih, status);
end;
end;
end;
function TFantomSpirit.ClearMemory: boolean;
begin
Result := NXTDeleteUserFlash(True);
end;
function TFantomSpirit.Sleep(aVal: integer): boolean;
begin
Result := PowerDownTime(aVal);
end;
function TFantomSpirit.GetInputValue(aIn : integer) : integer;
var
bOpen : boolean;
begin
Result := -1;
bopen := Open;
if bOpen then
begin
Result := Poll(kRCX_InputValueType, aIn);
end;
end;
procedure TFantomSpirit.SetPort(const Value: string);
begin
if (Value <> fPort) or (fResPort = '') then
begin
Close;
inherited SetPort(Value);
fResPort := fPort;
LookupResourceName;
end;
end;
function TFantomSpirit.DownloadFirmware(aFile: string; bFast : Boolean;
bComp : Boolean; bUnlock : boolean): boolean;
var
MS : TMemoryStream;
begin
if not IsOpen then
Open;
Result := FileExists(aFile);
if Result then
begin
MS := TMemoryStream.Create;
try
MS.LoadFromFile(aFile);
DoDownloadStart;
Result := NXTDownloadStream(MS, aFile, nftFirmware);
DoDownloadDone;
finally
MS.Free;
end;
end;
end;
function TFantomSpirit.Ping: boolean;
var
time : cardinal;
begin
Result := IsOpen;
if not Result then Exit;
Result := KeepAlive(time);
end;
function TFantomSpirit.MuteSound: boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmdNoReply, kNXT_DCStopSoundPlayback);
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.UnmuteSound: boolean;
var
cmd : TNINxtCmd;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
// TODO : Implement Unmute Sound
finally
cmd.Free;
end;
end;
function TFantomSpirit.GetPortName: string;
begin
Result := FPort;
end;
function TFantomSpirit.GetFullPortName: string;
begin
Result := fResPort;
end;
function TFantomSpirit.GetNicePortName: string;
var
i : integer;
begin
i := Pos('::', fResPort);
if i > 0 then
Result := Copy(fResPort, 1, i-1)
else
Result := fResPort;
end;
function TFantomSpirit.GetIsOpen: boolean;
begin
Result := inherited GetIsOpen;
Result := Result and FantomAPILoaded;
end;
function TFantomSpirit.StartProgram(const filename: string): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.MakeCmdWithFilename(kNXT_DirectCmd, kNXT_DCStartProgram, filename);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 2, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.StopProgram: boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCStopProgram);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 2, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.PlaySoundFile(const filename: string; bLoop: boolean): boolean;
var
i : integer;
cmd : TNINxtCmd;
orig : PByte;
nxtFilename : string;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
// filename is limited to 19 bytes + null terminator
cmd.SetLength(23);
orig := cmd.GetBody;
orig^ := kNXT_DirectCmdNoReply;
inc(orig);
orig^ := kNXT_DCPlaySoundFile;
inc(orig);
orig^ := Ord(bLoop);
inc(orig);
i := 1;
nxtFilename := MakeValidNXTFilename(filename);
while i <= 19 do
begin
// copy the first nineteen bytes from the filename provided
if i > Length(nxtFilename) then
orig^ := 0
else
orig^ := Ord(nxtFilename[i]);
inc(orig);
inc(i);
end;
orig^ := 0; // set last byte to null
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.GetNXTOutputState(const aPort: byte; var power: integer;
var mode, regmode: byte; var turnratio: integer; var runstate: byte;
var tacholimit: cardinal; var tachocount, blocktachocount, rotationcount: Integer): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCGetOutputState, aPort);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 24, status);
Result := status >= kStatusNoError;
if not Result then
Exit;
// port := GetReplyByte(0)
power := ShortInt(GetReplyByte(1));
mode := GetReplyByte(2);
regmode := GetReplyByte(3);
turnratio := ShortInt(GetReplyByte(4));
runstate := GetReplyByte(5);
tacholimit := GetReplyCardinal(6);
tachocount := Integer(GetReplyCardinal(10));
blocktachocount := Integer(GetReplyCardinal(14));
rotationcount := Integer(GetReplyCardinal(18));
finally
cmd.Free;
end;
end;
function TFantomSpirit.SetNXTOutputState(const aPort: byte;
const power: integer; const mode, regmode: byte;
const turnratio: integer; const runstate: byte;
const tacholimit: cardinal): boolean;
var
cmd : TNINxtCmd;
// orig : PByte;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.MakeSetOutputState(aPort, mode, regmode, runstate, power, turnratio, tacholimit, False);
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.GetNXTInputValues(const aPort: byte; var valid,
calibrated: boolean; var stype, smode: byte; var raw, normalized: word;
var scaled, calvalue: smallint): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCGetInputValues, aPort);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 15, status);
Result := status >= kStatusNoError;
if not Result then
Exit;
// port := GetReplyByte(0);
valid := GetReplyByte(1) <> 0;
calibrated := GetReplyByte(2) <> 0;
stype := GetReplyByte(3);
smode := GetReplyByte(4);
raw := GetReplyWord(5);
normalized := GetReplyWord(7);
scaled := SmallInt(GetReplyWord(9));
calvalue := SmallInt(GetReplyWord(11));
finally
cmd.Free;
end;
end;
function TFantomSpirit.SetNXTInputMode(const aPort, stype, smode: byte): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmdNoReply, kNXT_DCSetInputMode, aPort, stype, smode);
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.ResetInputScaledValue(const aPort: byte): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmdNoReply, kNXT_DCResetInputScaledValue, aPort);
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.ResetOutputPosition(const aPort: byte;
const Relative: boolean): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmdNoReply, kNXT_DCResetMotorPosition, aPort, Ord(Relative));
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.MessageWrite(const inbox: byte; const msg: string): boolean;
var
i, len : integer;
cmd : TNINxtCmd;
orig : PByte;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
// message is limited to 59 bytes + null terminator
len := Min(Length(msg), kNXT_MaxBytes-5);
cmd.SetLength(len+5);
orig := cmd.GetBody;
orig^ := kNXT_DirectCmdNoReply;
inc(orig);
orig^ := kNXT_DCMessageWrite;
inc(orig);
orig^ := inbox;
inc(orig);
orig^ := len+1; // add null terminator
inc(orig);
i := 1;
while i <= len do
begin
orig^ := Ord(msg[i]);
inc(orig);
inc(i);
end;
orig^ := 0; // set last byte to null
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
function TFantomSpirit.KeepAlive(var time: cardinal; const chkResponse : boolean): boolean;
var
cmd : TNINxtCmd;
b : byte;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
result := False;
if chkResponse then
b := kNXT_DirectCmd
else
b := kNXT_DirectCmdNoReply;
cmd.SetVal(b, kNXT_DCKeepAlive);
if chkResponse then
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 6, status)
else
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
Result := status >= kStatusNoError;
if chkResponse then
begin
if not Result then
Exit;
time := Integer(GetReplyCardinal(0));
end;
finally
cmd.Free;
end;
end;
function TFantomSpirit.LSGetStatus(aPort : byte; var bytesReady: byte): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCLSGetStatus, aPort);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 3, status);
Result := status >= kStatusNoError;
if not Result then
Exit;
bytesReady := GetReplyByte(0);
finally
cmd.Free;
end;
end;
function TFantomSpirit.GetLSBlock(aPort: byte): NXTLSBlock;
var
cmd : TNINxtCmd;
i : integer;
status : integer;
begin
// LSRead
Result.TXCount := 0;
if not IsOpen then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCLSRead, aPort);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 19, status);
if status < kStatusNoError then
begin
Result.RXCount := 0;
Exit;
end;
Result.RXCount := GetReplyByte(0);
for i := 1 to 16 do
begin
Result.Data[i-1] := GetReplyByte(i);
end;
finally
cmd.Free;
end;
end;
procedure TFantomSpirit.SetLSBlock(aPort: byte; const Value: NXTLSBlock);
var
i, len : integer;
cmd : TNINxtCmd;
orig : PByte;
status : integer;
begin
// LSWrite
if not IsOpen then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
len := Min(Value.TXCount, 16);
cmd.SetLength(len+5); // up to a max of 21 bytes
orig := cmd.GetBody;
orig^ := kNXT_DirectCmdNoReply;
inc(orig);
orig^ := kNXT_DCLSWrite;
inc(orig);
orig^ := aPort;
inc(orig);
orig^ := len;
inc(orig);
orig^ := Min(Value.RXCount, 16);
inc(orig);
i := 0;
while i < len do
begin
orig^ := Value.Data[i];
inc(orig);
inc(i);
end;
orig^ := 0; // set last byte to null
iNXT_sendDirectCommand(fNXTHandle, 0, cmd.BytePtr, cmd.Len, nil, 0, status);
finally
cmd.Free;
end;
end;
function TFantomSpirit.GetCurrentProgramName(var name: string): boolean;
var
cmd : TNINxtCmd;
i : integer;
Buf : array[0..19] of Char;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCGetCurrentProgramName);
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 22, status);
Result := status >= kStatusNoError;
if not Result then
begin
name := '';
Exit;
end;
for i := 0 to 19 do
begin
Buf[i] := Char(GetReplyByte(i));
end;
name := Buf;
finally
cmd.Free;
end;
end;
function TFantomSpirit.GetButtonState(const idx: byte; const reset: boolean;
var pressed: boolean; var count: byte): boolean;
var
cmd : TNINxtCmd;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCGetButtonState, idx, Ord(reset));
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 3, status);
Result := status >= kStatusNoError;
if not Result then
Exit;
pressed := Boolean(GetReplyByte(0));
count := GetReplyByte(1);
finally
cmd.Free;
end;
end;
function TFantomSpirit.MessageRead(const remote, local: byte;
const remove: boolean; var Msg: NXTMessage): boolean;
var
cmd : TNINxtCmd;
i : integer;
status : integer;
begin
Msg.Inbox := 0;
Msg.Size := 0;
Result := IsOpen;
if not Result then Exit;
cmd := TNINxtCmd.Create;
try
status := kStatusNoError;
cmd.SetVal(kNXT_DirectCmd, kNXT_DCMessageRead, remote, local, Ord(remove));
iNXT_sendDirectCommand(fNXTHandle, 1, cmd.BytePtr, cmd.Len, dcBuffer, 63, status);
Result := status >= kStatusNoError;
if not Result then
Exit;
Msg.Inbox := GetReplyByte(0);
Msg.Size := GetReplyByte(1);
for i := 2 to 60 do
begin
Msg.Data[i-2] := GetReplyByte(i);
end;
finally
cmd.Free;
end;
end;
function TFantomSpirit.NXTOpenRead(const filename: string; var handle: cardinal;
var size: cardinal): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFile(fNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFile_openForRead(handle, status);
Result := status >= kStatusNoError;
if Result then
begin
size := iFile_getSize(handle, status);
Result := status >= kStatusNoError;
end;
if not Result then
begin
status := kStatusNoError;
iNXT_destroyFile(fNXTHandle, handle, status);
end;
end;
end;
function TFantomSpirit.NXTOpenReadLinear(const filename: string;
var handle: cardinal; var size: cardinal): boolean;
begin
Result := NXTOpenRead(filename, handle, size);
end;
function TFantomSpirit.NXTOpenAppendData(const filename: string;
var size: cardinal; var handle: cardinal): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFile(fNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFile_openForDataAppend(handle, status);
Result := status >= kStatusNoError;
if Result then
begin
size := iFile_getSize(handle, status);
Result := status >= kStatusNoError;
end;
if not Result then
begin
status := kStatusNoError;
iNXT_destroyFile(fNXTHandle, handle, status);
end;
end;
end;
function TFantomSpirit.NXTOpenWrite(const filename: string;
const size: cardinal; var handle: cardinal): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFile(fNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFile_openForWrite(handle, size, status);
Result := status >= kStatusNoError;
if not Result then
begin
status := kStatusNoError;
iNXT_destroyFile(fNXTHandle, handle, status);
end;
end;
end;
function TFantomSpirit.NXTOpenWriteData(const filename: string;
const size: cardinal; var handle: cardinal): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFile(fNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFile_openForDataWrite(handle, size, status);
Result := status >= kStatusNoError;
if not Result then
begin
status := kStatusNoError;
iNXT_destroyFile(fNXTHandle, handle, status);
end;
end;
end;
function TFantomSpirit.NXTOpenWriteLinear(const filename: string;
const size: cardinal; var handle: cardinal): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFile(fNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFile_openForLinearWrite(handle, size, status);
Result := status >= kStatusNoError;
if not Result then
begin
status := kStatusNoError;
iNXT_destroyFile(fNXTHandle, handle, status);
end;
end;
end;
function TFantomSpirit.NXTRead(var handle: cardinal; var count: word;
var buffer: NXTDataBuffer): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iFile_read(handle, @buffer.Data[0], count, status);
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTWrite(var handle: cardinal; const buffer: NXTDataBuffer;
var count: word; const chkResponse: boolean): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iFile_write(handle, @buffer.Data[0], count, status);
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTCloseFile(var handle: cardinal; const chkResponse: boolean): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iFile_close(handle, status);
Result := status >= kStatusNoError;
if Result then
begin
iNXT_destroyFile(FNXTHandle, handle, status);
Result := status >= kStatusNoError;
end;
end;
function TFantomSpirit.NXTDeleteFile(var filename: string; const chkResponse: boolean): boolean;
var
handle : cardinal;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFile(FNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFile_remove(handle, status);
Result := status >= kStatusNoError;
status := kStatusNoError;
iNXT_destroyFile(FNXTHandle, handle, status);
end;
end;
function TFantomSpirit.NXTFindFirstFile(var filename: string;
var handle: cardinal; var filesize : cardinal): boolean;
var
status : integer;
buf : array[0..19] of Char;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
handle := iNXT_createFileIterator(FNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
iFileIterator_getName(handle, buf, status);
filename := buf;
status := kStatusNoError;
filesize := iFileIterator_getSize(handle, status);
end;
end;
function TFantomSpirit.NXTFindNextFile(var handle: cardinal; var filename: string;
var filesize : cardinal): boolean;
var
status : integer;
Buf : array[0..19] of Char;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iFileIterator_advance(handle, status);
Result := status >= kStatusNoError;
if Result then
begin
iFileIterator_getName(handle, buf, status);
filename := buf;
status := kStatusNoError;
filesize := iFileIterator_getSize(handle, status);
end
else
begin
// destroy the iterator
status := kStatusNoError;
iNXT_destroyFileIterator(fNXTHandle, handle, status);
handle := 0;
filename := '';
end;
end;
function TFantomSpirit.NXTGetVersions(var protmin, protmaj, firmmin, firmmaj : byte): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_getFirmwareVersion(fNXTHandle, protmaj, protmin, firmmaj, firmmin, status);
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTCloseModuleHandle(var handle: cardinal; const chkResponse: boolean): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_destroyModule(fNXTHandle, handle, status);
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTBootCommand(const chkResponse: boolean): boolean;
var
status : integer;
resBuf : array[0..60] of Char;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_getResourceString(fNXTHandle, resBuf, status);
Result := status >= kStatusNoError;
if Result then
begin
iNXT_bootIntoFirmwareDownloadMode(resBuf, status);
Result := status >= kStatusNoError;
end;
end;
function TFantomSpirit.NXTSetBrickName(const name: string; const chkResponse: boolean): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_setName(fNXTHandle, PChar(name), status);
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTGetDeviceInfo(var name: string;
BTAddress : PByte; var BTSignal : Cardinal; var memFree : Cardinal): boolean;
var
status : integer;
buf : array[0..20] of Char;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_getDeviceInfo(fNXTHandle, buf, BTAddress, @BTSignal, memFree, status);
name := buf;
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTDeleteUserFlash(const chkResponse: boolean): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_eraseUserFlash(fNXTHandle, status);
Result := status >= kStatusNoError;
end;
function TFantomSpirit.NXTBTFactoryReset(const chkResponse: boolean): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iNXT_bluetoothFactoryReset(fNXTHandle, status);
Result := status >= kStatusNoError;
end;
type
TFileInfoRec = class
public
FileHandle : Cardinal;
TotalSize : Cardinal;
AvailableSize : Cardinal;
Name : string;
end;
function TFantomSpirit.NXTUploadFile(const filename: string; const dir : string): boolean;
var
handle : cardinal;
size, totalSize, availableSize : Cardinal;
MS : TMemoryStream;
tmpFilename : string;
NXTFileIteratorHandle : Cardinal;
status, i : integer;
buf : array[0..20] of Char;
fileBuf : PByte;
bEOFOnRead : boolean;
FIR : TFileInfoRec;
OL : TObjectList;
begin
Result := IsOpen;
if not Result then Exit;
// upload means from NXT to PC
OL := TObjectList.Create;
try
status := kStatusNoError;
NXTFileIteratorHandle := iNXT_createFileIterator(fNXTHandle, PChar(filename), status);
Result := status >= kStatusNoError;
if Result then
begin
while status >= kStatusNoError do
begin
iFileIterator_getName(NXTFileIteratorHandle, buf, status);
tmpFilename := buf;
status := kStatusNoError;
totalSize := iFileIterator_getSize(NXTFileIteratorHandle, status);
status := kStatusNoError;
handle := iFileIterator_getFile(NXTFileIteratorHandle, status);
status := kStatusNoError;
availableSize := iFile_getAvailableSize(handle, status);
// save the info for this file into our object list
FIR := TFileInfoRec.Create;
OL.Add(FIR);
FIR.FileHandle := handle;
FIR.Name := tmpFilename;
FIR.TotalSize := totalSize;
FIR.AvailableSize := availableSize;
// advance to the next file
status := kStatusNoError;
iFileIterator_advance(NXTFileIteratorHandle, status);
end;
status := kStatusNoError;
iNXT_destroyFileIterator(fNXTHandle, NXTFileIteratorHandle, status);
Result := OL.Count > 0;
for i := 0 to OL.Count - 1 do
begin
FIR := TFileInfoRec(OL.Items[i]);
tmpFilename := FIR.Name;
handle := FIR.FileHandle;
size := FIR.TotalSize - FIR.AvailableSize;
status := kStatusNoError;
iFile_openForRead(handle, status);
MS := TMemoryStream.Create;
try
GetMem(fileBuf, size);
try
FillChar(fileBuf^, size, 0);
status := kStatusNoError;
iFile_read(handle, fileBuf, size, status);
bEOFOnRead := status = kStatusFWEndOfFile;
Result := (status >= kStatusNoError) or bEOFOnRead;
if Result then
MS.Write(fileBuf^, size);
finally
FreeMem(fileBuf);
end;
// hmmm we may have a problem here. If we encountered an EOF on
// read then that means the file we are trying to upload is one of
// those files which has been created using the syscall file io
// functions and it's contents are less than its reported size.
// In that case we need to discard what we just did and try to
// read the file one byte at a time.
if bEOFOnRead then
begin
status := kStatusNoError;
iFile_close(handle, status); // close the file and reopen it
status := kStatusNoError;
iFile_openForRead(handle, status);
Result := status >= kStatusNoError;
MS.Clear; // empty the stream
GetMem(fileBuf, 1);
try
FillChar(fileBuf^, 1, 0);
while status >= kStatusNoError do
begin
iFile_read(handle, fileBuf, 1, status);
if status >= kStatusNoError then
MS.Write(fileBuf^, 1);
end;
finally
FreeMem(fileBuf);
end;
end;
// now try to save the file
if dir <> '' then
tmpFilename := IncludeTrailingPathDelimiter(dir) + tmpFilename;
if Result then
MS.SaveToFile(tmpFilename);
finally
MS.Free;
end;
NXTCloseFile(handle);
end;
end;
finally
OL.Free;
end;
end;
function TFantomSpirit.NXTListFiles(const searchPattern: string; Files: TStrings): boolean;
var
size : Cardinal;
tmpfilename : string;
NXTFileIteratorHandle : Cardinal;
buf : array[0..20] of Char;
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
NXTFileIteratorHandle := iNXT_createFileIterator(fNXTHandle, PChar(searchPattern), status);
Result := status >= kStatusNoError;
while status >= kStatusNoError do
begin
iFileIterator_getName(NXTFileIteratorHandle, buf, status);
tmpFilename := buf;
size := iFileIterator_getSize(NXTFileIteratorHandle, status);
Files.Add(tmpfilename + '=' + IntToStr(size));
Result := status >= kStatusNoError;
iFileIterator_advance(NXTFileIteratorHandle, status);
end;
status := kStatusNoError;
iNXT_destroyFileIterator(fNXTHandle, NXTFileIteratorHandle, status);
end;
function TFantomSpirit.NXTListModules(const searchPattern: string;
Modules: TStrings): boolean;
var
size, mID, NXTModuleIteratorHandle, handle : Cardinal;
buf : array[0..20] of Char;
status : integer;
iosize : Word;
tmpname : string;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
NXTModuleIteratorHandle := iNXT_createModuleIterator(fNXTHandle, PChar(searchPattern), status);
Result := status >= kStatusNoError;
while status >= kStatusNoError do
begin
handle := iModuleIterator_getModule(NXTModuleIteratorHandle, status);
iModule_getName(handle, buf, status);
tmpname := buf;
status := kStatusNoError;
iosize := iModule_getIOMapSize(handle, status);
status := kStatusNoError;
mID := iModule_getModuleID(handle, status);
status := kStatusNoError;
size := iModule_getModuleSize(handle, status);
Modules.Add(Format('%s=%d, %d, %d', [tmpname, mID, size, iosize]));
status := kStatusNoError;
iNXT_destroyModule(fNXTHandle, handle, status);
status := kStatusNoError;
iModuleIterator_advance(NXTModuleIteratorHandle, status);
end;
status := kStatusNoError;
iNXT_destroyModuleIterator(fNXTHandle, NXTModuleIteratorHandle, status);
end;
function TFantomSpirit.NXTDownloadFile(const filename: string;
const filetype: TNXTFileType): boolean;
var
MS : TMemoryStream;
begin
Result := IsOpen;
if not Result then Exit;
// download means from PC to NXT
Result := FileExists(filename);
if Result then
begin
MS := TMemoryStream.Create;
try
MS.LoadFromFile(filename);
Result := NXTDownloadStream(MS, filename, filetype);
finally
MS.Free;
end;
end;
end;
function TFantomSpirit.TransferFirmware(aStream : TStream) : boolean;
var
size : Cardinal;
resBuf : array[0..255] of Char;
status : integer;
buf : PByte;
elapsedTime : Cardinal;
bStop : boolean;
cur, i : integer;
const
K_SEC = 1000;
MaximumWait = 15*K_SEC; // 15 seconds
K_STEPS = 30;
begin
Result := IsOpen;
size := aStream.Size;
bStop := False;
status := kStatusNoError;
cur := 0;
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
if Result then
begin
// if we could open the NXT then it isn't in firmware download mode
iNXT_getResourceString(fNXTHandle, resBuf, status);
Result := status >= kStatusNoError;
if Result then
begin
iNXT_bootIntoFirmwareDownloadMode(resBuf, status);
Result := status >= kStatusNoError;
if Result then
destroyNXT(fNXTHandle, status);
end;
inc(cur);
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
end;
// the device should now be in firmware download mode
elapsedTime := 0;
repeat
SysUtils.Sleep(K_SEC);
inc(elapsedTime, K_SEC);
status := kStatusNoError;
iNXT_findDeviceInFirmwareDownloadMode(resBuf, status);
inc(cur);
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
until (status >= kStatusNoError) or (elapsedTime >= MaximumWait);
cur := 16;
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
// now download the firmware
if status >= kStatusNoError then
begin
fNXTHandle := createNXT(resBuf, status, 0);
inc(cur);
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
GetMem(buf, size);
try
aStream.Position := 0; // start at the beginning
aStream.Read(buf^, size);
status := kStatusNoError;
iNXT_downloadFirmware(fNXTHandle, buf, size, status);
inc(cur);
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
finally
FreeMem(buf);
end;
for i := 0 to 9 do begin
SysUtils.Sleep(K_SEC);
inc(cur);
DoDownloadStatus(cur, K_STEPS, bStop);
if bStop then begin
Result := False;
Exit;
end;
end;
Close;
Result := status >= kStatusNoError;
end;
end;
function TFantomSpirit.NXTDownloadStream(aStream: TStream; const dest : string;
const filetype: TNXTFileType): boolean;
var
size : Cardinal;
handle : cardinal;
status : integer;
buf : PByte;
nxtFilename, delname : string;
begin
Result := IsOpen;
if not FantomAPILoaded then Exit;
status := kStatusNoError;
if filetype = nftFirmware then
begin
Result := TransferFirmware(aStream);
end
else
begin
if not Result then Exit;
size := aStream.Size;
// download means from PC to NXT
// make destination filename a valid NXT filename (15.3)
nxtFilename := MakeValidNXTFilename(dest);
delname := nxtFilename;
NXTDeleteFile(delname, True);
if filetype in [nftProgram, nftGraphics] then
Result := NXTOpenWriteLinear(nxtFilename, size, handle)
else if filetype = nftData then
Result := NXTOpenWriteData(nxtFilename, size, handle)
else
Result := NXTOpenWrite(nxtFilename, size, handle);
if Result then
begin
GetMem(buf, size);
try
aStream.Position := 0; // start at the beginning
aStream.Read(buf^, size);
status := kStatusNoError;
iFile_write(handle, buf, size, status);
Result := status >= kStatusNoError;
finally
FreeMem(buf);
end;
Result := NXTCloseFile(handle) and Result;
end;
end;
end;
function TFantomSpirit.NXTPollCommandLen(const bufNum : byte; var count: byte): boolean;
var
status : integer;
begin
Result := IsOpen;
if not Result then Exit;
count := iNXT_pollAvailableLength(fNXTHandle, bufNum, status);
Result := status < kStatusNoError;
if not Result then
count := 0;
end;
function TFantomSpirit.NXTPollCommand(const bufNum: byte; var count: byte;
var buffer: NXTDataBuffer): boolean;
var
dataBuffer : PByte;
status : Integer;
begin
Result := IsOpen;
if not Result then Exit;
if count > 64 then
count := 64;
dataBuffer := @buffer.Data[0];
count := iNXT_readBufferData(fNXTHandle, dataBuffer, bufNum, count, status);
Result := status >= kStatusNoError;
if not Result then
count := 0;
end;
function TFantomSpirit.NXTWriteIOMap(var ModID: Cardinal;
const Offset: Word; var count: Word; const buffer: NXTDataBuffer;
chkResponse : Boolean): boolean;
var
status : integer;
mh : Cardinal;
modName : string;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
modName := NXTModuleIDToName(ModID);
mh := iNXT_createModule(fNXTHandle, PChar(modName), ModID, 0, 0, status);
if status >= kStatusNoError then
begin
// found the correct module
status := kStatusNoError;
iModule_writeIOMap(mh, Offset, count, @(buffer.Data), status);
// now destroy it
status := kStatusNoError;
iNXT_destroyModule(fNXTHandle, mh, status);
end;
end;
function TFantomSpirit.NXTReadIOMap(var ModID: Cardinal;
const Offset: Word; var Count: Word; var buffer: NXTDataBuffer): boolean;
var
status : integer;
mh : Cardinal;
modName : string;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
modName := NXTModuleIDToName(ModID);
mh := iNXT_createModule(fNXTHandle, PChar(modName), ModID, 0, 0, status);
if status >= kStatusNoError then
begin
// found the correct module
status := kStatusNoError;
FillChar(buffer.Data[0], kNXT_MaxBytes, 0);
iModule_readIOMap(mh, Offset, Count, @(buffer.Data), status);
Result := status = kStatusNoError;
// now destroy it
status := kStatusNoError;
iNXT_destroyModule(fNXTHandle, mh, status);
end;
end;
function TFantomSpirit.NXTFindNextModule(var Handle: cardinal;
var ModName: string; var ModID, ModSize: Cardinal;
var IOMapSize: Word): boolean;
var
status : integer;
Buf : array[0..19] of Char;
mh : cardinal;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
iModuleIterator_advance(Handle, status);
Result := status >= kStatusNoError;
if Result then
begin
mh := iModuleIterator_getModule(Handle, status);
status := kStatusNoError;
iModule_getName(mh, buf, status);
ModName := buf;
status := kStatusNoError;
ModSize := iModule_getModuleSize(mh, status);
status := kStatusNoError;
ModID := iModule_getModuleID(mh, status);
status := kStatusNoError;
IOMapSize := iModule_getIOMapSize(mh, status);
status := kStatusNoError;
iNXT_destroyModule(FNXTHandle, mh, status);
end
else
begin
// destroy the iterator
status := kStatusNoError;
iNXT_destroyModuleIterator(fNXTHandle, Handle, status);
handle := 0;
ModName := '';
end;
end;
function TFantomSpirit.NXTFindFirstModule(var ModName: string; var Handle: cardinal;
var ModID, ModSize: Cardinal; var IOMapSize: Word): boolean;
var
status : integer;
buf : array[0..19] of Char;
mh : cardinal;
begin
Result := IsOpen;
if not Result then Exit;
status := kStatusNoError;
Handle := iNXT_createModuleIterator(FNXTHandle, PChar(ModName), status);
Result := status >= kStatusNoError;
if Result then
begin
mh := iModuleIterator_getModule(Handle, status);
status := kStatusNoError;
iModule_getName(mh, buf, status);
ModName := buf;
status := kStatusNoError;
ModSize := iModule_getModuleSize(mh, status);
status := kStatusNoError;
ModID := iModule_getModuleID(mh, status);
status := kStatusNoError;
IOMapSize := iModule_getIOMapSize(mh, status);
status := kStatusNoError;
iNXT_destroyModule(FNXTHandle, mh, status);
end;
end;
function TFantomSpirit.dcBuffer: PByte;
begin
Result := @dcResponse[0];
end;
function BytesToCardinal(b1 : byte; b2 : byte = 0; b3 : byte = 0; b4 : Byte = 0) : Cardinal;
begin
Result := Cardinal(b1) + (Cardinal(b2) shl 8) + (Cardinal(b3) shl 16) + (Cardinal(b4) shl 24);
end;
function TFantomSpirit.GetReplyByte(index: integer): Byte;
const
DCReplyOffset = 2;
begin
Result := dcResponse[index + DCReplyOffset];
end;
function TFantomSpirit.GetReplyCardinal(index: integer): Cardinal;
begin
Result := BytesToCardinal(GetReplyByte(index),
GetReplyByte(index+1),
GetReplyByte(index+2),
GetReplyByte(index+3));
end;
function TFantomSpirit.GetReplyWord(index: integer): Word;
begin
Result := Word(BytesToCardinal(GetReplyByte(index), GetReplyByte(index+1)));
end;
function TFantomSpirit.NXTListBricks(Bricks: TStrings): boolean;
var
nih : Cardinal;
status, status2 : integer;
resNamePC : array[0..255] of Char;
resName, alias, tmp : string;
begin
Result := False;
Bricks.Clear;
if FantomAPILoaded then
begin
resName := '';
status := kStatusNoError;
// use Fantom API to obtain a handle to an NXT on either USB or bluetooth
nih := createNXTIterator(1, BluetoothSearchTimeout, status);
while status >= kStatusNoError do
begin
status2 := kStatusNoError;
iNXTIterator_getName(nih, resNamePC, status2);
resName := AnsiUpperCase(resNamePC);
// if the resource name starts with BTH then grab the beginning of
// the resource name and use it as the alias
// if the resource name starts with USB then grab the end of the
// resource name instead
if Pos('BTH', resName) = 1 then
begin
tmp := Copy(resName, 6, MaxInt);
alias := 'BTH::' + Copy(tmp, 1, Pos('::', tmp)-1);
end
else
begin
alias := Copy(resName, 23, MaxInt);
System.Delete(alias, Length(alias)-4, 5);
end;
// alias := AnsiLowerCase(Copy(resName, 1, Pos('::', resName)-1));
Bricks.Add(alias + '=' + resName);
iNXTIterator_advance(nih, status);
end;
status := kStatusNoError;
destroyNXTIterator(nih, status);
// also look for bricks in firmware download mode
status := kStatusNoError;
iNXT_findDeviceInFirmwareDownloadMode(resNamePC, status);
if status >= kStatusNoError then
begin
resName := AnsiUpperCase(resNamePC);
alias := Copy(resName, 23, MaxInt);
System.Delete(alias, Length(alias)-4, 5);
// alias := AnsiLowerCase(Copy(resName, 1, Pos('::', resName)-1));
Bricks.Add(alias + '=' + resName);
end;
Result := Bricks.Count > 0;
end;
end;
function TFantomSpirit.GetDownloadWaitTime: Integer;
begin
Result := 0;
end;
function TFantomSpirit.GetEEPROM(addr: Byte): Byte;
begin
Result := 0;
end;
function TFantomSpirit.GetEEPROMBlock(idx: Integer): EEPROMBlock;
begin
// do nothing
end;
function TFantomSpirit.GetLinkLog: string;
begin
Result := '';
end;
function TFantomSpirit.GetOmitHeader: Boolean;
begin
Result := False;
end;
function TFantomSpirit.GetQuiet: Boolean;
begin
Result := False;
end;
function TFantomSpirit.GetRCXFirmwareChunkSize: Integer;
begin
Result := 200;
end;
function TFantomSpirit.GetRxTimeout: Word;
begin
Result := 400;
end;
procedure TFantomSpirit.SetDownloadWaitTime(const Value: Integer);
begin
// do nothing
end;
procedure TFantomSpirit.SetEEPROM(addr: Byte; const Value: Byte);
begin
// do nothing
end;
procedure TFantomSpirit.SetOmitHeader(const Value: Boolean);
begin
// do nothing
end;
procedure TFantomSpirit.SetQuiet(const Value: Boolean);
begin
// do nothing
end;
procedure TFantomSpirit.SetRCXFirmwareChunkSize(const Value: Integer);
begin
// do nothing
end;
procedure TFantomSpirit.SetRxTimeout(const Value: Word);
begin
// do nothing
end;
function TFantomSpirit.AbsVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.AndVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.BrickAlive: boolean;
begin
Result := Open;
end;
function TFantomSpirit.CalibrateEvent(enum, upper, lower,
hysteresis: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.CalibrateLightSensor: boolean;
begin
Result := Open;
end;
function TFantomSpirit.ClearAllEvents: boolean;
begin
Result := Open;
end;
function TFantomSpirit.ClearCounter(num: TCounterNumber): boolean;
begin
Result := Open;
end;
function TFantomSpirit.ClearSound: boolean;
begin
Result := Open;
end;
function TFantomSpirit.ClearTachoCounter(aMotorList: Byte): boolean;
var
i : integer;
begin
Result := Open;
if Result then
begin
for i := 0 to 2 do
begin
if (MotorBits[i] and aMotorList) = MotorBits[i] then
begin
Result := Result and ResetOutputPosition(i, False);
if not Result then Break;
end;
end;
end;
end;
function TFantomSpirit.ClearTimer(aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.DatalogNext(aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.DecCounter(num: TCounterNumber): boolean;
begin
Result := Open;
end;
function TFantomSpirit.DeleteAllSubs: boolean;
begin
Result := Open;
end;
function TFantomSpirit.DeleteAllTasks: boolean;
begin
Result := Open;
end;
function TFantomSpirit.DeleteSub(aSub: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.DeleteTask(aTask: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.DivVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.DownloadMemoryMap: TStrings;
var
SL : TStringList;
i, p, id : integer;
tmp : string;
begin
fMemMap.Clear;
SL := TStringList.Create;
try
fMemMap.Add('Files');
fMemMap.Add('');
if NXTListFiles('*.*', SL) then
begin
for i := 0 to SL.Count - 1 do
begin
fMemMap.Add(SL.Names[i]);
fMemMap.Add(SL.ValueFromIndex[i]);
end;
end;
SL.Clear;
fMemMap.Add('');
fMemMap.Add('');
fMemMap.Add('Modules');
fMemMap.Add('');
if NXTListModules('*.*', SL) then
begin
for i := 0 to SL.Count - 1 do
begin
fMemMap.Add(SL.Names[i]);
tmp := SL.ValueFromIndex[i];
// tmp = moduleID, size, iosize
p := Pos(',', tmp);
id := StrToIntDef(Copy(tmp, 1, p-1), 0);
Delete(tmp, 1, p);
p := Pos(',', tmp);
Delete(tmp, 1, p);
fMemMap.Add(IntToStr(id)+'|'+tmp); // moduleID|iomap size
end;
end;
fMemMap.Add('');
fMemMap.Add('');
i := NXTFreeMemory;
fMemMap.Add('Free Memory');
fMemMap.Add(IntToStr(i));
finally
SL.Free;
end;
Result := fMemMap;
end;
function TFantomSpirit.Drive(aLeft, aRight: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.GetCounterValue(aNum: integer): integer;
begin
Result := Poll(kRCX_CounterType, aNum);
end;
function TFantomSpirit.GetMessageValue(aNum: integer): integer;
begin
Result := Poll(kRCX_MessageType, aNum);
end;
function TFantomSpirit.GetOutputStatus(aOut: integer): integer;
var
res : boolean;
mode, regmode, runstate : byte;
power, turnratio : integer;
tacholimit : cardinal;
tachocount, blocktachocount, rotationcount : integer;
bBrake : boolean;
begin
Result := 0;
res := GetNXTOutputState(aOut, power, mode, regmode, turnratio, runstate,
tacholimit, tachocount, blocktachocount, rotationcount);
if res then
begin
// what is the power?
fMotorOn[aOut] := ((mode and OUT_MODE_MOTORON) = OUT_MODE_MOTORON) and
((runstate and OUT_RUNSTATE_RUNNING) = OUT_RUNSTATE_RUNNING) and
(power <> 0);
bBrake := (mode and OUT_MODE_BRAKE) = OUT_MODE_BRAKE;
// if the power is 0 and fMotorOn[aOut] is false then do not change
// the stored power level
if fMotorOn[aOut] then
fMotorPower[aOut] := abs(power div 14) mod 8;
fMotorForward[aOut] := power >= 0;
Result := fMotorPower[aOut]; // bits 0..2
if fMotorForward[aOut] then
Result := Result + (1 shl 3); // bit 3
if bBrake then
Result := Result + (1 shl 6); // bit 6
if fMotorOn[aOut] then
Result := Result + (1 shl 7); // bit 7
end;
end;
function TFantomSpirit.GetTimerValue(aNum: integer): integer;
begin
Result := Poll(kRCX_TimerType, aNum);
end;
function TFantomSpirit.GetVariableValue(aVar: integer): integer;
begin
Result := Poll(kRCX_VariableType, aVar);
end;
function TFantomSpirit.IncCounter(num: TCounterNumber): boolean;
begin
Result := Open;
end;
function TFantomSpirit.MonitorIR(aSeconds: integer): TStrings;
begin
Result := fMemData;
end;
function TFantomSpirit.MulVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.OnWait(aMotorList: Byte; aNum: integer; aTime: Byte): boolean;
begin
Result := Open;
end;
function TFantomSpirit.OnWaitDifferent(aMotorList: Byte; aNum0, aNum1,
aNum2: integer; aTime: Byte): boolean;
begin
Result := Open;
end;
function TFantomSpirit.OrVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.PlaySystemSound(aSnd: byte): boolean;
begin
Result := Open;
end;
function TFantomSpirit.Poll(aSrc, aNum: integer): integer;
var
valid, calibrated, res : boolean;
stype, smode : byte;
raw, normalized : word;
scaled, calvalue : smallint;
modID : Cardinal;
count : Word;
buffer : NXTDataBuffer;
power, turnratio, tachocount, blocktachocount, rotationcount : integer;
mode, regmode, runstate : byte;
tacholimit : cardinal;
protmin, protmaj, firmmin, firmmaj : byte;
begin
Result := 0;
case aSrc of
kRCX_ConstantType : begin
Result := aNum;
end;
kRCX_OutputStatusType : begin
Result := GetOutputStatus(aNum);
end;
kRCX_RandomType : begin
Result := Random(aNum);
end;
kRCX_TachCounterType : begin
res := GetNXTOutputState(aNum, power, mode, regmode, turnratio, runstate,
tacholimit, tachocount, blocktachocount, rotationcount);
if res then
Result := rotationcount;
end;
kRCX_TimerType : begin
// IOMapRead CommandOffsetTick
modID := kNXT_ModuleCmd;
count := 4;
res := NXTReadIOMap(modID, CommandOffsetTick, count, buffer);
if res then
begin
Result := BytesToCardinal(buffer.Data[0], buffer.Data[1], buffer.Data[2], buffer.Data[3]);
end;
end;
kRCX_BatteryLevelType : begin
Result := BatteryLevel;
end;
kRCX_FirmwareVersionType : begin
if NXTGetVersions(protmin, protmaj, firmmin, firmmaj) then
begin
// 1.03 => 1030
Result := (firmmaj * 100) + firmmin;
end;
end;
kRCX_InputTypeType, kRCX_InputModeType,
kRCX_InputValueType, kRCX_InputRawType,
kRCX_InputBooleanType : begin
// get input type or input mode
res := GetNXTInputValues(aNum, valid, calibrated, stype, smode,
raw, normalized, scaled, calvalue);
if res then
begin
if aSrc = kRCX_InputTypeType then
begin
fSensorType[aNum] := stype;
Result := stype;
end
else if aSrc = kRCX_InputModeType then
begin
fSensorMode[aNum] := smode;
Result := smode;
end
else if aSrc = kRCX_InputValueType then
begin
Result := scaled; // normalized?
end
else if aSrc = kRCX_InputRawType then
begin
Result := raw;
end
else if aSrc = kRCX_InputBooleanType then
begin
Result := scaled;
end;
end;
end;
end;
end;
function TFantomSpirit.PollEEPROM(block: Integer): TStrings;
var
i, j, start, finish, status : Integer;
mh, Offset, cnt : Cardinal;
buf : PByte;
const
MAX_BLOCK = $803;
BLOCK_SIZE = $10;
begin
Open;
Result := fMemData;
fMemData.Clear;
start := block;
finish := block;
if block < 0 then
begin
start := 0;
finish := MAX_BLOCK;
end
else if block > MAX_BLOCK then
begin
start := MAX_BLOCK;
finish := MAX_BLOCK;
end;
mh := iNXT_createModule(fNXTHandle, PChar(kNXT_ModuleCmdName), kNXT_ModuleCmd, 0, 0, status);
// are we in a position to poll memory?
if status >= kStatusNoError then
begin
GetMem(buf, BLOCK_SIZE);
try
for j := start to finish do
begin
status := kStatusNoError;
Offset := j*BLOCK_SIZE;
cnt := iModule_readIOMap(mh, Offset, BLOCK_SIZE, buf, status);
if status >= kStatusNoError then
begin
for i := 0 to cnt - 1 do
begin
fMemData.Add(Format('%d', [PByte(PChar(buf) + i)^]));
end;
end
else
Break;
end;
finally
FreeMem(buf);
end;
// now destroy the module handle
status := kStatusNoError;
iNXT_destroyModule(fNXTHandle, mh, status);
end;
end;
function TFantomSpirit.PollMemory(address, size: Integer): TStrings;
var
status, cnt : integer;
mh, Offset : Cardinal;
amt, i : Integer;
buf : PByte;
const
// CHUNK = $FFFF;
CHUNK = $36;
begin
Open;
fMemData.Clear;
Result := fMemData;
mh := iNXT_createModule(fNXTHandle, PChar(kNXT_ModuleCmdName), kNXT_ModuleCmd, 0, 0, status);
// are we in a position to poll memory?
if status >= kStatusNoError then
begin
// found the Command module now use it
Offset := address;
amt := 0;
GetMem(buf, CHUNK);
try
while (amt < size) and (status >= kStatusNoError) do
begin
status := kStatusNoError;
cnt := Min(CHUNK, size-amt);
cnt := iModule_readIOMap(mh, Offset, cnt, buf, status);
if status >= kStatusNoError then
begin
for i := 0 to cnt - 1 do
begin
fMemData.Add(Format('%d', [PByte(PChar(buf) + i)^]));
end;
end;
inc(amt, CHUNK);
inc(Offset, CHUNK);
end;
finally
FreeMem(buf);
end;
// now destroy the module handle
status := kStatusNoError;
iNXT_destroyModule(fNXTHandle, mh, status);
end;
end;
function TFantomSpirit.PowerDownTime(aTime: integer): boolean;
var
modID : Cardinal;
count : Word;
buffer : NXTDataBuffer;
begin
Result := Open;
if not Result then Exit;
modID := kNXT_ModuleUI;
count := 1;
buffer.Data[0] := Byte(abs(aTime) mod $FF);
Result := NXTWriteIOMap(modID, UIOffsetSleepTimeout, count, buffer);
end;
function TFantomSpirit.PrepareBrick: boolean;
begin
Result := Open;
end;
function TFantomSpirit.Scout(bPower: boolean): boolean;
begin
Result := Open;
end;
function TFantomSpirit.Scout(aVal: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.ScoutRules(motion: TScoutMotion; touch: TScoutTouch;
light: TScoutLight; time: TScoutScale; fx: TScoutEffects): boolean;
begin
Result := Open;
end;
function TFantomSpirit.ScoutSound(bSoundEnable, bSoundOff: boolean;
aNum: TSoundSetNumber): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SelectDisplay(aSrc, aNumber: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SelectProgram(aProg: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SendMessage(aMsg: integer): boolean;
begin
Result := MessageWrite(0, IntToStr(aMsg));
end;
function TFantomSpirit.SendRawCommand(aCmd: string; bRetry: boolean): string;
begin
Result := '';
end;
function TFantomSpirit.SendRemote(aEvent: string; aRepeat: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SendRemote(aEvent: Word; aRepeat: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SendUARTData(start, size: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SendVLL(aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetCounterLimit(num: TCounterNumber; src: TTCSource;
val: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetDatalog(aSize: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetEvent(enum, snum, etype: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetFeedback(src, val: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetGlobalDirection(motors: TMotorsNum; action: TGlobalDirAction): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetGlobalOutput(motors: TMotorsNum; action: TGlobalOutAction): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetLight(bOn: boolean): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetLightSensorBlinkTime(src: TLSSource; val: TBlinkTimeValue): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetLightSensorHysteresis(src: TLSSource; val: TThresholdValue): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetLightSensorLowerThreshold(src: TLSSource; val: TThresholdValue): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetLightSensorUpperThreshold(src: TLSSource; val: TThresholdValue): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetMaxPower(motors: TMotorsNum; src, num: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetSourceValue(aDestSrc, aDestVal, aOrigSrc: Byte; aOrigVal: Smallint): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetTimerLimit(num: TTimerNumber; src: TTCSource; val: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetWatch(aTime: string): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SetWatch(aHrs, aMins: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SgnVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.StartTask(aTask: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.StopAllTasks: boolean;
begin
Result := Open;
end;
function TFantomSpirit.StopTask(aTask: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SubVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.SumVar(aVar, aSrc, aNum: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.TowerExists: boolean;
begin
Result := Open;
end;
function TFantomSpirit.TransmitPower(aLevel: TTransmitLevel): boolean;
begin
Result := Open;
end;
function TFantomSpirit.UnlockBrick: string;
begin
Open;
Result := '';
end;
function TFantomSpirit.UnlockFirmware: boolean;
begin
Result := Open;
end;
function TFantomSpirit.UploadDatalog(bVerbose: boolean): TStrings;
begin
Open;
Result := fDataLog;
end;
function TFantomSpirit.UploadDatalog(aFrom, aSize: integer): TStrings;
begin
Open;
Result := fDataLog;
end;
function TFantomSpirit.Version(var rom, ram: Cardinal): boolean;
var
protmin, protmaj, firmmin, firmmaj : byte;
begin
Result := NXTGetVersions(protmin, protmaj, firmmin, firmmaj);
rom := (protmin shl 8) + (protmaj shl 16);
ram := (firmmin shl 0) + (firmmaj shl 16);
end;
function TFantomSpirit.ViewSourceValue(prec, src, value: integer): boolean;
begin
Result := Open;
end;
function TFantomSpirit.GetUseBT: Boolean;
begin
Result := fUseBT or (Pos('BTH', fResPort) > 0);
if Result then
fUseBT := True;
end;
procedure TFantomSpirit.NXTInitializeResourceNames;
var
SL : TStringList;
name : string;
begin
SL := TStringList.Create;
try
NXTListBricks(SL);
name := GetInitFilename;
ForceDirectories(ExtractFilePath(name));
SL.SaveToFile(name);
finally
SL.Free;
end;
end;
function TFantomSpirit.NXTFreeMemory: integer;
var
BTAddr : PByte;
memFree, BTSig : Cardinal;
nxtName : string;
begin
Result := 0;
GetMem(BTAddr, 7);
try
if NXTGetDeviceInfo(nxtName, BTAddr, BTSig, memFree) then
begin
Result := memFree;
end;
finally
FreeMem(BTAddr);
end;
end;
function TFantomSpirit.NXTRenameFile(const old, new: string;
const chkResponse: boolean): boolean;
var
cmd : TNxtCmd;
status : integer;
b : byte;
buf, readBuf : PByte;
bufLen : Cardinal;
begin
Result := Open;
if not Result then Exit;
cmd := TNxtCmd.Create;
try
if chkResponse then
b := kNXT_SystemCmd
else
b := kNXT_SystemCmdNoReply;
cmd.MakeCmdRenameFile(b, new, old);
// cmd.MakeCmdRenameFile(b, old, new);
buf := cmd.GetBody;
bufLen := cmd.GetLength;
iNXT_write(fNXTHandle, buf, bufLen, status);
// now read the response
if (status >= kStatusNoError) and chkResponse then
begin
GetMem(readBuf, 44);
try
iNXT_read(fNXTHandle, readBuf, 44, status);
finally
FreeMem(readBuf);
end;
end;
Result := status >= kStatusNoError;
finally
cmd.Free;
end;
end;
procedure TFantomSpirit.SetResourcePort(const name: string);
var
sl : TStringList;
i : integer;
fname : string;
begin
fResPort := name;
sl := TStringList.Create;
try
fname := GetInitFilename;
if FileExists(fname) then
begin
sl.LoadFromFile(fname);
for i := 0 to sl.Count - 1 do
begin
if Pos(fResPort, sl[i]) > 0 then
Exit;
end;
// if we get here then we need to add this resource string to
// our nxt.dat file
sl.Add('alias' + IntToStr(sl.Count) + '=' + fResPort);
sl.SaveToFile(fname);
end;
finally
sl.Free;
end;
end;
procedure TFantomSpirit.LookupResourceName;
var
name : string;
i : integer;
begin
// lookup a resource string given this port name
if fResourceNames.Count = 0 then
begin
name := GetInitFilename;
if FileExists(name) then
begin
fResourceNames.LoadFromFile(name);
end;
end;
i := fResourceNames.IndexOfName(fPort);
if i <> -1 then
fResPort := fResourceNames.Values[fPort];
end;
end.
| 29.395583 | 123 | 0.657227 |
c307f9e423baca6b127fa4bb8c5784f0217def69 | 6,492 | pas | Pascal | CrossRoads_DelphiVER280_Port/CrossRoads/Project/fmSprint.pas | VincentGsell/CrossRoads | a620deae75ee6b0ef1dd597810de1408d61efe8e | [
"Apache-2.0"
]
| 1 | 2016-12-17T13:04:58.000Z | 2016-12-17T13:04:58.000Z | CrossRoads_DelphiVER280_Port/CrossRoads/Project/fmSprint.pas | VincentGsell/CrossRoads | a620deae75ee6b0ef1dd597810de1408d61efe8e | [
"Apache-2.0"
]
| null | null | null | CrossRoads_DelphiVER280_Port/CrossRoads/Project/fmSprint.pas | VincentGsell/CrossRoads | a620deae75ee6b0ef1dd597810de1408d61efe8e | [
"Apache-2.0"
]
| null | null | null | unit fmSprint;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Objects, FMX.Layouts,
unStructure, unGlobal;
type
TfrmSprint = class(TForm)
layBody: TLayout;
rectCalBody: TRectangle;
rectHeader: TRectangle;
layDate: TLayout;
txtYear: TText;
txtWeekNum: TText;
LayHeaderBody: TLayout;
txtPeriod: TText;
layContent: TLayout;
imgFond: TImage;
layHeaderBottom: TLayout;
imgNext: TImage;
imgPrevious: TImage;
layestim: TLayout;
txtEstim: TText;
layDisabled: TLayout;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure imgNextClick(Sender: TObject);
procedure imgPreviousClick(Sender: TObject);
private
FSprintRec: TSprintRecord;
FfrmTargetList: TList;
FSprintOrder: integer;
FTaskList: TTaskList;
public
procedure Initialize(aDate: TDatetime; aSprintOrder: Integer);
procedure InitTasks;
end;
var
frmSprint: TfrmSprint;
implementation
uses DateUtils, StrUtils, fmTaskPostIt, unFunctions, fmTasks, dmTypeList;
{$R *.fmx}
procedure TfrmSprint.FormCreate(Sender: TObject);
var
i: integer;
lfrmTaskPostIt : TfrmTaskPostIt;
begin
FTaskList := TTaskList.Create;
//
FfrmTargetList := TList.Create;
for i := 0 to CST_Max_TodosToShow-1 do
begin
lfrmTaskPostIt := TfrmTaskPostIt.Create(nil);
lfrmTaskPostIt.layBody.Parent := layContent;
lfrmTaskPostIt.OnNextImageClick := imgNextClick;
lfrmTaskPostIt.OnPreviousImageClick := imgPreviousClick;
lfrmTaskPostIt.Initialize(CST_TargetScheduled);
FfrmTargetList.Add(lfrmTaskPostIt);
end;
//
for i := CST_Max_TodosToShow-1 downto 0 do
begin
lfrmTaskPostIt := FfrmTargetList[i];
lfrmTaskPostIt.layBody.Align := TAlignLayout.alTop;
end;
//
layDisabled.BringToFront;
end;
procedure TfrmSprint.FormDestroy(Sender: TObject);
var
i: integer;
lfrmTaskPostIt : TfrmTaskPostIt;
begin
FTaskList.Free;
//
for i := 0 to FfrmTargetList.Count-1 do
begin
lfrmTaskPostIt := FfrmTargetList[i];
lfrmTaskPostIt.Free;
end;
FfrmTargetList.Clear;
end;
procedure TfrmSprint.imgNextClick(Sender: TObject);
var
lTask: TTask;
lTaskRec: TTaskRecord;
lNextSprintCode: string;
lDescLog: TStringList;
begin
// GOTO Next sprint
if FSprintOrder>3 then exit;
lTask := FTaskList.Search(TControl(Sender).Tag);
lTaskRec := lTask.Data;
lNextSprintCode := GetSprintCode(FSprintRec.BeginDate+7);
lTaskRec.SprintCode := lNextSprintCode;
TaskDatamodule.UpdateTask(lTaskRec);
//
frmTasks.InitSprints;
//
lDescLog := TStringList.Create;
lDescLog.Add('A to-do task has been postponed:');
lDescLog.Add(Format('- %s (%d)',[lTask.Data.TaskName, lTask.Data.ProjectTaskNum]));
lDescLog.Add(Format('- postponed from %s to %s',[FSprintRec.SprintCode,lNextSprintCode]));
UserLogDatamodule.AddUserLog(CST_UserLogType_Info, lDescLog.Text);
lDescLog.Free;
end;
procedure TfrmSprint.imgPreviousClick(Sender: TObject);
var
lTask: TTask;
lTaskRec: TTaskRecord;
lNextSprintCode: string;
lDescLog: TStringList;
begin
// GOTO previous sprint
lTask := FTaskList.Search(TControl(Sender).Tag);
lTaskRec := lTask.Data;
lDescLog := TStringList.Create;
if FSprintOrder=1 then
begin
lTaskRec.Status := staValidated;
lTaskRec.SprintCode := '';
//
lDescLog.Add('A schedule has been canceled:');
lDescLog.Add(Format('- %s (%d)',[lTask.Data.TaskName, lTask.Data.ProjectTaskNum]));
UserLogDatamodule.AddUserLog(CST_UserLogType_Info, lDescLog.Text);
end
else
begin
lNextSprintCode := GetSprintCode(FSprintRec.BeginDate-7);
lTaskRec.SprintCode := lNextSprintCode;
//
lDescLog.Add('A to-do task has been postponed:');
lDescLog.Add(Format('- %s (%d)',[lTask.Data.TaskName, lTask.Data.ProjectTaskNum]));
lDescLog.Add(Format('- postponed from %s to %s',[FSprintRec.SprintCode,lNextSprintCode]));
UserLogDatamodule.AddUserLog(CST_UserLogType_Info, lDescLog.Text);
end;
lDescLog.Free;
TaskDatamodule.UpdateTask(lTaskRec);
//
frmTasks.InitSprints;
if FSprintOrder=1 then
frmTasks.InitTodo;
end;
procedure TfrmSprint.Initialize(aDate: TDatetime; aSprintOrder: integer);
var
lID: string;
const
CST_DateMonth = 'DD.MM';
begin
FSprintOrder := aSprintOrder;
lID := GetSprintCode(aDate);
TypeDatamodule.GetSprint(lID, FSprintRec);
txtYear.Text := IntToSTr(FSprintRec.Year);
txtWeekNum.Text := IntToSTr(FSprintRec.WeekNum);
txtPeriod.Text := Format('from %s to %s',[FormatDatetime(CST_DateMonth,FSprintRec.BeginDate),
FormatDatetime(CST_DateMonth,FSprintRec.EndDate)]);
//
layDisabled.Visible := (FSprintOrder=CST_SprintOld);
if FSprintOrder=CST_SprintOld then
begin
rectHeader.Opacity := 0.7;
imgFond.Opacity := 0.05;
end
else
begin
rectHeader.Opacity := 1;
imgFond.Opacity := 0.2;
end;
InitTasks;
end;
procedure TfrmSprint.InitTasks;
var
lfrmTaskPostIt: TfrmTaskPostIt;
i: Integer;
lTask: TTask;
lDelay: Single;
lIndexForm: Integer;
lTotEstim, lTotDone: integer;
begin
FTaskList.Load(GlobalVar.CurrentProjectNum, CST_TargetScheduled, 0, FSprintRec.SprintCode);
if (FSprintOrder=CST_SprintResume) then
FTaskList.SortByDoneDate;
// initialize to-do
for i := 0 to CST_Max_TodosToShow - 1 do
begin
lfrmTaskPostIt := FfrmTargetList[i];
if FSprintOrder=CST_SprintResume then
lfrmTaskPostIt.Initialize(CST_TargetResume)
else
lfrmTaskPostIt.Initialize(CST_TargetScheduled);
end;
//
lIndexForm := 0;
lTotEstim := 0;
lTotDone := 0;
for i := 0 to FTaskList.Count - 1 do
begin
if lIndexForm >= CST_Max_TodosToShow then
break;
//
lTask := FTaskList.Items(i);
lfrmTaskPostIt := FfrmTargetList[lIndexForm];
lDelay := CST_TransitionDelay * (i + 1);
lfrmTaskPostIt.Initialize(lTask, lDelay);
inc(lIndexForm);
//
lTotEstim := lTotEstim + lTask.Data.Estimation;
if lTask.Data.Status=staDone then
lTotDone := lTotDone + lTask.Data.Estimation;
end;
txtEstim.Text := Format('%d task(s): %d/%d',[FTaskList.Count,lTotDone,lTotEstim]);
end;
end.
| 28.473684 | 96 | 0.692391 |
47496f43d76169ddc718bb341eb1178618af8a8d | 157,753 | pas | Pascal | mORMot/SynBidirSock.pas | LongDirtyAnimAlf/AsphyrePXL | 9151ff88eca1fa01dce083b09e7ea20076f6d334 | [
"Apache-2.0"
]
| 4 | 2020-04-24T07:43:43.000Z | 2021-08-29T08:36:08.000Z | mORMot/SynBidirSock.pas | LongDirtyAnimAlf/AsphyrePXL | 9151ff88eca1fa01dce083b09e7ea20076f6d334 | [
"Apache-2.0"
]
| null | null | null | mORMot/SynBidirSock.pas | LongDirtyAnimAlf/AsphyrePXL | 9151ff88eca1fa01dce083b09e7ea20076f6d334 | [
"Apache-2.0"
]
| 2 | 2020-08-18T09:42:33.000Z | 2021-04-22T08:15:27.000Z | /// implements bidirectional client and server protocol, e.g. WebSockets
// - this unit is a part of the freeware Synopse mORMot framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynBidirSock;
{
This file is part of the Synopse framework.
Synopse framework. Copyright (C) 2020 Arnaud Bouchez
Synopse Informatique - https://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
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 Synopse mORMot framework.
The Initial Developer of the Original Code is Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (C) 2020
the Initial Developer. All Rights Reserved.
Contributor(s):
- Alfred (alf)
- f-vicente
- nortg
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
TODO: broadcast a message to several aCallingThread: THttpServerResp values
(add TWebSocketClientRequest? or asynch notifications may be enough, and
the "broadcast" feature should be implementation at application level,
using a list of callbacks)
TODO: enhance TWebSocketServer process to use events, and not threads
- current implementation has its threads spending most time waiting in loops
- eventually also at SynCrtSock's THttpServer class level also
}
{$I Synopse.inc} // define HASINLINE CPU32 CPU64 OWNNORMTOUPPER
interface
uses
{$ifdef MSWINDOWS}
Windows,
SynWinSock,
{$else}
SynFPCSock, // shared with Kylix
{$ifdef KYLIX3}
LibC,
Types,
SynKylix,
{$endif}
{$ifdef FPC}
SynFPCLinux,
{$endif}
{$endif}
SysUtils,
Classes,
Contnrs,
SyncObjs,
SynLZ,
SynCommons,
SynTable,
SynLog,
SynCrtSock,
SynCrypto, // for SHA and AES
SynEcc; // for TECDHEProtocol
{ -------------- high-level SynCrtSock classes depending on SynCommons }
type
/// in-memory storage of one THttpRequestCached entry
THttpRequestCache = record
Tag: RawUTF8;
Content: RawByteString;
end;
/// in-memory storage of all THttpRequestCached entries
THttpRequestCacheDynArray = array of THttpRequestCache;
/// handles cached HTTP connection to a remote server
// - use in-memory cached content when HTTP_NOTMODIFIED (304) is returned
// for an already known ETAG header value
THttpRequestCached = class(TSynPersistent)
protected
fURI: TURI;
fHttp: THttpRequest; // either fHttp or fSocket is used
fSocket: THttpClientSocket;
fKeepAlive: integer;
fTokenHeader: RawUTF8;
fCache: TSynDictionary;
public
/// initialize the cache for a given server
// - once set, you can change the request URI using the Address property
// - aKeepAliveSeconds = 0 will force "Connection: Close" HTTP/1.0 requests
// - an internal cache will be maintained, and entries will be flushed after
// aTimeoutSeconds - i.e. 15 minutes per default - setting 0 will disable
// the client-side cache content
// - aToken is an optional token which will be transmitted as HTTP header:
// $ Authorization: Bearer <aToken>
// - TWinHttp will be used by default under Windows, unless you specify
// another class
constructor Create(const aURI: RawUTF8; aKeepAliveSeconds: integer=30;
aTimeoutSeconds: integer=15*60; const aToken: RawUTF8='';
aHttpClass: THttpRequestClass=nil); reintroduce;
/// finalize the current connnection and flush its in-memory cache
// - you may use LoadFromURI() to connect to a new server
procedure Clear;
/// connect to a new server
// - aToken is an optional token which will be transmitted as HTTP header:
// $ Authorization: Bearer <aToken>
// - TWinHttp will be used by default under Windows, unless you specify
// another class
function LoadFromURI(const aURI: RawUTF8; const aToken: RawUTF8='';
aHttpClass: THttpRequestClass=nil): boolean;
/// finalize the cache
destructor Destroy; override;
/// retrieve a resource from the server, or internal cache
// - aModified^ = true if server returned a HTTP_SUCCESS (200) with some new
// content, or aModified^ = false if HTTP_NOTMODIFIED (304) was returned
function Get(const aAddress: SockString; aModified: PBoolean=nil;
aStatus: PInteger=nil): SockString;
/// erase one resource from internal cache
function Flush(const aAddress: SockString): boolean;
/// read-only access to the connected server
property URI: TURI read fURI;
end;
/// will remove most usual HTTP headers which are to be recomputed on sending
function PurgeHeaders(P: PUTF8Char): RawUTF8;
{ ------------ client or server asynchronous process of multiple connections }
type
/// exception associated with TAsynchConnection / TAsynchConnections process
EAsynchConnections = class(ESynException);
/// 32-bit integer value used to identify an asynchronous connection
// - will start from 1, and increase during the TAsynchConnections live-time
TAsynchConnectionHandle = type integer;
TAsynchConnections = class;
/// abstract class to store one TAsynchConnections connection
// - may implement e.g. WebSockets frames, or IoT binary protocol
// - each connection will be identified by a TAsynchConnectionHandle integer
// - idea is to minimize the resources used per connection, and allow full
// customization of the process by overriding the OnRead virtual method (and,
// if needed, AfterCreate/AfterWrite/BeforeDestroy/OnLastOperationIdle)
TAsynchConnection = class(TSynPersistent)
protected
fSlot: TPollSocketsSlot;
fHandle: TAsynchConnectionHandle;
fLastOperation: cardinal;
fRemoteIP: RawUTF8;
/// this method is called when the instance is connected to a poll
// - default implementation will set fLastOperation content
procedure AfterCreate(Sender: TAsynchConnections); virtual;
/// this method is called when the some input data is pending on the socket
// - should extract frames or requests from fSlot.readbuf, and handle them
// - this is where the input should be parsed and extracted according to
// the implemented procotol; fSlot.readbuf could be kept as temporary
// buffer during the parsing, and voided by the caller once processed
// - Sender.Write() could be used for asynchronous answer sending
// - Sender.LogVerbose() allows logging of escaped data
// - could return sorClose to shutdown the socket, e.g. on parsing error
function OnRead(Sender: TAsynchConnections): TPollAsynchSocketOnRead; virtual; abstract;
/// this method is called when some data has been written to the socket
// - default implementation will do nothing
procedure AfterWrite(Sender: TAsynchConnections); virtual;
/// this method is called when the instance is about to be deleted from a poll
// - default implementation will reset fHandle to 0
procedure BeforeDestroy(Sender: TAsynchConnections); virtual;
// called after TAsynchConnections.LastOperationIdleSeconds of no activity
// - reset fLastOperation by default - overriden code should be fast
// - Sender.Write() could be used to send e.g. a hearbeat frame
procedure OnLastOperationIdle(Sender: TAsynchConnections); virtual;
public
/// initialize this instance
constructor Create(const aRemoteIP: RawUTF8); reintroduce; virtual;
published
/// the associated remote IP4/IP6, as text
property RemoteIP: RawUTF8 read fRemoteIP;
/// read-only access to the handle number associated with this connection
property Handle: TAsynchConnectionHandle read fHandle;
/// read-only access to the socket number associated with this connection
property Socket: TSocket read fSlot.socket;
end;
/// meta-class of one TAsynchConnections connection
TAsynchConnectionClass = class of TAsynchConnection;
/// used to store a dynamic array of TAsynchConnection
TAsynchConnectionObjArray = array of TAsynchConnection;
/// handle multiple non-blocking connections using TAsynchConnection instances
// - OnRead will redirect to TAsynchConnection.OnRead virtual method
// - OnClose will remove the instance from TAsynchConnections.fConnections[]
// - OnError will return false to shutdown the connection (unless
// acoOnErrorContinue is defined in TAsynchConnections.Options)
TAsynchConnectionsSockets = class(TPollAsynchSockets)
protected
fOwner: TAsynchConnections;
function SlotFromConnection(connection: TObject): PPollSocketsSlot; override;
function OnRead(connection: TObject): TPollAsynchSocketOnRead; override;
procedure AfterWrite(connection: TObject); override;
procedure OnClose(connection: TObject); override;
function OnError(connection: TObject; events: TPollSocketEvents): boolean; override;
function GetTotal: integer;
public
/// add some data to the asynchronous output buffer of a given connection
// - this overriden method will refresh TAsynchConnection.LastOperation
// - can be executed from an TAsynchConnection.OnRead method
function Write(connection: TObject; const data; datalen: integer;
timeout: integer=5000): boolean; override;
published
/// how many clients have been handled by the poll, from the beginning
property Total: integer read GetTotal;
end;
/// used to implement a thread poll to process TAsynchConnection instances
TAsynchConnectionsThread = class(TSynThread)
protected
fOwner: TAsynchConnections;
fProcess: TPollSocketEvent; // pseRead or pseWrite
procedure Execute; override;
public
/// initialize the thread
constructor Create(aOwner: TAsynchConnections; aProcess: TPollSocketEvent); reintroduce;
end;
/// low-level options for TAsynchConnections processing
// - TAsynchConnectionsSockets.OnError will shutdown the connection on any error,
// unless acoOnErrorContinue is defined
// - acoOnAcceptFailureStop will let failed Accept() finalize the process
// - acoNoLogRead and acoNoLogWrite could reduce the log verbosity
// - acoVerboseLog will log transmitted frames content, for debugging purposes
// - acoLastOperationNoRead and acoLastOperationNoWrite could be used to
// avoid TAsynchConnection.fLastOperation reset at read or write
TAsynchConnectionsOptions = set of (acoOnErrorContinue,
acoOnAcceptFailureStop, acoNoLogRead, acoNoLogWrite, acoVerboseLog,
acoLastOperationNoRead, acoLastOperationNoWrite);
/// implements an abstract thread-pooled high-performance TCP clients or server
// - internal TAsynchConnectionsSockets will handle high-performance process
// of a high number of long-living simultaneous connections
// - will use a TAsynchConnection inherited class to maintain connection state
// - don't use this abstract class but either TAsynchServer or TAsynchClients
// - under Linux/POSIX, check your "ulimit -H -n" value: one socket consumes
// two file descriptors: you may better add the following line to your
// /etc/limits.conf or /etc/security/limits.conf system file:
// $ * hard nofile 65535
TAsynchConnections = class(TServerGeneric)
protected
fStreamClass: TAsynchConnectionClass;
fConnection: TAsynchConnectionObjArray;
fConnectionCount: integer;
fConnections: TDynArray; // fConnection[] sorted by TAsynchConnection.Handle
fClients: TAsynchConnectionsSockets;
fThreads: array of TAsynchConnectionsThread;
fLastHandle: integer;
fLog: TSynLogClass;
fTempConnectionForSearchPerHandle: TAsynchConnection;
fOptions: TAsynchConnectionsOptions;
fLastOperationIdleSeconds: cardinal;
fThreadClients: record // used by TAsynchClient
Count, Timeout: integer;
Address, Port: SockString;
end;
fConnectionLock: TSynLocker;
procedure IdleEverySecond;
function ConnectionCreate(aSocket: TSocket; const aRemoteIp: RawUTF8;
out aConnection: TAsynchConnection): boolean; virtual;
function ConnectionAdd(aSocket: TSocket; aConnection: TAsynchConnection): boolean; virtual;
function ConnectionDelete(aHandle: TAsynchConnectionHandle): boolean; overload; virtual;
function ConnectionDelete(aConnection: TAsynchConnection; aIndex: integer): boolean; overload;
procedure ThreadClientsConnect; // from fThreadClients
public
/// initialize the multiple connections
// - warning: currently reliable only with aThreadPoolCount=1
constructor Create(OnStart,OnStop: TNotifyThreadEvent;
aStreamClass: TAsynchConnectionClass; const ProcessName: SockString;
aLog: TSynLogClass; aOptions: TAsynchConnectionsOptions; aThreadPoolCount: integer); reintroduce; virtual;
/// shut down the instance, releasing all associated threads and sockets
destructor Destroy; override;
/// high-level access to a connection instance, from its handle
// - could be executed e.g. from a TAsynchConnection.OnRead method
// - returns nil if the handle was not found
// - returns the maching instance, and caller should release the lock as:
// ! try ... finally UnLock; end;
function ConnectionFindLocked(aHandle: TAsynchConnectionHandle;
aIndex: PInteger=nil): TAsynchConnection;
/// just a wrapper around fConnectionLock.Lock
procedure Lock;
/// just a wrapper around fConnectionLock.UnLock
procedure Unlock;
/// remove an handle from the internal list, and close its connection
// - could be executed e.g. from a TAsynchConnection.OnRead method
function ConnectionRemove(aHandle: TAsynchConnectionHandle): boolean;
/// add some data to the asynchronous output buffer of a given connection
// - could be executed e.g. from a TAsynchConnection.OnRead method
function Write(connection: TAsynchConnection; const data; datalen: integer): boolean; overload;
/// add some data to the asynchronous output buffer of a given connection
// - could be executed e.g. from a TAsynchConnection.OnRead method
function Write(connection: TAsynchConnection; const data: SockString): boolean; overload;
/// log some binary data with proper escape
// - can be executed from an TAsynchConnection.OnRead method to track content:
// $ if acoVerboseLog in Sender.Options then Sender.LogVerbose(self,...);
procedure LogVerbose(connection: TAsynchConnection; const ident: RawUTF8;
frame: pointer; framelen: integer); overload;
/// log some binary data with proper escape
// - can be executed from an TAsynchConnection.OnRead method to track content:
// $ if acoVerboseLog in Sender.Options then Sender.LogVerbose(...);
procedure LogVerbose(connection: TAsynchConnection; const ident: RawUTF8;
const frame: RawByteString); overload;
/// will execute TAsynchConnection.OnLastOperationIdle after an idle period
// - could be used to send heartbeats after read/write inactivity
// - equals 0 (i.e. disabled) by default
property LastOperationIdleSeconds: cardinal read fLastOperationIdleSeconds
write fLastOperationIdleSeconds;
/// allow to customize low-level options for processing
property Options: TAsynchConnectionsOptions read fOptions write fOptions;
/// access to the associated log class
property Log: TSynLogClass read fLog;
/// low-level unsafe direct access to the connection instances
// - ensure this property is used in a thread-safe manner, i.e. via
// ! Lock; try ... finally UnLock; end;
property Connection: TAsynchConnectionObjArray read fConnection;
/// low-level unsafe direct access to the connection count
// - ensure this property is used in a thread-safe manner, i.e. via
// ! Lock; try ... finally UnLock; end;
property ConnectionCount: integer read fConnectionCount;
published
/// access to the TCP client sockets poll
// - TAsynchConnection.OnRead should rather use Write() and LogVerbose()
// methods of this TAsynchConnections class instead of using Clients
property Clients: TAsynchConnectionsSockets read fClients;
end;
/// implements a thread-pooled high-performance TCP server
// - will use a TAsynchConnection inherited class to maintain connection state
// for server process
TAsynchServer = class(TAsynchConnections)
protected
fServer: TCrtSocket;
fExecuteFinished: boolean;
procedure Execute; override;
public
/// run the TCP server, listening on a supplied IP port
constructor Create(const aPort: SockString; OnStart,OnStop: TNotifyThreadEvent;
aStreamClass: TAsynchConnectionClass; const ProcessName: SockString;
aLog: TSynLogClass; aOptions: TAsynchConnectionsOptions; aThreadPoolCount: integer=1); reintroduce; virtual;
/// shut down the server, releasing all associated threads and sockets
destructor Destroy; override;
published
/// access to the TCP server socket
property Server: TCrtSocket read fServer;
end;
/// implements thread-pooled high-performance TCP multiple clients
// - e.g. to run some load stress tests with optimized resource use
// - will use a TAsynchConnection inherited class to maintain connection state
// of each connected client
TAsynchClient = class(TAsynchConnections)
protected
procedure Execute; override;
public
/// start the TCP client connections, connecting to the supplied IP server
constructor Create(const aServer,aPort: SockString;
aClientsCount,aClientsTimeoutSecs: integer; OnStart,OnStop: TNotifyThreadEvent;
aStreamClass: TAsynchConnectionClass; const ProcessName: SockString;
aLog: TSynLogClass; aOptions: TAsynchConnectionsOptions; aThreadPoolCount: integer=1); reintroduce; virtual;
published
/// server IP address
property Server: SockString read fThreadClients.Address;
/// server IP port
property Port: SockString read fThreadClients.Port;
end;
{ -------------- WebSockets shared classes for bidirectional remote access }
type
/// Exception raised when processing WebSockets
EWebSockets = class(ESynException);
/// defines the interpretation of the WebSockets frame data
// - match order expected by the WebSockets RFC
TWebSocketFrameOpCode = (
focContinuation, focText, focBinary,
focReserved3, focReserved4, focReserved5, focReserved6, focReserved7,
focConnectionClose, focPing, focPong,
focReservedB, focReservedC, focReservedD, focReservedE, focReservedF);
/// set of WebSockets frame interpretation
TWebSocketFrameOpCodes = set of TWebSocketFrameOpCode;
/// define one attribute of a WebSockets frame data
TWebSocketFramePayload = (
fopAlreadyCompressed);
/// define the attributes of a WebSockets frame data
TWebSocketFramePayloads = set of TWebSocketFramePayload;
/// stores a WebSockets frame
// - see @http://tools.ietf.org/html/rfc6455 for reference
TWebSocketFrame = record
/// the interpretation of the frame data
opcode: TWebSocketFrameOpCode;
/// what is stored in the frame data, i.e. in payload field
content: TWebSocketFramePayloads;
/// equals GetTickCount64 shr 10, as used for TWebSocketFrameList timeout
tix: cardinal;
/// the frame data itself
// - is plain UTF-8 for focText kind of frame
// - is raw binary for focBinary or any other frames
payload: RawByteString;
end;
/// points to a WebSockets frame
PWebSocketFrame = ^TWebSocketFrame;
/// a dynamic list of WebSockets frames
TWebSocketFrameDynArray = array of TWebSocketFrame;
{$M+}
TWebSocketProcess = class;
{$M-}
/// callback event triggered by TWebSocketProtocol for any incoming message
// - called before TWebSocketProtocol.ProcessIncomingFrame for incoming
// focText/focBinary frames
// - should return true if the frame has been handled, or false if the
// regular processing should take place
TOnWebSocketProtocolIncomingFrame =
function(Sender: TWebSocketProcess; var Frame: TWebSocketFrame): boolean of object;
/// one instance implementing application-level WebSockets protocol
// - shared by TWebSocketServer and TWebSocketClient classes
// - once upgraded to WebSockets, a HTTP link could be used e.g. to transmit our
// proprietary 'synopsejson' or 'synopsebin' application content, as stated
// by this typical handshake:
// $ GET /myservice HTTP/1.1
// $ Host: server.example.com
// $ Upgrade: websocket
// $ Connection: Upgrade
// $ Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
// $ Sec-WebSocket-Protocol: synopsejson
// $ Sec-WebSocket-Version: 13
// $ Origin: http://example.com
// $
// $ HTTP/1.1 101 Switching Protocols
// $ Upgrade: websocket
// $ Connection: Upgrade
// $ Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
// $ Sec-WebSocket-Protocol: synopsejson
// - the TWebSocketProtocolJSON inherited class will implement
// $ Sec-WebSocket-Protocol: synopsejson
// - the TWebSocketProtocolBinary inherited class will implement
// $ Sec-WebSocket-Protocol: synopsebin
TWebSocketProtocol = class(TSynPersistent)
protected
fName: RawUTF8;
fURI: RawUTF8;
fFramesInCount: integer;
fFramesOutCount: integer;
fFramesInBytes: QWord;
fFramesOutBytes: QWord;
fOnBeforeIncomingFrame: TOnWebSocketProtocolIncomingFrame;
fRemoteLocalhost: boolean;
fRemoteIP: SockString;
fUpgradeURI: RawUTF8;
fLastError: string;
fEncryption: IProtocol;
// calls fEncryption.ProcessHandshake, if defined
function ProcessHandshake(const ExtIn: TRawUTF8DynArray; out ExtOut: RawUTF8;
ErrorMsg: PRawUTF8): boolean; virtual;
function ProcessURI(const aClientURI: RawUTF8): boolean; virtual; // e.g. for authentication
// focText/focBinary or focContinuation/focConnectionClose from ProcessStart/ProcessStop
procedure ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8); virtual; abstract;
function SendFrames(Owner: TWebSocketProcess;
var Frames: TWebSocketFrameDynArray; var FramesCount: integer): boolean; virtual;
procedure AfterGetFrame(var frame: TWebSocketFrame); virtual;
procedure BeforeSendFrame(var frame: TWebSocketFrame); virtual;
function FrameData(const frame: TWebSocketFrame; const Head: RawUTF8;
HeadFound: PRawUTF8=nil): pointer; virtual;
function FrameType(const frame: TWebSocketFrame): RawUTF8; virtual;
function GetRemoteIP: SockString;
function GetEncrypted: boolean;
// fName by default, but e.g. 'synopsebin, synopsebinary'
function GetSubprotocols: RawUTF8; virtual;
function SetSubprotocol(const aProtocolName: RawUTF8): boolean; virtual;
public
/// abstract constructor to initialize the protocol
// - the protocol should be named, so that the client may be able to request
// for a given protocol
// - if aURI is '', any URI would potentially upgrade to this protocol; you can
// specify an URI to limit the protocol upgrade to a single resource
constructor Create(const aName,aURI: RawUTF8); reintroduce;
/// compute a new instance of the WebSockets protocol, with same parameters
function Clone(const aClientURI: RawUTF8): TWebSocketProtocol; virtual; abstract;
/// set the fEncryption: IProtocol according to the supplied key
// - any asymetric algorithm need to know which side (client/server) to work on
// - try TECDHEProtocol.FromKey(aKey) and fallback to TProtocolAES.Create(TAESCFB)
// using SHA256Weak(aKey)
procedure SetEncryptKey(aServer: boolean; const aKey: RawUTF8);
/// set the fEncryption: IProtocol as TProtocolAES.Create(TAESCFB)
procedure SetEncryptKeyAES(const aKey; aKeySize: cardinal);
/// allow low-level interception before ProcessIncomingFrame is done
property OnBeforeIncomingFrame: TOnWebSocketProtocolIncomingFrame
read fOnBeforeIncomingFrame write fOnBeforeIncomingFrame;
/// access low-level frame encryption
property Encryption: IProtocol read fEncryption;
published
/// the Sec-WebSocket-Protocol application name currently involved
// - e.g. 'synopsejson', 'synopsebin' or 'synopsebinary'
property Name: RawUTF8 read fName;
/// the optional URI on which this protocol would be enabled
// - leave to '' if any URI should match
property URI: RawUTF8 read fURI;
/// the associated 'Remote-IP' HTTP header value
// - returns '' if self=nil or RemoteLocalhost=true
property RemoteIP: SockString read GetRemoteIP;
/// the URI on which this protocol has been upgraded
property UpgradeURI: RawUTF8 read fUpgradeURI;
/// the last error message, during frame processing
property LastError: string read fLastError;
/// returns TRUE if encryption is enabled during the transmission
// - is currently only available for TWebSocketProtocolBinary
property Encrypted: boolean read GetEncrypted;
/// how many frames have been received by this instance
property FramesInCount: integer read fFramesInCount;
/// how many frames have been sent by this instance
property FramesOutCount: integer read fFramesOutCount;
/// how many (uncompressed) bytes have been received by this instance
property FramesInBytes: QWord read fFramesInBytes;
/// how many (uncompressed) bytes have been sent by this instance
property FramesOutBytes: QWord read fFramesOutBytes;
end;
/// callback event triggered by TWebSocketProtocolChat for any incoming message
// - a first call with frame.opcode=focContinuation will take place when
// the connection will be upgraded to WebSockets
// - then any incoming focText/focBinary events will trigger this callback
// - eventually, a focConnectionClose will notify the connection ending
TOnWebSocketProtocolChatIncomingFrame =
procedure(Sender: THttpServerResp; const Frame: TWebSocketFrame) of object;
/// simple chatting protocol, allowing to receive and send WebSocket frames
// - you can use this protocol to implement simple asynchronous communication
// with events expecting no answers, e.g. with AJAX applications
// - see TWebSocketProtocolRest for bi-directional events expecting answers
TWebSocketProtocolChat = class(TWebSocketProtocol)
protected
fOnIncomingFrame: TOnWebSocketProtocolChatIncomingFrame;
procedure ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8); override;
public
/// initialize the chat protocol with an incoming frame callback
constructor Create(const aName,aURI: RawUTF8;
const aOnIncomingFrame: TOnWebSocketProtocolChatIncomingFrame); overload;
/// compute a new instance of the WebSockets protocol, with same parameters
function Clone(const aClientURI: RawUTF8): TWebSocketProtocol; override;
/// on the server side, allows to send a message over the wire to a
// specified client connection
// - a temporary copy of the Frame content will be made for safety
function SendFrame(Sender: THttpServerResp; const Frame: TWebSocketFrame): boolean;
/// on the server side, allows to send a JSON message over the wire to a
// specified client connection
// - the supplied JSON content is supplied as "var", since it may be
// modified during execution, e.g. XORed for frame masking
function SendFrameJson(Sender: THttpServerResp; var JSON: RawUTF8): boolean;
/// you can assign an event to this property to be notified of incoming messages
property OnIncomingFrame: TOnWebSocketProtocolChatIncomingFrame
read fOnIncomingFrame write fOnIncomingFrame;
end;
/// handle a REST application-level bi-directional WebSockets protocol
// - will emulate a bi-directional REST process, using THttpServerRequest to
// store and handle the request parameters: clients would be able to send
// regular REST requests to the server, but the server could use the same
// communication channel to push REST requests to the client
// - a local THttpServerRequest will be used on both client and server sides,
// to store REST parameters and compute the corresponding WebSockets frames
TWebSocketProtocolRest = class(TWebSocketProtocol)
protected
fSequencing: boolean;
fSequence: integer;
procedure ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8); override;
procedure FrameCompress(const Head: RawUTF8; const Values: array of const;
const Content,ContentType: RawByteString; var frame: TWebSocketFrame); virtual; abstract;
function FrameDecompress(const frame: TWebSocketFrame; const Head: RawUTF8;
const values: array of PRawByteString; var contentType,content: RawByteString): Boolean; virtual; abstract;
/// convert the input information of REST request to a WebSocket frame
procedure InputToFrame(Ctxt: THttpServerRequest; aNoAnswer: boolean;
out request: TWebSocketFrame; out head: RawUTF8); virtual;
/// convert a WebSocket frame to the input information of a REST request
function FrameToInput(var request: TWebSocketFrame; out aNoAnswer: boolean;
Ctxt: THttpServerRequest): boolean; virtual;
/// convert a WebSocket frame to the output information of a REST request
function FrameToOutput(var answer: TWebSocketFrame; Ctxt: THttpServerRequest): cardinal; virtual;
/// convert the output information of REST request to a WebSocket frame
procedure OutputToFrame(Ctxt: THttpServerRequest; Status: Cardinal;
var outhead: RawUTF8; out answer: TWebSocketFrame); virtual;
end;
/// used to store the class of a TWebSocketProtocol type
TWebSocketProtocolClass = class of TWebSocketProtocol;
/// handle a REST application-level WebSockets protocol using JSON for transmission
// - could be used e.g. for AJAX or non Delphi remote access
// - this class will implement then following application-level protocol:
// $ Sec-WebSocket-Protocol: synopsejson
TWebSocketProtocolJSON = class(TWebSocketProtocolRest)
protected
procedure FrameCompress(const Head: RawUTF8; const Values: array of const;
const Content,ContentType: RawByteString; var frame: TWebSocketFrame); override;
function FrameDecompress(const frame: TWebSocketFrame; const Head: RawUTF8;
const values: array of PRawByteString; var contentType,content: RawByteString): Boolean; override;
function FrameData(const frame: TWebSocketFrame; const Head: RawUTF8;
HeadFound: PRawUTF8=nil): pointer; override;
function FrameType(const frame: TWebSocketFrame): RawUTF8; override;
public
/// initialize the WebSockets JSON protocol
// - if aURI is '', any URI would potentially upgrade to this protocol; you can
// specify an URI to limit the protocol upgrade to a single resource
constructor Create(const aURI: RawUTF8); reintroduce;
/// compute a new instance of the WebSockets protocol, with same parameters
function Clone(const aClientURI: RawUTF8): TWebSocketProtocol; override;
end;
/// handle a REST application-level WebSockets protocol using compressed and
// optionally AES-CFB encrypted binary
// - this class will implement then following application-level protocol:
// $ Sec-WebSocket-Protocol: synopsebin
// or fallback to the previous subprotocol
// $ Sec-WebSocket-Protocol: synopsebinary
// - 'synopsebin' will expect requests sequenced as 'r000001','r000002',...
// headers matching 'a000001','a000002',... instead of 'request'/'answer'
TWebSocketProtocolBinary = class(TWebSocketProtocolRest)
protected
fCompressed: boolean;
fFramesInBytesSocket: QWord;
fFramesOutBytesSocket: QWord;
procedure FrameCompress(const Head: RawUTF8; const Values: array of const;
const Content,ContentType: RawByteString; var frame: TWebSocketFrame); override;
function FrameDecompress(const frame: TWebSocketFrame; const Head: RawUTF8;
const values: array of PRawByteString; var contentType,content: RawByteString): Boolean; override;
procedure AfterGetFrame(var frame: TWebSocketFrame); override;
procedure BeforeSendFrame(var frame: TWebSocketFrame); override;
function FrameData(const frame: TWebSocketFrame; const Head: RawUTF8;
HeadFound: PRawUTF8=nil): pointer; override;
function FrameType(const frame: TWebSocketFrame): RawUTF8; override;
function SendFrames(Owner: TWebSocketProcess;
var Frames: TWebSocketFrameDynArray; var FramesCount: integer): boolean; override;
procedure ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8); override;
function GetFramesInCompression: integer;
function GetFramesOutCompression: integer;
function GetSubprotocols: RawUTF8; override;
function SetSubprotocol(const aProtocolName: RawUTF8): boolean; override;
public
/// initialize the WebSockets binary protocol with no encryption
// - if aURI is '', any URI would potentially upgrade to this protocol; you
// can specify an URI to limit the protocol upgrade to a single resource
// - SynLZ compression is enabled by default, unless aCompressed is false
constructor Create(const aURI: RawUTF8; aCompressed: boolean=true); reintroduce; overload; virtual;
/// initialize the WebSockets binary protocol with a symmetric AES key
// - if aURI is '', any URI would potentially upgrade to this protocol; you
// can specify an URI to limit the protocol upgrade to a single resource
// - if aKeySize if 128, 192 or 256, TProtocolAES (i.e. AES-CFB encryption)
// will be used to secure the transmission
// - SynLZ compression is enabled by default, unless aCompressed is false
constructor Create(const aURI: RawUTF8; const aKey; aKeySize: cardinal;
aCompressed: boolean=true); reintroduce; overload;
/// initialize the WebSockets binary protocol from a textual key
// - if aURI is '', any URI would potentially upgrade to this protocol; you
// can specify an URI to limit the protocol upgrade to a single resource
// - will create a TProtocolAES or TECDHEProtocol instance, corresponding to
// the supplied aKey and aServer values, to secure the transmission using
// a symmetric or assymetric algorithm
// - SynLZ compression is enabled by default, unless aCompressed is false
constructor Create(const aURI: RawUTF8; aServer: boolean; const aKey: RawUTF8;
aCompressed: boolean=true); reintroduce; overload;
/// compute a new instance of the WebSockets protocol, with same parameters
function Clone(const aClientURI: RawUTF8): TWebSocketProtocol; override;
published
/// defines if SynLZ compression is enabled during the transmission
// - is set to TRUE by default
property Compressed: boolean read fCompressed write fCompressed;
/// how many bytes have been received by this instance from the wire
property FramesInBytesSocket: QWord read fFramesInBytesSocket;
/// how many bytes have been sent by this instance to the wire
property FramesOutBytesSocket: QWord read fFramesOutBytesSocket;
/// compression ratio of frames received by this instance
property FramesInCompression: integer read GetFramesInCompression;
/// compression ratio of frames Sent by this instance
property FramesOutCompression: integer read GetFramesOutCompression;
end;
/// used to maintain a list of websocket protocols (for the server side)
TWebSocketProtocolList = class(TSynPersistentLock)
protected
fProtocols: array of TWebSocketProtocol;
// caller should make fSafe.Lock/UnLock
function FindIndex(const aName,aURI: RawUTF8): integer;
public
/// add a protocol to the internal list
// - returns TRUE on success
// - if this protocol is already existing for this given name and URI,
// returns FALSE: it is up to the caller to release aProtocol if needed
function Add(aProtocol: TWebSocketProtocol): boolean;
/// add once a protocol to the internal list
// - if this protocol is already existing for this given name and URI, any
// previous one will be released - so it may be confusing on a running server
// - returns TRUE if the protocol was added for the first time, or FALSE
// if the protocol has been replaced or is invalid (e.g. aProtocol=nil)
function AddOnce(aProtocol: TWebSocketProtocol): boolean;
/// erase a protocol from the internal list, specified by its name
function Remove(const aProtocolName,aURI: RawUTF8): boolean;
/// finalize the list storage
destructor Destroy; override;
/// create a new protocol instance, from the internal list
function CloneByName(const aProtocolName, aClientURI: RawUTF8): TWebSocketProtocol;
/// create a new protocol instance, from the internal list
function CloneByURI(const aClientURI: RawUTF8): TWebSocketProtocol;
/// how many protocols are stored
function Count: integer;
end;
/// indicates which kind of process did occur in the main WebSockets loop
TWebSocketProcessOne = (
wspNone, wspPing, wspDone, wspAnswer, wspError, wspClosed);
/// indicates how TWebSocketProcess.NotifyCallback() will work
TWebSocketProcessNotifyCallback = (
wscBlockWithAnswer, wscBlockWithoutAnswer, wscNonBlockWithoutAnswer);
/// used to manage a thread-safe list of WebSockets frames
TWebSocketFrameList = class(TSynPersistentLock)
protected
fTimeoutSec: PtrInt;
procedure Delete(i: integer);
public
/// low-level access to the WebSocket frames list
List: TWebSocketFrameDynArray;
/// current number of WebSocket frames in the list
Count: integer;
/// initialize the list
constructor Create(timeoutsec: integer); reintroduce;
/// add a WebSocket frame in the list
// - this method is thread-safe
procedure Push(const frame: TWebSocketFrame);
/// add a void WebSocket frame in the list
// - this method is thread-safe
procedure PushVoidFrame(opcode: TWebSocketFrameOpCode);
/// retrieve a WebSocket frame from the list, oldest first
// - you should specify a frame type to search for, according to the
// specified WebSockets protocl
// - this method is thread-safe
function Pop(protocol: TWebSocketProtocol;
const head: RawUTF8; out frame: TWebSocketFrame): boolean;
/// how many 'answer' frames are to be ignored
// - this method is thread-safe
function AnswerToIgnore(incr: integer=0): integer;
end;
/// parameters to be used for WebSockets process
{$ifdef USERECORDWITHMETHODS}TWebSocketProcessSettings = record
{$else}TWebSocketProcessSettings = object{$endif}
public
/// time in milli seconds between each focPing commands sent to the other end
// - default is 0, i.e. no automatic ping sending on client side, and
// 20000, i.e. 20 seconds, on server side
HeartbeatDelay: cardinal;
/// maximum period time in milli seconds when ProcessLoop thread will stay
// idle before checking for the next pending requests
// - default is 500 ms, but you may put a lower value, if you expects e.g.
// REST commands or NotifyCallback(wscNonBlockWithoutAnswer) to be processed
// with a lower delay
LoopDelay: cardinal;
/// ms between sending - allow to gather output frames
// - GetTickCount resolution is around 16ms under Windows, so default 10ms
// seems fine for a cross-platform similar behavior
SendDelay: cardinal;
/// will close the connection after a given number of invalid Heartbeat sent
// - when a Hearbeat is failed to be transmitted, the class will start
// counting how many ping/pong did fail: when this property value is
// reached, it will release and close the connection
// - default value is 5
DisconnectAfterInvalidHeartbeatCount: cardinal;
/// how many milliseconds the callback notification should wait acquiring
// the connection before failing
// - defaut is 5000, i.e. 5 seconds
CallbackAcquireTimeOutMS: cardinal;
/// how many milliseconds the callback notification should wait for the
// client to return its answer
// - defaut is 30000, i.e. 30 seconds
CallbackAnswerTimeOutMS: cardinal;
/// callback run when a WebSockets client is just connected
// - triggerred by TWebSocketProcess.ProcessStart
OnClientConnected: TNotifyEvent;
/// callback run when a WebSockets client is just disconnected
// - triggerred by TWebSocketProcess.ProcessStop
OnClientDisconnected: TNotifyEvent;
/// by default, contains [] to minimize the logged information
// - set logHeartbeat if you want the ping/pong frames to be logged
// - set logTextFrameContent if you want the text frame content to be logged
// - set logBinaryFrameContent if you want the binary frame content to be logged
// - used only if WebSocketLog global variable is set to a TSynLog class
LogDetails: set of (logHeartbeat,logTextFrameContent,logBinaryFrameContent);
/// will set the default values
procedure SetDefaults;
/// will set LogDetails to its highest level of verbosity
// - used only if WebSocketLog global variable is set
procedure SetFullLog;
end;
/// points to parameters to be used for WebSockets process
// - using a pointer/reference type will allow in-place modification of
// any TWebSocketProcess.Settings, TWebSocketServer.Settings or
// THttpClientWebSockets.Settings property
PWebSocketProcessSettings = ^TWebSocketProcessSettings;
/// the current state of the WebSockets process
TWebSocketProcessState = (wpsCreate,wpsRun,wpsClose,wpsDestroy);
/// abstract WebSockets process, used on both client or server sides
// - CanGetFrame/ReceiveBytes/SendBytes abstract methods should be overriden with
// actual communication, and fState and ProcessStart/ProcessStop should be
// updated from the actual processing thread (e.g. as in TWebCrtSocketProcess)
TWebSocketProcess = class(TSynPersistent)
protected
fProcessName: RawUTF8;
fIncoming: TWebSocketFrameList;
fOutgoing: TWebSocketFrameList;
fOwnerThread: TSynThread;
fOwnerConnection: THttpServerConnectionID;
fState: TWebSocketProcessState;
fProtocol: TWebSocketProtocol;
fMaskSentFrames: byte;
fProcessEnded: boolean;
fNoConnectionCloseAtDestroy: boolean;
fProcessCount: integer;
fSettings: TWebSocketProcessSettings;
fSafeIn, fSafeOut: PSynLocker;
fInvalidPingSendCount: cardinal;
fSafePing: PSynLocker;
fLastSocketTicks: Int64;
function LastPingDelay: Int64;
procedure SetLastPingTicks(invalidPing: boolean=false);
/// callback methods run by ProcessLoop
procedure ProcessStart; virtual;
procedure ProcessStop; virtual;
// called by ProcessLoop - TRUE=continue, FALSE=ended
// - caller may have checked that some data is pending to read
function ProcessLoopStepReceive: boolean;
// called by ProcessLoop - TRUE=continue, FALSE=ended
// - caller may check that LastPingDelay>fSettings.SendDelay and Socket is writable
function ProcessLoopStepSend: boolean;
// blocking process, for one thread handling all WebSocket connection process
procedure ProcessLoop;
function ComputeContext(out RequestProcess: TOnHttpServerRequest): THttpServerRequest; virtual; abstract;
procedure HiResDelay(const start: Int64);
procedure Log(const frame: TWebSocketFrame; const aMethodName: RawUTF8;
aEvent: TSynLogInfo=sllTrace; DisableRemoteLog: Boolean=false); virtual;
function SendPendingOutgoingFrames: boolean;
public
/// initialize the WebSockets process on a given connection
// - the supplied TWebSocketProtocol will be owned by this instance
// - other parameters should reflect the client or server expectations
constructor Create(aProtocol: TWebSocketProtocol; aOwnerConnection: THttpServerConnectionID;
aOwnerThread: TSynThread; const aSettings: TWebSocketProcessSettings;
const aProcessName: RawUTF8); reintroduce;
/// finalize the context
// - if needed, will notify the other end with a focConnectionClose frame
// - will release the TWebSocketProtocol associated instance
destructor Destroy; override;
/// abstract low-level method to retrieve pending input data
// - should return the number of bytes (<=count) received and written to P
// - is defined separated to allow multi-thread pooling
function ReceiveBytes(P: PAnsiChar; count: integer): integer;
virtual; abstract;
/// abstract low-level method to send pending output data
// - returns false on any error, try on success
// - is defined separated to allow multi-thread pooling
function SendBytes(P: pointer; Len: integer): boolean;
virtual; abstract;
/// abstract low-level method to check if there is some pending input data
// in the input Socket ready for GetFrame/ReceiveBytes
// - is defined separated to allow multi-thread pooling
function CanGetFrame(TimeOut: cardinal; ErrorWithoutException: PInteger): boolean;
virtual; abstract;
/// blocking process incoming WebSockets framing protocol
// - CanGetFrame should have been called and returned true before
// - will call overriden ReceiveBytes() for the actual communication
function GetFrame(out Frame: TWebSocketFrame; ErrorWithoutException: PInteger): boolean;
/// process outgoing WebSockets framing protocol -> to be overriden
// - will call overriden SendBytes() for the actual communication
// - use Outgoing.Push() to send frames asynchronously
function SendFrame(var Frame: TWebSocketFrame): boolean;
/// will push a request or notification to the other end of the connection
// - caller should set the aRequest with the outgoing parameters, and
// optionally receive a response from the other end
// - the request may be sent in blocking or non blocking mode
// - returns the HTTP Status code (e.g. HTTP_SUCCESS=200 for success)
function NotifyCallback(aRequest: THttpServerRequest;
aMode: TWebSocketProcessNotifyCallback): cardinal; virtual;
/// the settings currently used during the WebSockets process
// - defined as a pointer so that you may be able to change the values
function Settings: PWebSocketProcessSettings; {$ifdef HASINLINE}inline;{$endif}
/// returns the current state of the underlying connection
function State: TWebSocketProcessState;
/// the associated 'Remote-IP' HTTP header value
// - returns '' if Protocol=nil or Protocol.RemoteLocalhost=true
function RemoteIP: SockString;
/// direct access to the low-level incoming frame stack
property Incoming: TWebSocketFrameList read fIncoming;
/// direct access to the low-level outgoing frame stack
// - call Outgoing.Push() to send frames asynchronously, with optional
// jumboframe gathering (if supported by the protocol)
property Outgoing: TWebSocketFrameList read fOutgoing;
/// the associated low-level processing thread
property OwnerThread: TSynThread read fOwnerThread;
/// the associated low-level WebSocket connection opaque identifier
property OwnerConnection: THttpServerConnectionID read fOwnerConnection;
/// how many frames are currently processed by this connection
property ProcessCount: integer read fProcessCount;
/// may be set to TRUE before Destroy to force raw socket disconnection
property NoConnectionCloseAtDestroy: boolean
read fNoConnectionCloseAtDestroy write fNoConnectionCloseAtDestroy;
published
/// the Sec-WebSocket-Protocol application protocol currently involved
// - TWebSocketProtocolJSON or TWebSocketProtocolBinary in the mORMot context
// - could be nil if the connection is in standard HTTP/1.1 mode
property Protocol: TWebSocketProtocol read fProtocol;
/// the associated process name
property ProcessName: RawUTF8 read fProcessName write fProcessName;
/// how many invalid heartbeat frames have been sent
// - a non 0 value indicates a connection problem
property InvalidPingSendCount: cardinal read fInvalidPingSendCount;
end;
/// TCrtSocket-based WebSockets process, used on both client or server sides
// - will use the socket in blocking mode, so expects its own processing thread
TWebCrtSocketProcess = class(TWebSocketProcess)
protected
fSocket: TCrtSocket;
public
/// initialize the WebSockets process on a given TCrtSocket connection
// - the supplied TWebSocketProtocol will be owned by this instance
// - other parameters should reflect the client or server expectations
constructor Create(aSocket: TCrtSocket; aProtocol: TWebSocketProtocol;
aOwnerConnection: THttpServerConnectionID; aOwnerThread: TSynThread;
const aSettings: TWebSocketProcessSettings;
const aProcessName: RawUTF8); reintroduce; virtual;
/// first step of the low level incoming WebSockets framing protocol over TCrtSocket
// - in practice, just call fSocket.SockInPending to check for pending data
function CanGetFrame(TimeOut: cardinal; ErrorWithoutException: PInteger): boolean; override;
/// low level receive incoming WebSockets frame data over TCrtSocket
// - in practice, just call fSocket.SockInRead to check for pending data
function ReceiveBytes(P: PAnsiChar; count: integer): integer; override;
/// low level receive incoming WebSockets frame data over TCrtSocket
// - in practice, just call fSocket.TrySndLow to send pending data
function SendBytes(P: pointer; Len: integer): boolean; override;
/// the associated communication socket
// - on the server side, is a THttpServerSocket
// - access to this instance is protected by Safe.Lock/Unlock
property Socket: TCrtSocket read fSocket;
end;
{ -------------- WebSockets Server classes for bidirectional remote access }
type
TWebSocketServerSocket = class(THttpServerSocket)
public
/// overriden to detect upgrade: websocket header and return grOwned
function GetRequest(withBody: boolean;
headerMaxTix: Int64): THttpServerSocketGetRequestResult; override;
end;
type
{$M+}
TWebSocketServerResp = class;
{$M-}
/// implements WebSockets process as used on server side
TWebSocketProcessServer = class(TWebCrtSocketProcess)
protected
fServerResp: TWebSocketServerResp;
function ComputeContext(out RequestProcess: TOnHttpServerRequest): THttpServerRequest; override;
end;
/// an enhanced input/output structure used for HTTP and WebSockets requests
// - this class will contain additional parameters used to maintain the
// WebSockets execution context in overriden TWebSocketServer.Process method
TWebSocketServerResp = class(THttpServerResp)
protected
fProcess: TWebSocketProcessServer;
public
/// initialize the context, associated to a HTTP/WebSockets server instance
constructor Create(aServerSock: THttpServerSocket; aServer: THttpServer); override;
/// push a notification to the client
function NotifyCallback(Ctxt: THttpServerRequest; aMode: TWebSocketProcessNotifyCallback): cardinal; virtual;
/// the Sec-WebSocket-Protocol application protocol currently involved
// - TWebSocketProtocolJSON or TWebSocketProtocolBinary in the mORMot context
// - could be nil if the connection is in standard HTTP/1.1 mode
function WebSocketProtocol: TWebSocketProtocol;
/// low-level WebSocket protocol processing instance
property WebSocketProcess: TWebSocketProcessServer read fProcess;
end;
/// main HTTP/WebSockets server Thread using the standard Sockets API (e.g. WinSock)
// - once upgraded to WebSockets from the client, this class is able to serve
// any Sec-WebSocket-Protocol application content
TWebSocketServer = class(THttpServer)
protected
fWebSocketConnections: TSynObjectListLocked;
fProtocols: TWebSocketProtocolList;
fSettings: TWebSocketProcessSettings;
/// validate the WebSockets handshake, then call Context.fProcess.ProcessLoop()
function WebSocketProcessUpgrade(ClientSock: THttpServerSocket;
Context: TWebSocketServerResp): integer; virtual;
/// overriden method which will recognize the WebSocket protocol handshake,
// then run the whole bidirectional communication in its calling thread
// - here ConnectionThread is a THttpServerResp, and ClientSock.Headers
// and ConnectionUpgrade properties should be checked for the handshake
procedure Process(ClientSock: THttpServerSocket;
ConnectionID: THttpServerConnectionID; ConnectionThread: TSynThread); override;
public
/// create a Server Thread, binded and listening on a port
// - this constructor will raise a EHttpServer exception if binding failed
// - expects the port to be specified as string, e.g. '1234'; you can
// optionally specify a server address to bind to, e.g. '1.2.3.4:1234'
// - due to the way how WebSockets works, one thread will be created
// for any incoming connection
// - note that this constructor will not register any protocol, so is
// useless until you execute Protocols.Add()
// - in the current implementation, the ServerThreadPoolCount parameter will
// use two threads by default to handle shortliving HTTP/1.0 "connection: close"
// requests, and one thread will be maintained per keep-alive/websockets client
// - by design, the KeepAliveTimeOut value is ignored with this server
// once it has been upgraded to WebSockets
constructor Create(const aPort: SockString; OnStart,OnStop: TNotifyThreadEvent;
const ProcessName: SockString; ServerThreadPoolCount: integer=2;
KeepAliveTimeOut: integer=30000; HeadersNotFiltered: boolean=false); override;
/// close the server
destructor Destroy; override;
/// will send a given frame to all connected clients
// - expect aFrame.opcode to be either focText or focBinary
// - will call TWebSocketProcess.Outgoing.Push for asynchronous sending
procedure WebSocketBroadcast(const aFrame: TWebSocketFrame); overload;
/// will send a given frame to clients matching the supplied connection IDs
// - expect aFrame.opcode to be either focText or focBinary
// - will call TWebSocketProcess.Outgoing.Push for asynchronous sending
procedure WebSocketBroadcast(const aFrame: TWebSocketFrame;
const aClientsConnectionID: THttpServerConnectionIDDynArray); overload;
/// give access to the underlying connection from its ID
// - also identifies an incoming THttpServerResp as a valid TWebSocketServerResp
function IsActiveWebSocket(ConnectionID: THttpServerConnectionID): TWebSocketServerResp;
/// give access to the underlying connection from its connection thread
// - also identifies an incoming THttpServerResp as a valid TWebSocketServerResp
function IsActiveWebSocketThread(ConnectionThread: TSynThread): TWebSocketServerResp;
/// the settings to be used for WebSockets process
// - note that those parameters won't be propagated to existing connections
// - defined as a pointer so that you may be able to change the values
function Settings: PWebSocketProcessSettings; {$ifdef HASINLINE}inline;{$endif}
/// how many WebSockets connections are currently maintained
function WebSocketConnections: integer;
/// access to the protocol list handled by this server
property WebSocketProtocols: TWebSocketProtocolList read fProtocols;
end;
/// main HTTP/WebSockets server Thread using the standard Sockets API (e.g. WinSock)
// - once upgraded to WebSockets from the client, this class is able to serve
// our proprietary Sec-WebSocket-Protocol: 'synopsejson' or 'synopsebin'
// application content, managing regular REST client-side requests and
// also server-side push notifications
// - once in 'synopse*' mode, the Request() method will be trigerred from
// any incoming REST request from the client, and the OnCallback event
// will be available to push a request from the server to the client
TWebSocketServerRest = class(TWebSocketServer)
public
/// create a Server Thread, binded and listening on a port, with our
// 'synopsebin' and optionally 'synopsejson' modes
// - if aWebSocketsURI is '', any URI would potentially upgrade; you can
// specify an URI to limit the protocol upgrade to a single resource
// - TWebSocketProtocolBinary will always be registered by this constructor
// - if the encryption key text is not '', TWebSocketProtocolBinary will
// use AES-CFB 256 bits encryption
// - if aWebSocketsAJAX is TRUE, it will also register TWebSocketProtocolJSON
// so that AJAX applications would be able to connect to this server
// - warning: WaitStarted should be called after Create() to check for
// for actual port binding in the background thread
constructor Create(const aPort: SockString; OnStart,OnStop: TNotifyThreadEvent;
const aProcessName, aWebSocketsURI, aWebSocketsEncryptionKey: RawUTF8;
aWebSocketsAJAX: boolean=false); reintroduce; overload;
/// defines the WebSockets protocols to be used for this Server
// - i.e. 'synopsebin' and optionally 'synopsejson' modes
// - if aWebSocketsURI is '', any URI would potentially upgrade; you can
// specify an URI to limit the protocol upgrade to a single resource
// - TWebSocketProtocolBinary will always be registered by this constructor
// - if the encryption key text is not '', TWebSocketProtocolBinary will
// use AES-CFB 256 bits encryption
// - if aWebSocketsAJAX is TRUE, it will also register TWebSocketProtocolJSON
// so that AJAX applications would be able to connect to this server
procedure WebSocketsEnable(const aWebSocketsURI, aWebSocketsEncryptionKey: RawUTF8;
aWebSocketsAJAX: boolean=false; aWebSocketsCompressed: boolean=true);
/// server can send a request back to the client, when the connection has
// been upgraded to WebSocket
// - InURL/InMethod/InContent properties are input parameters (InContentType
// is ignored)
// - OutContent/OutContentType/OutCustomHeader are output parameters
// - CallingThread should be set to the client's Ctxt.CallingThread
// value, so that the method could know which connnection is to be used -
// it will return STATUS_NOTFOUND (404) if the connection is unknown
// - result of the function is the HTTP error code (200 if OK, e.g.)
function Callback(Ctxt: THttpServerRequest; aNonBlocking: boolean): cardinal; override;
end;
/// used to return the text corresponding to a specified WebSockets frame data
function ToText(opcode: TWebSocketFrameOpCode): PShortString; overload;
/// used to return the text corresponding to a specified WebSockets sending mode
function ToText(mode: TWebSocketProcessNotifyCallback): PShortString; overload;
/// low-level intitialization of a TWebSocketFrame for proper REST content
procedure FrameInit(opcode: TWebSocketFrameOpCode; const Content, ContentType: RawByteString;
out frame: TWebSocketFrame);
{ -------------- WebSockets Client classes for bidirectional remote access }
type
{$M+}
THttpClientWebSockets = class;
TWebSocketProcessClientThread = class;
{$M-}
/// implements WebSockets process as used on client side
TWebSocketProcessClient = class(TWebCrtSocketProcess)
protected
fClientThread: TWebSocketProcessClientThread;
function ComputeContext(out RequestProcess: TOnHttpServerRequest): THttpServerRequest; override;
public
/// initialize the client process for a given THttpClientWebSockets
constructor Create(aSender: THttpClientWebSockets; aProtocol: TWebSocketProtocol;
const aProcessName: RawUTF8); reintroduce; virtual;
/// finalize the process
destructor Destroy; override;
end;
/// the current state of the client side processing thread
TWebSocketProcessClientThreadState = (sCreate, sRun, sFinished, sClosed);
/// WebSockets processing thread used on client side
// - will handle any incoming callback
TWebSocketProcessClientThread = class(TSynThread)
protected
fThreadState: TWebSocketProcessClientThreadState;
fProcess: TWebSocketProcessClient;
procedure Execute; override;
public
constructor Create(aProcess: TWebSocketProcessClient); reintroduce;
end;
/// Socket API based REST and HTTP/1.1 client, able to upgrade to WebSockets
// - will implement regular HTTP/1.1 until WebSocketsUpgrade() is called
THttpClientWebSockets = class(THttpClientSocket)
protected
fProcess: TWebSocketProcessClient;
fSettings: TWebSocketProcessSettings;
fOnCallbackRequestProcess: TOnHttpServerRequest;
fOnBeforeIncomingFrame: TOnWebSocketProtocolIncomingFrame;
fOnWebSocketsClosed: TNotifyEvent;
procedure SetInt32OptionByIndex(OptName, OptVal: integer); override;
public
/// low-level initialization of a client WebSockets connection
// - calls Open() then WebSocketsUpgrade() for a given protocol
// - with proper error interception and optional logging, returning nil
class function WebSocketsConnect(const aHost, aPort: SockString;
aProtocol: TWebSocketProtocol; aLog: TSynLogClass=nil;
const aLogContext: RawUTF8=''; const aURI: RawUTF8='';
const aCustomHeaders: RawUTF8=''): THttpClientWebSockets;
/// common initialization of all constructors
// - this overridden method will set the UserAgent with some default value
constructor Create(aTimeOut: PtrInt=10000); override;
/// finalize the connection
destructor Destroy; override;
/// process low-level REST request, either on HTTP/1.1 or via WebSockets
// - after WebSocketsUpgrade() call, will use WebSockets for the communication
function Request(const url, method: SockString; KeepAlive: cardinal;
const header, Data, DataType: SockString; retry: boolean): integer; override;
/// upgrade the HTTP client connection to a specified WebSockets protocol
// - i.e. 'synopsebin' and optionally 'synopsejson' modes
// - you may specify an URI to as expected by the server for upgrade
// - if aWebSocketsAJAX equals default FALSE, it will register the
// TWebSocketProtocolBinaryprotocol, with AES-CFB 256 bits encryption
// if the encryption key text is not '' and optional SynLZ compression
// - if aWebSocketsAJAX is TRUE, it will register the slower and less secure
// TWebSocketProtocolJSON (to be used for AJAX debugging/test purposes only)
// and aWebSocketsEncryptionKey/aWebSocketsCompression parameters won't be used
// - alternatively, you can specify your own custom TWebSocketProtocol instance
// (owned by this method and immediately released on error)
// - will return '' on success, or an error message on failure
function WebSocketsUpgrade(const aWebSocketsURI, aWebSocketsEncryptionKey: RawUTF8;
aWebSocketsAJAX: boolean=false; aWebSocketsCompression: boolean=true;
aProtocol: TWebSocketProtocol=nil; const aCustomHeaders: RawUTF8=''): RawUTF8;
/// the settings to be used for WebSockets process
// - note that those parameters won't be propagated to existing connections
// - defined as a pointer so that you may be able to change the values
function Settings: PWebSocketProcessSettings; {$ifdef HASINLINE}inline;{$endif}
/// this event handler will be executed for any incoming push notification
property OnCallbackRequestProcess: TOnHttpServerRequest
read fOnCallbackRequestProcess write fOnCallbackRequestProcess;
/// event handler trigerred when the WebSocket link is destroyed
// - may happen e.g. after graceful close from the server side, or
// after DisconnectAfterInvalidHeartbeatCount is reached
property OnWebSocketsClosed: TNotifyEvent
read fOnWebSocketsClosed write fOnWebSocketsClosed;
/// allow low-level interception before
// TWebSocketProcessClient.ProcessIncomingFrame is executed
property OnBeforeIncomingFrame: TOnWebSocketProtocolIncomingFrame
read fOnBeforeIncomingFrame write fOnBeforeIncomingFrame;
published
/// the current WebSockets processing class
// - equals nil for plain HTTP/1.1 mode
// - points to the current WebSockets process instance, after a successful
// WebSocketsUpgrade() call, so that you could use e.g. WebSockets.Protocol
// to retrieve the protocol currently used
property WebSockets: TWebSocketProcessClient read fProcess;
end;
var
/// if set, will log all WebSockets raw information
// - see also TWebSocketProcessSettings.LogDetails and
// TWebSocketProcessSettings.SetFullLog to setup even more verbose information,
// e.g. by setting HttpServerFullWebSocketsLog and HttpClientFullWebSocketsLog
// global variables to true (as defined in mORMotHttpServer/mORMotHttpClient)
WebSocketLog: TSynLogClass;
/// number of bytes above which SynLZ compression may be done
// - when working with TWebSocketProtocolBinary
// - it is useless to compress smaller frames, which fits in network MTU
WebSocketsBinarySynLzThreshold: integer = 450;
/// how replay attacks will be handled in TWebSocketProtocolBinary encryption
// - you may set this global value to repCheckedIfAvailable if you are
// really paranoid (but resulting security may be lower, since the IV is
// somewhat more predictable than plain random)
WebSocketsIVReplayAttackCheck: TAESIVReplayAttackCheck = repNoCheck;
/// the allowed maximum size, in MB, of a WebSockets frame
WebSocketsMaxFrameMB: cardinal = 256;
implementation
{ -------------- high-level SynCrtSock classes depending on SynCommons }
{ THttpRequestCached }
constructor THttpRequestCached.Create(const aURI: RawUTF8;
aKeepAliveSeconds, aTimeoutSeconds: integer; const aToken: RawUTF8;
aHttpClass: THttpRequestClass);
begin
inherited Create;
fKeepAlive := aKeepAliveSeconds*1000;
if aTimeoutSeconds > 0 then // 0 means no cache
fCache := TSynDictionary.Create(TypeInfo(TRawUTF8DynArray),
TypeInfo(THttpRequestCacheDynArray),true,aTimeoutSeconds);
if not LoadFromURI(aURI,aToken,aHttpClass) then
raise ESynException.CreateUTF8('%.Create: invalid aURI=%',[self,aURI]);
end;
procedure THttpRequestCached.Clear;
begin
FreeAndNil(fHttp); // either fHttp or fSocket is used
FreeAndNil(fSocket);
if fCache <> nil then
fCache.DeleteAll;
fURI.Clear;
fTokenHeader := '';
end;
destructor THttpRequestCached.Destroy;
begin
fCache.Free;
fHttp.Free;
fSocket.Free;
inherited Destroy;
end;
function THttpRequestCached.Get(const aAddress: SockString;
aModified: PBoolean; aStatus: PInteger): SockString;
var cache: THttpRequestCache;
headin, headout: SockString;
status: integer;
modified: boolean;
begin
result := '';
if (fHttp=nil) and (fSocket=nil) then // either fHttp or fSocket is used
exit;
if (fCache <> nil) and fCache.FindAndCopy(aAddress,cache) then
FormatUTF8('If-None-Match: %',[cache.Tag],RawUTF8(headin));
if fTokenHeader<>'' then begin
if headin<>'' then
headin := headin+#13#10;
headin := headin+fTokenHeader;
end;
if fSocket<>nil then begin
status := fSocket.Get(aAddress,fKeepAlive,headin);
result := fSocket.Content;
end else
status := fHttp.Request(aAddress,'GET',fKeepAlive,headin,'','',headout,result);
modified := true;
case status of
STATUS_SUCCESS:
if fCache <> nil then begin
if fHttp <> nil then
FindNameValue(headout,'ETAG:',cache.Tag) else
cache.Tag := fSocket.HeaderGetValue('ETAG');
if cache.Tag <> '' then begin
cache.Content := result;
fCache.AddOrUpdate(aAddress,cache);
end;
end;
STATUS_NOTMODIFIED: begin
result := cache.Content;
modified := false;
end;
end;
if aModified<>nil then
aModified^ := modified;
if aStatus<>nil then
aStatus^ := status;
end;
function THttpRequestCached.LoadFromURI(const aURI, aToken: RawUTF8;
aHttpClass: THttpRequestClass): boolean;
begin
result := false;
if (self=nil) or (fHttp<>nil) or (fSocket<>nil) or not fURI.From(aURI) then
exit;
fTokenHeader := AuthorizationBearer(aToken);
if aHttpClass=nil then begin
{$ifdef USEWININET}
aHttpClass := TWinHTTP;
{$else}
{$ifdef USELIBCURL}
if fURI.Https then
aHttpClass := TCurlHTTP;
{$endif}
{$endif}
end;
if aHttpClass=nil then
fSocket := THttpClientSocket.Open(fURI.Server,fURI.Port) else
fHttp := aHttpClass.Create(fURI.Server,fURI.Port,fURI.Https);
result := true;
end;
function THttpRequestCached.Flush(const aAddress: SockString): boolean;
begin
if fCache <> nil then
result := fCache.Delete(aAddress)>=0 else
result := true;
end;
function PurgeHeaders(P: PUTF8Char): RawUTF8;
var
tmp: TTextWriterStackBuffer;
next: PUTF8Char;
W: TTextWriter;
begin
result := '';
W := nil;
try
while P <> nil do begin
next := GotoNextLine(P);
if IdemPCharArray(P, ['CONTENT-', 'CONNECTION:', 'KEEP-ALIVE:', 'TRANSFER-',
'X-POWERED', 'USER-AGENT', 'REMOTEIP:', 'HOST:', 'ACCEPT:']) < 0 then begin
if W = nil then
W := TTextWriter.CreateOwnedStream(tmp);
W.AddNoJSONEscape(P, next - P);
end;
P := next;
end;
if W <> nil then
W.SetText(result);
finally
W.Free;
end;
end;
{ -------------- WebSockets shared classes for bidirectional remote access }
var
_TWebSocketFrameOpCode: array[TWebSocketFrameOpCode] of PShortString;
_TWebSocketProcessNotifyCallback: array[TWebSocketProcessNotifyCallback] of PShortString;
function ToText(opcode: TWebSocketFrameOpCode): PShortString;
begin
result := _TWebSocketFrameOpCode[opcode];
end;
function ToText(mode: TWebSocketProcessNotifyCallback): PShortString;
begin
result := _TWebSocketProcessNotifyCallback[mode];
end;
function ToText(st: TWebSocketProcessClientThreadState): PShortString; overload;
begin
result := GetEnumName(TypeInfo(TWebSocketProcessClientThreadState),ord(st));
end;
function ToText(ev: TPollSocketEvent): PShortString; overload;
begin
result := GetEnumName(TypeInfo(TPollSocketEvent),ord(ev));
end;
function ToText(st: TWebSocketProcessState): PShortString; overload;
begin
result := GetEnumName(TypeInfo(TWebSocketProcessState),ord(st));
end;
const
STATUS_WEBSOCKETCLOSED = 0;
procedure ComputeChallenge(const Base64: RawByteString; out Digest: TSHA1Digest);
const SALT: string[36] = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
var SHA: TSHA1;
begin
SHA.Init;
SHA.Update(pointer(Base64),length(Base64));
SHA.Update(@SALT[1],36);
SHA.Final(Digest);
end;
{ TWebSocketProcessSettings }
procedure TWebSocketProcessSettings.SetDefaults;
begin
HeartbeatDelay := 0;
LoopDelay := 500;
SendDelay := 10;
DisconnectAfterInvalidHeartbeatCount := 5;
CallbackAcquireTimeOutMS := 5000;
CallbackAnswerTimeOutMS := 5000;
LogDetails := [];
OnClientConnected := nil;
OnClientDisconnected := nil;
end;
procedure TWebSocketProcessSettings.SetFullLog;
begin
LogDetails := [logHeartbeat,logTextFrameContent,logBinaryFrameContent];
end;
{ TWebSocketProtocol }
constructor TWebSocketProtocol.Create(const aName,aURI: RawUTF8);
begin
fName := aName;
fURI := aURI;
end;
procedure TWebSocketProtocol.SetEncryptKey(aServer: boolean; const aKey: RawUTF8);
var key: TSHA256Digest;
begin
if aKey='' then
fEncryption := nil else begin
fEncryption := TECDHEProtocol.FromKey(aKey,aServer);
if fEncryption=nil then begin
SHA256Weak(aKey,key); // fallback to TProtocolAES/TAESCFB
SetEncryptKeyAES(key,256);
end;
end;
end;
procedure TWebSocketProtocol.SetEncryptKeyAES(const aKey; aKeySize: cardinal);
begin
if aKeySize>=128 then
fEncryption := TProtocolAES.Create(
TAESCFB,aKey,aKeySize,WebSocketsIVReplayAttackCheck);
end;
procedure TWebSocketProtocol.AfterGetFrame(var frame: TWebSocketFrame);
begin
inc(fFramesInCount);
inc(fFramesInBytes,length(frame.payload)+2);
end;
procedure TWebSocketProtocol.BeforeSendFrame(var frame: TWebSocketFrame);
begin
inc(fFramesOutCount);
inc(fFramesOutBytes,length(frame.payload)+2);
end;
function TWebSocketProtocol.FrameData(const frame: TWebSocketFrame;
const Head: RawUTF8; HeadFound: PRawUTF8): pointer;
begin
result := nil; // no frame type by default
end;
function TWebSocketProtocol.FrameType(
const frame: TWebSocketFrame): RawUTF8;
begin
result := '*'; // no frame URI by default
end;
function TWebSocketProtocol.ProcessHandshake(const ExtIn: TRawUTF8DynArray;
out ExtOut: RawUTF8; ErrorMsg: PRawUTF8): boolean;
var res: TProtocolResult;
msgin,msgout: RawUTF8;
synhk: boolean;
i: integer;
begin
result := fEncryption=nil;
if result then
exit; // nothing to handshake for -> try to continue
synhk := false;
if ExtIn<>nil then begin
for i := 0 to length(ExtIn)-1 do
if IdemPropNameU(ExtIn[i],'synhk') then
synhk := true else
if synhk and IdemPChar(pointer(ExtIn[i]),'HK=') then begin
msgin := copy(ExtIn[i],4,maxInt);
break;
end;
if (msgin='') or not synhk then
exit;
end;
res := fEncryption.ProcessHandshake(msgin,msgout);
case res of
sprSuccess: begin
AddToCSV('synhk; hk='+msgout,ExtOut,'; ');
result := true;
exit;
end;
sprUnsupported:
if not synhk then begin
result := true; // try to continue execution
exit;
end;
end;
WebSocketLog.Add.Log(sllWarning,'ProcessHandshake=% In=[%]',[ToText(res)^,msgin],self);
if ErrorMsg<>nil then
ErrorMsg^ := FormatUTF8('%: %',[ErrorMsg^,
GetCaptionFromEnum(TypeInfo(TProtocolResult),ord(res))]);
end;
function TWebSocketProtocol.ProcessURI(const aClientURI: RawUTF8): boolean;
begin
result := true; // override and return false to return STATUS_UNAUTHORIZED
end;
function TWebSocketProtocol.SendFrames(Owner: TWebSocketProcess;
var Frames: TWebSocketFrameDynArray; var FramesCount: integer): boolean;
var i,n: integer;
begin // this default implementation will send all frames one by one
n := FramesCount;
if (n>0) and (Owner<>nil) then begin
result := false;
FramesCount := 0;
for i := 0 to n-1 do
if Owner.SendFrame(Frames[i]) then
Frames[i].payload := '' else
exit;
end;
result := true;
end;
function TWebSocketProtocol.GetEncrypted: boolean;
begin
result := (self<>nil) and (fEncryption<>nil);
end;
function TWebSocketProtocol.GetSubprotocols: RawUTF8;
begin
result := fName;
end;
function TWebSocketProtocol.SetSubprotocol(const aProtocolName: RawUTF8): boolean;
begin
result := IdemPropNameU(aProtocolName,fName);
end;
function TWebSocketProtocol.GetRemoteIP: SockString;
begin
if (self = nil) or fRemoteLocalhost then
result := '' else
result := fRemoteIP;
end;
{ TWebSocketFrameList }
constructor TWebSocketFrameList.Create(timeoutsec: integer);
begin
inherited Create;
fTimeoutSec := timeoutsec;
end;
function TWebSocketFrameList.AnswerToIgnore(incr: integer): integer;
begin
Safe^.Lock;
if incr<>0 then
inc(Safe^.Padding[0].VInteger,incr);
result := Safe^.Padding[0].VInteger;
Safe^.UnLock;
end;
function TWebSocketFrameList.Pop(protocol: TWebSocketProtocol; const head: RawUTF8;
out frame: TWebSocketFrame): boolean;
var i: integer;
tix: cardinal;
item: PWebSocketFrame;
begin
result := false;
if (self=nil) or (Count=0) or (head='') or (protocol=nil) then
exit;
if fTimeoutSec=0 then
tix := 0 else
tix := {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64 shr 10;
Safe.Lock;
try
for i := Count-1 downto 0 do begin
item := @List[i];
if protocol.FrameData(item^,head)<>nil then begin
result := true;
frame := item^;
Delete(i);
exit;
end else
if (tix>0) and (tix>item^.tix) then
Delete(i);
end;
finally
Safe.UnLock;
end;
end;
procedure TWebSocketFrameList.Push(const frame: TWebSocketFrame);
begin
if self=nil then
exit;
Safe.Lock;
try
if Count>=length(List) then
SetLength(List,Count+Count shr 3+8);
List[Count] := frame;
if fTimeoutSec>0 then
List[Count].tix := fTimeoutSec+
({$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64 shr 10);
inc(Count);
finally
Safe.UnLock;
end;
end;
procedure TWebSocketFrameList.PushVoidFrame(opcode: TWebSocketFrameOpCode);
var frame: TWebSocketFrame;
begin
frame.opcode := opcode;
frame.content := [];
Push(frame);
end;
procedure TWebSocketFrameList.Delete(i: integer);
begin // faster than a TDynArray which will release the memory
List[i].payload := '';
dec(Count);
if i<Count then begin
MoveFast(List[i+1],List[i],(Count-i)*sizeof(List[i]));
pointer(List[Count].payload) := nil;
end;
end;
{ TWebSocketProtocolChat }
constructor TWebSocketProtocolChat.Create(const aName, aURI: RawUTF8;
const aOnIncomingFrame: TOnWebSocketProtocolChatIncomingFrame);
begin
inherited Create(aName,aURI);
fOnIncomingFrame := aOnIncomingFrame;
end;
function TWebSocketProtocolChat.Clone(const aClientURI: RawUTF8): TWebSocketProtocol;
begin
result := TWebSocketProtocolChat.Create(fName,fURI);
if fEncryption<>nil then
result.fEncryption := fEncryption.Clone;
TWebSocketProtocolChat(result).OnIncomingFrame := OnIncomingFrame;
end;
procedure TWebSocketProtocolChat.ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8);
begin
if Assigned(OnInComingFrame) then
try
if Sender.InheritsFrom(TWebSocketProcessServer) then
OnIncomingFrame(TWebSocketProcessServer(Sender).fServerResp,request) else
OnIncomingFrame(nil,request);
except
// ignore any exception in the callback
end;
end;
function TWebSocketProtocolChat.SendFrame(Sender: THttpServerResp;
const frame: TWebSocketFrame): boolean;
var tmp: TWebSocketFrame; // SendFrame() may change frame content (e.g. mask)
begin
result := false;
if (self=nil) or (Sender=nil) or Sender.Terminated or
not (Frame.opcode in [focText,focBinary]) or
((Sender.Server as TWebSocketServer).IsActiveWebSocketThread(Sender)<>Sender) then
exit;
tmp.opcode := frame.opcode;
tmp.content := frame.content;
SetString(tmp.payload,PAnsiChar(Pointer(frame.payload)),length(frame.payload));
result := (Sender as TWebSocketServerResp).fProcess.SendFrame(tmp)
end;
function TWebSocketProtocolChat.SendFrameJson(Sender: THttpServerResp;
var JSON: RawUTF8): boolean;
var frame: TWebSocketFrame;
begin
result := false;
if (self=nil) or (Sender=nil) or Sender.Terminated or
((Sender.Server as TWebSocketServer).IsActiveWebSocketThread(Sender)<>Sender) then
exit;
frame.opcode := focText;
frame.content := [];
frame.payload := JSON;
result := (Sender as TWebSocketServerResp).fProcess.SendFrame(frame)
end;
{ TWebSocketProtocolRest }
procedure TWebSocketProtocolRest.ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8);
var Ctxt: THttpServerRequest;
onRequest: TOnHttpServerRequest;
status: cardinal;
noAnswer: boolean;
answer: TWebSocketFrame;
head: RawUTF8;
begin
if not (request.opcode in [focText,focBinary]) then
exit; // ignore e.g. from TWebSocketServerResp.ProcessStart/ProcessStop
if FrameData(request,'r',@head)<>nil then
try
Ctxt := Sender.ComputeContext(onRequest);
try
if (Ctxt=nil) or not Assigned(onRequest) then
raise EWebSockets.CreateUTF8('%.ProcessOne: onRequest=nil',[self]);
if (head='') or not FrameToInput(request,noAnswer,Ctxt) then
raise EWebSockets.CreateUTF8('%.ProcessOne: invalid frame',[self]);
request.payload := ''; // release memory ASAP
if info<>'' then
Ctxt.AddInHeader(info);
status := onRequest(Ctxt); // blocking call to compute the answer
if (Ctxt.OutContentType=HTTP_RESP_NORESPONSE) or noAnswer then
exit;
OutputToFrame(Ctxt,status,head,answer);
if not Sender.SendFrame(answer) then
fLastError := UTF8ToString(FormatUTF8('SendFrame error %',[Sender]));
finally
Ctxt.Free;
end;
except
on E: Exception do
FormatString('% [%]',[E.ClassName,E.Message],fLastError);
end else
if (Sender.fIncoming.AnswerToIgnore>0) and (FrameData(request,'answer')<>nil) then begin
Sender.fIncoming.AnswerToIgnore(-1);
Sender.Log(request,'Ignored answer after NotifyCallback TIMEOUT',sllWarning);
end else
Sender.fIncoming.Push(request); // e.g. asynch 'answer'
end;
// by convention, defaults are POST and JSON, to reduce frame size for SOA calls
procedure TWebSocketProtocolRest.InputToFrame(Ctxt: THttpServerRequest;
aNoAnswer: boolean; out request: TWebSocketFrame; out head: RawUTF8);
var Method,InContentType: RawByteString;
seq: integer;
begin
if not IdemPropNameU(Ctxt.Method,'POST') then
Method := Ctxt.Method;
if (Ctxt.InContent<>'') and (Ctxt.InContentType<>'') and
not IdemPropNameU(Ctxt.InContentType,JSON_CONTENT_TYPE) then
InContentType := Ctxt.InContentType;
if fSequencing then begin
seq := InterlockedIncrement(fSequence);
SetLength(head,7); // safe overlap after 16,777,216 frames
PAnsiChar(pointer(head))^ := 'r';
BinToHexDisplay(@seq,PAnsiChar(pointer(head))+1,3);
end else
head := 'request';
FrameCompress(head,[Method,Ctxt.URL,Ctxt.InHeaders,ord(aNoAnswer)],
Ctxt.InContent,InContentType,request);
if fSequencing then
head[1] := 'a' else
head := 'answer';
end;
function TWebSocketProtocolRest.FrameToInput(var request: TWebSocketFrame;
out aNoAnswer: boolean; Ctxt: THttpServerRequest): boolean;
var URL,Method,InHeaders,NoAnswer,InContentType,InContent: RawByteString;
begin
result := FrameDecompress(request,'r',[@Method,@URL,@InHeaders,@NoAnswer],
InContentType,InContent);
if result then begin
if (InContentType='') and (InContent<>'') then
InContentType := JSON_CONTENT_TYPE_VAR;
if Method='' then
Method := 'POST';
Ctxt.Prepare(URL,Method,InHeaders,InContent,InContentType,fRemoteIP,Ctxt.UseSSL);
aNoAnswer := NoAnswer='1';
end;
end;
procedure TWebSocketProtocolRest.OutputToFrame(Ctxt: THttpServerRequest;
Status: Cardinal; var outhead: RawUTF8; out answer: TWebSocketFrame);
var OutContentType: RawByteString;
begin
if (Ctxt.OutContent<>'') and
not IdemPropNameU(Ctxt.OutContentType,JSON_CONTENT_TYPE) then
OutContentType := Ctxt.OutContentType;
if NormToUpperAnsi7[outhead[3]]='Q' then
outhead := 'answer' else // 'request' -> 'answer'
outhead[1] := 'a'; // 'r000001' -> 'a000001'
FrameCompress(outhead,[Status,Ctxt.OutCustomHeaders],
Ctxt.OutContent,OutContentType,answer);
end;
function TWebSocketProtocolRest.FrameToOutput(
var answer: TWebSocketFrame; Ctxt: THttpServerRequest): cardinal;
var status,outHeaders,outContentType,outContent: RawByteString;
begin
result := STATUS_NOTFOUND;
if not FrameDecompress(answer,'a',[@status,@outHeaders],outContentType,outContent) then
exit;
result := GetInteger(pointer(status));
Ctxt.OutCustomHeaders := outHeaders;
if (outContentType='') and (outContent<>'') then
Ctxt.OutContentType := JSON_CONTENT_TYPE_VAR else
Ctxt.OutContentType := outContentType;
Ctxt.OutContent := outContent;
end;
{ TWebSocketProtocolJSON }
constructor TWebSocketProtocolJSON.Create(const aURI: RawUTF8);
begin
inherited Create('synopsejson',aURI);
end;
function TWebSocketProtocolJSON.Clone(const aClientURI: RawUTF8): TWebSocketProtocol;
begin
result := TWebSocketProtocolJSON.Create(fURI);
end;
procedure TWebSocketProtocolJSON.FrameCompress(const Head: RawUTF8;
const Values: array of const; const Content, ContentType: RawByteString;
var frame: TWebSocketFrame);
var WR: TTextWriter;
tmp: TTextWriterStackBuffer;
i: integer;
begin
frame.opcode := focText;
frame.content := [];
WR := TTextWriter.CreateOwnedStream(tmp);
try
WR.Add('{');
WR.AddFieldName(Head);
WR.Add('[');
for i := 0 to High(Values) do begin
WR.AddJSONEscape(Values[i]);
WR.Add(',');
end;
WR.Add('"');
WR.AddString(ContentType);
WR.Add('"',',');
if Content='' then
WR.Add('"','"') else
if (ContentType='') or
IdemPropNameU(ContentType,JSON_CONTENT_TYPE) then
WR.AddNoJSONEscape(pointer(Content),length(Content)) else
if IdemPChar(pointer(ContentType),'TEXT/') then
WR.AddCSVUTF8([Content]) else
WR.WrBase64(pointer(Content),length(Content),true);
WR.Add(']','}');
WR.SetText(RawUTF8(frame.payload));
finally
WR.Free;
end;
end;
function TWebSocketProtocolJSON.FrameData(const frame: TWebSocketFrame;
const Head: RawUTF8; HeadFound: PRawUTF8): pointer;
var P,txt: PUTF8Char;
len: integer;
begin
result := nil;
if (length(frame.payload)<10) or (frame.opcode<>focText) then
exit;
P := pointer(frame.payload);
if not NextNotSpaceCharIs(P,'{') then
exit;
while P^<>'"' do begin
inc(P);
if P^=#0 then exit;
end;
txt := P+1;
P := GotoEndOfJSONString(P); // here P^ should be '"'
len := length(Head);
if (P^<>#0) and (P-txt>=len) and CompareMem(pointer(Head),txt,len) then begin
result := P+1;
if HeadFound<>nil then
SetString(HeadFound^,txt,P-txt);
end;
end;
function TWebSocketProtocolJSON.FrameDecompress(
const frame: TWebSocketFrame; const Head: RawUTF8;
const values: array of PRawByteString;
var contentType,content: RawByteString): Boolean;
var i: Integer;
P: PUTF8Char;
b64: PUTF8Char;
b64len: integer;
procedure GetNext(var content: RawByteString);
var txt: PUTF8Char;
txtlen: integer;
begin
txt := GetJSONField(P,P,nil,nil,@txtlen);
SetString(content,txt,txtlen);
end;
begin
result := false;
P := FrameData(frame,Head);
if P=nil then
exit;
if not NextNotSpaceCharIs(P,':') or
not NextNotSpaceCharIs(P,'[') then
exit;
for i := 0 to high(values) do
GetNext(values[i]^);
GetNext(contentType);
if P=nil then
exit;
if (contentType='') or IdemPropNameU(contentType,JSON_CONTENT_TYPE) then
GetJSONItemAsRawJSON(P,RawJSON(content)) else
if IdemPChar(pointer(contentType),'TEXT/') then
GetNext(content) else begin
b64 := GetJSONField(P,P,nil,nil,@b64len);
if not Base64MagicCheckAndDecode(b64,b64len,content) then
exit;
end;
result := true;
end;
function TWebSocketProtocolJSON.FrameType(
const frame: TWebSocketFrame): RawUTF8;
var P,txt: PUTF8Char;
begin
result := '*';
if (length(frame.payload)<10) or (frame.opcode<>focText) then
exit;
P := pointer(frame.payload);
if not NextNotSpaceCharIs(P,'{') or
not NextNotSpaceCharIs(P,'"') then
exit;
txt := P;
P := GotoEndOfJSONString(P);
SetString(result,txt,P-Txt);
end;
{ TWebSocketProtocolBinary }
constructor TWebSocketProtocolBinary.Create(const aURI: RawUTF8;
aCompressed: boolean);
begin
inherited Create('synopsebin',aURI);
fCompressed := aCompressed;
end;
constructor TWebSocketProtocolBinary.Create(const aURI: RawUTF8;
const aKey; aKeySize: cardinal; aCompressed: boolean);
begin
Create(aURI,aCompressed);
SetEncryptKeyAES(aKey, aKeySize);
end;
constructor TWebSocketProtocolBinary.Create(const aURI: RawUTF8;
aServer: boolean; const aKey: RawUTF8; aCompressed: boolean);
begin
Create(aURI,aCompressed);
SetEncryptKey(aServer,aKey);
end;
function TWebSocketProtocolBinary.Clone(const aClientURI: RawUTF8): TWebSocketProtocol;
begin
result := TWebSocketProtocolBinary.Create(fURI,{dummykey=}self,0,fCompressed);
TWebSocketProtocolBinary(result).fSequencing := fSequencing;
if fEncryption<>nil then
result.fEncryption := fEncryption.Clone;
end;
const
FRAME_HEAD_SEP = #1;
procedure FrameInit(opcode: TWebSocketFrameOpCode; const Content, ContentType: RawByteString;
out frame: TWebSocketFrame);
begin
frame.opcode := opcode;
if (ContentType<>'') and (Content<>'') and
not IdemPChar(pointer(ContentType),'TEXT/') and
IsContentCompressed(pointer(Content),length(Content)) then
frame.content := [fopAlreadyCompressed] else
frame.content := [];
end;
procedure TWebSocketProtocolBinary.FrameCompress(const Head: RawUTF8;
const Values: array of const; const Content, ContentType: RawByteString;
var frame: TWebSocketFrame);
var item: RawUTF8;
i: integer;
W: TFileBufferWriter;
begin
FrameInit(focBinary,Content,ContentType,frame);
W := TFileBufferWriter.Create(TRawByteStringStream);
try
W.WriteBinary(Head);
W.Write1(byte(FRAME_HEAD_SEP));
for i := 0 to high(Values) do
with Values[i] do begin
VarRecToUTF8(Values[i],item);
W.Write(item);
end;
W.Write(ContentType);
W.WriteBinary(Content);
W.Flush;
frame.payload := TRawByteStringStream(W.Stream).DataString;
finally
W.Free;
end;
end;
function TWebSocketProtocolBinary.FrameData(const frame: TWebSocketFrame;
const Head: RawUTF8; HeadFound: PRawUTF8): pointer;
var len: integer;
P: PAnsiChar;
begin
P := pointer(frame.payload);
len := length(Head);
if (frame.opcode=focBinary) and (length(frame.payload)>=len+6) and
CompareMemSmall(pointer(Head),P,len) then begin
result := PosChar(PUTF8Char(P)+len,FRAME_HEAD_SEP);
if result<>nil then begin
if HeadFound<>nil then
SetString(HeadFound^,P,PAnsiChar(result)-P);
inc(PByte(result));
end;
end else
result := nil;
end;
function TWebSocketProtocolBinary.FrameType(
const frame: TWebSocketFrame): RawUTF8;
var i: integer;
begin
if (length(frame.payload)<10) or (frame.opcode<>focBinary) then
i := 0 else
i := PosExChar(FRAME_HEAD_SEP,frame.payload);
if i=0 then
result := '*' else
result := copy(frame.payload,1,i-1);
end;
procedure TWebSocketProtocolBinary.BeforeSendFrame(var frame: TWebSocketFrame);
var value: RawByteString;
threshold: integer;
begin
inherited BeforeSendFrame(frame);
if frame.opcode=focBinary then begin
if fCompressed then begin
if fRemoteLocalhost or (fopAlreadyCompressed in frame.content) then
threshold := maxInt else // localhost or compressed -> no SynLZ
threshold := WebSocketsBinarySynLzThreshold;
SynLZCompress(pointer(frame.payload),length(frame.payload),value,threshold);
end else
value := frame.payload;
if fEncryption<>nil then
fEncryption.Encrypt(value,frame.payload) else
frame.payload := value;
end;
inc(fFramesOutBytesSocket,length(frame.payload)+2);
end;
procedure TWebSocketProtocolBinary.AfterGetFrame(var frame: TWebSocketFrame);
var value: RawByteString;
res: TProtocolResult;
begin
inc(fFramesInBytesSocket,length(frame.payload)+2);
if frame.opcode=focBinary then begin
if fEncryption<>nil then begin
res := fEncryption.Decrypt(frame.payload,value);
if res<>sprSuccess then
raise EWebSockets.CreateUTF8('%.AfterGetFrame: encryption error %',
[self,ToText(res)^]);
end else
value := frame.payload;
if fCompressed then
SynLZDecompress(pointer(value),length(value),frame.payload) else
frame.payload := value;
end;
inherited AfterGetFrame(frame);
end;
function TWebSocketProtocolBinary.FrameDecompress(const frame: TWebSocketFrame;
const Head: RawUTF8; const values: array of PRawByteString;
var contentType,content: RawByteString): Boolean;
var i: integer;
P: PByte;
begin
result := false;
P := FrameData(frame,Head);
if P=nil then
exit;
for i := 0 to high(values) do
values[i]^ := FromVarString(P);
contentType := FromVarString(P);
i := length(frame.payload)-(PAnsiChar(P)-pointer(frame.payload));
if i<0 then
exit;
SetString(content,PAnsiChar(P),i);
result := true;
end;
function TWebSocketProtocolBinary.SendFrames(Owner: TWebSocketProcess;
var Frames: TWebSocketFrameDynArray; var FramesCount: integer): boolean;
const JUMBO_HEADER: array[0..6] of AnsiChar = 'frames'+FRAME_HEAD_SEP;
var jumboFrame: TWebSocketFrame;
i, len: integer;
P: PByte;
begin
if (FramesCount=0) or (Owner=nil) then begin
result := true;
exit;
end;
dec(FramesCount);
if FramesCount=0 then begin
result := Owner.SendFrame(Frames[0]);
exit;
end;
jumboFrame.opcode := focBinary;
jumboFrame.content := [];
len := sizeof(JUMBO_HEADER)+ToVarUInt32Length(FramesCount);
for i := 0 to FramesCount do
if Frames[i].opcode=focBinary then
inc(len,ToVarUInt32LengthWithData(length(Frames[i].payload))) else
raise EWebSockets.CreateUTF8('%.SendFrames[%]: Unexpected opcode=%',
[self,i,ord(Frames[i].opcode)]);
SetString(jumboframe.payload,nil,len);
P := pointer(jumboframe.payload);
MoveFast(JUMBO_HEADER,P^,SizeOf(JUMBO_HEADER));
inc(P,SizeOf(JUMBO_HEADER));
P := ToVarUInt32(FramesCount,P);
for i := 0 to FramesCount do begin
len := length(Frames[i].payload);
P := ToVarUInt32(len,P);
MoveFast(pointer(Frames[i].payload)^,P^,len);
inc(P,len);
end;
FramesCount := 0;
Frames := nil;
result := Owner.SendFrame(jumboFrame); // send all frames at once
end;
procedure TWebSocketProtocolBinary.ProcessIncomingFrame(Sender: TWebSocketProcess;
var request: TWebSocketFrame; const info: RawUTF8);
var jumboInfo: RawByteString;
n,i: integer;
frame: TWebSocketFrame;
P: PByte;
begin
P := FrameData(request,'frames');
if P<>nil then begin
n := FromVarUInt32(P);
for i := 0 to n do begin
if i=0 then
jumboInfo:= 'Sec-WebSocket-Frame: [0]' else
if i=n then
jumboInfo := 'Sec-WebSocket-Frame: [1]' else
jumboInfo := '';
frame.opcode := focBinary;
frame.content := [];
frame.payload := FromVarString(P);
Sender.Log(frame,FormatUTF8('GetSubFrame(%/%)',[i+1,n+1]));
inherited ProcessIncomingFrame(Sender,frame,jumboInfo);
end;
end else
inherited ProcessIncomingFrame(Sender,request,info);
end;
function TWebSocketProtocolBinary.GetFramesInCompression: integer;
begin
if (self=nil) or (fFramesInBytes=0) then
result := 100 else
if not fCompressed or (fFramesInBytesSocket<fFramesInBytes) then
result := 0 else
result := 100-(fFramesInBytesSocket*100) div fFramesInBytes;
end;
function TWebSocketProtocolBinary.GetFramesOutCompression: integer;
begin
if (self=nil) or (fFramesOutBytes=0) then
result := 100 else
if not fCompressed or (fFramesOutBytesSocket<=fFramesOutBytes) then
result := 0 else
result := 100-(fFramesOutBytesSocket*100) div fFramesOutBytes;
end;
function TWebSocketProtocolBinary.GetSubprotocols: RawUTF8;
begin
result := 'synopsebin, synopsebinary';
end;
function TWebSocketProtocolBinary.SetSubprotocol(
const aProtocolName: RawUTF8): boolean;
begin
case FindPropName(['synopsebin', 'synopsebinary'], aProtocolName) of
0: fSequencing := true;
1: fSequencing := false;
else begin
result := false;
exit;
end;
end;
result := true;
end;
{ TWebSocketProtocolList }
function TWebSocketProtocolList.CloneByName(
const aProtocolName, aClientURI: RawUTF8): TWebSocketProtocol;
var i: Integer;
begin
result := nil;
if self=nil then
exit;
fSafe.Lock;
try
for i := 0 to length(fProtocols)-1 do
with fProtocols[i] do
if ((fURI='') or IdemPropNameU(fURI,aClientURI)) and
SetSubprotocol(aProtocolName) then begin
result := fProtocols[i].Clone(aClientURI);
result.fName := aProtocolName;
exit;
end;
finally
fSafe.UnLock;
end;
end;
function TWebSocketProtocolList.CloneByURI(const aClientURI: RawUTF8): TWebSocketProtocol;
var i: integer;
begin
result := nil;
if (self=nil) or (aClientURI='') then
exit;
fSafe.Lock;
try
for i := 0 to length(fProtocols)-1 do
if IdemPropNameU(fProtocols[i].fURI,aClientURI) then begin
result := fProtocols[i].Clone(aClientURI);
exit;
end;
finally
fSafe.UnLock;
end;
end;
function TWebSocketProtocolList.Count: integer;
begin
if self=nil then
result := 0 else
result := length(fProtocols);
end;
destructor TWebSocketProtocolList.Destroy;
begin
ObjArrayClear(fProtocols);
inherited;
end;
function TWebSocketProtocolList.FindIndex(const aName,aURI: RawUTF8): integer;
begin
if aName<>'' then
for result := 0 to high(fProtocols) do
with fProtocols[result] do
if IdemPropNameU(fName,aName) and
((fURI='') or IdemPropNameU(fURI,aURI)) then
exit;
result := -1;
end;
function TWebSocketProtocolList.Add(aProtocol: TWebSocketProtocol): boolean;
var i: Integer;
begin
result := false;
if aProtocol=nil then
exit;
fSafe.Lock;
try
i := FindIndex(aProtocol.Name,aProtocol.URI);
if i<0 then begin
ObjArrayAdd(fProtocols,aProtocol);
result := true;
end;
finally
fSafe.UnLock;
end;
end;
function TWebSocketProtocolList.AddOnce(aProtocol: TWebSocketProtocol): boolean;
var i: Integer;
begin
result := false;
if aProtocol=nil then
exit;
fSafe.Lock;
try
i := FindIndex(aProtocol.Name,aProtocol.URI);
if i<0 then begin
ObjArrayAdd(fProtocols,aProtocol);
result := true;
end else begin
fProtocols[i].Free;
fProtocols[i] := aProtocol;
end;
finally
fSafe.UnLock;
end;
end;
function TWebSocketProtocolList.Remove(const aProtocolName,aURI: RawUTF8): Boolean;
var i: Integer;
begin
fSafe.Lock;
try
i := FindIndex(aProtocolName,aURI);
if i>=0 then begin
ObjArrayDelete(fProtocols,i);
result := true;
end else
result := false;
finally
fSafe.UnLock;
end;
end;
{ TWebSocketProcess }
constructor TWebSocketProcess.Create(aProtocol: TWebSocketProtocol;
aOwnerConnection: THttpServerConnectionID; aOwnerThread: TSynThread;
const aSettings: TWebSocketProcessSettings; const aProcessName: RawUTF8);
begin
inherited Create;
fProcessName := aProcessName;
fProtocol := aProtocol;
fOwnerConnection := aOwnerConnection;
fOwnerThread := aOwnerThread;
fSettings := aSettings;
fIncoming := TWebSocketFrameList.Create(30*60);
fOutgoing := TWebSocketFrameList.Create(0);
fSafeIn := NewSynLocker;
fSafeOut := NewSynLocker;
fSafePing := NewSynLocker;
end;
destructor TWebSocketProcess.Destroy;
var frame: TWebSocketFrame;
timeout: Int64;
log: ISynLog;
dummyerror: integer;
begin
log := WebSocketLog.Enter('Destroy %',[ToText(fState)^],self);
if fState = wpsCreate then
fProcessEnded := true else
if not fNoConnectionCloseAtDestroy then begin
if log<>nil then
log.Log(sllTrace,'Destroy: notify focConnectionClose',self);
InterlockedIncrement(fProcessCount);
try
fState := wpsDestroy;
if fOutgoing.Count>0 then
SendPendingOutgoingFrames;
frame.opcode := focConnectionClose;
dummyerror := 0;
if not SendFrame(frame) or not CanGetFrame(1000,@dummyerror) or
not GetFrame(frame,@dummyerror) then
if log<>nil then // expects an answer from peer
log.Log(sllWarning,'Destroy: no focConnectionClose ACK %',[dummyerror],self);
finally
InterlockedDecrement(fProcessCount);
end;
end;
fState := wpsDestroy;
if (fProcessCount>0) or not fProcessEnded then begin
if log<>nil then
log.Log(sllDebug,'Destroy: wait for fProcessCount=%',[fProcessCount],self);
timeOut := GetTickCount64+5000;
repeat
SleepHiRes(2);
until ((fProcessCount=0) and fProcessEnded) or (GetTickCount64>timeOut);
if log<>nil then
log.Log(sllDebug,'Destroy: waited fProcessCount=%',[fProcessCount],self);
end;
fProtocol.Free;
fOutgoing.Free;
fIncoming.Free;
fSafeIn.DoneAndFreeMem;
fSafeOut.DoneAndFreeMem;
fSafePing.DoneAndFreeMem; // to be done lately to avoid GPF in above Destroy
inherited Destroy;
end;
procedure TWebSocketProcess.ProcessStart;
var frame: TWebSocketFrame; // notify e.g. TOnWebSocketProtocolChatIncomingFrame
begin
if Assigned(fSettings.OnClientConnected) then
try
WebSocketLog.Add.Log(sllTrace,'ProcessStart: OnClientConnected',self);
fSettings.OnClientConnected(Self);
except
end;
WebSocketLog.Add.Log(sllTrace,'ProcessStart: callbacks',self);
frame.opcode := focContinuation;
if not Assigned(fProtocol.fOnBeforeIncomingFrame) or
not fProtocol.fOnBeforeIncomingFrame(self,frame) then
fProtocol.ProcessIncomingFrame(self,frame,''); // any exception would abort
WebSocketLog.Add.Log(sllDebug,'ProcessStart %', [fProtocol],self);
end;
procedure TWebSocketProcess.ProcessStop;
var frame: TWebSocketFrame; // notify e.g. TOnWebSocketProtocolChatIncomingFrame
begin
try
WebSocketLog.Add.Log(sllTrace,'ProcessStop: callbacks',self);
frame.opcode := focConnectionClose;
if not Assigned(fProtocol.fOnBeforeIncomingFrame) or
not fProtocol.fOnBeforeIncomingFrame(self,frame) then
fProtocol.ProcessIncomingFrame(self,frame,'');
if Assigned(fSettings.OnClientDisconnected) then begin
WebSocketLog.Add.Log(sllTrace,'ProcessStop: OnClientDisconnected',self);
fSettings.OnClientDisconnected(Self);
end;
except // exceptions are just ignored at shutdown
end;
fProcessEnded := true;
WebSocketLog.Add.Log(sllDebug,'ProcessStop %', [fProtocol], self);
end;
procedure TWebSocketProcess.SetLastPingTicks(invalidPing: boolean);
var tix: Int64;
begin
tix := {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64;
fSafePing.Lock;
try
fLastSocketTicks := tix;
if invalidPing then begin
inc(fInvalidPingSendCount);
fNoConnectionCloseAtDestroy := true;
end else
fInvalidPingSendCount := 0;
finally
fSafePing.UnLock;
end;
end;
function TWebSocketProcess.LastPingDelay: Int64;
begin
result := {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64;
fSafePing.Lock;
try
dec(result,fLastSocketTicks);
finally
fSafePing.UnLock;
end;
end;
function TWebSocketProcess.ProcessLoopStepReceive: boolean;
var request: TWebSocketFrame;
sockerror: integer;
begin
if fState=wpsRun then begin
InterlockedIncrement(fProcessCount); // flag currently processing
try
if CanGetFrame({timeout=}1,@sockerror) and GetFrame(request,@sockerror) then begin
case request.opcode of
focPing: begin
request.opcode := focPong;
SendFrame(request);
end;
focPong:
; // nothing to do
focText,focBinary:
if not Assigned(fProtocol.fOnBeforeIncomingFrame) or
not fProtocol.fOnBeforeIncomingFrame(self,request) then
fProtocol.ProcessIncomingFrame(self,request,'');
focConnectionClose: begin
if fState=wpsRun then begin
fState := wpsClose; // will close the connection
SendFrame(request); // send back the frame as ACK
end;
end;
end;
end else
if (fOwnerThread<>nil) and fOwnerThread.Terminated then
fState := wpsClose else
if sockerror<>0 then begin
WebSocketLog.Add.Log(sllInfo,'GetFrame SockInPending error % on %',
[sockerror,fProtocol],self);
fState := wpsClose;
end;
finally
InterlockedDecrement(fProcessCount); // release flag
end;
end;
result := (fState=wpsRun);
end;
function TWebSocketProcess.ProcessLoopStepSend: boolean;
var request: TWebSocketFrame;
elapsed: cardinal;
begin
if fState=wpsRun then begin
InterlockedIncrement(fProcessCount); // flag currently processing
try
elapsed := LastPingDelay;
if elapsed>fSettings.SendDelay then
if (fOutgoing.Count>0) and not SendPendingOutgoingFrames then
fState := wpsClose
else
if (fSettings.HeartbeatDelay<>0) and
(elapsed>fSettings.HeartbeatDelay) then begin
request.opcode := focPing;
if not SendFrame(request) then
if (fSettings.DisconnectAfterInvalidHeartbeatCount<>0) and
(fInvalidPingSendCount>=fSettings.DisconnectAfterInvalidHeartbeatCount) then
fState := wpsClose
else
SetLastPingTicks(true); // mark invalid, and avoid immediate retry
end;
finally
InterlockedDecrement(fProcessCount); // release flag
end;
end;
result := (fState=wpsRun);
end;
procedure TWebSocketProcess.ProcessLoop;
begin
if fProtocol=nil then
exit;
try
ProcessStart; // any exception will close the socket
try
SetLastPingTicks;
fState := wpsRun;
while (fOwnerThread=nil) or not fOwnerThread.Terminated do
if ProcessLoopStepReceive and ProcessLoopStepSend then
HiResDelay(fLastSocketTicks)
else
break; // connection ended
finally
ProcessStop;
end;
except // don't be optimistic: abort and close connection
fState := wpsClose;
end;
end;
procedure TWebSocketProcess.HiResDelay(const start: Int64);
var delay: cardinal;
begin
case {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64-start of
0..50: delay := 0; // 10 microsecs on POSIX
51..200: delay := 1;
201..500: delay := 5;
501..2000: delay := 50;
2001..5000: delay := 100;
else delay := 500;
end;
if (fSettings.LoopDelay<>0) and (delay>fSettings.LoopDelay) then
delay := fSettings.LoopDelay;
SleepHiRes(delay);
end;
function TWebSocketProcess.Settings: PWebSocketProcessSettings;
begin
result := @fSettings;
end;
function TWebSocketProcess.State: TWebSocketProcessState;
begin
if self=nil then
result := wpsCreate else
result := fState;
end;
function TWebSocketProcess.RemoteIP: SockString;
begin
if (self=nil) or (fProtocol=nil) or fProtocol.fRemoteLocalhost then
result := '' else
result := fProtocol.fRemoteIP;
end;
function TWebSocketProcess.NotifyCallback(aRequest: THttpServerRequest;
aMode: TWebSocketProcessNotifyCallback): cardinal;
var request,answer: TWebSocketFrame;
i: integer;
start,max: Int64;
head: RawUTF8;
begin
result := STATUS_NOTFOUND;
if (fProtocol=nil) or (aRequest=nil) or
not fProtocol.InheritsFrom(TWebSocketProtocolRest) then
exit;
if WebSocketLog<>nil then
WebSocketLog.Add.Log(sllTrace,'NotifyCallback(%,%)',
[aRequest.URL,_TWebSocketProcessNotifyCallback[aMode]^],self);
TWebSocketProtocolRest(fProtocol).InputToFrame(
aRequest,aMode in [wscBlockWithoutAnswer,wscNonBlockWithoutAnswer],request,head);
case aMode of
wscNonBlockWithoutAnswer: begin
// add to the internal sending list for asynchronous sending
fOutgoing.Push(request);
result := STATUS_SUCCESS;
exit;
end;
wscBlockWithAnswer:
if fIncoming.AnswerToIgnore>0 then begin
WebSocketLog.Add.Log(sllDebug,'NotifyCallback: Waiting for AnswerToIgnore=%',
[fIncoming.AnswerToIgnore],self);
start := GetTickCount64;
max := start+30000;
repeat
HiResDelay(start);
if fState in [wpsDestroy,wpsClose] then begin
result := STATUS_WEBSOCKETCLOSED;
exit;
end;
if fIncoming.AnswerToIgnore=0 then
break; // it is now safe to send a new 'request'
if GetTickCount64<max then
continue;
self.Log(request,'NotifyCallback AnswerToIgnore TIMEOUT -> abort connection',sllInfo);
result := STATUS_NOTIMPLEMENTED; // 501 will force recreate connection
exit;
until false;
end;
end;
i := InterlockedIncrement(fProcessCount);
try
if (i>2) and (WebSocketLog<>nil) then
WebSocketLog.Add.Log(sllWarning,'NotifyCallback with fProcessCount=%',[i],self);
if not SendFrame(request) then
exit;
if aMode=wscBlockWithoutAnswer then begin
result := STATUS_SUCCESS;
exit;
end;
start := {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64;
if fSettings.CallbackAnswerTimeOutMS=0 then
max := start+30000 else // never wait for ever
if fSettings.CallbackAnswerTimeOutMS<2000 then
max := start+2000 else // 2 seconds minimal wait
max := start+fSettings.CallbackAnswerTimeOutMS;
while not fIncoming.Pop(fProtocol,head,answer) do
if fState in [wpsDestroy,wpsClose] then begin
result := STATUS_WEBSOCKETCLOSED;
exit;
end else
if {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64>max then begin
WebSocketLog.Add.Log(sllWarning,'NotifyCallback TIMEOUT %',[head],self);
if head='answer' then
fIncoming.AnswerToIgnore(1); // ignore next 'answer'
exit; // returns STATUS_NOTFOUND
end else
HiResDelay(start);
finally
InterlockedDecrement(fProcessCount);
end;
result := TWebSocketProtocolRest(fProtocol).FrameToOutput(answer,aRequest);
end;
function TWebSocketProcess.SendPendingOutgoingFrames: boolean;
begin
result := false;
fOutgoing.Safe.Lock;
try
if fProtocol.SendFrames(self,fOutgoing.List,fOutgoing.Count) then
result := true else
WebSocketLog.Add.Log(sllInfo,'SendPendingOutgoingFrames: SendFrames failed',self);
finally
fOutgoing.Safe.UnLock;
end;
end;
procedure TWebSocketProcess.Log(const frame: TWebSocketFrame;
const aMethodName: RawUTF8; aEvent: TSynLogInfo; DisableRemoteLog: Boolean);
var tmp: TLogEscape;
log: TSynLog;
len: integer;
begin
if WebSocketLog<>nil then
with WebSocketLog.Family do
if aEvent in Level then
if (logHeartbeat in fSettings.LogDetails) or
not (frame.opcode in [focPing,focPong]) then begin
log := SynLog;
log.DisableRemoteLog(DisableRemoteLog);
try
if (frame.opcode=focText) and
(logTextFrameContent in fSettings.LogDetails) then
log.Log(aEvent,'% % % focText %',[aMethodName,fProtocol.GetRemoteIP,
Protocol.FrameType(frame),frame.PayLoad],self) else begin
len := length(frame.PayLoad);
log.Log(aEvent,'% % % % len=%%',[aMethodName,fProtocol.GetRemoteIP,
Protocol.FrameType(frame),_TWebSocketFrameOpCode[frame.opcode]^,len,
LogEscape(pointer(frame.PayLoad),len,tmp,
logBinaryFrameContent in fSettings.LogDetails)],self);
end;
finally
log.DisableRemoteLog(false);
end;
end;
end;
const
FRAME_OPCODE_FIN=128;
FRAME_LEN_MASK=128;
FRAME_LEN_2BYTES=126;
FRAME_LEN_8BYTES=127;
type
TFrameHeader = packed record
first: byte;
len8: byte;
len32: cardinal;
len64: cardinal;
mask: cardinal; // 0 indicates no payload masking
end;
procedure ProcessMask(data: pointer; mask: cardinal; len: PtrInt);
var i,maskCount: PtrInt;
begin
maskCount := len shr 2;
for i := 0 to maskCount-1 do
PCardinalArray(data)^[i] := PCardinalArray(data)^[i] xor mask;
maskCount := maskCount shl 2;
for i := maskCount to maskCount+(len and 3)-1 do begin
PByteArray(data)^[i] := PByteArray(data)^[i] xor mask;
mask := mask shr 8;
end;
end;
type
// asynchronous state machine to process incoming frames
TWebProcessInFrameState = (
pfsHeader1, pfsData1, pfsHeaderN, pfsDataN, pfsDone, pfsError);
TWebProcessInFrame = object
hdr: TFrameHeader;
opcode: TWebSocketFrameOpCode;
masked: boolean;
st: TWebProcessInFrameState;
process: TWebSocketProcess;
outputframe: PWebSocketFrame;
len: integer;
data: RawByteString;
procedure Init(owner: TWebSocketProcess; output: PWebSocketFrame);
function GetBytes(P: PAnsiChar; count: integer): boolean;
function GetHeader: boolean;
function GetData: boolean;
function Step(ErrorWithoutException: PInteger): TWebProcessInFrameState;
end;
function TWebProcessInFrame.GetBytes(P: PAnsiChar; count: integer): boolean;
begin // SockInRead() below raise a ECrtSocket error on failure
inc(len,process.ReceiveBytes(P+len,count-len));
result := len=count;
end;
function TWebProcessInFrame.GetHeader: boolean;
begin
result := false;
if len<2 then begin
data := '';
FillCharFast(hdr,sizeof(hdr),0);
if not GetBytes(@hdr,2) then // first+len8
exit;
end;
opcode := TWebSocketFrameOpCode(hdr.first and 15);
masked := hdr.len8 and FRAME_LEN_MASK<>0;
if masked then
hdr.len8 := hdr.len8 and 127;
if hdr.len8<FRAME_LEN_2BYTES then
hdr.len32 := hdr.len8 else
if hdr.len8=FRAME_LEN_2BYTES then begin
if not GetBytes(@hdr,4) then // first+len8+len32.low
exit;
hdr.len32 := swap(word(hdr.len32)); // FPC expects explicit word() cast
end else
if hdr.len8=FRAME_LEN_8BYTES then begin
if not GetBytes(@hdr,10) then // first+len8+len32+len64.low
exit;
if hdr.len32<>0 then // size is more than 32 bits -> reject
hdr.len32 := maxInt else
hdr.len32 := bswap32(hdr.len64);
if hdr.len32>WebSocketsMaxFrameMB shl 20 then
raise EWebSockets.CreateUTF8('%.GetFrame: length should be < % MB',
[process,WebSocketsMaxFrameMB]);
end;
if masked then begin
len := 0; // not appended to hdr
if not GetBytes(@hdr.mask,4) then
raise EWebSockets.CreateUTF8('%.GetFrame: truncated mask',[process]);
end;
len := 0; // prepare upcoming GetData
result := true;
end;
function TWebProcessInFrame.GetData: boolean;
begin
if length(data)<>integer(hdr.len32) then
SetString(data,nil,hdr.len32);
result := GetBytes(pointer(data),hdr.len32);
if result then begin
if hdr.mask<>0 then
ProcessMask(pointer(data),hdr.mask,hdr.len32);
len := 0; // prepare upcoming GetHeader
end;
end;
function TWebProcessInFrame.Step(ErrorWithoutException: PInteger): TWebProcessInFrameState;
begin
while true do // process incoming data as much as possible
case st of
pfsHeader1:
if GetHeader then begin
outputframe.opcode := opcode;
outputframe.content := [];
st := pfsData1;
end else
break; // quit when not enough data is available from input
pfsData1:
if GetData then begin
outputframe.payload := data;
if hdr.first and FRAME_OPCODE_FIN=0 then
st := pfsHeaderN else
st := pfsDone;
end else
break;
pfsHeaderN:
if GetHeader then
if (opcode<>focContinuation) and (opcode<>outputframe.opcode) then begin
st := pfsError;
if ErrorWithoutException<>nil then begin
WebSocketLog.Add.Log(sllDebug, 'GetFrame: received %, expected %',
[_TWebSocketFrameOpCode[opcode]^,_TWebSocketFrameOpCode[outputframe.opcode]^],process);
ErrorWithoutException^ := maxInt;
end else
raise EWebSockets.CreateUTF8('%.GetFrame: received %, expected %',
[process,_TWebSocketFrameOpCode[opcode]^,_TWebSocketFrameOpCode[outputframe.opcode]^]);
end else
st := pfsDataN else
break;
pfsDataN:
if GetData then begin
outputframe.payload := outputframe.payload+data;
if hdr.first and FRAME_OPCODE_FIN=0 then
st := pfsHeaderN else
st := pfsDone;
end else
break;
pfsDone: begin
data := '';
{$ifdef HASCODEPAGE}
if opcode=focText then
SetCodePage(outputframe.payload,CP_UTF8,false); // identify text value as UTF-8
{$endif}
if (process.fProtocol<>nil) and (outputframe.payload<>'') then
process.fProtocol.AfterGetFrame(outputframe^);
process.Log(outputframe^,'GetFrame');
process.SetLastPingTicks;
break;
end;
else // e.g. pfsError
break;
end;
result := st;
end;
procedure TWebProcessInFrame.Init(owner: TWebSocketProcess; output: PWebSocketFrame);
begin
process := owner;
outputframe := output;
st := pfsHeader1;
len := 0;
end;
function TWebSocketProcess.GetFrame(out Frame: TWebSocketFrame;
ErrorWithoutException: PInteger): boolean;
var f: TWebProcessInFrame;
begin
f.Init(self,@Frame);
fSafeIn.Lock;
try
repeat until f.Step(ErrorWithoutException) in [pfsDone,pfsError];
result := f.st=pfsDone;
finally
fSafeIn.UnLock;
end;
end;
function TWebSocketProcess.SendFrame(var Frame: TWebSocketFrame): boolean;
var hdr: TFrameHeader;
hdrlen, len: cardinal;
tmp: TSynTempBuffer;
begin
fSafeOut.Lock;
try
Log(frame,'SendFrame',sllTrace,true);
try
result := true;
if Frame.opcode=focConnectionClose then
fNoConnectionCloseAtDestroy := true; // to be done once on each end
if (fProtocol<>nil) and (Frame.payload<>'') then
fProtocol.BeforeSendFrame(Frame);
len := Length(Frame.payload);
hdr.first := byte(Frame.opcode) or FRAME_OPCODE_FIN; // single frame
if len<FRAME_LEN_2BYTES then begin
hdr.len8 := len or fMaskSentFrames;
hdrlen := 2; // opcode+len8
end else
if len<65536 then begin
hdr.len8 := FRAME_LEN_2BYTES or fMaskSentFrames;
hdr.len32 := swap(word(len)); // FPC expects explicit word() cast
hdrlen := 4; // opcode+len8+len32.low
end else begin
hdr.len8 := FRAME_LEN_8BYTES or fMaskSentFrames;
hdr.len64 := bswap32(len);
hdr.len32 := 0;
hdrlen := 10; // opcode+len8+len32+len64.low
end;
if fMaskSentFrames<>0 then begin
hdr.mask := Random32gsl; // https://tools.ietf.org/html/rfc6455#section-10.3
ProcessMask(pointer(Frame.payload),hdr.mask,len);
inc(hdrlen,4);
end;
tmp.Init(hdrlen+len); // avoid most memory allocations
try
MoveSmall(@hdr,tmp.buf,hdrlen);
if fMaskSentFrames<>0 then
PInteger(PAnsiChar(tmp.buf)+hdrlen-4)^ := hdr.mask;
MoveFast(pointer(Frame.payload)^,PAnsiChar(tmp.buf)[hdrlen],len);
if not SendBytes(tmp.buf,hdrlen+len) then
result := false;
finally
tmp.Done;
end;
SetLastPingTicks(not result);
except
result := false;
end;
finally
fSafeOut.UnLock;
end;
end;
{ TWebCrtSocketProcess }
constructor TWebCrtSocketProcess.Create(aSocket: TCrtSocket; aProtocol: TWebSocketProtocol;
aOwnerConnection: THttpServerConnectionID; aOwnerThread: TSynThread;
const aSettings: TWebSocketProcessSettings; const aProcessName: RawUTF8);
begin
inherited Create(aProtocol,aOwnerConnection,aOwnerThread,aSettings,aProcessName);
fSocket := aSocket;
end;
function TWebCrtSocketProcess.CanGetFrame(TimeOut: cardinal; ErrorWithoutException: PInteger): boolean;
var pending: integer;
begin
if ErrorWithoutException<>nil then
ErrorWithoutException^ := 0;
pending := fSocket.SockInPending(TimeOut,{PendingAlsoInSocket=}true);
if pending<0 then // socket error
if ErrorWithoutException<>nil then begin
ErrorWithoutException^ := fSocket.LastLowSocketError;
result := false;
exit;
end else
raise EWebSockets.CreateUTF8('SockInPending() Error % on %:% - from %',
[fSocket.LastLowSocketError,fSocket.Server,fSocket.Port,fProtocol.fRemoteIP]);
result := (pending>=2);
end;
function TWebCrtSocketProcess.ReceiveBytes(P: PAnsiChar; count: integer): integer;
begin
result := fSocket.SockInRead(P,count,{useonlysockin=}false);
end;
function TWebCrtSocketProcess.SendBytes(P: pointer; Len: integer): boolean;
begin
result := fSocket.TrySndLow(P,Len);
end;
{ -------------- WebSockets Server classes for bidirectional remote access }
function HttpServerWebSocketUpgrade(ClientSock: THttpServerSocket;
Protocols: TWebSocketProtocolList; out Protocol: TWebSocketProtocol): integer;
var uri,version,prot,subprot,key,extin,extout,header: RawUTF8;
extins: TRawUTF8DynArray;
P: PUTF8Char;
Digest: TSHA1Digest;
begin
result := STATUS_BADREQUEST;
try
if not IdemPropNameU(ClientSock.Upgrade,'websocket') then
exit;
version := ClientSock.HeaderGetValue('SEC-WEBSOCKET-VERSION');
if GetInteger(pointer(version))<13 then
exit; // we expect WebSockets protocol version 13 at least
uri := Trim(RawUTF8(ClientSock.URL));
if (uri<>'') and (uri[1]='/') then
Delete(uri,1,1);
prot := ClientSock.HeaderGetValue('SEC-WEBSOCKET-PROTOCOL');
P := pointer(prot);
if P<>nil then begin
repeat
GetNextItemTrimed(P,',',subprot);
Protocol := Protocols.CloneByName(subprot,uri);
until (P=nil) or (Protocol<>nil);
if (Protocol<>nil) and (Protocol.URI='') and not Protocol.ProcessURI(uri) then begin
Protocol.Free;
result := STATUS_UNAUTHORIZED;
exit;
end;
end else
// if no protocol is specified, try to match by URI
Protocol := Protocols.CloneByURI(uri);
if Protocol=nil then
exit;
Protocol.fUpgradeURI := uri;
Protocol.fRemoteIP := ClientSock.HeaderGetValue('SEC-WEBSOCKET-REMOTEIP');
if Protocol.fRemoteIP='' then
Protocol.fRemoteIP := ClientSock.RemoteIP;
Protocol.fRemoteLocalhost := Protocol.fRemoteIP='127.0.0.1';
extin := ClientSock.HeaderGetValue('SEC-WEBSOCKET-EXTENSIONS');
if extin<>'' then begin
CSVToRawUTF8DynArray(pointer(extin),extins,';',true);
if not Protocol.ProcessHandshake(extins,extout,nil) then begin
Protocol.Free;
result := STATUS_UNAUTHORIZED;
exit;
end;
end;
key := ClientSock.HeaderGetValue('SEC-WEBSOCKET-KEY');
if Base64ToBinLengthSafe(pointer(key),length(key))<>16 then begin
Protocol.Free;
exit; // this nonce must be a Base64-encoded value of 16 bytes
end;
ComputeChallenge(key,Digest);
if extout<>'' then
extout := 'Sec-WebSocket-Extensions: '+extout+#13#10;
FormatUTF8('HTTP/1.1 101 Switching Protocols'#13#10+
'Upgrade: websocket'#13#10'Connection: Upgrade'#13#10+
'Sec-WebSocket-Protocol: %'#13#10'%Sec-WebSocket-Accept: %'#13#10#13#10,
[Protocol.Name,extout,BinToBase64Short(@Digest,sizeof(Digest))],header);
if not ClientSock.TrySndLow(pointer(header),length(header)) then begin
Protocol.Free;
result := STATUS_WEBSOCKETCLOSED;
exit;
end;
result := STATUS_SUCCESS; // connection upgraded: never back to HTTP/1.1
finally
if result<>STATUS_SUCCESS then begin // notify upgrade failure to client
FormatUTF8('HTTP/1.0 % WebSocket Upgrade Error'#13#10+
'Connection: Close'#13#10#13#10,[result],header);
ClientSock.TrySndLow(pointer(header),length(header));
ClientSock.KeepAliveClient := false;
end;
end;
end;
{ TWebSocketServer }
constructor TWebSocketServer.Create(const aPort: SockString; OnStart,OnStop: TNotifyThreadEvent;
const ProcessName: SockString; ServerThreadPoolCount, KeepAliveTimeOut: integer;
HeadersNotFiltered: boolean);
begin
// override with custom processing classes
fSocketClass := TWebSocketServerSocket;
fThreadRespClass := TWebSocketServerResp;
// initialize protocols and connections
fWebSocketConnections := TSynObjectListLocked.Create({owned=}false);
fProtocols := TWebSocketProtocolList.Create;
fSettings.SetDefaults;
fSettings.HeartbeatDelay := 20000;
fCanNotifyCallback := true;
// start the server
inherited Create(aPort,OnStart,OnStop,ProcessName,ServerThreadPoolCount,
KeepAliveTimeOut,HeadersNotFiltered);
end;
function TWebSocketServer.WebSocketProcessUpgrade(ClientSock: THttpServerSocket;
Context: TWebSocketServerResp): integer;
var protocol: TWebSocketProtocol;
begin
result := HttpServerWebSocketUpgrade(ClientSock,fProtocols,protocol);
if result<>STATUS_SUCCESS then
exit;
ClientSock.KeepAliveClient := false; // close connection with WebSockets
Context.fProcess := TWebSocketProcessServer.Create(
ClientSock,protocol,Context.ConnectionID,Context,fSettings,fProcessName);
Context.fProcess.fServerResp := Context;
fWebSocketConnections.Add(Context);
try
Context.fProcess.ProcessLoop; // run main blocking loop
finally
FreeAndNil(Context.fProcess); // notify end of WebSockets
fWebSocketConnections.Remove(Context);
end;
end;
procedure TWebSocketServer.Process(ClientSock: THttpServerSocket;
ConnectionID: THttpServerConnectionID; ConnectionThread: TSynThread);
var err: integer;
begin
if (connectionUpgrade in ClientSock.HeaderFlags) and ClientSock.KeepAliveClient and
IdemPropNameU('GET',ClientSock.Method) and
IdemPropNameU(ClientSock.Upgrade,'websocket') and
ConnectionThread.InheritsFrom(TWebSocketServerResp) then begin
err := WebSocketProcessUpgrade(ClientSock,TWebSocketServerResp(ConnectionThread));
if err<>STATUS_SUCCESS then
WebSocketLog.Add.Log(sllTrace,'Process: WebSocketProcessUpgrade failed as %',[err],self);
end else
inherited Process(ClientSock,ConnectionID,ConnectionThread);
end;
destructor TWebSocketServer.Destroy;
begin
inherited Destroy; // close any pending connection
fWebSocketConnections.Free;
fProtocols.Free;
end;
function TWebSocketServer.Settings: PWebSocketProcessSettings;
begin
result := @fSettings;
end;
function TWebSocketServer.WebSocketConnections: integer;
begin
result := fWebSocketConnections.Count;
end;
type
PWebSocketServerResp = ^TWebSocketServerResp;
function TWebSocketServer.IsActiveWebSocketThread(ConnectionThread: TSynThread): TWebSocketServerResp;
var i: Integer;
c: PWebSocketServerResp;
begin // no need to optimize (not called often)
result := nil;
if Terminated or (ConnectionThread=nil) or
not ConnectionThread.InheritsFrom(TWebSocketServerResp) then
exit;
fWebSocketConnections.Safe.Lock;
try
c := pointer(fWebSocketConnections.List);
for i := 1 to fWebSocketConnections.Count do
if c^=ConnectionThread then begin
if c^.fProcess.State=wpsRun then
result := c^;
exit;
end else
inc(c);
finally
fWebSocketConnections.Safe.UnLock;
end;
end;
function FastFindConnection(c: PWebSocketServerResp; n: integer; id: THttpServerConnectionID): TWebSocketServerResp;
begin // speedup brute force check in case of high number of connections
if n>0 then
repeat
result := c^;
if result.ConnectionID=id then
exit;
inc(c);
dec(n);
if n=0 then
break;
result := c^;
if result.ConnectionID=id then
exit;
inc(c);
dec(n);
until n=0;
result := nil;
end;
function TWebSocketServer.IsActiveWebSocket(ConnectionID: THttpServerConnectionID): TWebSocketServerResp;
begin
result := nil;
if Terminated or (ConnectionID=0) then
exit;
fWebSocketConnections.Safe.Lock;
try
result := FastFindConnection(pointer(fWebSocketConnections.List),
fWebSocketConnections.Count, ConnectionID);
finally
fWebSocketConnections.Safe.UnLock;
end;
end;
procedure TWebSocketServer.WebSocketBroadcast(const aFrame: TWebSocketFrame);
begin
WebSocketBroadcast(aFrame,nil);
end;
procedure TWebSocketServer.WebSocketBroadcast(const aFrame: TWebSocketFrame;
const aClientsConnectionID: THttpServerConnectionIDDynArray);
var i, len, ids: Integer;
c: ^TWebSocketServerResp;
temp: TWebSocketFrame; // local copy since SendFrame() modifies the payload
sorted: TSynTempBuffer;
begin
if Terminated or not(aFrame.opcode in [focText, focBinary]) then
exit;
ids := length(aClientsConnectionID);
if ids>0 then begin
sorted.Init(pointer(aClientsConnectionID),ids*8);
QuickSortInt64(sorted.buf,0,ids-1); // faster O(log(n)) binary search
end;
dec(ids); // WebSocketBroadcast(nil) -> ids<0
temp.opcode := aFrame.opcode;
temp.content := aFrame.content;
len := length(aFrame.payload);
fWebSocketConnections.Safe.Lock;
try
c := pointer(fWebSocketConnections.List);
for i := 1 to fWebSocketConnections.Count do begin
if (c^.fProcess.State=wpsRun) and
((ids<0) or (FastFindInt64Sorted(sorted.buf,ids,c^.ConnectionID)>=0)) then begin
SetString(temp.payload,PAnsiChar(pointer(aFrame.payload)),len);
c^.fProcess.Outgoing.Push(temp); // non blocking asynchronous sending
end;
inc(c);
end;
finally
fWebSocketConnections.Safe.UnLock;
if ids>=0 then
sorted.Done;
end;
end;
{ TWebSocketServerRest }
constructor TWebSocketServerRest.Create(const aPort: SockString;
OnStart,OnStop: TNotifyThreadEvent; const aProcessName,
aWebSocketsURI, aWebSocketsEncryptionKey: RawUTF8; aWebSocketsAJAX: boolean);
begin
Create(aPort,OnStart,OnStop,aProcessName);
WebSocketsEnable(aWebSocketsURI,aWebSocketsEncryptionKey,aWebSocketsAJAX);
end;
procedure TWebSocketServerRest.WebSocketsEnable(const aWebSocketsURI,
aWebSocketsEncryptionKey: RawUTF8; aWebSocketsAJAX,aWebSocketsCompressed: boolean);
begin
if self=nil then
exit;
fProtocols.AddOnce(TWebSocketProtocolBinary.Create(
aWebSocketsURI,true,aWebSocketsEncryptionKey,aWebSocketsCompressed));
if aWebSocketsAJAX then
fProtocols.AddOnce(TWebSocketProtocolJSON.Create(aWebSocketsURI));
end;
function TWebSocketServerRest.Callback(
Ctxt: THttpServerRequest; aNonBlocking: boolean): cardinal;
var connection: TWebSocketServerResp;
mode: TWebSocketProcessNotifyCallback;
begin
if Ctxt=nil then
connection := nil else begin
WebSocketLog.Add.Log(sllTrace,'Callback(%) on socket=%',
[Ctxt.URL,Ctxt.ConnectionID],self);
connection := IsActiveWebSocket(Ctxt.ConnectionID);
end;
if connection<>nil then begin
// this request is a websocket, on a non broken connection
if aNonBlocking then // see TInterfacedObjectFakeServer.CallbackInvoke
mode := wscNonBlockWithoutAnswer else
mode := wscBlockWithAnswer;
result := connection.NotifyCallback(Ctxt,mode);
end else begin
WebSocketLog.Add.Log(sllError,'Callback() on inactive socket',self);
result := STATUS_NOTFOUND;
end;
end;
{ TWebSocketServerResp }
constructor TWebSocketServerResp.Create(aServerSock: THttpServerSocket;
aServer: THttpServer);
begin
if not aServer.InheritsFrom(TWebSocketServer) then
raise EWebSockets.CreateUTF8('%.Create(%: TWebSocketServer?)',[self,aServer]);
inherited Create(aServerSock,aServer);
end;
function TWebSocketServerResp.NotifyCallback(Ctxt: THttpServerRequest;
aMode: TWebSocketProcessNotifyCallback): cardinal;
begin
if fProcess=nil then
result := STATUS_NOTFOUND else begin
result := fProcess.NotifyCallback(Ctxt,aMode);
if result=STATUS_WEBSOCKETCLOSED then begin
WebSocketLog.Add.Log(sllError,'NotifyCallback on closed connection',self);
ServerSock.KeepAliveClient := false; // force close the connection
result := STATUS_NOTFOUND;
end;
end;
end;
function TWebSocketServerResp.WebSocketProtocol: TWebSocketProtocol;
begin
if (Self=nil) or (fProcess=nil) then
result := nil else
result := fProcess.Protocol;
end;
{ TWebSocketProcessServer }
function TWebSocketProcessServer.ComputeContext(
out RequestProcess: TOnHttpServerRequest): THttpServerRequest;
begin
result := THttpServerRequest.Create(
(fOwnerThread as TWebSocketServerResp).fServer,fOwnerConnection,fOwnerThread);
RequestProcess := TWebSocketServerResp(fOwnerThread).fServer.Request;
end;
{ TWebSocketServerSocket }
function TWebSocketServerSocket.GetRequest(withBody: boolean;
headerMaxTix: Int64): THttpServerSocketGetRequestResult;
begin
result := inherited GetRequest(withBody, headerMaxTix);
if (result=grHeaderReceived) and (connectionUpgrade in HeaderFlags) and
KeepAliveClient and IdemPropNameU('GET',Method) and IdemPropNameU(Upgrade,'websocket') then
//writeln('!!');
end;
{ -------------- WebSockets Client classes for bidirectional remote access }
{ THttpClientWebSockets }
constructor THttpClientWebSockets.Create(aTimeOut: PtrInt);
begin
inherited;
fSettings.SetDefaults;
fSettings.CallbackAnswerTimeOutMS := aTimeOut;
end;
class function THttpClientWebSockets.WebSocketsConnect(const aHost,
aPort: SockString; aProtocol: TWebSocketProtocol; aLog: TSynLogClass;
const aLogContext, aURI, aCustomHeaders: RawUTF8): THttpClientWebSockets;
var error: RawUTF8;
begin
result := nil;
if (aProtocol = nil) or (aHost = '') then
raise EWebSockets.CreateUTF8('%.WebSocketsConnect(nil)', [self]);
try
result := Open(aHost, aPort); // constructor
error := result.WebSocketsUpgrade(aURI, '', false, false, aProtocol, aCustomHeaders);
if error <> '' then
FreeAndNil(result);
except
on E: Exception do begin
aProtocol.Free; // as done in WebSocketsUpgrade()
FreeAndNil(result);
FormatUTF8('% %', [E, E.Message], error);
end;
end;
if aLog <> nil then
if result <> nil then
aLog.Add.Log(sllDebug, '%: WebSocketsConnect %', [aLogContext, result])
else
aLog.Add.Log(sllWarning, '%: WebSocketsConnect %:% failed - %',
[aLogContext, aHost, aPort, error]);
end;
destructor THttpClientWebSockets.Destroy;
begin
FreeAndNil(fProcess);
inherited;
end;
function THttpClientWebSockets.Request(const url, method: SockString;
KeepAlive: cardinal; const header, Data, DataType: SockString;
retry: boolean): integer;
var Ctxt: THttpServerRequest;
block: TWebSocketProcessNotifyCallback;
resthead: RawUTF8;
begin
if fProcess<>nil then begin
if fProcess.fClientThread.fThreadState=sCreate then
sleep(10); // allow TWebSocketProcessClientThread.Execute warmup
if fProcess.fClientThread.fThreadState<>sRun then
// WebSockets closed by server side
result := STATUS_NOTIMPLEMENTED else begin
// send the REST request over WebSockets
Ctxt := THttpServerRequest.Create(
nil,fProcess.fOwnerConnection,fProcess.fOwnerThread);
try
Ctxt.Prepare(url,method,header,data,dataType,'',fTLS);
FindNameValue(header,'SEC-WEBSOCKET-REST:',resthead);
if resthead='NonBlocking' then
block := wscNonBlockWithoutAnswer else
block := wscBlockWithAnswer;
result := fProcess.NotifyCallback(Ctxt,block);
if IdemPChar(pointer(Ctxt.OutContentType), JSON_CONTENT_TYPE_UPPER) then
HeaderSetText(Ctxt.OutCustomHeaders) else
HeaderSetText(Ctxt.OutCustomHeaders,Ctxt.OutContentType);
Content := Ctxt.OutContent;
ContentType := Ctxt.OutContentType;
ContentLength := length(Ctxt.OutContent);
finally
Ctxt.Free;
end;
end;
end else
// standard HTTP/1.1 REST request (before WebSocketsUpgrade call)
result := inherited Request(url,method,KeepAlive,header,Data,DataType,retry);
end;
procedure THttpClientWebSockets.SetInt32OptionByIndex(OptName, OptVal: integer);
begin
inherited SetInt32OptionByIndex(OptName,OptVal);
if OptName=SO_RCVTIMEO then
fSettings.CallbackAnswerTimeOutMS := OptVal;
end;
function THttpClientWebSockets.Settings: PWebSocketProcessSettings;
begin
result := @fSettings;
end;
function THttpClientWebSockets.WebSocketsUpgrade(const aWebSocketsURI,
aWebSocketsEncryptionKey: RawUTF8; aWebSocketsAJAX: boolean;
aWebSocketsCompression: boolean; aProtocol: TWebSocketProtocol;
const aCustomHeaders: RawUTF8): RawUTF8;
var key: TAESBlock;
bin1,bin2: RawByteString;
extin,extout,prot: RawUTF8;
extins: TRawUTF8DynArray;
cmd: SockString;
digest1,digest2: TSHA1Digest;
begin
try
try
if fProcess<>nil then begin
result := 'Already upgraded to WebSockets';
if IdemPropNameU(fProcess.Protocol.URI,aWebSocketsURI) then
result := result+' on this URI' else
result := FormatUTF8('% with URI=[%] but requested [%]',
[result,fProcess.Protocol.URI,aWebSocketsURI]);
exit;
end;
if aProtocol = nil then
if aWebSocketsAJAX then
aProtocol := TWebSocketProtocolJSON.Create(aWebSocketsURI) else
aProtocol := TWebSocketProtocolBinary.Create(
aWebSocketsURI,false,aWebSocketsEncryptionKey,aWebSocketsCompression);
aProtocol.fOnBeforeIncomingFrame := fOnBeforeIncomingFrame;
RequestSendHeader(aWebSocketsURI,'GET');
TAESPRNG.Main.FillRandom(key);
bin1 := BinToBase64(@key,sizeof(key));
SockSend(['Content-Length: 0'#13#10'Connection: Upgrade'#13#10+
'Upgrade: websocket'#13#10'Sec-WebSocket-Key: ',bin1,#13#10+
'Sec-WebSocket-Protocol: ',aProtocol.GetSubprotocols,#13#10+
'Sec-WebSocket-Version: 13']);
if aProtocol.ProcessHandshake(nil,extout,nil) and (extout<>'') then
SockSend(['Sec-WebSocket-Extensions: ',extout]);
if aCustomHeaders<>'' then
SockSend(aCustomHeaders);
SockSend; // CRLF
SockSendFlush('');
SockRecvLn(cmd);
GetHeader(false);
prot := HeaderGetValue('SEC-WEBSOCKET-PROTOCOL');
result := 'Invalid HTTP Upgrade Header';
if not IdemPChar(pointer(cmd),'HTTP/1.1 101') or
not (connectionUpgrade in HeaderFlags) or (ContentLength>0) or
not IdemPropNameU(Upgrade,'websocket') or
not aProtocol.SetSubprotocol(prot) then
exit;
aProtocol.fName := prot;
result := 'Invalid HTTP Upgrade Accept Challenge';
ComputeChallenge(bin1,digest1);
bin2 := HeaderGetValue('SEC-WEBSOCKET-ACCEPT');
if not Base64ToBin(pointer(bin2),@digest2,length(bin2),sizeof(digest2),false) or
not IsEqual(digest1,digest2) then
exit;
if extout<>'' then begin
result := 'Invalid HTTP Upgrade ProcessHandshake';
extin := HeaderGetValue('SEC-WEBSOCKET-EXTENSIONS');
CSVToRawUTF8DynArray(pointer(extin),extins,';',true);
if (extins=nil) or not aProtocol.ProcessHandshake(extins,extout,@result) then
exit;
end;
// if we reached here, connection is successfully upgraded to WebSockets
if (Server='localhost') or (Server='127.0.0.1') then begin
aProtocol.fRemoteIP := '127.0.0.1';
aProtocol.fRemoteLocalhost := true;
end else
aProtocol.fRemoteIP := Server;
result := ''; // no error message = success
fProcess := TWebSocketProcessClient.Create(self,aProtocol,fProcessName);
aProtocol := nil; // protocol instance is owned by fProcess now
finally
aProtocol.Free;
end;
except
on E: Exception do begin
FreeAndNil(fProcess);
FormatUTF8('%: %',[E,E.Message],result);
end;
end;
end;
{ TWebSocketProcessClient }
constructor TWebSocketProcessClient.Create(aSender: THttpClientWebSockets;
aProtocol: TWebSocketProtocol; const aProcessName: RawUTF8);
begin
fMaskSentFrames := FRAME_LEN_MASK; // https://tools.ietf.org/html/rfc6455#section-10.3
inherited Create(aSender,aProtocol,0,nil,aSender.fSettings,aProcessName);
// initialize the thread after everything is set (Execute may be instant)
fClientThread := TWebSocketProcessClientThread.Create(self);
end;
destructor TWebSocketProcessClient.Destroy;
var tix: Int64;
begin
with WebSocketLog.Enter('Destroy: ThreadState=%', [ToText(fClientThread.fThreadState)^], self) do
try
// focConnectionClose would be handled in this thread -> close client thread
fClientThread.Terminate;
tix := GetTickCount64+7000; // never wait forever
while (fClientThread.fThreadState=sRun) and (GetTickCount64<tix) do
SleepHiRes(1);
fClientThread.fProcess := nil;
finally
// SendPendingOutgoingFrames + SendFrame/GetFrame(focConnectionClose)
inherited Destroy;
fClientThread.Free;
end;
end;
function TWebSocketProcessClient.ComputeContext(
out RequestProcess: TOnHttpServerRequest): THttpServerRequest;
begin
RequestProcess := (fSocket as THttpClientWebSockets).fOnCallbackRequestProcess;
if Assigned(RequestProcess) then
result := THttpServerRequest.Create(nil,0,fOwnerThread) else
result := nil;
end;
{ TWebSocketProcessClientThread }
constructor TWebSocketProcessClientThread.Create(
aProcess: TWebSocketProcessClient);
begin
fProcess := aProcess;
fProcess.fOwnerThread := self;
inherited Create(false);
end;
procedure TWebSocketProcessClientThread.Execute;
begin
if fProcess<>nil then // may happen when debugging under FPC (alf)
SetCurrentThreadName('% % %',[fProcess.fProcessName,self,fProcess.Protocol.Name]);
fThreadState := sRun;
try
WebSocketLog.Add.Log(sllDebug,'Execute: before ProcessLoop %', [fProcess], self);
if not Terminated and (fProcess<>nil) then
fProcess.ProcessLoop;
WebSocketLog.Add.Log(sllDebug,'Execute: after ProcessLoop %',[fProcess],self);
if (fProcess<>nil) and (fProcess.Socket<>nil) and
fProcess.Socket.InheritsFrom(THttpClientWebSockets) then
with THttpClientWebSockets(fProcess.Socket) do
if Assigned(OnWebSocketsClosed) then
OnWebSocketsClosed(self);
except // ignore any exception in the thread
end;
if (fProcess<>nil) and (fProcess.fState=wpsClose) then
fThreadState := sClosed else
fThreadState := sFinished;
WebSocketLog.Add.Log(sllDebug,'Execute: done (%)',[ToText(fThreadState)^],self);
end;
{ ------------ client or server asynchronous process of multiple connections }
{ TAsynchConnection }
constructor TAsynchConnection.Create(const aRemoteIP: RawUTF8);
begin
inherited Create;
fRemoteIP := aRemoteIP;
end;
procedure TAsynchConnection.AfterCreate(Sender: TAsynchConnections);
begin
fLastOperation := UnixTimeUTC;
end;
procedure TAsynchConnection.OnLastOperationIdle(Sender: TAsynchConnections);
begin
fLastOperation := UnixTimeUTC;
end;
procedure TAsynchConnection.AfterWrite(Sender: TAsynchConnections);
begin // do nothing
end;
procedure TAsynchConnection.BeforeDestroy(Sender: TAsynchConnections);
begin
fHandle := 0; // to detect any dangling pointer
end;
{ TAsynchConnectionsSockets }
procedure TAsynchConnectionsSockets.OnClose(connection: TObject);
begin
// caller did call Stop() before calling OnClose (socket=0)
fOwner.fLog.Add.Log(sllTrace,'OnClose%',[connection],self);
fOwner.ConnectionDelete((connection as TAsynchConnection).Handle); // do connection.Free
end;
function TAsynchConnectionsSockets.OnError(connection: TObject;
events: TPollSocketEvents): boolean;
begin
fOwner.fLog.Add.Log(sllDebug,'OnError% events=[%] -> free socket and instance',
[connection,GetSetName(TypeInfo(TPollSocketEvents),events)],self);
result := acoOnErrorContinue in fOwner.Options; // false=close by default
end;
function TAsynchConnectionsSockets.OnRead(connection: TObject): TPollAsynchSocketOnRead;
var ac: TAsynchConnection;
begin
ac := connection as TAsynchConnection;
if not(acoNoLogRead in fOwner.Options) then
fOwner.fLog.Add.Log(sllTrace,'OnRead% len=%',[ac,length(ac.fSlot.readbuf)],self);
result := ac.OnRead(fOwner);
if not (acoLastOperationNoRead in fOwner.Options) then
ac.fLastOperation := UnixTimeUTC;
end;
function TAsynchConnectionsSockets.SlotFromConnection(connection: TObject): PPollSocketsSlot;
begin
if not connection.InheritsFrom(TAsynchConnection) or
(TAsynchConnection(connection).Handle=0) then begin
fOwner.fLog.Add.Log(sllStackTrace,'SlotFromConnection() with dangling pointer',self);
result := nil;
end else
result := @TAsynchConnection(connection).fSlot;
end;
function TAsynchConnectionsSockets.Write(connection: TObject;
const data; datalen, timeout: integer): boolean;
var tmp: TLogEscape;
begin
result := inherited Write(connection,data,datalen,timeout);
if result and not (acoLastOperationNoWrite in fOwner.Options) then
(connection as TAsynchConnection).fLastOperation := UnixTimeUTC;
if (fOwner.fLog<>nil) and not(acoNoLogWrite in fOwner.Options) then
fOwner.fLog.Add.Log(sllTrace,'Write%=% len=%%',
[connection,BOOL_STR[result],datalen,LogEscape(@data,datalen,tmp,
acoVerboseLog in fOwner.Options)],self);
end;
procedure TAsynchConnectionsSockets.AfterWrite(connection: TObject);
begin
(connection as TAsynchConnection).AfterWrite(fOwner);
end;
function TAsynchConnectionsSockets.GetTotal: integer;
begin
result := fOwner.fLastHandle; // by definition
end;
{ TAsynchConnectionsThread }
constructor TAsynchConnectionsThread.Create(aOwner: TAsynchConnections;
aProcess: TPollSocketEvent);
begin
fOwner := aOwner;
fProcess := aProcess;
fOnThreadTerminate := fOwner.fOnThreadTerminate;
inherited Create(false);
end;
procedure TAsynchConnectionsThread.Execute;
var idletix: Int64;
begin
SetCurrentThreadName('% % %',[fOwner.fProcessName,self,ToText(fProcess)^]);
fOwner.NotifyThreadStart(self);
try
idletix := {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64+1000;
while not Terminated and (fOwner.fClients<>nil) do begin
// implement parallel client connections for TAsynchClient
if (fOwner.fThreadClients.Count>0) and
(InterlockedDecrement(fOwner.fThreadClients.Count)>=0) then
fOwner.ThreadClientsConnect else
// generic TAsynchConnections read/write process
case fProcess of
pseRead:
fOwner.fClients.ProcessRead(30000);
pseWrite: begin
fOwner.fClients.ProcessWrite(30000);
if {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64>=idletix then begin
fOwner.IdleEverySecond; // may take some time -> retrieve ticks again
idletix := {$ifdef FPCLINUX}SynFPCLinux.{$endif}GetTickCount64+1000;
end;
end;
else
raise EAsynchConnections.CreateUTF8('%.Execute: unexpected fProcess=%',
[self,ToText(fProcess)^]);
end;
end;
except
on E: Exception do
fOwner.fLog.Add.Log(sllWarning,'Execute raised a % -> terminate % thread',
[E.ClassType,fOwner.fStreamClass],self);
end;
fOwner.fLog.Add.Log(sllDebug,'Execute: done', self);
end;
{ TAsynchConnections }
function TAsynchConnectionCompareByHandle(const A,B): integer;
begin // for fast binary search from the connection handle
result := TAsynchConnection(A).Handle-TAsynchConnection(B).Handle;
end;
constructor TAsynchConnections.Create(OnStart, OnStop: TNotifyThreadEvent;
aStreamClass: TAsynchConnectionClass; const ProcessName: SockString;
aLog: TSynLogClass; aOptions: TAsynchConnectionsOptions; aThreadPoolCount: integer);
var i: integer;
log: ISynLog;
begin
log := aLog.Enter('Create(%,%,%)',[aStreamClass,ProcessName,aThreadPoolCount],self);
if (aStreamClass=TAsynchConnection) or (aStreamClass=nil) then
raise EAsynchConnections.CreateUTF8('%.Create(%)',[self,aStreamClass]);
if aThreadPoolCount<=0 then
aThreadPoolCount := 1;
fLog := aLog;
fStreamClass := aStreamClass;
fConnectionLock.Init;
fConnections.Init(TypeInfo(TAsynchConnectionObjArray),fConnection,@fConnectionCount);
fConnections.Compare := TAsynchConnectionCompareByHandle;
fConnections.IsObjArray := false; // to call TAsynchConnection.BeforeDestroy
fClients := TAsynchConnectionsSockets.Create;
fClients.fOwner := self;
fTempConnectionForSearchPerHandle := fStreamClass.Create('');
fOptions := aOptions;
inherited Create(false,OnStart,OnStop,ProcessName);
SetLength(fThreads,aThreadPoolCount+1);
fThreads[0] := TAsynchConnectionsThread.Create(self,pseWrite);
for i := 1 to aThreadPoolCount do
fThreads[i] := TAsynchConnectionsThread.Create(self,pseRead);
end;
destructor TAsynchConnections.Destroy;
var i: integer;
begin
with fClients do
fLog.Add.Log(sllDebug,'Destroy total=% reads=%/% writes=%/%',[Total,
ReadCount,KB(ReadBytes),WriteCount,KB(WriteBytes)],self);
Terminate;
for i := 0 to high(fThreads) do
fThreads[i].Terminate; // stop ProcessRead/ProcessWrite when polling stops
FreeAndNil(fClients); // stop polling and refuse further Write/ConnectionRemove
ObjArrayClear(fThreads);
inherited Destroy;
for i := 0 to fConnectionCount-1 do
try
fConnection[i].BeforeDestroy(self);
fConnection[i].Free;
except
end;
fConnectionLock.Done;
fTempConnectionForSearchPerHandle.Free;
end;
procedure TAsynchConnections.ThreadClientsConnect;
var client: TSocket;
connection: TAsynchConnection;
begin
with fThreadClients do
client := CallServer(Address,Port,false,cslTCP,Timeout);
if client<0 then
raise ECrtSocket.CreateFmt('%s: %s:%s connection failure', // ECrtSocket for error
[ClassName,fThreadClients.Address,fThreadClients.Port],-1);
connection := nil;
if not ConnectionCreate(client,{ip=}'',connection) then
DirectShutdown(client);
end;
function TAsynchConnections.ConnectionCreate(aSocket: TSocket; const aRemoteIp: RawUTF8;
out aConnection: TAsynchConnection): boolean;
begin // you can override this class then call ConnectionAdd
if Terminated then
result := false else begin
aConnection := fStreamClass.Create(aRemoteIP);
result := ConnectionAdd(aSocket,aConnection);
end;
end;
function TAsynchConnections.ConnectionAdd(aSocket: TSocket;
aConnection: TAsynchConnection): boolean;
begin
result := false; // caller should release aSocket
if Terminated then
exit;
aConnection.fSlot.socket := aSocket;
fConnectionLock.Lock;
try
inc(fLastHandle);
aConnection.fHandle := fLastHandle;
fConnections.Add(aConnection);
fLog.Add.Log(sllTrace,'ConnectionAdd% count=%',[aConnection,fConnectionCount],self);
fConnections.Sorted := true; // handles are increasing
finally
fConnectionLock.UnLock;
end;
aConnection.AfterCreate(self);
result := true; // indicates aSocket owned by the pool
end;
function TAsynchConnections.ConnectionDelete(
aConnection: TAsynchConnection; aIndex: integer): boolean;
var t: TClass;
h: TAsynchConnectionHandle;
begin // caller should have done fConnectionLock.Lock
try
h := aConnection.Handle;
t := aConnection.ClassType;
aConnection.BeforeDestroy(self);
aConnection.Free;
finally
fConnections.FastDeleteSorted(aIndex);
end;
fLog.Add.Log(sllTrace,'ConnectionDelete %.Handle=% count=%',[t,h,fConnectionCount],self);
result := true;
end;
function TAsynchConnections.ConnectionDelete(aHandle: TAsynchConnectionHandle): boolean;
var i: integer;
conn: TAsynchConnection;
begin // don't call fClients.Stop() here - see ConnectionRemove()
result := false;
if Terminated or (aHandle<=0) then
exit;
conn := ConnectionFindLocked(aHandle,@i);
if conn<>nil then
try
result := ConnectionDelete(conn,i);
finally
fConnectionLock.UnLock;
end;
if not result then
fLog.Add.Log(sllTrace,'ConnectionDelete(%)=false count=%',
[aHandle,fConnectionCount],self);
end;
function TAsynchConnections.ConnectionFindLocked(aHandle: TAsynchConnectionHandle;
aIndex: PInteger): TAsynchConnection;
var i: integer;
begin
result := nil;
if (self=nil) or Terminated or (aHandle<=0) then
exit;
fConnectionLock.Lock;
try
fTempConnectionForSearchPerHandle.fHandle := aHandle;
i := fConnections.Find(fTempConnectionForSearchPerHandle); // fast O(log(n)) binary search
if i>=0 then begin
result := fConnection[i];
if aIndex<>nil then
aIndex^ := i;
end;
fLog.Add.Log(sllTrace,'ConnectionFindLocked(%)=%',[aHandle,result],self);
finally
if result=nil then
fConnectionLock.UnLock;
end;
end;
function TAsynchConnections.ConnectionRemove(aHandle: TAsynchConnectionHandle): boolean;
var i: integer;
conn: TAsynchConnection;
begin
result := false;
if (self=nil) or Terminated or (aHandle<=0) then
exit;
conn := ConnectionFindLocked(aHandle,@i);
if conn<>nil then
try
if not fClients.Stop(conn) then
fLog.Add.Log(sllDebug,'ConnectionRemove: Stop=false for %',[conn],self);
result := ConnectionDelete(conn,i);
finally
fConnectionLock.UnLock;
end;
if not result then
fLog.Add.Log(sllTrace,'ConnectionRemove(%)=false',[aHandle],self);
end;
procedure TAsynchConnections.Lock;
begin
fConnectionLock.Lock;
end;
procedure TAsynchConnections.Unlock;
begin
fConnectionLock.UnLock;
end;
function TAsynchConnections.Write(connection: TAsynchConnection;
const data; datalen: integer): boolean;
begin
if Terminated then
result := false else
result := fClients.Write(connection,data,datalen);
end;
function TAsynchConnections.Write(connection: TAsynchConnection;
const data: SockString): boolean;
begin
if Terminated then
result := false else
result := fClients.WriteString(connection,data);
end;
procedure TAsynchConnections.LogVerbose(connection: TAsynchConnection;
const ident: RawUTF8; frame: pointer; framelen: integer);
var tmp: TLogEscape;
begin
if not(acoNoLogRead in Options) and (acoVerboseLog in Options) and (fLog<>nil) then
fLog.Add.Log(sllTrace,'% len=%%',[ident,framelen,
LogEscape(frame,framelen,tmp)],connection);
end;
procedure TAsynchConnections.LogVerbose(connection: TAsynchConnection;
const ident: RawUTF8; const frame: RawByteString);
begin
LogVerbose(connection,ident,pointer(frame),length(frame));
end;
procedure TAsynchConnections.IdleEverySecond;
var i,n: integer;
allowed: cardinal;
log: ISynLog;
begin
if Terminated or (LastOperationIdleSeconds<=0) then
exit;
fConnectionLock.Lock;
try
n := 0;
allowed := UnixTimeUTC-LastOperationIdleSeconds;
for i := 0 to fConnectionCount-1 do
if fConnection[i].fLastOperation<allowed then
try
if log=nil then
log := fLog.Enter(self{$ifndef DELPHI5OROLDER},'IdleEverySecond'{$endif});
fConnection[i].OnLastOperationIdle(self);
inc(n);
except
end;
if log<>nil then
log.Log(sllTrace,'IdleEverySecond notified % %',[n,fStreamClass],self);
finally
fConnectionLock.UnLock;
end;
end;
{ TAsynchServer }
constructor TAsynchServer.Create(const aPort: SockString; OnStart,
OnStop: TNotifyThreadEvent; aStreamClass: TAsynchConnectionClass;
const ProcessName: SockString; aLog: TSynLogClass;
aOptions: TAsynchConnectionsOptions; aThreadPoolCount: integer);
begin
fServer := TCrtSocket.Bind(aPort);
inherited Create(OnStart,OnStop,aStreamClass,ProcessName,aLog,aOptions,aThreadPoolCount);
end;
destructor TAsynchServer.Destroy;
var endtix: Int64;
begin
Terminate;
fServer.Close; // shutdown the socket to unlock Accept() in Execute
DirectShutdown(CallServer('127.0.0.1',fServer.Port,false,cslTCP,1)); // paranoid
endtix := GetTickCount64+10000;
inherited Destroy;
while not fExecuteFinished and (GetTickCount64<endtix) do
SleepHiRes(1); // wait for Execute to be finalized (unlikely)
fServer.Free;
end;
procedure TAsynchServer.Execute;
var client: TSocket;
connection: TAsynchConnection;
sin: TVarSin;
ip: SockString;
err: string;
begin
SetCurrentThreadName('% % Accept',[fProcessName,self]);
NotifyThreadStart(self);
if fServer.Sock<>0 then
try
while not Terminated do begin
client := Accept(fServer.Sock,sin);
if client<0 then
if Terminated then
break else begin
err := SocketErrorMessage;
fLog.Add.Log(sllWarning,'Execute: Accept()=%',[err],self);
if acoOnAcceptFailureStop in fOptions then
if WSAGetLastError=WSAEMFILE then
raise EAsynchConnections.CreateUTF8('%.Execute: too many connections', [self]) else
raise EAsynchConnections.CreateUTF8('%.Execute: Accept failed as %',[self,err]);
SleepHiRes(1);
continue;
end;
if Terminated then begin
DirectShutdown(client);
break;
end;
IPText(sin,ip);
if ConnectionCreate(client,ip,connection) then
if fClients.Start(connection) then
fLog.Add.Log(sllTrace,'Execute: Accept()=%',[connection], self) else
connection.Free else
DirectShutdown(client);
end;
except
on E: Exception do
fLog.Add.Log(sllWarning,'Execute raised % -> terminate %',
[E.ClassType,fProcessName],self);
end;
fLog.Add.Log(sllDebug, 'Execute: % done', [fProcessName], self);
fExecuteFinished := true;
end;
{ TAsynchClient }
constructor TAsynchClient.Create(const aServer, aPort: SockString;
aClientsCount,aClientsTimeoutSecs: integer; OnStart, OnStop: TNotifyThreadEvent;
aStreamClass: TAsynchConnectionClass; const ProcessName: SockString;
aLog: TSynLogClass; aOptions: TAsynchConnectionsOptions; aThreadPoolCount: integer);
begin
fThreadClients.Count := aClientsCount;
fThreadClients.Timeout := aClientsTimeoutSecs*1000;
fThreadClients.Address := aServer;
fThreadClients.Port := aPort;
inherited Create(OnStart,OnStop,aStreamClass,ProcessName,aLog,aOptions,aThreadPoolCount);
end;
procedure TAsynchClient.Execute;
begin
SetCurrentThreadName('% %',[fProcessName,self]);
NotifyThreadStart(self);
try
while InterlockedDecrement(fThreadClients.Count)>=0 do
ThreadClientsConnect; // will connect some clients in this main thread
except
on E: Exception do
fLog.Add.Log(sllWarning,'Execute raised % -> terminate %',
[E.ClassType,fProcessName],self);
end;
fLog.Add.Log(sllDebug, 'Execute: % done', [fProcessName], self);
end;
initialization
GetEnumNames(TypeInfo(TWebSocketFrameOpCode),@_TWebSocketFrameOpCode);
GetEnumNames(TypeInfo(TWebSocketProcessNotifyCallback),@_TWebSocketProcessNotifyCallback);
end.
| 37.83953 | 116 | 0.73127 |
c361e24a10534e954b5aadda811a1b56d66d4653 | 967 | pas | Pascal | 81-PieChart/Unit1.pas | FMXExpress/Cross-Platform-Samples | d6b761b81a6521652db814b0c1e65263dff4f694 | [
"BSD-3-Clause"
]
| 140 | 2019-08-07T23:22:44.000Z | 2022-02-23T18:27:51.000Z | 81-PieChart/Unit1.pas | azrael11/Cross-Platform-Samples | f2c16ae3ae23d1ecca00110af1571313eb4e4c51 | [
"BSD-3-Clause"
]
| 1 | 2020-06-08T11:23:04.000Z | 2020-06-08T11:23:04.000Z | 81-PieChart/Unit1.pas | azrael11/Cross-Platform-Samples | f2c16ae3ae23d1ecca00110af1571313eb4e4c51 | [
"BSD-3-Clause"
]
| 54 | 2019-08-09T21:37:51.000Z | 2022-03-13T12:13:16.000Z | unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMXTee.Engine,
FMXTee.Series, FMXTee.Procs, FMXTee.Chart, FMX.StdCtrls, FMX.Effects,
FMX.Controls.Presentation;
type
TForm1 = class(TForm)
MaterialOxfordBlueSB: TStyleBook;
ToolBar1: TToolBar;
ShadowEffect4: TShadowEffect;
Label1: TLabel;
Chart1: TChart;
Series1: TPieSeries;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.FormCreate(Sender: TObject);
begin
Chart1.Series[0].Clear;
Chart1.Series[0].Add(50,'Delphi');
Chart1.Series[0].Add(10,'is');
Chart1.Series[0].Add(40,'Awesome!');
Chart1.Series[0].Add(50,'Delphi');
Chart1.Series[0].Add(10,'is');
Chart1.Series[0].Add(40,'Awesome!');
end;
end.
| 21.488889 | 81 | 0.703206 |
c326f41567767d09122a4349e032d98a49879a83 | 1,663 | pas | Pascal | Source/DB/AqDrop.DB.SQLite.pas | AquasoftTI/AqDrop | 88ed2183e2faa9a8a8483be33d77d9c4c67f8378 | [
"MIT"
]
| 39 | 2017-05-12T17:37:01.000Z | 2021-04-05T17:51:28.000Z | Source/DB/AqDrop.DB.SQLite.pas | juliomar/AqDrop | 88ed2183e2faa9a8a8483be33d77d9c4c67f8378 | [
"MIT"
]
| 1 | 2020-11-12T02:50:23.000Z | 2020-11-12T02:50:23.000Z | Source/DB/AqDrop.DB.SQLite.pas | juliomar/AqDrop | 88ed2183e2faa9a8a8483be33d77d9c4c67f8378 | [
"MIT"
]
| 14 | 2017-05-12T17:37:06.000Z | 2021-01-29T21:43:03.000Z | unit AqDrop.DB.SQLite;
interface
uses
AqDrop.DB.SQL.Intf,
AqDrop.DB.Adapter;
type
TAqDBSQLiteSQLSolver = class(TAqDBSQLSolver)
strict protected
function SolveLimit(pSelect: IAqDBSQLSelect): string; override;
function SolveOffset(pSelect: IAqDBSQLSelect): string; override;
function SolveBooleanConstant(pConstant: IAqDBSQLBooleanConstant): string; override;
public
function SolveSelect(pSelect: IAqDBSQLSelect): string; override;
function GetAutoIncrementQuery(const pGeneratorName: string): string; override;
end;
implementation
uses
System.SysUtils,
AqDrop.Core.Helpers;
{ TAqDBSQLiteSQLSolver }
function TAqDBSQLiteSQLSolver.GetAutoIncrementQuery(const pGeneratorName: string): string;
begin
Result := 'select last_insert_rowid()';
end;
function TAqDBSQLiteSQLSolver.SolveBooleanConstant(pConstant: IAqDBSQLBooleanConstant): string;
begin
if pConstant.Value then
begin
Result := '1';
end else begin
Result := '0';
end;
end;
function TAqDBSQLiteSQLSolver.SolveLimit(pSelect: IAqDBSQLSelect): string;
begin
if pSelect.IsLimitDefined then
begin
Result := ' limit ' + pSelect.Limit.ToString;
end else begin
Result := '';
end;
end;
function TAqDBSQLiteSQLSolver.SolveOffset(pSelect: IAqDBSQLSelect): string;
begin
if pSelect.IsOffsetDefined then
begin
Result := ' offset ' + pSelect.Offset.ToString;
end else begin
Result := '';
end;
end;
function TAqDBSQLiteSQLSolver.SolveSelect(pSelect: IAqDBSQLSelect): string;
begin
Result := inherited + SolveLimit(pSelect) + SolveOffset(pSelect);
end;
end.
| 24.101449 | 96 | 0.727601 |
c38977aae8bc31eab25952c84e02dff0cf553cd4 | 47,133 | pas | Pascal | dependencies/jcl/JclPreProcessorParser.pas | grahamegrieve/fhirserver | 28f69977bde75490adac663e31a3dd77bc016f7c | [
"BSD-3-Clause"
]
| 132 | 2015-02-02T00:22:40.000Z | 2021-08-11T12:08:08.000Z | dependencies/jcl/JclPreProcessorParser.pas | grahamegrieve/fhirserver | 28f69977bde75490adac663e31a3dd77bc016f7c | [
"BSD-3-Clause"
]
| 113 | 2015-03-20T01:55:20.000Z | 2021-10-08T16:15:28.000Z | dependencies/jcl/JclPreProcessorParser.pas | grahamegrieve/fhirserver | 28f69977bde75490adac663e31a3dd77bc016f7c | [
"BSD-3-Clause"
]
| 49 | 2015-04-11T14:59:43.000Z | 2021-03-30T10:29:18.000Z | { **************************************************************************** }
{ }
{ Pascal PreProcessor Parser }
{ Copyright (c) 2001 Barry Kelly. }
{ barry_j_kelly@hotmail.com }
{ }
{ 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 PppParser.pas }
{ }
{ The Initial Developer of the Original Code is Barry Kelly. }
{ Portions created by Barry Kelly are Copyright (C) 2001 }
{ Barry Kelly. All Rights Reserved. }
{ }
{ Contributors: }
{ Robert Rossmair, }
{ Peter Thvrnqvist, }
{ Florent Ouchet }
{ }
{ Alternatively, the contents of this file may be used under the terms }
{ of the Lesser GNU Public License (the "LGPL License"), in which case }
{ the provisions of LGPL License are applicable instead of those }
{ above. If you wish to allow use of your version of this file only }
{ under the terms of the LPGL License and not to allow others to use }
{ your version of this file under the MPL, indicate your decision by }
{ deleting the provisions above and replace them with the notice and }
{ other provisions required by the LGPL License. If you do not delete }
{ the provisions above, a recipient may use your version of this file }
{ under either the MPL or the LPGL License. }
{ }
{ **************************************************************************** }
{ }
{ Last modified: $Date:: $ }
{ Revision: $Rev:: $ }
{ Author: $Author:: $ }
{ }
{ **************************************************************************** }
unit JclPreProcessorParser;
{$I jcl.inc}
interface
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils, System.Classes,
{$ELSE ~HAS_UNITSCOPE}
SysUtils, Classes,
{$ENDIF ~HAS_UNITSCOPE}
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
JclBase, JclContainerIntf, JclPreProcessorLexer;
type
TPppState = class;
EPppParserError = class(EJclError);
TJppParser = class
private
FLexer: TJppLexer;
FState: TPppState;
FResult: string;
FResultLen: Integer;
FLineBreakPos: Integer;
FAllWhiteSpaceIn: Boolean;
FAllWhiteSpaceOut: Boolean;
protected
procedure AddResult(const S: string; FixIndent: Boolean = False; ForceRecurseTest: Boolean = False);
function IsExcludedInclude(const FileName: string): Boolean;
procedure NextToken;
procedure ParseText;
procedure ParseCondition(Token: TJppToken);
function ParseInclude: string;
procedure ParseDefine(Skip: Boolean);
procedure ParseUndef(Skip: Boolean);
procedure ParseDefineMacro;
procedure ParseExpandMacro;
procedure ParseUndefMacro;
procedure ParseGetBoolValue;
procedure ParseGetIntValue;
procedure ParseGetStrValue;
procedure ParseLoop;
procedure ParseSetBoolValue;
procedure ParseSetIntValue;
procedure ParseSetStrValue;
public
constructor Create(const ABuffer: string; APppState: TPppState);
destructor Destroy; override;
function Parse: string;
property Lexer: TJppLexer read FLexer;
property State: TPppState read FState;
end;
EPppState = class(EJclError);
TPppOption = (poProcessIncludes, poProcessDefines, poStripComments,
poProcessMacros, poProcessValues, poNoWarningHeader, poKeepTabAndSpaces,
poIgnoreUnterminatedStrings);
TPppOptions = set of TPppOption;
TTriState = (ttUnknown, ttUndef, ttDefined);
TPppStateItem = class
public
DefinedKeywords: IJclStrMap;
ExcludedFiles: IJclStrList;
Macros: IJclStrIntfMap;
SearchPath: IJclStrList;
TriState: TTriState;
end;
TPppStateItemClass = class of TPppStateItem;
TPppProvider = class(TPersistent)
protected
function GetBoolValue(const Name: string): Boolean; virtual; abstract;
function GetDefine(const ASymbol: string): TTriState; virtual; abstract;
function GetIntegerValue(const Name: string): Integer; virtual; abstract;
function GetStringValue(const Name: string): string; virtual; abstract;
procedure SetBoolValue(const Name: string; Value: Boolean); virtual; abstract;
procedure SetDefine(const ASymbol: string; const Value: TTriState); virtual; abstract;
procedure SetIntegerValue(const Name: string; Value: Integer); virtual; abstract;
procedure SetStringValue(const Name, Value: string); virtual; abstract;
public
property Defines[const ASymbol: string]: TTriState read GetDefine write SetDefine;
property BoolValues[const Name: string]: Boolean read GetBoolValue write SetBoolValue;
property StringValues[const Name: string]: string read GetStringValue write SetStringValue;
property IntegerValues[const Name: string]: Integer read GetIntegerValue write SetIntegerValue;
end;
TPppState = class(TPppProvider)
private
FStateStack: IJclStack;
FOptions: TPppOptions;
function InternalPeekDefines: IJclStrMap;
function InternalPeekExcludedFiles: IJclStrList;
function InternalPeekMacros: IJclStrIntfMap;
function InternalPeekSearchPath: IJclStrList;
function InternalPeekTriState: TTriState;
procedure InternalSetTriState(Value: TTriState);
protected
class function StateItemClass: TPppStateItemClass; virtual;
procedure InternalPushState(FromStateItem, ToStateItem: TPppStateItem); virtual;
function PeekStateItem: TPppStateItem;
function GetOptions: TPppOptions;
procedure SetOptions(AOptions: TPppOptions);
function FindMacro(const AMacroName: string): IJclStrList;
function AssociateParameters(const ParamNames: IJclStrList;
const ParamValues: TDynStringArray): TDynWideStringArray;
function GetBoolValue(const Name: string): Boolean; override;
function GetDefine(const ASymbol: string): TTriState; override;
function GetIntegerValue(const Name: string): Integer; override;
function GetStringValue(const Name: string): string; override;
procedure SetBoolValue(const Name: string; Value: Boolean); override;
procedure SetDefine(const ASymbol: string; const Value: TTriState); override;
procedure SetIntegerValue(const Name: string; Value: Integer); override;
procedure SetStringValue(const Name, Value: string); override;
public
constructor Create;
destructor Destroy; override;
procedure AfterConstruction; override;
{ PushState is called at the start of every unit, and PopState at the
end. This means that any declarations like $DEFINE will be file-local
in scope. }
procedure PushState;
procedure PopState;
property TriState: TTriState read InternalPeekTriState write InternalSetTriState;
procedure Define(const ASymbol: string);
procedure Undef(const ASymbol: string);
function FindFile(const AName: string): TStream;
procedure AddToSearchPath(const AName: string);
procedure AddFileToExclusionList(const AName: string);
function IsFileExcluded(const AName: string): Boolean;
function ExpandMacro(const AName: string; const ParamValues: TDynStringArray): string; virtual;
procedure DefineMacro(const AName: string; const ParamNames: TDynStringArray;
const Value: string);
procedure UndefMacro(const AName: string; const ParamNames: TDynStringArray);
property Options: TPppOptions read GetOptions write SetOptions;
end;
TPppStateClass = class of TPppState;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JCL\source\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
uses
{$IFDEF HAS_UNITSCOPE}
System.TypInfo,
{$ELSE ~HAS_UNITSCOPE}
TypInfo,
{$ENDIF ~HAS_UNITSCOPE}
JclStrings, JclStreams, JclSysUtils, JclArrayLists, JclHashMaps, JclStacks;
function AllWhiteSpace(P: PChar; KeepTabAndSpaces: Boolean): Boolean;
var
I: Integer;
begin
Result := True;
for I := 1 to StrLen(P) do
case P^ of
NativeTab, NativeSpace:
if KeepTabAndSpaces then
begin
Result := False;
Break;
end
else
Inc(P);
NativeLineFeed, NativeCarriageReturn:
Inc(P);
else
Result := False;
Break;
end;
end;
function ParseMacro(const MacroText: string; var MacroName: string; var ParamNames: TDynStringArray;
ParamDeclaration: Boolean): Integer;
var
I, J: Integer;
Comment: Boolean;
ParenthesisCount: Integer;
MacroTextLen: Integer;
MacroParenthesis, MacroBracket: Boolean;
begin
MacroTextLen := Length(MacroText);
I := 1;
while (I <= MacroTextLen) and not CharIsSpace(MacroText[I]) do
Inc(I);
while (I <= MacroTextLen) and CharIsSpace(MacroText[I]) do
Inc(I);
J := I;
while (J <= MacroTextLen) and CharIsValidIdentifierLetter(MacroText[J]) do
Inc(J);
MacroName := Copy(MacroText, I, J - I);
if J <= MacroTextLen then
begin
SetLength(ParamNames, 0);
MacroParenthesis := MacroText[J] = '(';
MacroBracket := MacroText[J] = '[';
if MacroParenthesis or MacroBracket then
begin
Inc(J);
if ParamDeclaration then
begin
repeat
while (J <= MacroTextLen) and CharIsSpace(MacroText[J]) do
Inc(J);
I := J;
while (I <= MacroTextLen) and CharIsValidIdentifierLetter(MacroText[I]) do
Inc(I);
SetLength(ParamNames, Length(ParamNames) + 1);
ParamNames[High(ParamNames)] := Copy(MacroText, J, I - J);
while (I <= MacroTextLen) and CharIsSpace(MacroText[I]) do
Inc(I);
if (I <= MacroTextLen) then
begin
if MacroParenthesis then
case MacroText[I] of
',':
Inc(I);
')': ;
else
raise EPppParserError.CreateFmt('invalid parameter declaration in macro "%s"', [MacroText]);
end;
if MacroBracket then
case MacroText[I] of
'|':
Inc(I);
']': ;
else
raise EPppParserError.CreateFmt('invalid parameter declaration in macro "%s"', [MacroText]);
end;
end;
J := I;
until (J > MacroTextLen) or (MacroParenthesis and (MacroText[J] = ')')) or (MacroBracket and (MacroText[J] = ']'));
end
else
begin
repeat
I := J;
Comment := False;
ParenthesisCount := 0;
while I <= MacroTextLen do
begin
case MacroText[I] of
NativeSingleQuote:
Comment := not Comment;
'(':
if not Comment then
Inc(ParenthesisCount);
')':
begin
if MacroParenthesis and (not Comment) and (ParenthesisCount = 0) then
Break;
if not Comment then
Dec(ParenthesisCount);
end;
']':
if MacroBracket and (not Comment) and (ParenthesisCount = 0) then
Break;
NativeBackslash:
if (not Comment) and (ParenthesisCount = 0) and (I < MacroTextLen) and (MacroText[i + 1] = NativeComma) then
Inc(I);
NativeComma:
if MacroParenthesis and (not Comment) and (ParenthesisCount = 0) then
Break;
'|':
if MacroBracket and (not Comment) and (ParenthesisCount = 0) then
Break;
end;
Inc(I);
end;
SetLength(ParamNames, Length(ParamNames) + 1);
ParamNames[High(ParamNames)] := Copy(MacroText, J, I - J);
StrReplace(ParamNames[High(ParamNames)], '\,', ',', [rfReplaceAll]);
if MacroParenthesis then
begin
if (I < MacroTextLen) and (MacroText[I] = ')') then
begin
J := I;
Break;
end;
if (I < MacroTextLen) and (MacroText[I] = ',') then
Inc(I);
end;
if MacroBracket then
begin
if (I < MacroTextLen) and (MacroText[I] = ']') then
begin
J := I;
Break;
end;
if (I < MacroTextLen) and (MacroText[I] = '|') then
Inc(I);
end;
J := I;
until J > MacroTextLen;
end;
if J <= MacroTextLen then
begin
if MacroParenthesis and (MacroText[J] = ')') then
Inc(J) // skip )
else
if MacroBracket and (MacroText[J] = ']') then
Inc(J) // skip ]
else
raise EPppParserError.CreateFmt('Unterminated list of arguments for macro "%s"', [MacroText]);
end;
end
else
begin
while (J <= MacroTextLen) and CharIsSpace(MacroText[J]) do
Inc(J);
end;
end;
Result := J;
end;
{ TJppParser }
constructor TJppParser.Create(const ABuffer: string; APppState: TPppState);
begin
inherited Create;
Assert(APppState <> nil);
FLexer := TJppLexer.Create(ABuffer, poIgnoreUnterminatedStrings in APppState.Options);
FState := APppState;
FState.Undef('PROTOTYPE');
end;
destructor TJppParser.Destroy;
begin
FLexer.Free;
inherited Destroy;
end;
procedure TJppParser.AddResult(const S: string; FixIndent, ForceRecurseTest: Boolean);
var
I, J: Integer;
LinePrefix, AResult, Line: string;
TempMemoryStream: TMemoryStream;
TempStringStream: TJclAutoStream;
TempLexer: TJppLexer;
TempParser: TJppParser;
Lines: TStrings;
Recurse: Boolean;
begin
if State.TriState = ttUndef then
Exit;
AResult := S;
// recurse macro expanding
if (AResult <> '') and (ForceRecurseTest or (StrIPos('$JPP', AResult) > 0)) then
begin
try
Recurse := False;
TempLexer := TJppLexer.Create(AResult, poIgnoreUnterminatedStrings in State.Options);
try
State.PushState;
while True do
begin
case TempLexer.CurrTok of
ptEof:
Break;
ptDefine,
ptJppDefine,
ptUndef,
ptJppUndef:
if poProcessDefines in State.Options then
begin
Recurse := True;
Break;
end;
ptIfdef, ptIfndef:
if (poProcessDefines in State.Options) and (State.Defines[TempLexer.TokenAsString] in [ttDefined, ttUndef]) then
begin
Recurse := True;
Break;
end;
ptJppDefineMacro,
ptJppExpandMacro,
ptJppUndefMacro:
if poProcessMacros in State.Options then
begin
Recurse := True;
Break;
end;
ptJppGetStrValue,
ptJppGetIntValue,
ptJppGetBoolValue,
ptJppSetStrValue,
ptJppSetIntValue,
ptJppSetBoolValue,
ptJppLoop:
if poProcessValues in State.Options then
begin
Recurse := True;
Break;
end;
end;
TempLexer.NextTok;
end;
finally
State.PopState;
TempLexer.Free;
end;
if Recurse then
begin
TempMemoryStream := TMemoryStream.Create;
try
TempStringStream := TJclAutoStream.Create(TempMemoryStream);
try
TempStringStream.WriteString(AResult, 1, Length(AResult));
TempStringStream.Seek(0, soBeginning);
TempParser := TJppParser.Create(TempStringStream.ReadString, State);
try
AResult := TempParser.Parse;
finally
TempParser.Free;
end;
finally
TempStringStream.Free;
end;
finally
TempMemoryStream.Free;
end;
end;
except
// The text might not be well-formed Pascal source and
// thus exceptions might be raised, in such case, just add the text without recursion
AResult := S;
end;
end;
if FixIndent and (AResult <> '') then
begin
// find the number of white space at the beginning of the current line (indentation level)
I := FResultLen + 1;
while (I > 1) and not CharIsReturn(FResult[I - 1]) do
Dec(I);
J := I;
while (J <= FResultLen) and CharIsWhiteSpace(FResult[J]) do
Inc(J);
LinePrefix := StrRepeat(NativeSpace, J - I);
Lines := TStringList.Create;
try
StrToStrings(AResult, NativeLineBreak, Lines);
if not (poKeepTabAndSpaces in State.Options) then
begin
// remove first empty lines
while Lines.Count > 0 do
begin
if Lines.Strings[0] = '' then
Lines.Delete(0)
else
Break;
end;
// remove last empty lines
for I := Lines.Count - 1 downto 0 do
begin
if Lines.Strings[I] = '' then
Lines.Delete(I)
else
Break;
end;
end;
// fix line offsets
if LinePrefix <> '' then
for I := 1 to Lines.Count - 1 do
begin
Line := Lines.Strings[I];
if Line <> '' then
Lines.Strings[I] := LinePrefix + Line;
end;
AResult := StringsToStr(Lines, NativeLineBreak);
finally
Lines.Free;
end;
end;
if AResult <> '' then
begin
while FResultLen + Length(AResult) > Length(FResult) do
SetLength(FResult, Length(FResult) * 2);
Move(AResult[1], FResult[FResultLen + 1], Length(AResult) * SizeOf(Char));
FAllWhiteSpaceOut := FAllWhiteSpaceOut and AllWhiteSpace(PChar(AResult), poKeepTabAndSpaces in State.Options);
Inc(FResultLen, Length(AResult));
end;
end;
function TJppParser.IsExcludedInclude(const FileName: string): Boolean;
begin
Result := State.IsFileExcluded(FileName);
end;
procedure TJppParser.NextToken;
begin
Lexer.NextTok;
if State.TriState = ttUndef then
Exit;
case Lexer.CurrTok of
ptEof, ptEol:
// do not change FAllWhiteSpaceIn
;
ptComment:
FAllWhiteSpaceIn := False;
ptText:
FAllWhiteSpaceIn := FAllWhiteSpaceIn and AllWhiteSpace(PChar(Lexer.TokenAsString), poKeepTabAndSpaces in State.Options);
ptDefine,
ptUndef,
ptIfdef,
ptIfndef,
ptIfopt,
ptElse,
ptEndif,
ptJppDefine,
ptJppUndef,
ptJppDefineMacro,
ptJppExpandMacro,
ptJppUndefMacro,
ptJppGetStrValue,
ptJppGetIntValue,
ptJppGetBoolValue,
ptJppSetStrValue,
ptJppSetIntValue,
ptJppSetBoolValue,
ptJppLoop:
FAllWhiteSpaceIn := False;
ptInclude:
FAllWhiteSpaceIn := IsExcludedInclude(Lexer.TokenAsString);
else
// Error
end;
end;
function TJppParser.Parse: string;
begin
FLexer.Reset;
SetLength(FResult, 64 * 1024);
FillChar(FResult[1], Length(FResult) * SizeOf(Char), 0);
FResultLen := 0;
FLineBreakPos := 1;
FAllWhiteSpaceOut := True;
ParseText;
SetLength(FResult, FResultLen);
Result := FResult;
end;
procedure TJppParser.ParseCondition(Token: TJppToken);
procedure PushAndExecute(NewTriState: TTriState);
var
NeedPush: Boolean;
begin
NeedPush := State.TriState <> NewTriState;
if NeedPush then
State.PushState;
try
State.TriState := NewTriState;
NextToken;
ParseText;
finally
if NeedPush then
State.PopState;
end;
end;
var
Condition: string;
ConditionTriState: TTriState;
begin
Condition := Lexer.TokenAsString;
ConditionTriState := State.Defines[Condition];
// parse the first part of the $IFDEF or $IFNDEF
case ConditionTriState of
ttUnknown:
begin
State.PushState;
try
// preserve the $IFDEF or $IFNDEF
AddResult(Lexer.RawComment);
// assume that the symbol is defined in the $IFDEF
if Token = ptIfdef then
State.Define(Condition)
else
// assume that the symbol is not defined in the $IFNDEF
if Token = ptIfndef then
State.Undef(Condition);
NextToken;
ParseText;
finally
State.PopState;
end;
end;
ttUndef:
if Token = ptIfdef then
PushAndExecute(ttUndef)
else
if Token = ptIfndef then
PushAndExecute(ttDefined);
ttDefined:
if Token = ptIfdef then
PushAndExecute(ttDefined)
else
if Token = ptIfndef then
PushAndExecute(ttUndef);
end;
// part the second part of the $IFDEF or $IFNDEF if any
if Lexer.CurrTok = ptElse then
begin
case ConditionTriState of
ttUnknown:
begin
State.PushState;
try
// preserve the $ELSE
AddResult(Lexer.RawComment);
// assume that the symbol is not defined after the $IFDEF
if Token = ptIfdef then
State.Undef(Condition)
else
// assume that the symbol is defined after the $IFNDEF
if Token = ptIfndef then
State.Define(Condition);
NextToken;
ParseText;
finally
State.PopState;
end;
end;
ttUndef:
begin
if Token = ptIfdef then
PushAndExecute(ttDefined)
else
if Token = ptIfndef then
PushAndExecute(ttUndef);
//State.Defines[Condition] := ttDefined;
end;
ttDefined:
begin
if Token = ptIfdef then
PushAndExecute(ttUndef)
else
if Token = ptIfndef then
PushAndExecute(ttDefined);
//State.Defines[Condition] := ttUndef;
end;
end;
end;
if Lexer.CurrTok <> ptEndif then
Lexer.Error('$ENDIF expected');
case ConditionTriState of
ttUnknown:
// preserve the $ENDIF
AddResult(Lexer.RawComment);
ttUndef: ;
ttDefined: ;
end;
NextToken;
end;
procedure TJppParser.ParseDefine(Skip: Boolean);
var
Condition: string;
begin
Condition := Lexer.TokenAsString;
case State.Defines[Condition] of
// the symbol is not defined
ttUnknown,
ttUndef:
begin
State.Defines[Lexer.TokenAsString] := ttDefined;
if not Skip then
AddResult(Lexer.RawComment);
end;
// the symbol is already defined, always skip it
ttDefined: ;
end;
NextToken;
end;
procedure TJppParser.ParseDefineMacro;
var
I, J: Integer;
MacroText, MacroName, MacroValue: string;
ParamNames: TDynStringArray;
begin
MacroText := Lexer.TokenAsString;
I := ParseMacro(MacroText, MacroName, ParamNames, True);
if I <= Length(MacroText) then
begin
if Copy(MacroText, I, Length(NativeLineBreak)) = NativeLineBreak then
Inc(I, Length(NativeLineBreak));
J := Length(MacroText);
if MacroText[J] = ')' then
Dec(J);
MacroValue := Copy(MacroText, I, J - I);
State.DefineMacro(MacroName, ParamNames, MacroValue);
end;
NextToken;
end;
procedure TJppParser.ParseExpandMacro;
var
MacroText, MacroName, AResult: string;
ParamNames: TDynStringArray;
begin
MacroText := Lexer.TokenAsString;
ParseMacro(MacroText, MacroName, ParamNames, False);
// macros are expanded in a sub-state
State.PushState;
try
AResult := State.ExpandMacro(MacroName, ParamNames);
// add result to buffer
AddResult(AResult, True, True);
finally
State.PopState;
end;
NextToken;
end;
procedure TJppParser.ParseUndef(Skip: Boolean);
var
Condition: string;
begin
Condition := Lexer.TokenAsString;
case State.Defines[Condition] of
// the symbol is not defined
ttUnknown,
ttDefined:
begin
State.Defines[Lexer.TokenAsString] := ttUndef;
if not Skip then
AddResult(Lexer.RawComment);
end;
// the symbol is already defined, skip it
ttUndef: ;
end;
NextToken;
end;
procedure TJppParser.ParseUndefMacro;
var
MacroText, MacroName: string;
ParamNames: TDynStringArray;
begin
MacroText := Lexer.TokenAsString;
ParseMacro(MacroText, MacroName, ParamNames, True);
State.UndefMacro(MacroName, ParamNames);
NextToken;
end;
function TJppParser.ParseInclude: string;
var
oldLexer, newLexer: TJppLexer;
fsIn: TStream;
ssIn: TJclAutoStream;
begin
Result := '';
Assert(Lexer.TokenAsString <> '');
{ we must prevent case of $I- & $I+ becoming file names }
if (Lexer.TokenAsString[1] = '-')
or (Lexer.TokenAsString[1] = '+')
or IsExcludedInclude(Lexer.TokenAsString) then
Result := Lexer.RawComment
else
begin
fsIn := nil;
ssIn := nil;
newLexer := nil;
oldLexer := Lexer;
try
try
fsIn := FState.FindFile(Lexer.TokenAsString);
except
on e: Exception do
Lexer.Error(e.Message);
end;
ssIn := TJclAutoStream.Create(fsIn);
newLexer := TJppLexer.Create(ssIn.ReadString, poIgnoreUnterminatedStrings in State.Options);
FLexer := newLexer;
ParseText;
finally
FLexer := oldLexer;
ssIn.Free;
fsIn.Free;
newLexer.Free;
end;
end;
NextToken;
end;
procedure TJppParser.ParseGetStrValue;
var
Name: string;
begin
Name := Lexer.TokenAsString;
AddResult(State.StringValues[Name]);
NextToken;
end;
procedure TJppParser.ParseGetIntValue;
var
Name: string;
begin
Name := Lexer.TokenAsString;
AddResult(IntToStr(State.IntegerValues[Name]));
NextToken;
end;
procedure TJppParser.ParseGetBoolValue;
var
Name: string;
begin
Name := Lexer.TokenAsString;
AddResult(BoolToStr(State.BoolValues[Name], True));
NextToken;
end;
procedure TJppParser.ParseLoop;
var
I, J, RepeatIndex, RepeatCount: Integer;
RepeatText, IndexName, CountName: string;
begin
I := 1;
RepeatText := Lexer.RawComment;
while (I <= Length(RepeatText)) and not CharIsWhiteSpace(RepeatText[I]) do
Inc(I);
while (I <= Length(RepeatText)) and CharIsWhiteSpace(RepeatText[I]) do
Inc(I);
J := I;
while (J <= Length(RepeatText)) and CharIsValidIdentifierLetter(RepeatText[J]) do
Inc(J);
IndexName := Copy(RepeatText, I, J - I);
while (J <= Length(RepeatText)) and CharIsWhiteSpace(RepeatText[J]) do
Inc(J);
I := J;
while (J <= Length(RepeatText)) and CharIsValidIdentifierLetter(RepeatText[I]) do
Inc(I);
CountName := Copy(RepeatText, J, I - J);
J := Length(RepeatText);
if RepeatText[J] = ')' then
Dec(J);
RepeatText := Copy(RepeatText, I, J - I);
RepeatCount := State.IntegerValues[CountName];
for RepeatIndex := 0 to RepeatCount - 1 do
begin
State.IntegerValues[IndexName] := RepeatIndex;
AddResult(RepeatText);
end;
State.IntegerValues[IndexName] := -1;
NextToken;
end;
procedure TJppParser.ParseSetStrValue;
var
I, J: Integer;
Text, Name, Value: string;
begin
I := 1;
Text := Lexer.RawComment;
while (I <= Length(Text)) and not CharIsWhiteSpace(Text[I]) do
Inc(I);
while (I <= Length(Text)) and CharIsWhiteSpace(Text[I]) do
Inc(I);
J := I;
while (J <= Length(Text)) and CharIsValidIdentifierLetter(Text[J]) do
Inc(J);
Name := Copy(Text, I, J - I);
while (J <= Length(Text)) and CharIsWhiteSpace(Text[J]) do
Inc(J);
I := Length(Text);
if Text[I] = ')' then
Dec(I);
Value := Copy(Text, J, I - J);
State.StringValues[Name] := Value;
NextToken;
end;
procedure TJppParser.ParseSetIntValue;
var
I, J: Integer;
Text, Name, Value: string;
begin
I := 1;
Text := Lexer.RawComment;
while (I <= Length(Text)) and not CharIsWhiteSpace(Text[I]) do
Inc(I);
while (I <= Length(Text)) and CharIsWhiteSpace(Text[I]) do
Inc(I);
J := I;
while (J <= Length(Text)) and CharIsValidIdentifierLetter(Text[J]) do
Inc(J);
Name := Copy(Text, I, J - I);
while (J <= Length(Text)) and CharIsWhiteSpace(Text[J]) do
Inc(J);
I := Length(Text);
if Text[I] = ')' then
Dec(I);
Value := Copy(Text, J, I - J);
State.IntegerValues[Name] := StrToInt(Value);
NextToken;
end;
procedure TJppParser.ParseSetBoolValue;
var
I, J: Integer;
Text, Name, Value: string;
begin
I := 1;
Text := Lexer.RawComment;
while (I <= Length(Text)) and not CharIsWhiteSpace(Text[I]) do
Inc(I);
while (I <= Length(Text)) and CharIsWhiteSpace(Text[I]) do
Inc(I);
J := I;
while (J <= Length(Text)) and CharIsValidIdentifierLetter(Text[J]) do
Inc(J);
Name := Copy(Text, I, J - I);
while (J <= Length(Text)) and CharIsWhiteSpace(Text[J]) do
Inc(J);
I := Length(Text);
if Text[I] = ')' then
Dec(I);
Value := Copy(Text, J, I - J);
State.BoolValues[Name] := StrToBoolean(Value);
NextToken;
end;
procedure TJppParser.ParseText;
procedure AddRawComment;
begin
AddResult(Lexer.RawComment);
NextToken;
end;
procedure DeleteCurrentLineIfOrphaned;
begin
if not FAllWhiteSpaceIn and FAllWhiteSpaceOut then
if FLineBreakPos <= FResultLen then
begin
FResultLen := FLineBreakPos - 1;
FResult[FResultLen + 1] := #0;
end;
end;
begin
while True do
case Lexer.CurrTok of
ptComment:
begin
if not (poStripComments in State.Options) then
AddResult(Lexer.TokenAsString);
NextToken;
end;
ptEof:
begin
DeleteCurrentLineIfOrphaned;
Break;
end;
ptEol:
begin
AddResult(Lexer.TokenAsString);
DeleteCurrentLineIfOrphaned;
FLineBreakPos := FResultLen + 1;
FAllWhiteSpaceIn := True;
FAllWhiteSpaceOut := True;
NextToken;
end;
ptText:
begin
AddResult(Lexer.TokenAsString);
NextToken;
end;
ptDefine, ptJppDefine, ptUndef, ptJppUndef, ptIfdef, ptIfndef, ptIfopt:
if poProcessDefines in State.Options then
case Lexer.CurrTok of
ptDefine:
ParseDefine(False);
ptJppDefine:
ParseDefine(True);
ptUndef:
ParseUndef(False);
ptJppUndef:
ParseUndef(True);
ptIfdef:
ParseCondition(ptIfdef);
ptIfndef:
ParseCondition(ptIfndef);
ptIfopt:
ParseCondition(ptIfopt);
end
else
AddRawComment;
ptElse, ptEndif:
if poProcessDefines in State.Options then
Break
else
AddRawComment;
ptInclude:
if poProcessIncludes in State.Options then
AddResult(ParseInclude)
else
AddRawComment;
ptJppDefineMacro, ptJppExpandMacro, ptJppUndefMacro:
if State.TriState = ttUndef then
NextToken
else
if poProcessMacros in State.Options then
case Lexer.CurrTok of
ptJppDefineMacro:
ParseDefineMacro;
ptJppExpandMacro:
ParseExpandMacro;
ptJppUndefMacro:
ParseUndefMacro;
end
else
AddRawComment;
ptJppGetStrValue,
ptJppGetIntValue,
ptJppGetBoolValue,
ptJppSetStrValue,
ptJppSetIntValue,
ptJppSetBoolValue,
ptJppLoop:
if State.TriState = ttUndef then
NextToken
else
if poProcessValues in State.Options then
case Lexer.CurrTok of
ptJppGetStrValue:
ParseGetStrValue;
ptJppGetIntValue:
ParseGetIntValue;
ptJppGetBoolValue:
ParseGetBoolValue;
ptJppSetStrValue:
ParseSetStrValue;
ptJppSetIntValue:
ParseSetIntValue;
ptJppSetBoolValue:
ParseSetBoolValue;
ptJppLoop:
ParseLoop;
end
else
AddRawComment;
else
Break;
end;
end;
//=== { TPppState } ==========================================================
constructor TPppState.Create;
begin
inherited Create;
FStateStack := TJclStack.Create(16, True);
end;
destructor TPppState.Destroy;
begin
FStateStack := nil;
inherited Destroy;
end;
procedure TPppState.AddFileToExclusionList(const AName: string);
begin
InternalPeekExcludedFiles.Add(AName);
end;
procedure TPppState.AddToSearchPath(const AName: string);
begin
InternalPeekSearchPath.Add(AName);
end;
procedure TPppState.AfterConstruction;
var
StateItem: TPppStateItem;
begin
StateItem := StateItemClass.Create;
InternalPushState(nil, StateItem);
FStateStack.Push(StateItem);
end;
function TPppState.AssociateParameters(const ParamNames: IJclStrList;
const ParamValues: TDynStringArray): TDynWideStringArray;
var
StrParams: TStrings;
AssociationByName: Boolean;
Index, ParamIndex: Integer;
AParamName, AParamText: string;
begin
SetLength(Result, Length(ParamValues));
AssociationByName := True;
StrParams := TStringList.Create;
try
for Index := Low(ParamValues) to High(ParamValues) do
begin
StrParams.Add(ParamValues[Index]);
AParamName := StrParams.Names[Index];
if Assigned(ParamNames) and (AParamName <> '') then
begin
// verify parameter names
ParamIndex := ParamNames.IndexOf(AParamName);
if ParamIndex < 0 then
AssociationByName := False;
end
else
AssociationByName := False;
end;
for Index := Low(ParamValues) to High(ParamValues) do
begin
if AssociationByName then
AParamText := StrParams.Values[ParamNames.Strings[Index]]
else
AParamText := StrParams.Strings[Index];
Result[Index] := WideString(AParamText);
end;
finally
StrParams.Free;
end;
end;
function TPppState.ExpandMacro(const AName: string;
const ParamValues: TDynStringArray): string;
var
AMacro: IJclStrList;
AMacroName, AMacroText: string;
Index: Integer;
Params: array of TVarRec;
AMacroParams: TDynWideStringArray;
begin
AMacroName := Format('%s`%d', [AName, Length(ParamValues)]);
AMacro := FindMacro(AMacroName);
// the macro text is the last item, previous items are the macro parameter names
AMacroText := AMacro.Strings[AMacro.Size - 1];
AMacroParams := AssociateParameters(AMacro.SubList(0, AMacro.Size - 1), ParamValues);
SetLength(Params, Length(ParamValues));
for Index := Low(ParamValues) to High(ParamValues) do
begin
Params[Index].VType := vtPWideChar;
Params[Index].VPWideChar := PWideChar(AMacroParams[Index]);
end;
Result := Format(AMacroText, Params);
end;
procedure TPppState.Define(const ASymbol: string);
begin
Defines[ASymbol] := ttDefined;
end;
procedure TPppState.DefineMacro(const AName: string;
const ParamNames: TDynStringArray; const Value: string);
var
AMacro: IJclStrList;
AMacros: IJclStrIntfMap;
AMacroNames: IJclStrIterator;
AMacroName, AMacroFormat: string;
Index: Integer;
begin
AMacros := InternalPeekMacros;
AMacroName := Format('%s`%d', [AName, Length(ParamNames)]);
AMacroNames := AMacros.KeySet.First;
while AMacroNames.HasNext do
if JclStrings.StrSame(AMacroNames.Next, AMacroName) then
raise EPppState.CreateFmt('macro "%s" is already defined', [AName]);
AMacroFormat := Value;
AMacro := TJclStrArrayList.Create(16);
for Index := Low(ParamNames) to High(ParamNames) do
begin
StrReplace(AMacroFormat, ParamNames[Index], '%' + IntToStr(Index) + ':s', [rfReplaceAll, rfIgnoreCase]);
// the first elements in the list are the macro parameter names
AMacro.Add(ParamNames[Index]);
end;
// the macro text is the last element in the list
AMacro.Add(AMacroFormat);
AMacros.Items[AMacroName] := AMacro;
end;
function TPppState.FindFile(const AName: string): TStream;
var
i: Integer;
fn: string;
Found: Boolean;
ASearchPath: IJclStrList;
begin
ASearchPath := InternalPeekSearchPath;
fn := AName;
Found := FileExists(fn);
if not Found then
for i := 0 to ASearchPath.Size - 1 do
begin
fn := ASearchPath.Strings[i] + PathDelim + AName;
if FileExists(fn) then
begin
Found := True;
Break;
end;
end;
if not Found then
raise EPppState.CreateFmt('File not found: %s', [AName]);
Result := TFileStream.Create(fn, fmOpenRead or fmShareDenyWrite);
end;
function TPppState.FindMacro(const AMacroName: string): IJclStrList;
var
AMacros: IJclStrIntfMap;
AMacroNames: IJclStrIterator;
begin
AMacros := InternalPeekMacros;
AMacroNames := AMacros.KeySet.First;
while AMacroNames.HasNext do
begin
if JclStrings.StrSame(AMacroNames.Next, AMacroName) then
begin
Result := AMacros.Items[AMacroNames.GetString] as IJclStrList;
Exit;
end;
end;
raise EPppState.CreateFmt('unknown macro "%s"', [AMacroName]);
end;
function TPppState.GetBoolValue(const Name: string): Boolean;
var
VariantValue: Variant;
begin
VariantValue := GetPropValue(Self, Name);
Result := Boolean(VariantValue);
end;
function TPppState.GetIntegerValue(const Name: string): Integer;
var
VariantValue: Variant;
begin
VariantValue := GetPropValue(Self, Name);
Result := Integer(VariantValue);
end;
function TPppState.GetStringValue(const Name: string): string;
var
VariantValue: Variant;
begin
VariantValue := GetPropValue(Self, Name, True);
Result := string(VariantValue);
end;
function TPppState.GetOptions: TPppOptions;
begin
Result := FOptions;
end;
function TPppState.GetDefine(const ASymbol: string): TTriState;
var
ADefines: IJclStrMap;
ASymbolNames: IJclStrIterator;
PI: PPropInfo;
PV: Variant;
begin
Result := ttUnknown;
ADefines := InternalPeekDefines;
ASymbolNames := ADefines.KeySet.First;
while ASymbolNames.HasNext do
begin
if JclStrings.StrSame(ASymbolNames.Next, ASymbol) then
begin
Result := TTriState(ADefines.Items[ASymbolNames.GetString]);
Break;
end;
end;
if Result = ttUnknown then
begin
PI := GetPropInfo(Self, ASymbol);
if Assigned(PI) then
begin
{$IFDEF COMPILER8_UP}
PV := GetPropValue(Self, PI);
{$ELSE ~COMPILER8_UP}
PV := GetPropValue(Self, PI^.Name);
{$ENDIF ~COMPILER8_UP}
if Boolean(PV) then
Result := ttDefined
else
Result := ttUndef;
end;
end;
end;
function TPppState.InternalPeekDefines: IJclStrMap;
begin
Result := PeekStateItem.DefinedKeywords;
end;
function TPppState.InternalPeekExcludedFiles: IJclStrList;
begin
Result := PeekStateItem.ExcludedFiles;
end;
function TPppState.InternalPeekMacros: IJclStrIntfMap;
begin
Result := PeekStateItem.Macros;
end;
function TPppState.InternalPeekSearchPath: IJclStrList;
begin
Result := PeekStateItem.SearchPath;
end;
function TPppState.InternalPeekTriState: TTriState;
begin
Result := PeekStateItem.TriState;
end;
procedure TPppState.InternalPushState(FromStateItem, ToStateItem: TPppStateItem);
begin
if Assigned(FromStateItem) then
begin
// clone
ToStateItem.DefinedKeywords := (FromStateItem.DefinedKeywords as IJclIntfCloneable).IntfClone as IJclStrMap;
ToStateItem.ExcludedFiles := (FromStateItem.ExcludedFiles as IJclIntfCloneable).IntfClone as IJclStrList;
ToStateItem.Macros := (FromStateItem.Macros as IJclIntfCloneable).IntfClone as IJclStrIntfMap;
ToStateItem.SearchPath := (FromStateItem.SearchPath as IJclIntfCloneable).IntfClone as IJclStrList;
ToStateItem.TriState := FromStateItem.TriState;
end
else
begin
// create the first item
ToStateItem.DefinedKeywords := TJclStrHashMap.Create(16, False);
ToStateItem.ExcludedFiles := TJclStrArrayList.Create(16);
ToStateItem.Macros := TJclStrIntfHashMap.Create(16);
ToStateItem.SearchPath := TJclStrArrayList.Create(16);
ToStateItem.TriState := ttDefined;
end;
end;
procedure TPppState.InternalSetTriState(Value: TTriState);
var
APppStateItem: TPppStateItem;
begin
APppStateItem := PeekStateItem;
if APppStateItem.TriState <> ttUndef then
APppStateItem.TriState := Value;
end;
function TPppState.IsFileExcluded(const AName: string): Boolean;
var
AExcludedFiles: IJclStrList;
AFileNames: IJclStrIterator;
begin
AExcludedFiles := InternalPeekExcludedFiles;
AFileNames := AExcludedFiles.First;
Result := False;
while AFileNames.HasNext do
begin
if JclStrings.StrSame(AFileNames.Next, AName) then
begin
Result := True;
Break;
end;
end;
end;
function TPppState.PeekStateItem: TPppStateItem;
begin
if FStateStack.Empty then
raise EPppState.Create('Internal error: PPP State stack is empty');
Result := FStateStack.Peek as TPppStateItem;
end;
procedure TPppState.PopState;
begin
if FStateStack.Size <= 1 then
raise EPppState.Create('Internal error: PPP State stack underflow');
FStateStack.Pop.Free;
end;
procedure TPppState.PushState;
var
FromStateItem, ToStateItem: TPppStateItem;
begin
FromStateItem := PeekStateItem;
ToStateItem := StateItemClass.Create;
InternalPushState(FromStateItem, ToStateItem);
FStateStack.Push(ToStateItem);
end;
procedure TPppState.SetOptions(AOptions: TPppOptions);
begin
FOptions := AOptions;
end;
procedure TPppState.SetBoolValue(const Name: string; Value: Boolean);
var
VariantValue: Variant;
begin
VariantValue := Value;
SetPropValue(Self, Name, VariantValue);
end;
procedure TPppState.SetDefine(const ASymbol: string;
const Value: TTriState);
var
ADefines: IJclStrMap;
ASymbolNames: IJclStrIterator;
PI: PPropInfo;
begin
ADefines := InternalPeekDefines;
ASymbolNames := ADefines.KeySet.First;
while ASymbolNames.HasNext do
begin
if JclStrings.StrSame(ASymbolNames.Next, ASymbol) then
begin
ADefines.Items[ASymbolNames.GetString] := TObject(Value);
Exit;
end;
end;
if Value <> ttUnknown then
begin
PI := GetPropInfo(Self, ASymbol);
if Assigned(PI) then
begin
if Value = ttDefined then
{$IFDEF COMPILER8_UP}
SetPropValue(Self, PI, True)
{$ELSE ~COMPILER8_UP}
SetPropValue(Self, PI^.Name, True)
{$ENDIF ~COMPILER8_UP}
else
{$IFDEF COMPILER8_UP}
SetPropValue(Self, PI, False);
{$ELSE ~COMPILER8_UP}
SetPropValue(Self, PI^.Name, False);
{$ENDIF ~COMPILER8_UP}
Exit;
end;
end;
ADefines.Items[ASymbol] := TObject(Value);
end;
procedure TPppState.SetIntegerValue(const Name: string; Value: Integer);
var
VariantValue: Variant;
begin
VariantValue := Value;
SetPropValue(Self, Name, VariantValue);
end;
procedure TPppState.SetStringValue(const Name, Value: string);
var
VariantValue: Variant;
begin
VariantValue := Value;
SetPropValue(Self, Name, VariantValue);
end;
class function TPppState.StateItemClass: TPppStateItemClass;
begin
Result := TPppStateItem;
end;
procedure TPppState.Undef(const ASymbol: string);
begin
Defines[ASymbol] := ttUndef;
end;
procedure TPppState.UndefMacro(const AName: string; const ParamNames: TDynStringArray);
var
AMacros: IJclStrIntfMap;
AMacroNames: IJclStrIterator;
AMacroName: string;
begin
AMacros := InternalPeekMacros;
AMacroName := Format('%s`%d', [AName, Length(ParamNames)]);
AMacroNames := AMacros.KeySet.First;
while AMacroNames.HasNext do
if JclStrings.StrSame(AMacroNames.Next, AMacroName) then
AMacros.Remove(AMacroNames.GetString);
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 29.736909 | 127 | 0.605054 |
c3c6e6f79457d4e4126f7aaeadf726f35a9f1177 | 3,893 | pas | Pascal | windows/src/engine/kmcomapi/util/utilkeymancontrol.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/engine/kmcomapi/util/utilkeymancontrol.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/engine/kmcomapi/util/utilkeymancontrol.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | (*
Name: utilkeymancontrol
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 20 Jun 2006
Modified Date: 25 Oct 2016
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 20 Jun 2006 - mcdurdin - Initial version
01 Aug 2006 - mcdurdin - Add HideVisualKeyboard and ShowVisualKeyboard
14 Sep 2006 - mcdurdin - Get path of kmcomapi.dll, not calling application
04 Dec 2006 - mcdurdin - Support running as elevated in Vista
16 May 2007 - mcdurdin - Return extra information if Keyman unable to start
30 May 2007 - mcdurdin - Refactor OS checks for newer OS versions
27 Mar 2008 - mcdurdin - Use the first active product for control when no product passed
12 Mar 2010 - mcdurdin - I2230 - Resolve crashes due to incorrect reference counting
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
18 May 2012 - mcdurdin - I3331 - V9.0 - Remove koRunElevatedInVista option
08 Jun 2012 - mcdurdin - I3349 - V9.0 - Consolidate all process creation into TUtilExecute
25 Oct 2016 - mcdurdin - I5125 - Failure to start Keyman due to path errors
*)
unit utilkeymancontrol;
interface
uses Windows, custinterfaces, keymanapi_TLB;
type
TKeymanController = class
private
FKeyman: TObject;
procedure ControlKeyman(const code: string);
public
constructor Create(AKeyman: TObject);
procedure StartKeyman;
procedure StopKeyman;
procedure ShowVisualKeyboard;
procedure HideVisualKeyboard;
end;
implementation
uses
System.SysUtils,
System.Variants,
ErrorControlledRegistry,
RegistryKeys,
keymanerrorcodes,
GetOsVersion,
KeymanOptionNames,
keymanpaths,
utilexecute,
keyman_implementation;
{ TKeymanController }
constructor TKeymanController.Create(AKeyman: TObject);
begin
inherited Create;
FKeyman := AKeyman;
end;
procedure TKeymanController.StartKeyman;
begin
ControlKeyman('start');
end;
procedure TKeymanController.StopKeyman;
begin
ControlKeyman('stop');
end;
procedure TKeymanController.ControlKeyman(const code: string);
var
verb, path: string;
hwnd: THandle;
begin
path := TKeymanPaths.KeymanEngineInstallPath(TKeymanPaths.S_KeymanExe);
if not FileExists(path) then
begin
(FKeyman as TKeyman).Errors.AddFmt(KMN_E_KeymanControl_CannotStartProduct, VarArrayOf([path, 'Keyman']), kesFatal);
Exit;
end;
hwnd := GetActiveWindow;
if hwnd = 0 then
hwnd := GetDesktopWindow;
if ((FKeyman as TKeyman).Options as IKeymanOptions).Items[koDebugging].Value = True then
begin
// We run Keyman elevated when Debugging mode is switched on. This is because starting a
// trace requires certain permissions which a normal user doesn't have (refer StartTrace
// documentation). This is also a good visual reminder to the user that Debugging is
// active and as it is slightly annoying to be prompted to elevate, will over time encourage
// them to switch it off again, which is good ;-)
verb := 'runas';
end
else
verb := 'open';
if not TUtilExecute.Shell(hwnd, path, ExtractFileDir(path), '-kmc '+code, SW_SHOWNORMAL, verb) then // I3349
(FKeyman as TKeyman).Errors.AddFmt(KMN_E_KeymanControl_CannotStartProduct, VarArrayOf([path + ' (error='+IntToStr(GetLastError)+','+SysErrorMessage(GetLastError)+')', 'Keyman']), kesFatal);
end;
procedure TKeymanController.HideVisualKeyboard;
begin
ControlKeyman('hidevisualkeyboard');
end;
procedure TKeymanController.ShowVisualKeyboard;
begin
ControlKeyman('showvisualkeyboard');
end;
end.
| 31.144 | 193 | 0.693296 |
6a52cf381090ae5d2f69331418199405d090b322 | 2,368 | pas | Pascal | transformer/FHIR.Transformer.ExceptionHandlerDlg.pas | rhausam/fhirserver | d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3 | [
"BSD-3-Clause"
]
| 132 | 2015-02-02T00:22:40.000Z | 2021-08-11T12:08:08.000Z | transformer/FHIR.Transformer.ExceptionHandlerDlg.pas | rhausam/fhirserver | d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3 | [
"BSD-3-Clause"
]
| 113 | 2015-03-20T01:55:20.000Z | 2021-10-08T16:15:28.000Z | transformer/FHIR.Transformer.ExceptionHandlerDlg.pas | rhausam/fhirserver | d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3 | [
"BSD-3-Clause"
]
| 49 | 2015-04-11T14:59:43.000Z | 2021-03-30T10:29:18.000Z | unit FHIR.Transformer.ExceptionHandlerDlg;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
{$I fhir.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, clipbrd;
type
TExceptionHandlerDialog = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Label1: TLabel;
eMessage: TLabel;
Button1: TButton;
Button2: TButton;
Label2: TLabel;
Label3: TLabel;
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ExceptionHandlerDialog: TExceptionHandlerDialog;
implementation
{$R *.DFM}
procedure TExceptionHandlerDialog.Button2Click(Sender: TObject);
begin
Clipboard.AsText := eMessage.Caption;
end;
end.
| 33.828571 | 98 | 0.754645 |
c3b0f60a520af8cc299b005f8a2b5f4c20090c04 | 6,528 | pas | Pascal | LoggerFormUnit.pas | mickyvac/fc-measure | 0b6db36af01f25479a956138cfceddd02a88d14d | [
"MIT"
]
| null | null | null | LoggerFormUnit.pas | mickyvac/fc-measure | 0b6db36af01f25479a956138cfceddd02a88d14d | [
"MIT"
]
| null | null | null | LoggerFormUnit.pas | mickyvac/fc-measure | 0b6db36af01f25479a956138cfceddd02a88d14d | [
"MIT"
]
| null | null | null | unit LoggerFormUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls,
Logger, FormGlobalConfig;
type
TLoggerForm = class(TForm)
PCLog: TPageControl;
TabProjectLog: TTabSheet;
TabWarningLog: TTabSheet;
TabErrorLog: TTabSheet;
MeProjLog: TMemo;
Button2: TButton;
BuClearProj: TButton;
Panel1: TPanel;
MeERRORlog: TMemo;
Panel2: TPanel;
MeWarningLog: TMemo;
BuClearWarning: TButton;
BuClearError: TButton;
BuResetWarning: TButton;
PanWarningCount: TPanel;
PanErrorCount: TPanel;
BuResetError: TButton;
Button1: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
BuHide: TButton;
Button7: TButton;
Button8: TButton;
TabReport: TTabSheet;
Button6: TButton;
Button9: TButton;
MeReport: TMemo;
procedure FormCreate(Sender: TObject);
procedure Init;
procedure Button2Click(Sender: TObject);
procedure BuHideClick(Sender: TObject);
procedure BuClearProjClick(Sender: TObject);
procedure BuClearWarningClick(Sender: TObject);
procedure BuClearErrorClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure BuResetWarningClick(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure BuResetErrorClick(Sender: TObject);
public //logging functions
procedure ProcessWarningErrorEventsLogMesages;
procedure LogProjectMsg(s: string);
procedure LogWarningMsg(s: string);
procedure LogErrorMsg(s: string);
procedure LogReportMsg(s: string);
private
{ Private declarations }
procedure UpdateDir;
procedure UpdateWarningCnt(n: longint);
procedure UpdateErrorCnt(n: longint);
function NowString: string; //returns actual datetime up to miliseconds
private
fWarningCnt: longint;
fErrorCnt: longint;
public
{ Public declarations }
property WarningCount: longint read fWarningCnt write UpdateWarningCnt;
property ErrorCount: longint read fErrorCnt write UpdateErrorCnt;
end;
var
LoggerForm: TLoggerForm;
implementation
uses FormProjectControl;
{$R *.dfm}
procedure TLoggerForm.FormCreate(Sender: TObject);
begin
LogMsg('TLoggerForm.FormCreate DONE.');
end;
procedure TLoggerForm.ProcessWarningErrorEventsLogMesages;
begin
if MsgQueueWarnings<>nil then
while not MsgQueueWarnings.IsEmpty do
LoggerForm.LogWarningMsg( MsgQueueWarnings.PopMsg );
//
if MsgQueueErrors<>nil then
while not MsgQueueErrors.IsEmpty do
LoggerForm.LogErrorMsg( MsgQueueErrors.PopMsg );
//
if MsgQueueProjectEvents<>nil then
while not MsgQueueProjectEvents.IsEmpty do
LoggerForm.LogProjectMsg( MsgQueueProjectEvents.PopMsg );
//
if MsgQueueResults<>nil then
while not MsgQueueResults.IsEmpty do
LoggerForm.LogReportMsg( MsgQueueResults.PopMsg );
end;
procedure TLoggerForm.Init;
Var
Pproc: TMsgProc;
begin
fWarningCnt := 0;
fErrorCnt := 0;
Panel2.Color := clOrange;
if ProjectControl = nil then exit;
ProjectControl.RegOnProjectUpdateMethod( UpdateDir );
UpdateDir;
LogMsg('TLoggerForm.Init DONE.');
end;
procedure TLoggerForm.UpdateDir;
Const
CprefProj = '!log_project_';
CprefReport = '!log_RESULTS_';
Csuff = '.txt';
Var
dir: string;
begin
if ProjectControl = nil then exit;
dir := ProjectControl.getProjPath; //placed in project directory
logmsg('TLoggerForm.UpdateDir - changing DIR, new dir is: '+ dir);
if LoggerProject<>nil then
begin
LoggerProject.LogMsg('will restart log - new dir is: ' + dir);
LoggerProject.CloseLog;
LoggerProject.StartLogFilePrefix( CprefProj, Csuff, dir); //placed in project directory
end;
//
if LoggerReport<>nil then
begin
LoggerReport.LogMsg('will restart log - new dir is: ' + dir);
LoggerReport.CloseLog;
LoggerReport.StartLogFilePrefix(CprefReport, Csuff, dir); //placed in project directory
end;
LogMsg('TLoggerForm.UpdateDir DONE.');
end;
procedure TLoggerForm.UpdateWarningCnt(n: longint);
begin
fWarningCnt := n;
PanWarningCount.Caption := IntToStr( n );
end;
procedure TLoggerForm.UpdateErrorCnt;
begin
fErrorCnt := n;
PanErrorCount.Caption := IntToStr( n );
end;
procedure TLoggerForm.LogProjectMsg(s: string);
begin
MeProjLog.Lines.Add( NowString + ' ' + s );
end;
procedure TLoggerForm.LogWarningMsg(s: string);
begin
MeWarningLog.Lines.Add( NowString + ' ' + s );
WarningCount := WarningCount + 1;
end;
procedure TLoggerForm.LogErrorMsg(s: string);
begin
MeErrorLog.Lines.Add( NowString + ' ' + s );
ErrorCount := ErrorCount + 1;
end;
procedure TLoggerForm.LogReportMsg(s: string);
begin
MeReport.Lines.Add( NowString + ' ' + s );
end;
function TLoggerForm.NowString: string; //returns actual datetime up to miliseconds
begin
DateTimeToString(Result, '[yyyy-mm-dd_hh:nn:ss.zzz]', Now()); // DateTimeToStr(Time); //datetimetostring DateTimeToString
end;
procedure TLoggerForm.Button2Click(Sender: TObject);
begin
LogProjectEvent('Test');
end;
procedure TLoggerForm.BuHideClick(Sender: TObject);
begin
LoggerForm.Hide;
end;
procedure TLoggerForm.BuClearProjClick(Sender: TObject);
begin
MeProjLog.Lines.Clear;
end;
procedure TLoggerForm.BuClearWarningClick(Sender: TObject);
begin
MeWarningLog.Lines.Clear;
LogWarningMsg('*** Log Cleared and Counter Reset ***');
WarningCount := 0;
end;
procedure TLoggerForm.BuClearErrorClick(Sender: TObject);
begin
MeERRORlog.Lines.Clear;
LogErrorMsg('*** Log Cleared and Counter Reset ***');
ErrorCount := 0;
end;
procedure TLoggerForm.Button1Click(Sender: TObject);
begin
LogWarningMsg('test');
end;
procedure TLoggerForm.Button3Click(Sender: TObject);
begin
LogErrorMsg('test');
end;
procedure TLoggerForm.BuResetWarningClick(Sender: TObject);
begin
LogWarningMsg('*** Reseting Warning counter...');
WarningCount := 0;
end;
procedure TLoggerForm.Button4Click(Sender: TObject);
begin
LogError('simul error');
end;
procedure TLoggerForm.BuResetErrorClick(Sender: TObject);
begin
LogErrorMsg('*** Reseting Error counter...');
ErrorCount := 0;
end;
end.
| 26.007968 | 134 | 0.700521 |
c3621cce52cded3c495710444bada21cb6bef08a | 10,182 | pas | Pascal | Native/Delphi/bo.Excel/ExcelUnit.pas | jpluimers/bo.codeplex | 787ef3b5a8c6ced0a985361243c48a6c76f5d655 | [
"BSD-3-Clause"
]
| 5 | 2017-05-12T08:03:54.000Z | 2022-02-15T08:23:27.000Z | Native/Delphi/bo.Excel/ExcelUnit.pas | jpluimers/bo.codeplex | 787ef3b5a8c6ced0a985361243c48a6c76f5d655 | [
"BSD-3-Clause"
]
| null | null | null | Native/Delphi/bo.Excel/ExcelUnit.pas | jpluimers/bo.codeplex | 787ef3b5a8c6ced0a985361243c48a6c76f5d655 | [
"BSD-3-Clause"
]
| null | null | null | unit ExcelUnit;
interface
uses
ExcelXmlUnit,
XMLIntf;
const
CSpace = ' ';
SDateTime = 'DateTime';
Excel2003_Workbook_DocumentProperties_Version = '11.9999';
type
TIso8601 = class(TObject)
public
class function DateTimeFromIso8601(const Value: string): TDateTime; static;
class function UtcDateTimeToIso8601(const Value: TDateTime): string; static;
class function DateTimeToIso8601(const Value: TDateTime): string; static;
class function UtcNow: TDateTime; static;
class function ToUtc(const Value: TDateTime): TDateTime; static;
class function FromUtc(const Value: TDateTime): TDateTime; static;
end;
TWorkbookProducer = class(TObject)
private
FProduct: IXMLWorkbookType;
strict protected
constructor Create;
class procedure AddAttribute(const XmlNode: IXMLNode; const namespacePrefix, namespaceUri: string); virtual;
property Product: IXMLWorkbookType read FProduct;
public
class function CreateWorkbook: IXMLWorkbookType; static;
class function CreateWorksheet(const Workbook: IXMLWorkbookType): IXMLWorksheetType; static;
class procedure SaveXml(const xmlFileName: string; const Workbook: IXMLWorkbookType; const PrettyPrintXml: Boolean = True); static;
class procedure SetCellData(const Cell: IXMLCellType; const Value: string); static;
class procedure SetCellDataDateTime(const Cell: IXMLCellType; const Value: TDateTime); static;
end;
const
SDate_Style_ID = 'Date';
SDateTime_Style_ID = 'DateTime';
SEnglishWeekday_Style_ID = 'EnglishWeekday';
SF400DefaultTime_Style_ID = 'F400';
SF800DefaultLongDate_Style_ID = 'F800';
implementation
uses
XSBuiltIns, IdGlobal, SysUtils, IdGlobalProtocols, Classes, XMLDoc, Variants;
const
SF400_Style_NumberFormat_Format = '[$-F400]';
SF800_Style_NumberFormat_Format = '[$-F800]';
S409Ddd_Style_NumberFormat_Format = '[$-409]ddd';
SYyyyMmDdHMmSs_Style_NumberFormat_Format = 'yyyy/mm/dd\ h:mm:ss';
SYyyyMmDd_Style_NumberFormat_Format = 'yyyy/mm/dd';
SBottom_Style_Alignment = 'Bottom';
SNormal_Style_Name = 'Normal';
SDefault_Style_ID = 'Default';
STRUE = 'TRUE';
SFALSE = 'FALSE';
SString = 'String';
class function TIso8601.DateTimeFromIso8601(const Value: string): TDateTime;
begin
with TXSDateTime.Create() do
try
XSToNative(value); // convert from WideString
Result := AsDateTime; // convert to TDateTime finally
finally
Free();
end;
end;
class function TIso8601.UtcDateTimeToIso8601(const Value: TDateTime): string;
begin
with TXSDateTime.Create() do
try
AsUTCDateTime := Value;
Result := NativeToXS; // convert to WideString
finally
Free();
end;
end;
class function TIso8601.DateTimeToIso8601(const Value: TDateTime): string;
begin
with TXSDateTime.Create() do
try
AsDateTime := Value; // convert from TDateTime
Result := NativeToXS; // convert to WideString
finally
Free();
end;
end;
class function TIso8601.UtcNow: TDateTime;
begin
Result := ToUtc(Now);
end;
class function TIso8601.ToUtc(const Value: TDateTime): TDateTime;
var
Bias: TDateTime;
begin
Bias := TimeZoneBias;
Result := Value + TimeZoneBias;
end;
class function TIso8601.FromUtc(const Value: TDateTime): TDateTime;
var
Bias: TDateTime;
begin
Bias := TimeZoneBias;
Result := Value - TimeZoneBias;
end;
constructor TWorkbookProducer.Create;
var
msoProcessingInstructionXmlNode: IXMLNode;
namespacePrefix: string;
namespaceUri: string;
Style: IXMLStyleType;
XmlDocument: IXMLDocument;
begin
inherited Create();
// add this processing instruction:
//<?mso-application progid="Excel.Sheet"?>
FProduct := NewWorkbook;
XmlDocument := Product.OwnerDocument;
// XmlDocument.Options := XmlDocument.Options + [doNodeAutoIndent];
msoProcessingInstructionXmlNode := XmlDocument.CreateNode('mso-application', ntProcessingInstr, 'progid="Excel.Sheet"');
XmlDocument.ChildNodes.Insert(1, msoProcessingInstructionXmlNode);
{ add the namespaces we need as xmlns attributes
xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40"
}
AddAttribute(Product, 'xmlns', 'urn:schemas-microsoft-com:office:spreadsheet');
AddAttribute(Product, 'xmlns:o', 'urn:schemas-microsoft-com:office:office');
AddAttribute(Product, 'xmlns:x', 'urn:schemas-microsoft-com:office:excel');
AddAttribute(Product, 'xmlns:ss', 'urn:schemas-microsoft-com:office:spreadsheet');
AddAttribute(Product, 'xmlns:html', 'http://www.w3.org/TR/REC-html40');
AddAttribute(Product.DocumentProperties, 'xmlns', 'urn:schemas-microsoft-com:office:office');
// <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
// <WindowHeight>9300</WindowHeight>
// <WindowWidth>15135</WindowWidth>
// <WindowTopX>120</WindowTopX>
// <WindowTopY>120</WindowTopY>
// <AcceptLabelsInFormulas/>
// <ProtectStructure>False</ProtectStructure>
// <ProtectWindows>False</ProtectWindows>
// </ExcelWorkbook>
Style := Product.Styles.Add();
Style.ID := SDefault_Style_ID;
Style.Name := SNormal_Style_Name;
Style.Alignment.Vertical := SBottom_Style_Alignment;
Style := Product.Styles.Add();
Style.ID := SDate_Style_ID;
Style.NumberFormat.Format := SYyyyMmDd_Style_NumberFormat_Format;
Style := Product.Styles.Add();
Style.ID := SDateTime_Style_ID;
Style.NumberFormat.Format := SYyyyMmDdHMmSs_Style_NumberFormat_Format;
Style := Product.Styles.Add();
Style.ID := SEnglishWeekday_Style_ID;
Style.NumberFormat.Format := S409Ddd_Style_NumberFormat_Format;
Style := Product.Styles.Add();
Style.ID := SF800DefaultLongDate_Style_ID;
Style.NumberFormat.Format := SF800_Style_NumberFormat_Format;
Style := Product.Styles.Add();
Style.ID := SF400DefaultTime_Style_ID;
Style.NumberFormat.Format := SF400_Style_NumberFormat_Format;
// <NumberFormat ss:Format="[ENG][$-409]ddd"/>
// <Styles>
// <Style ss:ID="Default" ss:Name="Normal">
// <Alignment ss:Vertical="Bottom"/>
// <Borders/>
// <Font/>
// <Interior/>
// <NumberFormat/>
// <Protection/>
// </Style>
// <Style ss:ID="s22">
// <NumberFormat ss:Format="yyyy/mm/dd"/>
// </Style>
// <Style ss:ID="s23">
// <NumberFormat ss:Format="yyyy/mm/dd\ h:mm:ss"/>
// </Style>
// <Style ss:ID="s31">
// <NumberFormat ss:Format="[ENG][$-409]ddd"/>
// </Style>
// </Styles>
end;
class procedure TWorkbookProducer.AddAttribute(const XmlNode: IXMLNode; const namespacePrefix, namespaceUri: string);
var
XmlDocument: IXMLDocument;
namespaceXmlNode: IXMLNode;
begin
XmlDocument := XmlNode.OwnerDocument;
namespaceXmlNode := XmlDocument.CreateNode(namespacePrefix, ntAttribute);
namespaceXmlNode.Text := namespaceUri;
XmlNode.AttributeNodes.Add(namespaceXmlNode);
end;
class function TWorkbookProducer.CreateWorkbook: IXMLWorkbookType;
begin
with TWorkbookProducer.Create() do
try
Result := Product;
finally
Free();
end;
end;
class function TWorkbookProducer.CreateWorksheet(const Workbook: IXMLWorkbookType): IXMLWorksheetType;
begin
Result := Workbook.Worksheet.Add();
// redefine default xmlns namespace
AddAttribute(Result.WorksheetOptions, 'xmlns', 'urn:schemas-microsoft-com:office:excel');
end;
class procedure TWorkbookProducer.SaveXml(const xmlFileName: string; const Workbook: IXMLWorkbookType; const PrettyPrintXml: Boolean = True);
var
PlainXml: string;
IndentedXml: string;
ExcelFileName: string;
Stream: TStream;
begin
PlainXml := {Workbook.XML; // does not get the processing instructions } Workbook.OwnerDocument.XML.Text;
try
// IndentedXml := PlainXml;
IndentedXml := FormatXMLData(PlainXml); // pretty print the XML
// Excel 2003 hates the 'Namespace Undeclaration': http://en.wikipedia.org/wiki/XML_namespace#Namespace_undeclaration
IndentedXml := StringReplace(IndentedXml, ' xmlns="">', '>', [rfReplaceAll]);
IndentedXml := StringReplace(IndentedXml, ' xmlns="" ', ' ', [rfReplaceAll]);
except
on E: Exception do
begin
Writeln(E.ClassName, ' ', E.Message);
Writeln(PlainXml);
IndentedXml := PlainXml;
end;
end;
ExcelFileName := ChangeFileExt(xmlFileName, '.xml');
Stream := TFileStream.Create(ExcelFileName, fmCreate);
try
// mimic TStringStream.WriteString
Stream.Write(PChar(IndentedXml)^, Length(IndentedXml));
finally
Stream.Free;
end;
end;
class procedure TWorkbookProducer.SetCellData(const Cell: IXMLCellType; const Value: string);
var
CurrencyValue: Currency;
DateTimeValue: TDateTime;
DateValue: TDateTime;
ExtendedValue: Extended;
Int64Value: Int64;
NeedsTick: Boolean;
StringValue: string;
TimeValue: TDateTime;
Character: Char;
begin
Cell.Data.Type_ := SString;
for Character in Value do
begin
if Character < CSpace then
StringValue := StringValue + '.'
else
StringValue := StringValue + Character;
end;
Cell.Data.Text := StringValue;
if Value <> NullAsStringValue then
begin
NeedsTick := AnsiSameText(SFALSE, Value);
NeedsTick := NeedsTick or AnsiSameText(STRUE, Value);
NeedsTick := NeedsTick or TryStrToInt64(Value, Int64Value);
NeedsTick := NeedsTick or TryStrToFloat(Value, ExtendedValue);
NeedsTick := NeedsTick or TryStrToDate(Value, DateValue);
NeedsTick := NeedsTick or TryStrToTime(Value, TimeValue);
NeedsTick := NeedsTick or TryStrToDateTime(Value, DateTimeValue);
NeedsTick := NeedsTick or TryStrToCurr(Value, CurrencyValue);
if NeedsTick then
Cell.Data.Ticked := 1;
end;
end;
class procedure TWorkbookProducer.SetCellDataDateTime(const Cell: IXMLCellType; const Value: TDateTime);
begin
Cell.Data.Type_ := SDateTime;
Cell.Data.Text := TIso8601.UtcDateTimeToIso8601(Value);
end;
end.
| 32.73955 | 142 | 0.715478 |
c3c4055f81eb20776fdd4ea5c2faebfa00220d5f | 424 | dfm | Pascal | windows/src/ext/jedi/jvcl/tests/restructured/examples/RALib/RaInterpreter/samples/TextDFM.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/tests/restructured/examples/RALib/RaInterpreter/samples/TextDFM.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/tests/restructured/examples/RALib/RaInterpreter/samples/TextDFM.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | object Form1: TForm1
Left = 150
Top = 69
Width = 220
Height = 156
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 72
Top = 48
Width = 47
Height = 13
Caption = 'Text DFM'
end
end
| 17.666667 | 32 | 0.634434 |
fc36723e17bb830526ce9b0ffc02d36979458416 | 2,295 | dfm | Pascal | SRC/Globals/KysyUnit.dfm | nola19842020/nola | a8058aaa8bde700ea56f3a3cb057e93baf8df214 | [
"BSD-3-Clause"
]
| null | null | null | SRC/Globals/KysyUnit.dfm | nola19842020/nola | a8058aaa8bde700ea56f3a3cb057e93baf8df214 | [
"BSD-3-Clause"
]
| null | null | null | SRC/Globals/KysyUnit.dfm | nola19842020/nola | a8058aaa8bde700ea56f3a3cb057e93baf8df214 | [
"BSD-3-Clause"
]
| null | null | null | object KysyFrm: TKysyFrm
Left = 564
Top = 417
Caption = 'KysyFrm'
ClientHeight = 73
ClientWidth = 445
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
OnKeyDown = FormKeyDown
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object PanA: TPanel
Left = 0
Top = 50
Width = 445
Height = 23
Align = alBottom
BevelOuter = bvNone
TabOrder = 0
object Btn1: TButton
Left = 64
Top = 1
Width = 75
Height = 22
Cancel = True
Caption = 'Btn1'
Default = True
TabOrder = 0
OnKeyDown = Btn1KeyDown
OnMouseDown = Btn1MouseDown
end
object Btn2: TButton
Left = 144
Top = 1
Width = 75
Height = 22
Caption = 'Btn2'
TabOrder = 1
Visible = False
OnKeyDown = Btn1KeyDown
OnMouseDown = Btn1MouseDown
end
object Btn3: TButton
Left = 226
Top = 1
Width = 75
Height = 22
Caption = 'Btn3'
TabOrder = 2
Visible = False
OnKeyDown = Btn1KeyDown
OnMouseDown = Btn1MouseDown
end
object Btn4: TButton
Left = 310
Top = 1
Width = 75
Height = 22
Caption = 'Btn4'
TabOrder = 3
Visible = False
OnKeyDown = Btn1KeyDown
OnMouseDown = Btn1MouseDown
end
end
object REdi: TRichEditNola
Left = 0
Top = 0
Width = 445
Height = 50
Align = alClient
Alignment = taCenter
BorderStyle = bsNone
Color = clScrollBar
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
Lines.Strings = (
'REdi'
' Btn1'#180'ss'#228' ainoana Default=TR =Enter vastaa klikki'#228'. Kyll'#228'kin ALT' +
' workkii, '
'ei Enter.')
ParentFont = False
TabOrder = 1
Zoom = 100
OnKeyDown = REdiKeyDown
Text =
'REdi'#13#10' Btn1'#180'ss'#228' ainoana Default=TR =Enter vastaa klikki'#228'. Kyll'#228'k' +
'in ALT workkii, '#13#10'ei Enter.'#13#10
end
end
| 22.722772 | 101 | 0.55512 |
c3b2558c9df6d577709b507c997b553334ea4236 | 3,629 | dfm | Pascal | VisaoControle/UFrmPesquisa.dfm | helnatanbp/general-control | 25e50cf7eac217f02ac9986161ac90dd2673c473 | [
"MIT"
]
| null | null | null | VisaoControle/UFrmPesquisa.dfm | helnatanbp/general-control | 25e50cf7eac217f02ac9986161ac90dd2673c473 | [
"MIT"
]
| null | null | null | VisaoControle/UFrmPesquisa.dfm | helnatanbp/general-control | 25e50cf7eac217f02ac9986161ac90dd2673c473 | [
"MIT"
]
| null | null | null | object frmPesquisa: TfrmPesquisa
Left = 226
Top = 187
ActiveControl = cbOpcoes
Caption = 'Pesquisa'
ClientHeight = 461
ClientWidth = 764
Color = clSilver
Ctl3D = False
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnResize = FormResize
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object pnlBotoes: TPanel
Left = 0
Top = 420
Width = 764
Height = 41
Align = alBottom
Color = clSilver
TabOrder = 3
DesignSize = (
764
41)
object btnSair: TBitBtn
Left = 645
Top = 4
Width = 115
Height = 33
Anchors = [akRight, akBottom]
Caption = '&Sair'
DoubleBuffered = True
ParentDoubleBuffered = False
TabOrder = 1
OnClick = btnSairClick
end
object btnConfirmar: TBitBtn
Left = 529
Top = 4
Width = 115
Height = 33
Anchors = [akRight, akBottom]
Caption = '&Confirmar'
DoubleBuffered = True
ModalResult = 1
ParentDoubleBuffered = False
TabOrder = 0
OnClick = btnConfirmarClick
end
end
object gbParametros: TGroupBox
Left = 0
Top = 28
Width = 764
Height = 58
Align = alTop
Caption = ' Par'#226'metros '
TabOrder = 1
object lbOpcao: TLabel
Left = 19
Top = 24
Width = 32
Height = 13
Alignment = taRightJustify
Caption = 'Op'#231#227'o'
end
object lbIgualA: TLabel
Left = 240
Top = 24
Width = 32
Height = 13
Alignment = taRightJustify
Caption = 'Igual a'
end
object edPesquisa: TEdit
Left = 280
Top = 21
Width = 233
Height = 19
Color = clBtnFace
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
ParentFont = False
TabOrder = 1
OnKeyDown = dbgClienteKeyDown
OnKeyUp = edPesquisaKeyUp
end
object cbOpcoes: TComboBox
Left = 57
Top = 21
Width = 177
Height = 21
BevelInner = bvNone
BevelOuter = bvNone
Style = csDropDownList
Color = clInfoBk
Ctl3D = False
Font.Charset = ANSI_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
ParentCtl3D = False
ParentFont = False
TabOrder = 0
OnChange = cbOpcoesChange
OnKeyDown = dbgClienteKeyDown
end
end
object pnlCabecalho: TPanel
Left = 0
Top = 0
Width = 764
Height = 28
Align = alTop
Color = clGray
TabOrder = 0
object lbCabecalho: TLabel
Left = 8
Top = 5
Width = 84
Height = 19
Caption = 'PESQUISA'
Font.Charset = ANSI_CHARSET
Font.Color = clWhite
Font.Height = -16
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
end
end
object dbgCliente: TDBGrid
Left = 0
Top = 86
Width = 764
Height = 334
Align = alClient
Color = clBtnFace
FixedColor = clGradientInactiveCaption
Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit]
ReadOnly = True
TabOrder = 2
TitleFont.Charset = DEFAULT_CHARSET
TitleFont.Color = clWindowText
TitleFont.Height = -11
TitleFont.Name = 'MS Sans Serif'
TitleFont.Style = []
OnDblClick = dbgClienteDblClick
OnKeyDown = dbgClienteKeyDown
end
end
| 22.401235 | 131 | 0.600441 |
c3b6748bb7c9b1c205ddd077cd251b29a93c0e83 | 1,096 | dpr | Pascal | Demos/02.ContentTypes/DemoContentTypes.dpr | eStreamSoftware/WiRL | 4bd105af425c65797791480426dffe6bc4e0d73b | [
"Apache-2.0"
]
| 1 | 2020-01-16T02:33:22.000Z | 2020-01-16T02:33:22.000Z | Demos/02.ContentTypes/DemoContentTypes.dpr | eStreamSoftware/WiRL | 4bd105af425c65797791480426dffe6bc4e0d73b | [
"Apache-2.0"
]
| null | null | null | Demos/02.ContentTypes/DemoContentTypes.dpr | eStreamSoftware/WiRL | 4bd105af425c65797791480426dffe6bc4e0d73b | [
"Apache-2.0"
]
| null | null | null | {******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
program DemoContentTypes;
uses
Forms,
Server.Forms.Main in 'Server.Forms.Main.pas' {MainForm},
Server.Resources in 'Server.Resources.pas';
{$R *.res}
begin
ReportMemoryLeaksOnShutdown := True;
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end. | 42.153846 | 81 | 0.311131 |
fce040c4e0ebab714d4eaaf5650428ecefa46e6d | 5,099 | pas | Pascal | math/0019.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | math/0019.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | math/0019.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | {
Hi, to All:
...While recently "tuning up" one of my Programs I'm currently
working on, I ran a little test to Compare the perfomance
of the different versions of Turbo Pascal from 5.0 through
to 7.0. The results were quite suprizing, and I thought I'd
share this With you guys/gals.
Here are the results of a "sieve" Program to find all the primes
in 1 - 100,000, running on my AMI 386SX-25 CPU desktop PC:
CompILER EXECUTION TIME RELATIVE TIME FACtoR
==================================================
TP 7.0 46.7 sec 1.00
TP 6.0 137.8 sec 2.95
TP 5.5 137.5 sec 2.94
TP 5.0 137.6 sec 2.95
Running the same Program to find all the primes in 1 - 10,000,
running on my 8086 - 9.54 Mhz NEC V20 CPU laptop PC:
CompILER EXECUTION TIME RELATIVE TIME FACtoR
==================================================
TP 7.0 14.1 sec 1.00
TP 6.0 28.3 sec 2.00
notE: This would seem to indicate that the TP 7.0 386 math-
library is kicking in when run on a 386 CPU.
Here is the source-code to my "seive" Program:
------------------------------------------------------------------------
}
{.$DEFinE DebugMode}
{$DEFinE SaveData}
{$ifDEF DebugMode}
{$ifDEF VER70}
{$ifDEF DPMI}
{$A+,B-,D+,E-,F-,G-,I+,L+,N-,P+,Q+,R+,S+,T+,V+,X-}
{$else}
{$A+,B-,D+,E-,F-,G-,I+,L+,N-,O-,P+,Q+,R+,S+,T+,V+,X-}
{$endif}
{$else}
{$ifDEF VER60}
{$A+,B-,D+,E-,F-,G-,I+,L+,N-,O-,R+,S+,V+,X-}
{$else}
{$A+,B-,D+,E-,F-,I+,L+,N-,O-,R+,S+,V+}
{$endif}
{$endif}
{$else}
{$ifDEF VER70}
{$ifDEF DPMI}
{$A+,B-,D-,E-,F-,G-,I-,L-,N-,P-,Q-,R-,S+,T-,V-,X-}
{$else}
{$A+,B-,D-,E-,F-,G-,I-,L-,N-,O-,P-,Q-,R-,S+,T-,V-,X-}
{$endif}
{$else}
{$ifDEF VER60}
{$A+,B-,D-,E-,F-,G-,I-,L-,N-,O-,R-,S+,V-,X-}
{$else}
{$A+,B-,D-,E-,F-,I-,L-,N-,O-,R-,S+,V-}
{$endif}
{$endif}
{$endif}
(* Find prime numbers - Guy McLoughlin, 1993. *)
Program Find_Primes;
(***** Check if a number is prime. *)
(* *)
Function Prime({input } lo_in : LongInt) : {output} Boolean;
Var
lo_Stop,
lo_Loop : LongInt;
begin
if (lo_in mod 2 = 0) then
begin
Prime := (lo_in = 2);
Exit
end;
if (lo_in mod 3 = 0) then
begin
Prime := (lo_in = 3);
Exit
end;
if (lo_in mod 5 = 0) then
begin
Prime := (lo_in = 5);
Exit
end;
lo_Stop := 7;
While ((lo_Stop * lo_Stop) <= lo_in) do
inc(lo_Stop, 2);
lo_Loop := 7;
While (lo_Loop < lo_Stop) do
begin
inc(lo_Loop, 2);
if (lo_in mod lo_Loop = 0) then
begin
Prime := False;
Exit
end
end;
Prime := True
end; (* Prime. *)
(***** Check For File IO errors. *)
(* *)
Procedure CheckIOerror;
Var
by_Error : Byte;
begin
by_Error := ioresult;
if (by_Error <> 0) then
begin
Writeln('File Error = ', by_Error);
halt
end
end; (* CheckIOerror. *)
Var
bo_Temp : Boolean;
wo_PrimeCount : Word;
lo_Temp,
lo_Loop : LongInt;
fite_Data : Text;
begin
lo_Temp := 100000;
{$ifDEF SaveData}
{$ifDEF VER50}
assign(fite_Data, 'PRIME.50');
{$endif}
{$ifDEF VER55}
assign(fite_Data, 'PRIME.55');
{$endif}
{$ifDEF VER60}
assign(fite_Data, 'PRIME.60');
{$endif}
{$ifDEF VER70}
assign(fite_Data, 'PRIME.70');
{$endif}
{$I-}
reWrite(fite_Data);
{$I+}
CheckIOerror;
{$endif}
wo_PrimeCount := 0;
For lo_Loop := 2 to lo_Temp do
if Prime(lo_Loop) then
{$ifDEF SaveData}
begin
Write(fite_Data, lo_Loop:6);
Write(fite_Data, ', ');
inc(wo_PrimeCount);
if ((wo_PrimeCount mod 10) = 0) then
Writeln(fite_Data)
end;
close(fite_Data);
CheckIOerror;
{$else}
inc(wo_PrimeCount);
{$endif}
Writeln(wo_PrimeCount, ' primes between: 1 - ', lo_Temp)
end.
{
...This little test would put TP 7.0's .EXE's between 2 to 3
times faster than TP4 - TP6 .EXE's. (I've found simmilar results
in testing other Programs I've written.) I guess this is one more
reason to upgrade to TP 7.0 .
...I'd be curious to see how StonyBrook's Pascal+ 6.1 Compares
to TP 7.0, in terms of execution speed With this Program.
- Guy
}
| 28.327778 | 73 | 0.452442 |
c3a614f4892b8cd7761caedcad45aedceb4ea3ca | 1,784 | pas | Pascal | Server/FHIR.Server.AccessControl.pas | niaz819/fhirserver | fee45e1e57053a776b893dba543f700dd9cb9075 | [
"BSD-3-Clause"
]
| null | null | null | Server/FHIR.Server.AccessControl.pas | niaz819/fhirserver | fee45e1e57053a776b893dba543f700dd9cb9075 | [
"BSD-3-Clause"
]
| null | null | null | Server/FHIR.Server.AccessControl.pas | niaz819/fhirserver | fee45e1e57053a776b893dba543f700dd9cb9075 | [
"BSD-3-Clause"
]
| null | null | null | unit FHIR.Server.AccessControl;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
FHIR.Support.Base,
FHIR.Base.Objects,
FHIR.Server.Session, FHIR.Server.Security;
Type
TAccessControlEngine = class abstract (TFslObject)
public
end;
implementation
end.
| 37.166667 | 97 | 0.797646 |
836e3423ae2b34590c1d046e5854a53add71e65b | 104,325 | dfm | Pascal | Projects/CL.Ag5/Source/CL.Ag5Client/Zoo/BancoDados/Femea/UfqrZoo_FichaFemea2.dfm | iclinicadoleite/controle-ag5 | 2e315c4a7c9bcb841a8d2f2390ae9d7c2c2cb721 | [
"Apache-2.0"
]
| 1 | 2020-05-07T07:51:27.000Z | 2020-05-07T07:51:27.000Z | Projects/CL.Ag5/Source/CL.Ag5Client/Zoo/BancoDados/Femea/UfqrZoo_FichaFemea2.dfm | iclinicadoleite/controle-ag5 | 2e315c4a7c9bcb841a8d2f2390ae9d7c2c2cb721 | [
"Apache-2.0"
]
| null | null | null | Projects/CL.Ag5/Source/CL.Ag5Client/Zoo/BancoDados/Femea/UfqrZoo_FichaFemea2.dfm | iclinicadoleite/controle-ag5 | 2e315c4a7c9bcb841a8d2f2390ae9d7c2c2cb721 | [
"Apache-2.0"
]
| 3 | 2020-02-17T18:01:52.000Z | 2020-05-07T07:51:28.000Z | inherited fqrZoo_FichaFemea: TfqrZoo_FichaFemea
Left = 762
Top = 48
Caption = 'fqrZoo_FichaFemea'
ClientHeight = 1053
ExplicitTop = -374
ExplicitHeight = 1092
PixelsPerInch = 96
TextHeight = 13
inherited QuickRep: TQuickRep
Left = 0
DataSet = cdsMaster
Functions.DATA = (
'0'
'0'
#39#39)
Page.Values = (
100.000000000000000000
2970.000000000000000000
100.000000000000000000
2100.000000000000000000
100.000000000000000000
100.000000000000000000
0.000000000000000000)
ExplicitLeft = 0
inherited rbPageHeader: TQRBand
Size.Values = (
63.500000000000000000
1899.708333333333000000)
inherited _qrsDateTime: TQRSysData
Left = 535
Width = 183
Size.Values = (
42.333333333333330000
1415.520833333333000000
0.000000000000000000
484.187500000000000000)
FontSize = 9
ExplicitLeft = 535
ExplicitWidth = 183
end
inherited _qrsPageNumber: TQRSysData
Left = 665
Width = 53
Height = 16
Size.Values = (
42.333333333333330000
1759.479166666667000000
0.000000000000000000
140.229166666666700000)
Font.Height = -12
FontSize = 9
ExplicitLeft = 665
ExplicitWidth = 53
ExplicitHeight = 16
end
inherited QRShapeHeaderSeparator2: TQRShape
Size.Values = (
2.645833333333333000
52.916666666666670000
44.979166666666670000
1796.520833333333000000)
end
inherited _qrsReportTitle2: TQRSysData
Left = 343
Width = 31
Size.Values = (
42.333333333333330000
907.520833333333300000
0.000000000000000000
82.020833333333330000)
FontSize = 9
ExplicitLeft = 343
ExplicitWidth = 31
end
end
inherited rbTitle: TQRBand
Height = 75
Size.Values = (
198.437500000000000000
1899.708333333333000000)
ExplicitHeight = 75
inherited _qrsReportTitle: TQRSysData
Left = 335
Width = 47
Size.Values = (
60.854166666666670000
886.354166666666700000
13.229166666666670000
124.354166666666700000)
FontSize = 14
ExplicitLeft = 335
ExplicitWidth = 47
end
inherited _qrsDateTimeTitle: TQRSysData
Left = 535
Width = 183
Size.Values = (
42.333333333333330000
1415.520833333333000000
203.729166666666700000
484.187500000000000000)
FontSize = 9
ExplicitLeft = 535
ExplicitWidth = 183
end
inherited _qrsPageNumberTitle: TQRSysData
Left = 665
Top = 92
Width = 53
Size.Values = (
42.333333333333330000
1759.479166666667000000
243.416666666666700000
140.229166666666700000)
FontSize = 9
ExplicitLeft = 665
ExplicitTop = 92
ExplicitWidth = 53
end
inherited _qrImageLogo: TQRImage
Left = 4
Height = 70
Size.Values = (
185.208333333333300000
10.583333333333330000
7.937500000000000000
254.000000000000000000)
ExplicitLeft = 4
ExplicitHeight = 70
end
inherited _qrlDescricao: TQRLabel
Size.Values = (
42.333333333333330000
846.666666666666700000
68.791666666666670000
206.375000000000000000)
FontSize = 9
end
inherited QRShapeHeaderSeparator: TQRShape
Left = 3
Width = 714
Size.Values = (
2.645833333333333000
7.937500000000000000
198.437500000000000000
1889.125000000000000000)
ExplicitLeft = 3
ExplicitWidth = 714
end
inherited QRImageDomain: TQRImage
Left = 564
Top = 5
Size.Values = (
156.104166666666700000
1492.250000000000000000
13.229166666666670000
391.583333333333300000)
ExplicitLeft = 564
ExplicitTop = 5
end
end
inherited rbDetail: TQRBand
Top = 154
Height = 144
Size.Values = (
381.000000000000000000
1899.708333333333000000)
ExplicitTop = 154
ExplicitHeight = 144
object QRLabel1: TQRLabel
Left = 11
Top = 2
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
5.291666666666667000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel2: TQRLabel
Left = 11
Top = 21
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
55.562500000000000000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel2'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel3: TQRLabel
Left = 11
Top = 42
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
111.125000000000000000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel3'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel4: TQRLabel
Left = 11
Top = 61
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
161.395833333333300000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel4'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel5: TQRLabel
Left = 11
Top = 80
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
211.666666666666700000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel5'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel6: TQRLabel
Left = 11
Top = 98
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
259.291666666666700000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel6'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel7: TQRLabel
Left = 11
Top = 112
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
296.333333333333300000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel7'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRLabel8: TQRLabel
Left = 11
Top = 126
Width = 48
Height = 15
Size.Values = (
39.687500000000000000
29.104166666666670000
333.375000000000000000
127.000000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel8'
Color = clWhite
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 8
end
object QRShape1: TQRShape
Left = 432
Top = 6
Width = 265
Height = 132
Size.Values = (
349.250000000000000000
1143.000000000000000000
15.875000000000000000
701.145833333333400000)
XLColumn = 0
XLNumFormat = nfGeneral
Pen.Style = psDot
Shape = qrsRectangle
VertAdjust = 0
end
object QRDBText1: TQRDBText
Left = 104
Top = 1
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
2.645833333333333000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText1'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText2: TQRDBText
Left = 104
Top = 18
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
47.625000000000000000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText2'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText3: TQRDBText
Left = 104
Top = 36
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
95.250000000000000000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText3'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText4: TQRDBText
Left = 104
Top = 54
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
142.875000000000000000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText4'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText5: TQRDBText
Left = 104
Top = 71
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
187.854166666666700000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText5'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText6: TQRDBText
Left = 104
Top = 89
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
235.479166666666700000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText6'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText7: TQRDBText
Left = 104
Top = 107
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
283.104166666666700000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText7'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
object QRDBText8: TQRDBText
Left = 104
Top = 125
Width = 57
Height = 15
Size.Values = (
39.687500000000000000
275.166666666666700000
330.729166666666700000
150.812500000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Color = clWhite
DataField = 'QRDBText8'
Transparent = False
ExportAs = exptText
WrapStyle = BreakOnSpaces
FullJustify = False
MaxBreakChars = 0
FontSize = 8
end
end
inherited rbPageFooter: TQRBand
Top = 1262
Height = 72
Size.Values = (
190.500000000000000000
1899.708333333333000000)
ExplicitTop = 1262
ExplicitHeight = 72
inherited _qrlFooter: TQRLabel
Size.Values = (
34.395833333333330000
0.000000000000000000
0.000000000000000000
140.229166666666700000)
FontSize = 7
end
inherited QRShapeFooterSeparator1: TQRShape
Size.Values = (
2.645833333333333000
52.916666666666670000
44.979166666666670000
1791.229166666667000000)
end
inherited QRLabelFooterSeparator1: TQRLabel
Size.Values = (
34.395833333333330000
55.562500000000000000
50.270833333333330000
518.583333333333300000)
FontSize = 7
end
inherited QRShapeFooterSeparator: TQRShape
Left = 113
Top = 42
Width = 587
Size.Values = (
2.645833333333333000
298.979166666666700000
111.125000000000000000
1553.104166666667000000)
ExplicitLeft = 113
ExplicitTop = 42
ExplicitWidth = 587
end
inherited QRLabelFooterSeparator: TQRLabel
Size.Values = (
34.395833333333330000
264.583333333333300000
89.958333333333330000
518.583333333333300000)
FontSize = 7
end
inherited LogoClinica: TQRImage
Left = 4
Top = 13
Size.Values = (
92.604166666666670000
10.583333333333330000
34.395833333333330000
198.437500000000000000)
ExplicitLeft = 4
ExplicitTop = 13
end
inherited _qrlLegenda: TQRLabel
Size.Values = (
39.687500000000000000
44.979166666666670000
31.750000000000000000
2.645833333333333000)
FontSize = 8
end
inherited _qrlLegenda1: TQRLabel
Size.Values = (
39.687500000000000000
44.979166666666670000
7.937500000000000000
2.645833333333333000)
FontSize = 8
end
end
inherited rbSummary: TQRBand
Top = 1245
Height = 17
Size.Values = (
44.979166666666670000
1899.708333333333000000)
ExplicitTop = 1245
ExplicitHeight = 17
end
inherited rbColumnHeader: TQRBand
Top = 137
Height = 17
Enabled = False
Size.Values = (
44.979166666666670000
1899.708333333333000000)
ExplicitTop = 137
ExplicitHeight = 17
end
object QRSubDetail3: TQRSubDetail
Left = 38
Top = 298
Width = 718
Height = 100
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
264.583333333333300000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
object QRPGrid1: TQRPGrid
Left = 3
Top = -11
Width = 710
Height = 142
Size.Values = (
375.708333333333300000
7.937500000000000000
-29.104166666666670000
1878.541666666667000000)
XLColumn = 0
XLNumFormat = nfGeneral
FixBottomPosition = False
StretchHeightWithBand = False
CellHorizAlignment = haNone
CellVertAlignment = vaNone
Columns = 10
Rows = 10
DrawFirstRowLine = True
FirstRowColor = clWhite
FirstColumnColor = clWhite
FirstCellColor = clWhite
FirstColumnJoined = False
FirstRowJoined = False
Transparent = False
end
end
object QRSubDetail1: TQRSubDetail
Left = 38
Top = 398
Width = 718
Height = 150
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
396.875000000000000000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
object QRImage1: TQRImage
Left = 11
Top = 3
Width = 692
Height = 246
Size.Values = (
650.875000000000000000
29.104166666666670000
7.937500000000000000
1830.916666666667000000)
XLColumn = 0
XLNumFormat = nfGeneral
end
end
object QRSubDetail2: TQRSubDetail
Left = 38
Top = 548
Width = 718
Height = 497
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
1314.979166666667000000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
object QRShape2: TQRShape
Left = 284
Top = 5
Width = 150
Height = 61
Size.Values = (
161.395833333333300000
751.416666666666700000
13.229166666666670000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel9: TQRLabel
Left = 293
Top = 6
Width = 35
Height = 13
Size.Values = (
34.395833333333330000
775.229166666666700000
15.875000000000000000
92.604166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -8
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 6
end
object QRLabel10: TQRLabel
Left = 293
Top = 17
Width = 35
Height = 13
Size.Values = (
34.395833333333330000
775.229166666666700000
44.979166666666670000
92.604166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -8
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 6
end
object QRLabel11: TQRLabel
Left = 293
Top = 29
Width = 35
Height = 13
Size.Values = (
34.395833333333330000
775.229166666666700000
76.729166666666670000
92.604166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -8
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 6
end
object QRLabel12: TQRLabel
Left = 293
Top = 41
Width = 35
Height = 13
Size.Values = (
34.395833333333330000
775.229166666666700000
108.479166666666700000
92.604166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -8
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 6
end
object QRLabel13: TQRLabel
Left = 293
Top = 54
Width = 35
Height = 13
Size.Values = (
34.395833333333330000
775.229166666666700000
142.875000000000000000
92.604166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -8
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 6
end
object QRShape3: TQRShape
Left = 544
Top = 6
Width = 150
Size.Values = (
171.979166666666700000
1439.333333333333000000
15.875000000000000000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel14: TQRLabel
Left = 553
Top = 8
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
21.166666666666670000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel15: TQRLabel
Left = 553
Top = 20
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
52.916666666666670000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel16: TQRLabel
Left = 553
Top = 32
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
84.666666666666670000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel17: TQRLabel
Left = 553
Top = 44
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
116.416666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel18: TQRLabel
Left = 553
Top = 57
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
150.812500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape4: TQRShape
Left = 23
Top = 6
Width = 150
Size.Values = (
171.979166666666700000
60.854166666666670000
15.875000000000000000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel19: TQRLabel
Left = 32
Top = 8
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
21.166666666666670000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel20: TQRLabel
Left = 32
Top = 20
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
52.916666666666670000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel21: TQRLabel
Left = 32
Top = 32
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
84.666666666666670000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel22: TQRLabel
Left = 32
Top = 44
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
116.416666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel23: TQRLabel
Left = 32
Top = 57
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
150.812500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape5: TQRShape
Left = 23
Top = 104
Width = 150
Size.Values = (
171.979166666666700000
60.854166666666670000
275.166666666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel24: TQRLabel
Left = 32
Top = 106
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
280.458333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel25: TQRLabel
Left = 32
Top = 118
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
312.208333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel26: TQRLabel
Left = 32
Top = 130
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
343.958333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel27: TQRLabel
Left = 32
Top = 142
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
375.708333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel28: TQRLabel
Left = 32
Top = 155
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
410.104166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape6: TQRShape
Left = 544
Top = 104
Width = 150
Size.Values = (
171.979166666666700000
1439.333333333333000000
275.166666666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel29: TQRLabel
Left = 553
Top = 106
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
280.458333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel30: TQRLabel
Left = 553
Top = 118
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
312.208333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel31: TQRLabel
Left = 553
Top = 130
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
343.958333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel32: TQRLabel
Left = 553
Top = 142
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
375.708333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel33: TQRLabel
Left = 553
Top = 155
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
410.104166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape7: TQRShape
Left = 207
Top = 75
Width = 150
Size.Values = (
171.979166666666700000
547.687500000000000000
198.437500000000000000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel34: TQRLabel
Left = 216
Top = 77
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
203.729166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel35: TQRLabel
Left = 216
Top = 89
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
235.479166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel36: TQRLabel
Left = 216
Top = 101
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
267.229166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel37: TQRLabel
Left = 216
Top = 113
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
298.979166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel38: TQRLabel
Left = 216
Top = 126
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
333.375000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape8: TQRShape
Left = 359
Top = 75
Width = 150
Size.Values = (
171.979166666666700000
949.854166666666700000
198.437500000000000000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel39: TQRLabel
Left = 368
Top = 77
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
203.729166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel40: TQRLabel
Left = 368
Top = 89
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
235.479166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel41: TQRLabel
Left = 368
Top = 101
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
267.229166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel42: TQRLabel
Left = 368
Top = 113
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
298.979166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel43: TQRLabel
Left = 368
Top = 126
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
333.375000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape9: TQRShape
Left = 23
Top = 242
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
60.854166666666670000
640.291666666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel44: TQRLabel
Left = 32
Top = 254
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
672.041666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel45: TQRLabel
Left = 32
Top = 266
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
703.791666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel46: TQRLabel
Left = 32
Top = 278
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
735.541666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel47: TQRLabel
Left = 32
Top = 290
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
767.291666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape10: TQRShape
Left = 207
Top = 143
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
547.687500000000000000
378.354166666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel48: TQRLabel
Left = 216
Top = 144
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
381.000000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel49: TQRLabel
Left = 216
Top = 156
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
412.750000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel50: TQRLabel
Left = 216
Top = 168
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
444.500000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel51: TQRLabel
Left = 216
Top = 180
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
476.250000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel52: TQRLabel
Left = 216
Top = 191
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
571.500000000000000000
505.354166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape11: TQRShape
Left = 209
Top = 212
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
552.979166666666700000
560.916666666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel53: TQRLabel
Left = 218
Top = 212
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
560.916666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel54: TQRLabel
Left = 218
Top = 226
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
597.958333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel55: TQRLabel
Left = 218
Top = 238
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
629.708333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel56: TQRLabel
Left = 218
Top = 250
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
661.458333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel57: TQRLabel
Left = 218
Top = 261
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
690.562500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape12: TQRShape
Left = 209
Top = 273
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
552.979166666666700000
722.312500000000000000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel58: TQRLabel
Left = 218
Top = 275
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
727.604166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel59: TQRLabel
Left = 218
Top = 287
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
759.354166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel60: TQRLabel
Left = 218
Top = 299
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
791.104166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel61: TQRLabel
Left = 218
Top = 311
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
822.854166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel62: TQRLabel
Left = 218
Top = 322
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
576.791666666666700000
851.958333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel63: TQRLabel
Left = 32
Top = 243
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
84.666666666666670000
642.937500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape13: TQRShape
Left = 359
Top = 143
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
949.854166666666700000
378.354166666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel64: TQRLabel
Left = 368
Top = 155
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
410.104166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel65: TQRLabel
Left = 368
Top = 167
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
441.854166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel66: TQRLabel
Left = 368
Top = 179
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
473.604166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel67: TQRLabel
Left = 368
Top = 192
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
508.000000000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape14: TQRShape
Left = 544
Top = 242
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
1439.333333333333000000
640.291666666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel68: TQRLabel
Left = 553
Top = 244
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
645.583333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel69: TQRLabel
Left = 553
Top = 256
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
677.333333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel70: TQRLabel
Left = 553
Top = 268
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
709.083333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel71: TQRLabel
Left = 553
Top = 279
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
738.187500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel72: TQRLabel
Left = 553
Top = 291
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
1463.145833333333000000
769.937500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape15: TQRShape
Left = 359
Top = 212
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
949.854166666666700000
560.916666666666700000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel73: TQRLabel
Left = 368
Top = 212
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
560.916666666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel74: TQRLabel
Left = 368
Top = 226
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
597.958333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel75: TQRLabel
Left = 368
Top = 238
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
629.708333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel76: TQRLabel
Left = 368
Top = 250
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
661.458333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel77: TQRLabel
Left = 368
Top = 261
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
690.562500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape16: TQRShape
Left = 359
Top = 273
Width = 150
Height = 60
Size.Values = (
158.750000000000000000
949.854166666666700000
722.312500000000000000
396.875000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrsRoundRect
RoundFactor = 0.125000000000000000
VertAdjust = 0
end
object QRLabel78: TQRLabel
Left = 368
Top = 274
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
724.958333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel79: TQRLabel
Left = 368
Top = 286
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
756.708333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel80: TQRLabel
Left = 368
Top = 298
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
788.458333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel81: TQRLabel
Left = 368
Top = 310
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
820.208333333333300000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel82: TQRLabel
Left = 368
Top = 321
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
849.312500000000000000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel83: TQRLabel
Left = 368
Top = 143
Width = 42
Height = 13
Size.Values = (
34.395833333333330000
973.666666666666700000
378.354166666666700000
111.125000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'QRLabel1'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape23: TQRShape
Left = 172
Top = 106
Width = 18
Height = 31
Size.Values = (
82.020833333333330000
455.083333333333300000
280.458333333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsLeftDiagonal
VertAdjust = 0
end
object QRShape24: TQRShape
Left = 529
Top = 137
Width = 17
Height = 32
Size.Values = (
84.666666666666670000
1399.645833333333000000
362.479166666666700000
44.979166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsLeftDiagonal
VertAdjust = 0
end
object QRShape25: TQRShape
Left = 172
Top = 138
Width = 18
Height = 32
Size.Values = (
84.666666666666670000
455.083333333333300000
365.125000000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRightDiagonal
VertAdjust = 0
end
object QRShape26: TQRShape
Left = 529
Top = 105
Width = 17
Height = 32
Size.Values = (
84.666666666666670000
1399.645833333333000000
277.812500000000000000
44.979166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRightDiagonal
VertAdjust = 0
end
object QRShape27: TQRShape
Left = 172
Top = 241
Width = 17
Height = 32
Size.Values = (
84.666666666666670000
455.083333333333300000
637.645833333333300000
44.979166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsLeftDiagonal
VertAdjust = 0
end
object QRShape28: TQRShape
Left = 528
Top = 272
Width = 17
Height = 32
Size.Values = (
84.666666666666670000
1397.000000000000000000
719.666666666666700000
44.979166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsLeftDiagonal
VertAdjust = 0
end
object QRShape29: TQRShape
Left = 172
Top = 273
Width = 17
Height = 32
Size.Values = (
84.666666666666670000
455.083333333333300000
722.312500000000000000
44.979166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRightDiagonal
VertAdjust = 0
end
object QRShape30: TQRShape
Left = 528
Top = 240
Width = 17
Height = 32
Size.Values = (
84.666666666666670000
1397.000000000000000000
635.000000000000000000
44.979166666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRightDiagonal
VertAdjust = 0
end
object QRShape34: TQRShape
Left = 510
Top = 303
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1349.375000000000000000
801.687500000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape35: TQRShape
Left = 510
Top = 240
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1349.375000000000000000
635.000000000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape36: TQRShape
Left = 510
Top = 168
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1349.375000000000000000
444.500000000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape37: TQRShape
Left = 510
Top = 106
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1349.375000000000000000
280.458333333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape38: TQRShape
Left = 189
Top = 304
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
500.062500000000000000
804.333333333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape39: TQRShape
Left = 189
Top = 241
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
500.062500000000000000
637.645833333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape40: TQRShape
Left = 189
Top = 169
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
500.062500000000000000
447.145833333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape41: TQRShape
Left = 189
Top = 106
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
500.062500000000000000
280.458333333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape17: TQRShape
Left = 173
Top = 36
Width = 110
Height = 1
Size.Values = (
2.645833333333333000
457.729166666666700000
95.250000000000000000
291.041666666666700000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape18: TQRShape
Left = 433
Top = 36
Width = 110
Height = 1
Size.Values = (
2.645833333333333000
1145.645833333333000000
95.250000000000000000
291.041666666666700000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape19: TQRShape
Left = 6
Top = 135
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
15.875000000000000000
357.187500000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape20: TQRShape
Left = 694
Top = 135
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1836.208333333333000000
357.187500000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRLabel84: TQRLabel
Left = 176
Top = 24
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
465.666666666666700000
63.500000000000000000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel85: TQRLabel
Left = 9
Top = 121
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
23.812500000000000000
320.145833333333300000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape21: TQRShape
Left = 6
Top = 273
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
15.875000000000000000
722.312500000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRLabel86: TQRLabel
Left = 7
Top = 259
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
18.520833333333330000
685.270833333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRShape22: TQRShape
Left = 694
Top = 273
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1836.208333333333000000
722.312500000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRLabel87: TQRLabel
Left = 694
Top = 259
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
1836.208333333333000000
685.270833333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel88: TQRLabel
Left = 695
Top = 121
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
1838.854166666667000000
320.145833333333300000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel89: TQRLabel
Left = 522
Top = 24
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
1381.125000000000000000
63.500000000000000000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRPShape1: TQRPShape
Left = 5
Top = 37
Width = 1
Height = 237
Size.Values = (
627.062500000000000000
13.229166666666670000
97.895833333333330000
2.645833333333333000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrpsRectangle
VertAdjust = 0
FixBottomPosition = False
StretchHeightWithBand = False
end
object QRPShape2: TQRPShape
Left = 713
Top = 38
Width = 1
Height = 236
Size.Values = (
624.416666666666700000
1886.479166666667000000
100.541666666666700000
2.645833333333333000)
XLColumn = 0
XLNumFormat = nfGeneral
Shape = qrpsRectangle
VertAdjust = 0
FixBottomPosition = False
StretchHeightWithBand = False
end
object QRShape31: TQRShape
Left = 695
Top = 37
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
1838.854166666667000000
97.895833333333330000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRShape32: TQRShape
Left = 6
Top = 37
Width = 18
Height = 1
Size.Values = (
2.645833333333333000
15.875000000000000000
97.895833333333330000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Brush.Style = bsClear
Shape = qrsRectangle
VertAdjust = 0
end
object QRLabel90: TQRLabel
Left = 191
Top = 89
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
505.354166666666700000
235.479166666666700000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel91: TQRLabel
Left = 512
Top = 89
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
1354.666666666667000000
235.479166666666700000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel92: TQRLabel
Left = 191
Top = 172
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
505.354166666666700000
455.083333333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel93: TQRLabel
Left = 512
Top = 172
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
1354.666666666667000000
455.083333333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel94: TQRLabel
Left = 191
Top = 224
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
505.354166666666700000
592.666666666666700000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel95: TQRLabel
Left = 191
Top = 307
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
505.354166666666700000
812.270833333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel96: TQRLabel
Left = 512
Top = 224
Width = 14
Height = 13
Size.Values = (
34.395833333333330000
1354.666666666667000000
592.666666666666700000
37.041666666666670000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'Pai'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
object QRLabel97: TQRLabel
Left = 512
Top = 307
Width = 18
Height = 13
Size.Values = (
34.395833333333330000
1354.666666666667000000
812.270833333333300000
47.625000000000000000)
XLColumn = 0
XLNumFormat = nfGeneral
Alignment = taLeftJustify
AlignToBand = False
Caption = 'M'#227'e'
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -9
Font.Name = 'Arial'
Font.Style = []
ParentFont = False
Transparent = True
ExportAs = exptText
WrapStyle = BreakOnSpaces
FontSize = 7
end
end
object QRSubDetail4: TQRSubDetail
Left = 38
Top = 1045
Width = 718
Height = 40
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
105.833333333333300000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
end
object QRSubDetail5: TQRSubDetail
Left = 38
Top = 1085
Width = 718
Height = 40
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
105.833333333333300000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
end
object QRSubDetail6: TQRSubDetail
Left = 38
Top = 1125
Width = 718
Height = 40
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
105.833333333333300000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
end
object QRSubDetail7: TQRSubDetail
Left = 38
Top = 1165
Width = 718
Height = 40
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
105.833333333333300000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
end
object QRSubDetail8: TQRSubDetail
Left = 38
Top = 1205
Width = 718
Height = 40
AlignToBottom = False
Color = clWhite
TransparentBand = False
ForceNewColumn = False
ForceNewPage = False
Size.Values = (
105.833333333333300000
1899.708333333333000000)
PreCaluculateBandHeight = False
KeepOnOnePage = False
Master = QuickRep
PrintBefore = False
PrintIfEmpty = True
end
end
object cdsMaster: TClientDataSet
Aggregates = <>
Params = <>
ProviderName = 'dspMaster'
Left = 256
Top = 8
end
object dspMaster: TDataSetProvider
DataSet = sqlMaster
Options = [poIncFieldProps, poReadOnly, poDisableInserts, poDisableEdits, poDisableDeletes]
UpdateMode = upWhereKeyOnly
Left = 224
Top = 32
end
object sqlMaster: TTcSQLDataSet
MaxBlobSize = -1
Params = <>
Left = 254
Top = 63
end
object sqlDetalhes: TTcSQLDataSet
DataSource = dtsSQLMaster
MaxBlobSize = -1
Params = <>
Left = 318
Top = 63
end
object dtsSQLMaster: TDataSource
DataSet = sqlMaster
Left = 286
Top = 79
end
object cdsDetalhes: TClientDataSet
Aggregates = <>
Params = <>
Left = 320
Top = 8
end
end
| 26.579618 | 95 | 0.551162 |
c36dfae1b36ef2db4f0dae9ef8b548f131e9e4a4 | 2,120 | pas | Pascal | src/RayTracer.PAS.Console/Geometry.Methods.pas | LucasHamera/raytracer.pas | 08e52957d927e0e651e0fb8b3559bba37c4b49ec | [
"MIT"
]
| 2 | 2020-07-16T16:31:34.000Z | 2020-07-16T17:13:47.000Z | src/RayTracer.PAS.Console/Geometry.Methods.pas | LucasHamera/raytracer.pas | 08e52957d927e0e651e0fb8b3559bba37c4b49ec | [
"MIT"
]
| 2 | 2020-07-14T22:49:41.000Z | 2020-07-14T22:49:58.000Z | src/RayTracer.PAS.Console/Geometry.Methods.pas | LucasHamera/raytracer.pas | 08e52957d927e0e651e0fb8b3559bba37c4b49ec | [
"MIT"
]
| null | null | null | unit Geometry.Methods;
interface
uses
Geometry.Types;
function Sqrt(const lVar: TReal): TReal;
function Pow(const lBase: TReal; lExp: Integer): TReal;
function Floor(const lVal: TReal): TReal;
function Clamp(const lVal: TReal; const lMin: TReal; const lMax: TReal): TReal;
function Dot(const lLeft, lRight: TVec3): TReal;
function Mag(const lVector: TVec3): TReal;
function Norm(const lVector: TVec3): TVec3;
function Cross(const lLeft, lRight: TVec3): TVec3;
function Scale(const lValue: TReal; const lColor: TColor): TColor;
implementation
function Sqrt(const lVar: TReal): TReal;
var
lCurr: TReal;
lPrev: TReal;
begin
lCurr := lVar;
lPrev := 0.0;
while (lCurr <> lPrev) do
begin
lPrev := lCurr;
lCurr := 0.5 * (lCurr + lVar / lCurr);
end;
Result := lCurr;
end;
function Pow(const lBase: TReal; lExp: Integer): TReal;
var
lVal: TReal;
begin
lVal := 1.0;
while (lExp > 0) do
begin
lVal := lVal * lBase;
Dec(lExp);
end;
Result := lVal;
end;
function Floor(const lVal: TReal): TReal;
begin
Result := Round(lVal);
if (lVal >= 0.0) then
begin
Exit;
end;
Result := Result - 1.0;
end;
function Clamp(const lVal: TReal; const lMin: TReal; const lMax: TReal): TReal;
begin
if (lVal < lMin) then
begin
Exit(lMin);
end;
if (lVal > lMax) then
begin
Exit(lMax);
end;
Exit(lVal);
end;
function Dot(const lLeft, lRight: TVec3): TReal;
begin
Result := lLeft.X * lRight.X + lLeft.Y * lRight.Y + lLeft.Z * lRight.Z;
end;
function Mag(const lVector: TVec3): TReal;
begin
Result := Sqrt(Dot(lVector, lVector));
end;
function Norm(const lVector: TVec3): TVec3;
begin
Result := (1.0 / Mag(lVector)) * lVector;
end;
function Cross(const lLeft, lRight: TVec3): TVec3;
begin
Result := TVec3.Create(
lLeft.Y * lRight.Z - lLeft.Z * lRight.Y,
lLeft.Z * lRight.X - lLeft.X * lRight.Z,
lLeft.X * lRight.Y - lLeft.Y * lRight.X
);
end;
function Scale(const lValue: TReal; const lColor: TColor): TColor;
begin
Result := TColor.Create(lValue * lColor.R, lValue * lColor.G, lValue * lColor.B);
end;
end.
| 18.928571 | 83 | 0.659434 |
fc1266ac00037755c0bee8546f3fcdaec6e1c764 | 347 | dfm | Pascal | datamodu.dfm | embedix/stag-pcapp | 3fed400fb80cce0f5d766d4edd7931b6f7191621 | [
"MIT"
]
| null | null | null | datamodu.dfm | embedix/stag-pcapp | 3fed400fb80cce0f5d766d4edd7931b6f7191621 | [
"MIT"
]
| null | null | null | datamodu.dfm | embedix/stag-pcapp | 3fed400fb80cce0f5d766d4edd7931b6f7191621 | [
"MIT"
]
| null | null | null | object DataMod: TDataMod
OldCreateOrder = False
Left = 192
Top = 107
Height = 153
Width = 176
object XML: TIcXMLParser
StandardXML = False
ValidateDocument = False
Version = '0.0.0.0'
FormatedOutput = True
RetrieveInternetURI = True
DefaultEncoding = UTF_8
Left = 40
Top = 32
end
end
| 19.277778 | 31 | 0.62536 |
836fc98c4ab19c0b96dcb7e72e6545c631488330 | 1,992 | dfm | Pascal | MainForm.dfm | MHumm/ClassTree | f8aac50735afe03cd996c7b9bf662de195e689d7 | [
"Apache-2.0"
]
| 7 | 2021-07-17T11:02:11.000Z | 2021-12-01T18:15:57.000Z | MainForm.dfm | MHumm/ClassTree | f8aac50735afe03cd996c7b9bf662de195e689d7 | [
"Apache-2.0"
]
| 1 | 2021-07-17T19:19:12.000Z | 2021-07-18T08:49:48.000Z | MainForm.dfm | MHumm/ClassTree | f8aac50735afe03cd996c7b9bf662de195e689d7 | [
"Apache-2.0"
]
| 3 | 2021-07-19T06:58:50.000Z | 2021-12-01T18:15:58.000Z | object Form1: TForm1
Left = 0
Top = 0
Caption = 'Class tree generator'
ClientHeight = 441
ClientWidth = 624
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Segoe UI'
Font.Style = []
PixelsPerInch = 96
TextHeight = 15
object ToolBar1: TToolBar
Left = 0
Top = 0
Width = 624
Height = 29
ButtonHeight = 21
ButtonWidth = 122
Caption = 'ToolBar1'
List = True
AllowTextButtons = True
TabOrder = 0
object tb_Generate: TToolButton
Left = 0
Top = 0
Caption = '&Generate'
ImageIndex = 0
Style = tbsTextButton
OnClick = tb_GenerateClick
end
object tb_Export: TToolButton
Left = 63
Top = 0
Caption = '&Export selected node'
ImageIndex = 1
Style = tbsTextButton
OnClick = tb_ExportClick
end
object tb_CopyToClipboard: TToolButton
Left = 189
Top = 0
Caption = '&Copy to clipboard'
ImageIndex = 2
Style = tbsTextButton
OnClick = tb_CopyToClipboardClick
end
end
object pc_Main: TPageControl
Left = 0
Top = 29
Width = 624
Height = 412
ActivePage = ts_Tree
Align = alClient
TabOrder = 1
object ts_Tree: TTabSheet
Caption = '&Complete tree'
object TreeView: TTreeView
Left = 0
Top = 0
Width = 616
Height = 382
Align = alClient
Indent = 19
TabOrder = 0
end
end
object ts_TextExport: TTabSheet
Caption = '&Text export'
ImageIndex = 1
object MemoExport: TMemo
Left = 0
Top = 0
Width = 616
Height = 382
Align = alClient
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Courier New'
Font.Style = []
ParentFont = False
ScrollBars = ssVertical
TabOrder = 0
end
end
end
end
| 21.652174 | 42 | 0.580823 |
f1af255f440d62eda079599476ab8dd7e650df29 | 70,729 | pas | Pascal | Source/SfmlAudio.pas | Mozzg/PasSFML | e39079c5432c22990707992cf0b2c685a413a427 | [
"Zlib"
]
| 56 | 2015-04-28T10:12:24.000Z | 2022-03-07T08:32:48.000Z | Source/SfmlAudio.pas | Mozzg/PasSFML | e39079c5432c22990707992cf0b2c685a413a427 | [
"Zlib"
]
| 10 | 2015-06-28T20:16:17.000Z | 2021-08-12T10:11:38.000Z | Source/SfmlAudio.pas | Mozzg/PasSFML | e39079c5432c22990707992cf0b2c685a413a427 | [
"Zlib"
]
| 18 | 2015-05-06T14:05:55.000Z | 2022-03-23T00:01:32.000Z | unit SfmlAudio;
////////////////////////////////////////////////////////////////////////////////
//
// PasSFML - Simple and Fast Multimedia Library for Pascal
// Copyright (C) 2015-2017 Christian-W. Budde (Christian@pcjv.de)
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
interface
{$I Sfml.inc}
uses
SfmlSystem;
const
{$IF Defined(MSWINDOWS)}
CSfmlAudioLibrary = 'csfml-audio-2.dll';
{$ELSEIF Defined(DARWIN) or Defined(MACOS)}
CSfmlAudioLibrary = 'csfml-audio-2.dylib';
{$ELSEIF Defined(UNIX)}
CSfmlAudioLibrary = 'csfml-audio.so';
{$IFEND}
type
// opaque structures
TSfmlMusicRecord = record end;
TSfmlSoundRecord = record end;
TSfmlSoundBufferRecord = record end;
TSfmlSoundBufferRecorderRecord = record end;
TSfmlSoundRecorderRecord = record end;
TSfmlSoundStreamRecord = record end;
// handles for opaque structures
PSfmlMusic = ^TSfmlMusicRecord;
PSfmlSound = ^TSfmlSoundRecord;
PSfmlSoundBuffer = ^TSfmlSoundBufferRecord;
PSfmlSoundBufferRecorder = ^TSfmlSoundBufferRecorderRecord;
PSfmlSoundRecorder = ^TSfmlSoundRecorderRecord;
PSfmlSoundStream = ^TSfmlSoundStreamRecord;
TSfmlSoundStatus = (sfStopped, sfPaused, sfPlaying);
TSfmlSoundStreamChunk = record
Samples: PSmallInt;
SampleCount: Cardinal;
end;
PSfmlSoundStreamChunk = ^TSfmlSoundStreamChunk;
TSfmlSoundStreamGetDataCallback = function (Chunk: PSfmlSoundStreamChunk; UserData: Pointer): LongBool; cdecl;
TSfmlSoundStreamSeekCallback = procedure (Time: TSfmlTime; UserData: Pointer); cdecl;
TSfmlSoundRecorderStartCallback = function (UserData: Pointer): LongBool; cdecl;
TSfmlSoundRecorderProcessCallback = function (Data: PSmallInt; SampleFrames: NativeUInt; UserData: Pointer): LongBool; cdecl;
TSfmlSoundRecorderStopCallback = procedure (UserData: Pointer); cdecl;
{$IFDEF DynLink}
TSfmlListenerSetGlobalVolume = procedure (Volume: Single); cdecl;
TSfmlListenerGetGlobalVolume = function : Single; cdecl;
TSfmlListenerSetPosition = procedure (Position: TSfmlVector3f); cdecl;
TSfmlListenerGetPosition = function : TSfmlVector3f; cdecl;
TSfmlListenerSetDirection = procedure (Direction: TSfmlVector3f); cdecl;
TSfmlListenerGetDirection = function : TSfmlVector3f; cdecl;
TSfmlListenerSetUpVector = procedure (UpVector: TSfmlVector3f); cdecl;
TSfmlListenerGetUpVector = function : TSfmlVector3f; cdecl;
TSfmlMusicCreateFromFile = function (const FileName: PAnsiChar): PSfmlMusic; cdecl;
TSfmlMusicCreateFromMemory = function (const Data: Pointer; SizeInBytes: NativeUInt): PSfmlMusic; cdecl;
TSfmlMusicCreateFromStream = function (Stream: PSfmlInputStream): PSfmlMusic; cdecl;
TSfmlMusicDestroy = procedure (Music: PSfmlMusic); cdecl;
TSfmlMusicSetLoop = procedure (Music: PSfmlMusic; Loop: LongBool); cdecl;
TSfmlMusicGetLoop = function (const Music: PSfmlMusic): LongBool; cdecl;
TSfmlMusicGetDuration = function (const Music: PSfmlMusic): TSfmlTime; cdecl;
TSfmlMusicPlay = procedure (Music: PSfmlMusic); cdecl;
TSfmlMusicPause = procedure (Music: PSfmlMusic); cdecl;
TSfmlMusicStop = procedure (Music: PSfmlMusic); cdecl;
TSfmlMusicGetChannelCount = function (const Music: PSfmlMusic): Cardinal; cdecl;
TSfmlMusicGetSampleRate = function (const Music: PSfmlMusic): Cardinal; cdecl;
TSfmlMusicGetStatus = function (const Music: PSfmlMusic): TSfmlSoundStatus; cdecl;
TSfmlMusicGetPlayingOffset = function (const Music: PSfmlMusic): TSfmlTime; cdecl;
TSfmlMusicSetPitch = procedure (Music: PSfmlMusic; Pitch: Single); cdecl;
TSfmlMusicSetVolume = procedure (Music: PSfmlMusic; Volume: Single); cdecl;
TSfmlMusicSetPosition = procedure (Music: PSfmlMusic; Position: TSfmlVector3f); cdecl;
TSfmlMusicSetRelativeToListener = procedure (Music: PSfmlMusic; Relative: LongBool); cdecl;
TSfmlMusicSetMinDistance = procedure (Music: PSfmlMusic; Distance: Single); cdecl;
TSfmlMusicSetAttenuation = procedure (Music: PSfmlMusic; Attenuation: Single); cdecl;
TSfmlMusicSetPlayingOffset = procedure (Music: PSfmlMusic; TimeOffset: TSfmlTime); cdecl;
TSfmlMusicGetPitch = function (const Music: PSfmlMusic): Single; cdecl;
TSfmlMusicGetVolume = function (const Music: PSfmlMusic): Single; cdecl;
TSfmlMusicGetPosition = function (const Music: PSfmlMusic): TSfmlVector3f; cdecl;
TSfmlMusicIsRelativeToListener = function (const Music: PSfmlMusic): LongBool; cdecl;
TSfmlMusicGetMinDistance = function (const Music: PSfmlMusic): Single; cdecl;
TSfmlMusicGetAttenuation = function (const Music: PSfmlMusic): Single; cdecl;
TSfmlSoundStreamCreate = function (OnGetData: TSfmlSoundStreamGetDataCallback; OnSeek: TSfmlSoundStreamSeekCallback; ChannelCount, SampleRate: Cardinal; UserData: Pointer): PSfmlSoundStream; cdecl;
TSfmlSoundStreamDestroy = procedure (SoundStream: PSfmlSoundStream); cdecl;
TSfmlSoundStreamPlay = procedure (SoundStream: PSfmlSoundStream); cdecl;
TSfmlSoundStreamPause = procedure (SoundStream: PSfmlSoundStream); cdecl;
TSfmlSoundStreamStop = procedure (SoundStream: PSfmlSoundStream); cdecl;
TSfmlSoundStreamGetStatus = function (const SoundStream: PSfmlSoundStream): TSfmlSoundStatus; cdecl;
TSfmlSoundStreamGetChannelCount = function (const SoundStream: PSfmlSoundStream): Cardinal; cdecl;
TSfmlSoundStreamGetSampleRate = function (const SoundStream: PSfmlSoundStream): Cardinal; cdecl;
TSfmlSoundStreamSetPitch = procedure (SoundStream: PSfmlSoundStream; Pitch: Single); cdecl;
TSfmlSoundStreamSetVolume = procedure (SoundStream: PSfmlSoundStream; Volume: Single); cdecl;
TSfmlSoundStreamSetPosition = procedure (SoundStream: PSfmlSoundStream; Position: TSfmlVector3f); cdecl;
TSfmlSoundStreamSetRelativeToListener = procedure (SoundStream: PSfmlSoundStream; Relative: LongBool); cdecl;
TSfmlSoundStreamSetMinDistance = procedure (SoundStream: PSfmlSoundStream; Distance: Single); cdecl;
TSfmlSoundStreamSetAttenuation = procedure (SoundStream: PSfmlSoundStream; Attenuation: Single); cdecl;
TSfmlSoundStreamSetPlayingOffset = procedure (SoundStream: PSfmlSoundStream; TimeOffset: TSfmlTime); cdecl;
TSfmlSoundStreamSetLoop = procedure (SoundStream: PSfmlSoundStream; Loop: LongBool); cdecl;
TSfmlSoundStreamGetPitch = function (const SoundStream: PSfmlSoundStream): Single; cdecl;
TSfmlSoundStreamGetVolume = function (const SoundStream: PSfmlSoundStream): Single; cdecl;
TSfmlSoundStreamGetPosition = function (const SoundStream: PSfmlSoundStream): TSfmlVector3f; cdecl;
TSfmlSoundStreamIsRelativeToListener = function (const SoundStream: PSfmlSoundStream): LongBool; cdecl;
TSfmlSoundStreamGetMinDistance = function (const SoundStream: PSfmlSoundStream): Single; cdecl;
TSfmlSoundStreamGetAttenuation = function (const SoundStream: PSfmlSoundStream): Single; cdecl;
TSfmlSoundStreamGetLoop = function (const SoundStream: PSfmlSoundStream): LongBool; cdecl;
TSfmlSoundStreamGetPlayingOffset = function (const SoundStream: PSfmlSoundStream): TSfmlTime; cdecl;
TSfmlSoundCreate = function : PSfmlSound; cdecl;
TSfmlSoundCopy = function (const Sound: PSfmlSound): PSfmlSound; cdecl;
TSfmlSoundDestroy = procedure (Sound: PSfmlSound); cdecl;
TSfmlSoundPlay = procedure (Sound: PSfmlSound); cdecl;
TSfmlSoundPause = procedure (Sound: PSfmlSound); cdecl;
TSfmlSoundStop = procedure (Sound: PSfmlSound); cdecl;
TSfmlSoundSetBuffer = procedure (Sound: PSfmlSound; const Buffer: PSfmlSoundBuffer); cdecl;
TSfmlSoundGetBuffer = function (const Sound: PSfmlSound): PSfmlSoundBuffer; cdecl;
TSfmlSoundSetLoop = procedure (Sound: PSfmlSound; Loop: LongBool); cdecl;
TSfmlSoundGetLoop = function (const Sound: PSfmlSound): LongBool; cdecl;
TSfmlSoundGetStatus = function (const Sound: PSfmlSound): TSfmlSoundStatus; cdecl;
TSfmlSoundSetPitch = procedure (Sound: PSfmlSound; Pitch: Single); cdecl;
TSfmlSoundSetVolume = procedure (Sound: PSfmlSound; Volume: Single); cdecl;
TSfmlSoundSetPosition = procedure (Sound: PSfmlSound; Position: TSfmlVector3f); cdecl;
TSfmlSoundSetRelativeToListener = procedure (Sound: PSfmlSound; Relative: LongBool); cdecl;
TSfmlSoundSetMinDistance = procedure (Sound: PSfmlSound; Distance: Single); cdecl;
TSfmlSoundSetAttenuation = procedure (Sound: PSfmlSound; Attenuation: Single); cdecl;
TSfmlSoundSetPlayingOffset = procedure (Sound: PSfmlSound; TimeOffset: TSfmlTime); cdecl;
TSfmlSoundGetPitch = function (const Sound: PSfmlSound): Single; cdecl;
TSfmlSoundGetVolume = function (const Sound: PSfmlSound): Single; cdecl;
TSfmlSoundGetPosition = function (const Sound: PSfmlSound): TSfmlVector3f; cdecl;
TSfmlSoundIsRelativeToListener = function (const Sound: PSfmlSound): LongBool; cdecl;
TSfmlSoundGetMinDistance = function (const Sound: PSfmlSound): Single; cdecl;
TSfmlSoundGetAttenuation = function (const Sound: PSfmlSound): Single; cdecl;
TSfmlSoundGetPlayingOffset = function (const Sound: PSfmlSound): TSfmlTime; cdecl;
TSfmlSoundBufferCreateFromFile = function (const FileName: PAnsiChar): PSfmlSoundBuffer; cdecl;
TSfmlSoundBufferCreateFromMemory = function (const Data: Pointer; SizeInBytes: NativeUInt): PSfmlSoundBuffer; cdecl;
TSfmlSoundBufferCreateFromStream = function (Stream: PSfmlInputStream): PSfmlSoundBuffer; cdecl;
TSfmlSoundBufferCreateFromSamples = function (const Samples: PSmallInt; SampleCount: UInt64; ChannelCount, SampleRate: Cardinal): PSfmlSoundBuffer; cdecl;
TSfmlSoundBufferCopy = function (const SoundBuffer: PSfmlSoundBuffer): PSfmlSoundBuffer; cdecl;
TSfmlSoundBufferDestroy = procedure (SoundBuffer: PSfmlSoundBuffer); cdecl;
TSfmlSoundBufferSaveToFile = function (const SoundBuffer: PSfmlSoundBuffer; const FileName: PAnsiChar): LongBool; cdecl;
TSfmlSoundBufferGetSamples = function (const SoundBuffer: PSfmlSoundBuffer): PSmallInt; cdecl;
TSfmlSoundBufferGetSampleCount = function (const SoundBuffer: PSfmlSoundBuffer): NativeUInt; cdecl;
TSfmlSoundBufferGetSampleRate = function (const SoundBuffer: PSfmlSoundBuffer): Cardinal; cdecl;
TSfmlSoundBufferGetChannelCount = function (const SoundBuffer: PSfmlSoundBuffer): Cardinal; cdecl;
TSfmlSoundBufferGetDuration = function (const SoundBuffer: PSfmlSoundBuffer): TSfmlTime; cdecl;
TSfmlSoundBufferRecorderCreate = function : PSfmlSoundBufferRecorder; cdecl;
TSfmlSoundBufferRecorderDestroy = procedure (soundBufferRecorder: PSfmlSoundBufferRecorder); cdecl;
TSfmlSoundBufferRecorderStart = function (soundBufferRecorder: PSfmlSoundBufferRecorder; SampleRate: Cardinal): LongBool; cdecl;
TSfmlSoundBufferRecorderStop = procedure (soundBufferRecorder: PSfmlSoundBufferRecorder); cdecl;
TSfmlSoundBufferRecorderGetSampleRate = function (const soundBufferRecorder: PSfmlSoundBufferRecorder): Cardinal; cdecl;
TSfmlSoundBufferRecorderGetBuffer = function (const soundBufferRecorder: PSfmlSoundBufferRecorder): PSfmlSoundBuffer; cdecl;
TSfmlSoundBufferRecorderSetDevice = function (SoundRecorder: PSfmlSoundBufferRecorder; const Name: PAnsiChar): LongBool; cdecl;
TSfmlSoundBufferRecorderGetDevice = function (SoundRecorder: PSfmlSoundBufferRecorder): PAnsiChar; cdecl;
TSfmlSoundRecorderCreate = function (OnStart: TSfmlSoundRecorderStartCallback; OnProcess: TSfmlSoundRecorderProcessCallback; OnStop: TSfmlSoundRecorderStopCallback; UserData: Pointer): PSfmlSoundRecorder; cdecl;
TSfmlSoundRecorderDestroy = procedure (SoundRecorder: PSfmlSoundRecorder); cdecl;
TSfmlSoundRecorderStart = function (SoundRecorder: PSfmlSoundRecorder; SampleRate: Cardinal): LongBool; cdecl;
TSfmlSoundRecorderStop = procedure (SoundRecorder: PSfmlSoundRecorder); cdecl;
TSfmlSoundRecorderGetSampleRate = function (const SoundRecorder: PSfmlSoundRecorder): Cardinal; cdecl;
TSfmlSoundRecorderIsAvailable = function : LongBool; cdecl;
TSfmlSoundRecorderSetProcessingInterval = procedure (SoundRecorder: PSfmlSoundRecorder; Interval: TSfmlTime); cdecl;
TSfmlSoundRecorderGetAvailableDevices = function (count: PNativeUInt): PPAnsiChar; cdecl;
TSfmlSoundRecorderGetDefaultDevice = function : PAnsiChar; cdecl;
TSfmlSoundRecorderSetDevice = function (SoundRecorder: PSfmlSoundRecorder; const Name: PAnsiChar): LongBool; cdecl;
TSfmlSoundRecorderGetDevice = function (SoundRecorder: PSfmlSoundRecorder): PAnsiChar; cdecl;
TSfmlSoundRecorderSetChannelCount = function (SoundRecorder: PSfmlSoundRecorder; const ChannelCount: Cardinal): LongBool; cdecl;
TSfmlSoundRecorderGetChannelCount = function (const SoundRecorder: PSfmlSoundRecorder): Cardinal; cdecl;
var
SfmlListenerSetGlobalVolume: TSfmlListenerSetGlobalVolume;
SfmlListenerGetGlobalVolume: TSfmlListenerGetGlobalVolume;
SfmlListenerSetPosition: TSfmlListenerSetPosition;
SfmlListenerGetPosition: TSfmlListenerGetPosition;
SfmlListenerSetDirection: TSfmlListenerSetDirection;
SfmlListenerGetDirection: TSfmlListenerGetDirection;
SfmlListenerSetUpVector: TSfmlListenerSetUpVector;
SfmlListenerGetUpVector: TSfmlListenerGetUpVector;
SfmlMusicCreateFromFile: TSfmlMusicCreateFromFile;
SfmlMusicCreateFromMemory: TSfmlMusicCreateFromMemory;
SfmlMusicCreateFromStream: TSfmlMusicCreateFromStream;
SfmlMusicDestroy: TSfmlMusicDestroy;
SfmlMusicSetLoop: TSfmlMusicSetLoop;
SfmlMusicGetLoop: TSfmlMusicGetLoop;
SfmlMusicPlay: TSfmlMusicPlay;
SfmlMusicPause: TSfmlMusicPause;
SfmlMusicStop: TSfmlMusicStop;
SfmlMusicGetChannelCount: TSfmlMusicGetChannelCount;
SfmlMusicGetSampleRate: TSfmlMusicGetSampleRate;
SfmlMusicGetStatus: TSfmlMusicGetStatus;
SfmlMusicSetPitch: TSfmlMusicSetPitch;
SfmlMusicSetVolume: TSfmlMusicSetVolume;
SfmlMusicSetPosition: TSfmlMusicSetPosition;
SfmlMusicSetRelativeToListener: TSfmlMusicSetRelativeToListener;
SfmlMusicSetMinDistance: TSfmlMusicSetMinDistance;
SfmlMusicSetAttenuation: TSfmlMusicSetAttenuation;
SfmlMusicSetPlayingOffset: TSfmlMusicSetPlayingOffset;
SfmlMusicGetPitch: TSfmlMusicGetPitch;
SfmlMusicGetVolume: TSfmlMusicGetVolume;
SfmlMusicGetPosition: TSfmlMusicGetPosition;
SfmlMusicIsRelativeToListener: TSfmlMusicIsRelativeToListener;
SfmlMusicGetMinDistance: TSfmlMusicGetMinDistance;
SfmlMusicGetAttenuation: TSfmlMusicGetAttenuation;
SfmlSoundStreamCreate: TSfmlSoundStreamCreate;
SfmlSoundStreamDestroy: TSfmlSoundStreamDestroy;
SfmlSoundStreamPlay: TSfmlSoundStreamPlay;
SfmlSoundStreamPause: TSfmlSoundStreamPause;
SfmlSoundStreamStop: TSfmlSoundStreamStop;
SfmlSoundStreamGetStatus: TSfmlSoundStreamGetStatus;
SfmlSoundStreamGetChannelCount: TSfmlSoundStreamGetChannelCount;
SfmlSoundStreamGetSampleRate: TSfmlSoundStreamGetSampleRate;
SfmlSoundStreamSetPitch: TSfmlSoundStreamSetPitch;
SfmlSoundStreamSetVolume: TSfmlSoundStreamSetVolume;
SfmlSoundStreamSetPosition: TSfmlSoundStreamSetPosition;
SfmlSoundStreamSetRelativeToListener: TSfmlSoundStreamSetRelativeToListener;
SfmlSoundStreamSetMinDistance: TSfmlSoundStreamSetMinDistance;
SfmlSoundStreamSetAttenuation: TSfmlSoundStreamSetAttenuation;
SfmlSoundStreamSetPlayingOffset: TSfmlSoundStreamSetPlayingOffset;
SfmlSoundStreamSetLoop: TSfmlSoundStreamSetLoop;
SfmlSoundStreamGetPitch: TSfmlSoundStreamGetPitch;
SfmlSoundStreamGetVolume: TSfmlSoundStreamGetVolume;
SfmlSoundStreamGetPosition: TSfmlSoundStreamGetPosition;
SfmlSoundStreamIsRelativeToListener: TSfmlSoundStreamIsRelativeToListener;
SfmlSoundStreamGetMinDistance: TSfmlSoundStreamGetMinDistance;
SfmlSoundStreamGetAttenuation: TSfmlSoundStreamGetAttenuation;
SfmlSoundStreamGetLoop: TSfmlSoundStreamGetLoop;
SfmlSoundCreate: TSfmlSoundCreate;
SfmlSoundCopy: TSfmlSoundCopy;
SfmlSoundDestroy: TSfmlSoundDestroy;
SfmlSoundPlay: TSfmlSoundPlay;
SfmlSoundPause: TSfmlSoundPause;
SfmlSoundStop: TSfmlSoundStop;
SfmlSoundSetBuffer: TSfmlSoundSetBuffer;
SfmlSoundGetBuffer: TSfmlSoundGetBuffer;
SfmlSoundSetLoop: TSfmlSoundSetLoop;
SfmlSoundGetLoop: TSfmlSoundGetLoop;
SfmlSoundGetStatus: TSfmlSoundGetStatus;
SfmlSoundSetPitch: TSfmlSoundSetPitch;
SfmlSoundSetVolume: TSfmlSoundSetVolume;
SfmlSoundSetPosition: TSfmlSoundSetPosition;
SfmlSoundSetRelativeToListener: TSfmlSoundSetRelativeToListener;
SfmlSoundSetMinDistance: TSfmlSoundSetMinDistance;
SfmlSoundSetAttenuation: TSfmlSoundSetAttenuation;
SfmlSoundSetPlayingOffset: TSfmlSoundSetPlayingOffset;
SfmlSoundGetPitch: TSfmlSoundGetPitch;
SfmlSoundGetVolume: TSfmlSoundGetVolume;
SfmlSoundGetPosition: TSfmlSoundGetPosition;
SfmlSoundIsRelativeToListener: TSfmlSoundIsRelativeToListener;
SfmlSoundGetMinDistance: TSfmlSoundGetMinDistance;
SfmlSoundGetAttenuation: TSfmlSoundGetAttenuation;
SfmlSoundBufferCreateFromFile: TSfmlSoundBufferCreateFromFile;
SfmlSoundBufferCreateFromMemory: TSfmlSoundBufferCreateFromMemory;
SfmlSoundBufferCreateFromStream: TSfmlSoundBufferCreateFromStream;
SfmlSoundBufferCreateFromSamples: TSfmlSoundBufferCreateFromSamples;
SfmlSoundBufferCopy: TSfmlSoundBufferCopy;
SfmlSoundBufferDestroy: TSfmlSoundBufferDestroy;
SfmlSoundBufferSaveToFile: TSfmlSoundBufferSaveToFile;
SfmlSoundBufferGetSamples: TSfmlSoundBufferGetSamples;
SfmlSoundBufferGetSampleCount: TSfmlSoundBufferGetSampleCount;
SfmlSoundBufferGetSampleRate: TSfmlSoundBufferGetSampleRate;
SfmlSoundBufferGetChannelCount: TSfmlSoundBufferGetChannelCount;
SfmlSoundBufferRecorderCreate: TSfmlSoundBufferRecorderCreate;
SfmlSoundBufferRecorderDestroy: TSfmlSoundBufferRecorderDestroy;
SfmlSoundBufferRecorderStart: TSfmlSoundBufferRecorderStart;
SfmlSoundBufferRecorderStop: TSfmlSoundBufferRecorderStop;
SfmlSoundBufferRecorderGetSampleRate: TSfmlSoundBufferRecorderGetSampleRate;
SfmlSoundBufferRecorderGetBuffer: TSfmlSoundBufferRecorderGetBuffer;
SfmlSoundBufferRecorderSetDevice: TSfmlSoundBufferRecorderSetDevice;
SfmlSoundBufferRecorderGetDevice: TSfmlSoundBufferRecorderGetDevice;
SfmlSoundRecorderCreate: TSfmlSoundRecorderCreate;
SfmlSoundRecorderDestroy: TSfmlSoundRecorderDestroy;
SfmlSoundRecorderStart: TSfmlSoundRecorderStart;
SfmlSoundRecorderStop: TSfmlSoundRecorderStop;
SfmlSoundRecorderGetSampleRate: TSfmlSoundRecorderGetSampleRate;
SfmlSoundRecorderIsAvailable: TSfmlSoundRecorderIsAvailable;
SfmlSoundRecorderSetProcessingInterval: TSfmlSoundRecorderSetProcessingInterval;
SfmlSoundRecorderGetAvailableDevices: TSfmlSoundRecorderGetAvailableDevices;
SfmlSoundRecorderGetDefaultDevice: TSfmlSoundRecorderGetDefaultDevice;
SfmlSoundRecorderSetDevice: TSfmlSoundRecorderSetDevice;
SfmlSoundRecorderGetDevice: TSfmlSoundRecorderGetDevice;
SfmlSoundRecorderSetChannelCount: TSfmlSoundRecorderSetChannelCount;
SfmlSoundRecorderGetChannelCount: TSfmlSoundRecorderGetChannelCount;
{$IFNDEF INT64RETURNWORKAROUND}
SfmlMusicGetDuration: TSfmlMusicGetDuration;
SfmlMusicGetPlayingOffset: TSfmlMusicGetPlayingOffset;
SfmlSoundStreamGetPlayingOffset: TSfmlSoundStreamGetPlayingOffset;
SfmlSoundGetPlayingOffset: TSfmlSoundGetPlayingOffset;
SfmlSoundBufferGetDuration: TSfmlSoundBufferGetDuration;
{$ENDIF}
{$ELSE}
// static linking
procedure SfmlListenerSetGlobalVolume(Volume: Single); cdecl; external CSfmlAudioLibrary name 'sfListener_setGlobalVolume';
function SfmlListenerGetGlobalVolume: Single; cdecl; external CSfmlAudioLibrary name 'sfListener_getGlobalVolume';
procedure SfmlListenerSetPosition(Position: TSfmlVector3f); cdecl; external CSfmlAudioLibrary name 'sfListener_setPosition';
function SfmlListenerGetPosition: TSfmlVector3f; cdecl; external CSfmlAudioLibrary name 'sfListener_getPosition';
procedure SfmlListenerSetDirection(Direction: TSfmlVector3f); cdecl; external CSfmlAudioLibrary name 'sfListener_setDirection';
function SfmlListenerGetDirection: TSfmlVector3f; cdecl; external CSfmlAudioLibrary name 'sfListener_getDirection';
procedure SfmlListenerSetUpVector(UpVector: TSfmlVector3f); cdecl; external CSfmlAudioLibrary name 'sfListener_setUpVector';
function SfmlListenerGetUpVector: TSfmlVector3f; cdecl; external CSfmlAudioLibrary name 'sfListener_getUpVector';
function SfmlMusicCreateFromFile(const FileName: PAnsiChar): PSfmlMusic; cdecl; external CSfmlAudioLibrary name 'sfMusic_createFromFile';
function SfmlMusicCreateFromMemory(const data: Pointer; SizeInBytes: NativeUInt): PSfmlMusic; cdecl; external CSfmlAudioLibrary name 'sfMusic_createFromMemory';
function SfmlMusicCreateFromStream(Stream: PSfmlInputStream): PSfmlMusic; cdecl; external CSfmlAudioLibrary name 'sfMusic_createFromStream';
procedure SfmlMusicDestroy(Music: PSfmlMusic); cdecl; external CSfmlAudioLibrary name 'sfMusic_destroy';
procedure SfmlMusicSetLoop(Music: PSfmlMusic; Loop: LongBool); cdecl; external CSfmlAudioLibrary name 'sfMusic_setLoop';
function SfmlMusicGetLoop(const Music: PSfmlMusic): LongBool; cdecl; external CSfmlAudioLibrary name 'sfMusic_getLoop';
{$IFNDEF INT64RETURNWORKAROUND}
function SfmlMusicGetDuration(const Music: PSfmlMusic): TSfmlTime; cdecl; external CSfmlAudioLibrary name 'sfMusic_getDuration';
{$ENDIF}
procedure SfmlMusicPlay(Music: PSfmlMusic); cdecl; external CSfmlAudioLibrary name 'sfMusic_play';
procedure SfmlMusicPause(Music: PSfmlMusic); cdecl; external CSfmlAudioLibrary name 'sfMusic_pause';
procedure SfmlMusicStop(Music: PSfmlMusic); cdecl; external CSfmlAudioLibrary name 'sfMusic_stop';
function SfmlMusicGetChannelCount(const Music: PSfmlMusic): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfMusic_getChannelCount';
function SfmlMusicGetSampleRate(const Music: PSfmlMusic): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfMusic_getSampleRate';
function SfmlMusicGetStatus(const Music: PSfmlMusic): TSfmlSoundStatus; cdecl; external CSfmlAudioLibrary name 'sfMusic_getStatus';
{$IFNDEF INT64RETURNWORKAROUND}
function SfmlMusicGetPlayingOffset(const Music: PSfmlMusic): TSfmlTime; cdecl; external CSfmlAudioLibrary name 'sfMusic_getPlayingOffset';
{$ENDIF}
procedure SfmlMusicSetPitch(Music: PSfmlMusic; Pitch: Single); cdecl; external CSfmlAudioLibrary name 'sfMusic_setPitch';
procedure SfmlMusicSetVolume(Music: PSfmlMusic; Volume: Single); cdecl; external CSfmlAudioLibrary name 'sfMusic_setVolume';
procedure SfmlMusicSetPosition(Music: PSfmlMusic; Position: TSfmlVector3f); cdecl; external CSfmlAudioLibrary name 'sfMusic_setPosition';
procedure SfmlMusicSetRelativeToListener(Music: PSfmlMusic; Relative: LongBool); cdecl; external CSfmlAudioLibrary name 'sfMusic_setRelativeToListener';
procedure SfmlMusicSetMinDistance(Music: PSfmlMusic; Distance: Single); cdecl; external CSfmlAudioLibrary name 'sfMusic_setMinDistance';
procedure SfmlMusicSetAttenuation(Music: PSfmlMusic; Attenuation: Single); cdecl; external CSfmlAudioLibrary name 'sfMusic_setAttenuation';
procedure SfmlMusicSetPlayingOffset(Music: PSfmlMusic; TimeOffset: TSfmlTime); cdecl; external CSfmlAudioLibrary name 'sfMusic_setPlayingOffset';
function SfmlMusicGetPitch(const Music: PSfmlMusic): Single; cdecl; external CSfmlAudioLibrary name 'sfMusic_getPitch';
function SfmlMusicGetVolume(const Music: PSfmlMusic): Single; cdecl; external CSfmlAudioLibrary name 'sfMusic_getVolume';
function SfmlMusicGetPosition(const Music: PSfmlMusic): TSfmlVector3f; cdecl; external CSfmlAudioLibrary name 'sfMusic_getPosition';
function SfmlMusicIsRelativeToListener(const Music: PSfmlMusic): LongBool; cdecl; external CSfmlAudioLibrary name 'sfMusic_isRelativeToListener';
function SfmlMusicGetMinDistance(const Music: PSfmlMusic): Single; cdecl; external CSfmlAudioLibrary name 'sfMusic_getMinDistance';
function SfmlMusicGetAttenuation(const Music: PSfmlMusic): Single; cdecl; external CSfmlAudioLibrary name 'sfMusic_getAttenuation';
function SfmlSoundStreamCreate(OnGetData: TSfmlSoundStreamGetDataCallback; OnSeek: TSfmlSoundStreamSeekCallback; ChannelCount, SampleRate: Cardinal; UserData: Pointer): PSfmlSoundStream; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_create';
procedure SfmlSoundStreamDestroy(SoundStream: PSfmlSoundStream); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_destroy';
procedure SfmlSoundStreamPlay(SoundStream: PSfmlSoundStream); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_play';
procedure SfmlSoundStreamPause(SoundStream: PSfmlSoundStream); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_pause';
procedure SfmlSoundStreamStop(SoundStream: PSfmlSoundStream); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_stop';
function SfmlSoundStreamGetStatus(const SoundStream: PSfmlSoundStream): TSfmlSoundStatus; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getStatus';
function SfmlSoundStreamGetChannelCount(const SoundStream: PSfmlSoundStream): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getChannelCount';
function SfmlSoundStreamGetSampleRate(const SoundStream: PSfmlSoundStream): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getSampleRate';
procedure SfmlSoundStreamSetPitch(SoundStream: PSfmlSoundStream; Pitch: Single); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setPitch';
procedure SfmlSoundStreamSetVolume(SoundStream: PSfmlSoundStream; Volume: Single); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setVolume';
procedure SfmlSoundStreamSetPosition(SoundStream: PSfmlSoundStream; Position: TSfmlVector3f); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setPosition';
procedure SfmlSoundStreamSetRelativeToListener(SoundStream: PSfmlSoundStream; Relative: LongBool); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setRelativeToListener';
procedure SfmlSoundStreamSetMinDistance(SoundStream: PSfmlSoundStream; Distance: Single); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setMinDistance';
procedure SfmlSoundStreamSetAttenuation(SoundStream: PSfmlSoundStream; Attenuation: Single); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setAttenuation';
procedure SfmlSoundStreamSetPlayingOffset(SoundStream: PSfmlSoundStream; TimeOffset: TSfmlTime); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setPlayingOffset';
procedure SfmlSoundStreamSetLoop(SoundStream: PSfmlSoundStream; Loop: LongBool); cdecl; external CSfmlAudioLibrary name 'sfSoundStream_setLoop';
function SfmlSoundStreamGetPitch(const SoundStream: PSfmlSoundStream): Single; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getPitch';
function SfmlSoundStreamGetVolume(const SoundStream: PSfmlSoundStream): Single; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getVolume';
function SfmlSoundStreamGetPosition(const SoundStream: PSfmlSoundStream): TSfmlVector3f; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getPosition';
function SfmlSoundStreamIsRelativeToListener(const SoundStream: PSfmlSoundStream): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_isRelativeToListener';
function SfmlSoundStreamGetMinDistance(const SoundStream: PSfmlSoundStream): Single; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getMinDistance';
function SfmlSoundStreamGetAttenuation(const SoundStream: PSfmlSoundStream): Single; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getAttenuation';
function SfmlSoundStreamGetLoop(const SoundStream: PSfmlSoundStream): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getLoop';
{$IFNDEF INT64RETURNWORKAROUND}
function SfmlSoundStreamGetPlayingOffset(const SoundStream: PSfmlSoundStream): TSfmlTime; cdecl; external CSfmlAudioLibrary name 'sfSoundStream_getPlayingOffset';
{$ENDIF}
function SfmlSoundCreate: PSfmlSound; cdecl; external CSfmlAudioLibrary name 'sfSound_create';
function SfmlSoundCopy(const Sound: PSfmlSound): PSfmlSound; cdecl; external CSfmlAudioLibrary name 'sfSound_copy';
procedure SfmlSoundDestroy(Sound: PSfmlSound); cdecl; external CSfmlAudioLibrary name 'sfSound_destroy';
procedure SfmlSoundPlay(Sound: PSfmlSound); cdecl; external CSfmlAudioLibrary name 'sfSound_play';
procedure SfmlSoundPause(Sound: PSfmlSound); cdecl; external CSfmlAudioLibrary name 'sfSound_pause';
procedure SfmlSoundStop(Sound: PSfmlSound); cdecl; external CSfmlAudioLibrary name 'sfSound_stop';
procedure SfmlSoundSetBuffer(Sound: PSfmlSound; const Buffer: PSfmlSoundBuffer); cdecl; external CSfmlAudioLibrary name 'sfSound_setBuffer';
function SfmlSoundGetBuffer(const Sound: PSfmlSound): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSound_getBuffer';
procedure SfmlSoundSetLoop(Sound: PSfmlSound; Loop: LongBool); cdecl; external CSfmlAudioLibrary name 'sfSound_setLoop';
function SfmlSoundGetLoop(const Sound: PSfmlSound): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSound_getLoop';
function SfmlSoundGetStatus(const Sound: PSfmlSound): TSfmlSoundStatus; cdecl; external CSfmlAudioLibrary name 'sfSound_getStatus';
procedure SfmlSoundSetPitch(Sound: PSfmlSound; Pitch: Single); cdecl; external CSfmlAudioLibrary name 'sfSound_setPitch';
procedure SfmlSoundSetVolume(Sound: PSfmlSound; Volume: Single); cdecl; external CSfmlAudioLibrary name 'sfSound_setVolume';
procedure SfmlSoundSetPosition(Sound: PSfmlSound; Position: TSfmlVector3f); cdecl; external CSfmlAudioLibrary name 'sfSound_setPosition';
procedure SfmlSoundSetRelativeToListener(Sound: PSfmlSound; Relative: LongBool); cdecl; external CSfmlAudioLibrary name 'sfSound_setRelativeToListener';
procedure SfmlSoundSetMinDistance(Sound: PSfmlSound; Distance: Single); cdecl; external CSfmlAudioLibrary name 'sfSound_setMinDistance';
procedure SfmlSoundSetAttenuation(Sound: PSfmlSound; Attenuation: Single); cdecl; external CSfmlAudioLibrary name 'sfSound_setAttenuation';
procedure SfmlSoundSetPlayingOffset(Sound: PSfmlSound; TimeOffset: TSfmlTime); cdecl; external CSfmlAudioLibrary name 'sfSound_setPlayingOffset';
function SfmlSoundGetPitch(const Sound: PSfmlSound): Single; cdecl; external CSfmlAudioLibrary name 'sfSound_getPitch';
function SfmlSoundGetVolume(const Sound: PSfmlSound): Single; cdecl; external CSfmlAudioLibrary name 'sfSound_getVolume';
function SfmlSoundGetPosition(const Sound: PSfmlSound): TSfmlVector3f; cdecl; external CSfmlAudioLibrary name 'sfSound_getPosition';
function SfmlSoundIsRelativeToListener(const Sound: PSfmlSound): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSound_isRelativeToListener';
function SfmlSoundGetMinDistance(const Sound: PSfmlSound): Single; cdecl; external CSfmlAudioLibrary name 'sfSound_getMinDistance';
function SfmlSoundGetAttenuation(const Sound: PSfmlSound): Single; cdecl; external CSfmlAudioLibrary name 'sfSound_getAttenuation';
{$IFNDEF INT64RETURNWORKAROUND}
function SfmlSoundGetPlayingOffset(const Sound: PSfmlSound): TSfmlTime; cdecl; external CSfmlAudioLibrary name 'sfSound_getPlayingOffset';
{$ENDIF}
function SfmlSoundBufferCreateFromFile(const FileName: PAnsiChar): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_createFromFile';
function SfmlSoundBufferCreateFromMemory(const Data: Pointer; SizeInBytes: NativeUInt): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_createFromMemory';
function SfmlSoundBufferCreateFromStream(Stream: PSfmlInputStream): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_createFromStream';
function SfmlSoundBufferCreateFromSamples(const Samples: PSmallInt; SampleCount: UInt64; ChannelCount, SampleRate: Cardinal): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_createFromSamples';
function SfmlSoundBufferCopy(const SoundBuffer: PSfmlSoundBuffer): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_copy';
procedure SfmlSoundBufferDestroy(SoundBuffer: PSfmlSoundBuffer); cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_destroy';
function SfmlSoundBufferSaveToFile(const SoundBuffer: PSfmlSoundBuffer; const FileName: PAnsiChar): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_saveToFile';
function SfmlSoundBufferGetSamples(const SoundBuffer: PSfmlSoundBuffer): PSmallInt; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_getSamples';
function SfmlSoundBufferGetSampleCount(const SoundBuffer: PSfmlSoundBuffer): NativeUInt; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_getSampleCount';
function SfmlSoundBufferGetSampleRate(const SoundBuffer: PSfmlSoundBuffer): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_getSampleRate';
function SfmlSoundBufferGetChannelCount(const SoundBuffer: PSfmlSoundBuffer): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_getChannelCount';
{$IFNDEF INT64RETURNWORKAROUND}
function SfmlSoundBufferGetDuration(const SoundBuffer: PSfmlSoundBuffer): TSfmlTime; cdecl; external CSfmlAudioLibrary name 'sfSoundBuffer_getDuration';
{$ENDIF}
function SfmlSoundBufferRecorderCreate: PSfmlSoundBufferRecorder; cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_create';
procedure SfmlSoundBufferRecorderDestroy(soundBufferRecorder: PSfmlSoundBufferRecorder); cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_destroy';
function SfmlSoundBufferRecorderStart(soundBufferRecorder: PSfmlSoundBufferRecorder; SampleRate: Cardinal): Longbool; cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_start';
procedure SfmlSoundBufferRecorderStop(soundBufferRecorder: PSfmlSoundBufferRecorder); cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_stop';
function SfmlSoundBufferRecorderGetSampleRate(const soundBufferRecorder: PSfmlSoundBufferRecorder): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_getSampleRate';
function SfmlSoundBufferRecorderGetBuffer(const soundBufferRecorder: PSfmlSoundBufferRecorder): PSfmlSoundBuffer; cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_getBuffer';
function SfmlSoundBufferRecorderSetDevice(SoundRecorder: PSfmlSoundBufferRecorder; const Name: PAnsiChar): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_setDevice';
function SfmlSoundBufferRecorderGetDevice(SoundRecorder: PSfmlSoundBufferRecorder): PAnsiChar; cdecl; external CSfmlAudioLibrary name 'sfSoundBufferRecorder_getDevice';
function SfmlSoundRecorderCreate(OnStart: TSfmlSoundRecorderStartCallback; OnProcess: TSfmlSoundRecorderProcessCallback; OnStop: TSfmlSoundRecorderStopCallback; UserData: Pointer): PSfmlSoundRecorder; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_create';
procedure SfmlSoundRecorderDestroy(SoundRecorder: PSfmlSoundRecorder); cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_destroy';
function SfmlSoundRecorderStart(SoundRecorder: PSfmlSoundRecorder; SampleRate: Cardinal): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_start';
procedure SfmlSoundRecorderStop(SoundRecorder: PSfmlSoundRecorder); cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_stop';
function SfmlSoundRecorderGetSampleRate(const SoundRecorder: PSfmlSoundRecorder): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_getSampleRate';
function SfmlSoundRecorderIsAvailable: LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_isAvailable';
procedure SfmlSoundRecorderSetProcessingInterval(SoundRecorder: PSfmlSoundRecorder; Interval: TSfmlTime); cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_setProcessingInterval';
function SfmlSoundRecorderGetAvailableDevices(count: PNativeUInt): PPAnsiChar; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_getAvailableDevices';
function SfmlSoundRecorderGetDefaultDevice: PAnsiChar; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_getDefaultDevice';
function SfmlSoundRecorderSetDevice(SoundRecorder: PSfmlSoundRecorder; const Name: PAnsiChar): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_setDevice';
function SfmlSoundRecorderGetDevice(SoundRecorder: PSfmlSoundRecorder): PAnsiChar; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_getDevice';
function SfmlSoundRecorderSetChannelCount(SoundRecorder: PSfmlSoundRecorder; const ChannelCount: Cardinal): LongBool; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_getChannelCount';
function SfmlSoundRecorderGetChannelCount(const SoundRecorder: PSfmlSoundRecorder): Cardinal; cdecl; external CSfmlAudioLibrary name 'sfSoundRecorder_setChannelCount';
{$ENDIF}
type
TSfmlSoundSource = class
protected
function GetAttenuation: Single; virtual; abstract;
function GetMinDistance: Single; virtual; abstract;
function GetPitch: Single; virtual; abstract;
function GetPosition: TSfmlVector3f; virtual; abstract;
function GetRelativeToListener: Boolean; virtual; abstract;
function GetStatus: TSfmlSoundStatus; virtual; abstract;
function GetVolume: Single; virtual; abstract;
procedure SetAttenuation(Attenuation: Single); virtual; abstract;
procedure SetMinDistance(Distance: Single); virtual; abstract;
procedure SetPitch(Pitch: Single); virtual; abstract;
procedure SetPosition(Position: TSfmlVector3f); virtual; abstract;
procedure SetRelativeToListener(Relative: Boolean); virtual; abstract;
procedure SetVolume(Volume: Single); virtual; abstract;
public
property Attenuation: Single read GetAttenuation write SetAttenuation;
property MinDistance: Single read GetMinDistance write SetMinDistance;
property Pitch: Single read GetPitch write SetPitch;
property Position: TSfmlVector3f read GetPosition write SetPosition;
property RelativeToListener: Boolean read GetRelativeToListener write SetRelativeToListener;
property Status: TSfmlSoundStatus read GetStatus;
property Volume: Single read GetVolume write SetVolume;
end;
TSfmlSoundStream = class(TSfmlSoundSource)
private
FHandle: PSfmlSoundStream;
protected
function GetAttenuation: Single; override;
function GetChannelCount: Cardinal; virtual;
function GetLoop: Boolean; virtual;
function GetMinDistance: Single; override;
function GetPitch: Single; override;
function GetPlayingOffset: TSfmlTime; virtual;
function GetPosition: TSfmlVector3f; override;
function GetRelativeToListener: Boolean; override;
function GetSampleRate: Cardinal; virtual;
function GetStatus: TSfmlSoundStatus; override;
function GetVolume: Single; override;
procedure SetAttenuation(Attenuation: Single); override;
procedure SetLoop(Loop: Boolean); virtual;
procedure SetMinDistance(Distance: Single); override;
procedure SetPitch(Pitch: Single); override;
procedure SetPlayingOffset(TimeOffset: TSfmlTime); virtual;
procedure SetPosition(Position: TSfmlVector3f); override;
procedure SetRelativeToListener(Relative: Boolean); override;
procedure SetVolume(Volume: Single); override;
public
constructor Create(OnGetData: TSfmlSoundStreamGetDataCallback;
OnSeek: TSfmlSoundStreamSeekCallback;
ChannelCount, SampleRate: Cardinal; UserData: Pointer);
destructor Destroy; override;
procedure Play;
procedure Pause;
procedure Stop;
property ChannelCount: Cardinal read GetChannelCount;
property Handle: PSfmlSoundStream read FHandle;
property Loop: Boolean read GetLoop write SetLoop;
property PlayingOffset: TSfmlTime read GetPlayingOffset write SetPlayingOffset;
property SampleRate: Cardinal read GetSampleRate;
end;
TSfmlMusic = class(TSfmlSoundStream)
private
FHandle: PSfmlMusic;
function GetDuration: TSfmlTime;
protected
function GetAttenuation: Single; override;
function GetChannelCount: Cardinal; override;
function GetLoop: Boolean; override;
function GetMinDistance: Single; override;
function GetPitch: Single; override;
function GetPlayingOffset: TSfmlTime; override;
function GetPosition: TSfmlVector3f; override;
function GetRelativeToListener: Boolean; override;
function GetSampleRate: Cardinal; override;
function GetStatus: TSfmlSoundStatus; override;
function GetVolume: Single; override;
procedure SetAttenuation(Attenuation: Single); override;
procedure SetLoop(Loop: Boolean); override;
procedure SetMinDistance(Distance: Single); override;
procedure SetPitch(Pitch: Single); override;
procedure SetPlayingOffset(TimeOffset: TSfmlTime); override;
procedure SetPosition(Position: TSfmlVector3f); override;
procedure SetRelativeToListener(Relative: Boolean); override;
procedure SetVolume(Volume: Single); override;
public
constructor Create(const FileName: AnsiString); overload;
constructor Create(const Data: Pointer; SizeInBytes: NativeUInt); overload;
constructor Create(Stream: PSfmlInputStream); overload;
destructor Destroy; override;
procedure Play;
procedure Pause;
procedure Stop;
property Attenuation: Single read GetAttenuation write SetAttenuation;
property ChannelCount: Cardinal read GetChannelCount;
property Duration: TSfmlTime read GetDuration;
property Handle: PSfmlMusic read FHandle;
property Loop: Boolean read GetLoop write SetLoop;
property MinDistance: Single read GetMinDistance write SetMinDistance;
property Pitch: Single read GetPitch write SetPitch;
property PlayingOffset: TSfmlTime read GetPlayingOffset write SetPlayingOffset;
property Position: TSfmlVector3f read GetPosition write SetPosition;
property RelativeToListener: Boolean read GetRelativeToListener write SetRelativeToListener;
property SampleRate: Cardinal read GetSampleRate;
property Status: TSfmlSoundStatus read GetStatus;
property Volume: Single read GetVolume write SetVolume;
end;
TSfmlSoundBuffer = class
private
FHandle: PSfmlSoundBuffer;
constructor Create(Handle: PSfmlSoundBuffer); overload;
function GetSampleCount: NativeUInt;
function GetSampleRate: Cardinal;
function GetChannelCount: Cardinal;
function GetDuration: TSfmlTime;
public
constructor Create(const FileName: AnsiString); overload;
constructor Create(const Data: Pointer; SizeInBytes: NativeUInt); overload;
constructor Create(Stream: PSfmlInputStream); overload;
constructor Create(const Samples: PSmallInt; SampleCount: NativeUInt;
ChannelCount, SampleRate: Cardinal); overload;
destructor Destroy; override;
function Copy: TSfmlSoundBuffer;
function SaveToFile(const FileName: AnsiString): Boolean;
function GetSamples: PSmallInt;
property ChannelCount: Cardinal read GetChannelCount;
property Duration: TSfmlTime read GetDuration;
property Handle: PSfmlSoundBuffer read FHandle;
property SampleCount: NativeUInt read GetSampleCount;
property SampleRate: Cardinal read GetSampleRate;
end;
TSfmlSound = class(TSfmlSoundSource)
private
FHandle: PSfmlSound;
constructor Create(Handle: PSfmlSound); overload;
function GetLoop: Boolean;
function GetPlayingOffset: TSfmlTime;
procedure SetLoop(Loop: Boolean);
procedure SetPlayingOffset(TimeOffset: TSfmlTime);
protected
function GetAttenuation: Single; override;
function GetPitch: Single; override;
function GetMinDistance: Single; override;
function GetPosition: TSfmlVector3f; override;
function GetRelativeToListener: Boolean; override;
function GetStatus: TSfmlSoundStatus; override;
function GetVolume: Single; override;
procedure SetAttenuation(Attenuation: Single); override;
procedure SetMinDistance(Distance: Single); override;
procedure SetPitch(Pitch: Single); override;
procedure SetPosition(Position: TSfmlVector3f); override;
procedure SetRelativeToListener(Relative: Boolean); override;
procedure SetVolume(Volume: Single); override;
public
constructor Create; overload;
constructor Create(Buffer: TSfmlSoundBuffer); overload;
destructor Destroy; override;
function Copy: TSfmlSound;
function GetBuffer: PSfmlSoundBuffer;
procedure SetBuffer(const Buffer: PSfmlSoundBuffer); overload;
procedure SetBuffer(const Buffer: TSfmlSoundBuffer); overload;
procedure Pause;
procedure Play;
procedure Stop;
property Handle: PSfmlSound read FHandle;
property Loop: Boolean read GetLoop write SetLoop;
property PlayingOffset: TSfmlTime read GetPlayingOffset write SetPlayingOffset;
end;
TSfmlSoundBufferRecorder = class
private
FHandle: PSfmlSoundBufferRecorder;
function GetSampleRate: Cardinal;
public
constructor Create;
destructor Destroy; override;
procedure Start(SampleRate: Cardinal);
procedure Stop;
function GetBuffer: PSfmlSoundBuffer;
property Handle: PSfmlSoundBufferRecorder read FHandle;
property SampleRate: Cardinal read GetSampleRate;
end;
TSfmlSoundRecorder = class
private
FHandle: PSfmlSoundRecorder;
function GetDevice: AnsiString;
function GetSampleRate: Cardinal;
procedure SetDevice(const Name: AnsiString);
public
constructor Create(OnStart: TSfmlSoundRecorderStartCallback;
OnProcess: TSfmlSoundRecorderProcessCallback;
OnStop: TSfmlSoundRecorderStopCallback; UserData: Pointer);
destructor Destroy; override;
function Start(SampleRate: Cardinal): Boolean;
procedure Stop;
procedure SetProcessingInterval(Interval: TSfmlTime);
property Handle: PSfmlSoundRecorder read FHandle;
property Device: AnsiString read GetDevice write SetDevice;
property SampleRate: Cardinal read GetSampleRate;
end;
{$IFDEF INT64RETURNWORKAROUND}
// Workarounds for the Delphi compiler
function SfmlMusicGetDuration(const Music: PSfmlMusic): TSfmlTime; cdecl;
function SfmlMusicGetPlayingOffset(const Music: PSfmlMusic): TSfmlTime; cdecl;
function SfmlSoundStreamGetPlayingOffset(const SoundStream: PSfmlSoundStream): TSfmlTime; cdecl;
function SfmlSoundGetPlayingOffset(const Sound: PSfmlSound): TSfmlTime; cdecl;
function SfmlSoundBufferGetDuration(const SoundBuffer: PSfmlSoundBuffer): TSfmlTime; cdecl;
{$ENDIF}
implementation
{$IFDEF DynLink}
uses
{$IFDEF FPC}
DynLibs;
{$ELSE}
{$IFDEF MSWindows}
Windows;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{ TSfmlMusic }
constructor TSfmlMusic.Create(const Data: Pointer; SizeInBytes: NativeUInt);
begin
FHandle := SfmlMusicCreateFromMemory(Data, SizeInBytes);
end;
constructor TSfmlMusic.Create(const FileName: AnsiString);
begin
FHandle := SfmlMusicCreateFromFile(PAnsiChar(FileName));
end;
constructor TSfmlMusic.Create(Stream: PSfmlInputStream);
begin
FHandle := SfmlMusicCreateFromStream(Stream);
end;
destructor TSfmlMusic.Destroy;
begin
SfmlMusicDestroy(FHandle);
inherited;
end;
function TSfmlMusic.GetAttenuation: Single;
begin
Result := SfmlMusicGetAttenuation(FHandle);
end;
function TSfmlMusic.GetChannelCount: Cardinal;
begin
Result := SfmlMusicGetChannelCount(FHandle);
end;
function TSfmlMusic.GetDuration: TSfmlTime;
begin
Result := SfmlMusicGetDuration(FHandle);
end;
function TSfmlMusic.GetLoop: Boolean;
begin
Result := SfmlMusicGetLoop(FHandle);
end;
function TSfmlMusic.GetMinDistance: Single;
begin
Result := SfmlMusicGetMinDistance(FHandle);
end;
function TSfmlMusic.GetPitch: Single;
begin
Result := SfmlMusicGetPitch(FHandle);
end;
function TSfmlMusic.GetPlayingOffset: TSfmlTime;
begin
Result := SfmlMusicGetPlayingOffset(FHandle);
end;
function TSfmlMusic.GetPosition: TSfmlVector3f;
begin
Result := SfmlMusicGetPosition(FHandle);
end;
function TSfmlMusic.GetSampleRate: Cardinal;
begin
Result := SfmlMusicGetSampleRate(FHandle);
end;
function TSfmlMusic.GetStatus: TSfmlSoundStatus;
begin
Result := SfmlMusicGetStatus(FHandle);
end;
function TSfmlMusic.GetVolume: Single;
begin
Result := SfmlMusicGetVolume(FHandle);
end;
function TSfmlMusic.GetRelativeToListener: Boolean;
begin
Result := SfmlMusicIsRelativeToListener(FHandle);
end;
procedure TSfmlMusic.Pause;
begin
SfmlMusicPause(FHandle);
end;
procedure TSfmlMusic.Play;
begin
SfmlMusicPlay(FHandle);
end;
procedure TSfmlMusic.SetAttenuation(Attenuation: Single);
begin
SfmlMusicSetAttenuation(FHandle, Attenuation);
end;
procedure TSfmlMusic.SetLoop(Loop: Boolean);
begin
SfmlMusicSetLoop(FHandle, Loop);
end;
procedure TSfmlMusic.SetMinDistance(Distance: Single);
begin
SfmlMusicSetMinDistance(FHandle, Distance);
end;
procedure TSfmlMusic.SetPitch(Pitch: Single);
begin
SfmlMusicSetPitch(FHandle, Pitch);
end;
procedure TSfmlMusic.SetPlayingOffset(TimeOffset: TSfmlTime);
begin
SfmlMusicSetPlayingOffset(FHandle, TimeOffset);
end;
procedure TSfmlMusic.SetPosition(Position: TSfmlVector3f);
begin
SfmlMusicSetPosition(FHandle, Position);
end;
procedure TSfmlMusic.SetRelativeToListener(Relative: Boolean);
begin
SfmlMusicSetRelativeToListener(FHandle, Relative);
end;
procedure TSfmlMusic.SetVolume(Volume: Single);
begin
SfmlMusicSetVolume(FHandle, Volume);
end;
procedure TSfmlMusic.Stop;
begin
SfmlMusicStop(FHandle);
end;
{ TSfmlSoundStream }
constructor TSfmlSoundStream.Create(OnGetData: TSfmlSoundStreamGetDataCallback;
OnSeek: TSfmlSoundStreamSeekCallback; ChannelCount, SampleRate: Cardinal;
UserData: Pointer);
begin
FHandle := SfmlSoundStreamCreate(OnGetData, OnSeek, ChannelCount, SampleRate,
UserData);
end;
destructor TSfmlSoundStream.Destroy;
begin
SfmlSoundStreamDestroy(FHandle);
inherited;
end;
function TSfmlSoundStream.GetAttenuation: Single;
begin
Result := SfmlSoundStreamGetAttenuation(FHandle);
end;
function TSfmlSoundStream.GetChannelCount: Cardinal;
begin
Result := SfmlSoundStreamGetChannelCount(FHandle);
end;
function TSfmlSoundStream.GetLoop: Boolean;
begin
Result := SfmlSoundStreamGetLoop(FHandle);
end;
function TSfmlSoundStream.GetMinDistance: Single;
begin
Result := SfmlSoundStreamGetMinDistance(FHandle);
end;
function TSfmlSoundStream.GetPitch: Single;
begin
Result := SfmlSoundStreamGetPitch(FHandle);
end;
function TSfmlSoundStream.GetPlayingOffset: TSfmlTime;
begin
Result := SfmlSoundStreamGetPlayingOffset(FHandle);
end;
function TSfmlSoundStream.GetPosition: TSfmlVector3f;
begin
Result := SfmlSoundStreamGetPosition(FHandle);
end;
function TSfmlSoundStream.GetSampleRate: Cardinal;
begin
Result := SfmlSoundStreamGetSampleRate(FHandle);
end;
function TSfmlSoundStream.GetStatus: TSfmlSoundStatus;
begin
Result := SfmlSoundStreamGetStatus(FHandle);
end;
function TSfmlSoundStream.GetVolume: Single;
begin
Result := SfmlSoundStreamGetVolume(FHandle);
end;
function TSfmlSoundStream.GetRelativeToListener: Boolean;
begin
Result := SfmlSoundStreamIsRelativeToListener(FHandle);
end;
procedure TSfmlSoundStream.Pause;
begin
SfmlSoundStreamPause(FHandle);
end;
procedure TSfmlSoundStream.Play;
begin
SfmlSoundStreamPlay(FHandle);
end;
procedure TSfmlSoundStream.SetAttenuation(Attenuation: Single);
begin
SfmlSoundStreamSetAttenuation(FHandle, Attenuation);
end;
procedure TSfmlSoundStream.SetLoop(Loop: Boolean);
begin
SfmlSoundStreamSetLoop(FHandle, Loop);
end;
procedure TSfmlSoundStream.SetMinDistance(Distance: Single);
begin
SfmlSoundStreamSetMinDistance(FHandle, Distance);
end;
procedure TSfmlSoundStream.SetPitch(Pitch: Single);
begin
SfmlSoundStreamSetPitch(FHandle, Pitch);
end;
procedure TSfmlSoundStream.SetPlayingOffset(TimeOffset: TSfmlTime);
begin
SfmlSoundStreamSetPlayingOffset(FHandle, TimeOffset);
end;
procedure TSfmlSoundStream.SetPosition(Position: TSfmlVector3f);
begin
SfmlSoundStreamSetPosition(FHandle, Position);
end;
procedure TSfmlSoundStream.SetRelativeToListener(Relative: Boolean);
begin
SfmlSoundStreamSetRelativeToListener(FHandle, Relative);
end;
procedure TSfmlSoundStream.SetVolume(Volume: Single);
begin
SfmlSoundStreamSetVolume(FHandle, Volume);
end;
procedure TSfmlSoundStream.Stop;
begin
SfmlSoundStreamStop(FHandle);
end;
{ TSfmlSoundBuffer }
constructor TSfmlSoundBuffer.Create(Handle: PSfmlSoundBuffer);
begin
FHandle := Handle;
end;
constructor TSfmlSoundBuffer.Create(const FileName: AnsiString);
begin
FHandle := SfmlSoundBufferCreateFromFile(PAnsiChar(FileName));
end;
constructor TSfmlSoundBuffer.Create(const Data: Pointer;
SizeInBytes: NativeUInt);
begin
FHandle := SfmlSoundBufferCreateFromMemory(Data, SizeInBytes);
end;
constructor TSfmlSoundBuffer.Create(const Samples: PSmallInt;
SampleCount: NativeUInt; ChannelCount, SampleRate: Cardinal);
begin
FHandle := SfmlSoundBufferCreateFromSamples(Samples, SampleCount,
ChannelCount, SampleRate);
end;
constructor TSfmlSoundBuffer.Create(Stream: PSfmlInputStream);
begin
FHandle := SfmlSoundBufferCreateFromStream(Stream);
end;
destructor TSfmlSoundBuffer.Destroy;
begin
SfmlSoundBufferDestroy(FHandle);
inherited;
end;
function TSfmlSoundBuffer.Copy: TSfmlSoundBuffer;
begin
Result := TSfmlSoundBuffer.Create(SfmlSoundBufferCopy(FHandle));
end;
function TSfmlSoundBuffer.GetChannelCount: Cardinal;
begin
Result := SfmlSoundBufferGetChannelCount(FHandle);
end;
function TSfmlSoundBuffer.GetDuration: TSfmlTime;
begin
Result := SfmlSoundBufferGetDuration(FHandle);
end;
function TSfmlSoundBuffer.GetSampleCount: NativeUInt;
begin
Result := SfmlSoundBufferGetSampleCount(FHandle);
end;
function TSfmlSoundBuffer.GetSampleRate: Cardinal;
begin
Result := SfmlSoundBufferGetSampleRate(FHandle);
end;
function TSfmlSoundBuffer.GetSamples: PSmallInt;
begin
Result := SfmlSoundBufferGetSamples(FHandle);
end;
function TSfmlSoundBuffer.SaveToFile(const FileName: AnsiString): Boolean;
begin
Result := SfmlSoundBufferSaveToFile(FHandle, PAnsiChar(FileName));
end;
{ TSfmlSound }
constructor TSfmlSound.Create;
begin
FHandle := SfmlSoundCreate;
end;
constructor TSfmlSound.Create(Buffer: TSfmlSoundBuffer);
begin
Create;
SetBuffer(Buffer);
end;
constructor TSfmlSound.Create(Handle: PSfmlSound);
begin
FHandle := Handle;
end;
destructor TSfmlSound.Destroy;
begin
SfmlSoundDestroy(FHandle);
inherited;
end;
function TSfmlSound.Copy: TSfmlSound;
begin
Result := TSfmlSound.Create(SfmlSoundCopy(FHandle))
end;
function TSfmlSound.GetAttenuation: Single;
begin
Result := SfmlSoundGetAttenuation(FHandle);
end;
function TSfmlSound.GetBuffer: PSfmlSoundBuffer;
begin
Result := SfmlSoundGetBuffer(FHandle);
end;
function TSfmlSound.GetLoop: Boolean;
begin
Result := SfmlSoundGetLoop(FHandle);
end;
function TSfmlSound.GetMinDistance: Single;
begin
Result := SfmlSoundGetMinDistance(FHandle);
end;
function TSfmlSound.GetPitch: Single;
begin
Result := SfmlSoundGetPitch(FHandle);
end;
function TSfmlSound.GetPlayingOffset: TSfmlTime;
begin
Result := SfmlSoundGetPlayingOffset(FHandle);
end;
function TSfmlSound.GetPosition: TSfmlVector3f;
begin
Result := SfmlSoundGetPosition(FHandle);
end;
function TSfmlSound.GetStatus: TSfmlSoundStatus;
begin
Result := SfmlSoundGetStatus(FHandle);
end;
function TSfmlSound.GetVolume: Single;
begin
Result := SfmlSoundGetVolume(FHandle);
end;
function TSfmlSound.GetRelativeToListener: Boolean;
begin
Result := SfmlSoundIsRelativeToListener(FHandle);
end;
procedure TSfmlSound.Pause;
begin
SfmlSoundPause(FHandle);
end;
procedure TSfmlSound.Play;
begin
SfmlSoundPlay(FHandle);
end;
procedure TSfmlSound.SetAttenuation(Attenuation: Single);
begin
SfmlSoundSetAttenuation(FHandle, Attenuation);
end;
procedure TSfmlSound.SetBuffer(const Buffer: PSfmlSoundBuffer);
begin
SfmlSoundSetBuffer(FHandle, Buffer);
end;
procedure TSfmlSound.SetBuffer(const Buffer: TSfmlSoundBuffer);
begin
SfmlSoundSetBuffer(FHandle, Buffer.Handle);
end;
procedure TSfmlSound.SetLoop(Loop: Boolean);
begin
SfmlSoundSetLoop(FHandle, Loop);
end;
procedure TSfmlSound.SetMinDistance(Distance: Single);
begin
SfmlSoundSetMinDistance(FHandle, Distance);
end;
procedure TSfmlSound.SetPitch(Pitch: Single);
begin
SfmlSoundSetPitch(FHandle, Pitch);
end;
procedure TSfmlSound.SetPlayingOffset(TimeOffset: TSfmlTime);
begin
SfmlSoundSetPlayingOffset(FHandle, TimeOffset);
end;
procedure TSfmlSound.SetPosition(Position: TSfmlVector3f);
begin
SfmlSoundSetPosition(FHandle, Position);
end;
procedure TSfmlSound.SetRelativeToListener(Relative: Boolean);
begin
SfmlSoundSetRelativeToListener(FHandle, Relative);
end;
procedure TSfmlSound.SetVolume(Volume: Single);
begin
SfmlSoundSetVolume(FHandle, Volume);
end;
procedure TSfmlSound.Stop;
begin
SfmlSoundStop(FHandle);
end;
{ TSfmlSoundBufferRecorder }
constructor TSfmlSoundBufferRecorder.Create;
begin
FHandle := SfmlSoundBufferRecorderCreate;
end;
destructor TSfmlSoundBufferRecorder.Destroy;
begin
SfmlSoundBufferRecorderDestroy(FHandle);
inherited;
end;
function TSfmlSoundBufferRecorder.GetBuffer: PSfmlSoundBuffer;
begin
Result := SfmlSoundBufferRecorderGetBuffer(FHandle);
end;
function TSfmlSoundBufferRecorder.GetSampleRate: Cardinal;
begin
Result := SfmlSoundBufferRecorderGetSampleRate(FHandle);
end;
procedure TSfmlSoundBufferRecorder.Start(SampleRate: Cardinal);
begin
SfmlSoundBufferRecorderStart(FHandle, SampleRate);
end;
procedure TSfmlSoundBufferRecorder.Stop;
begin
SfmlSoundBufferRecorderStop(FHandle);
end;
{ TSfmlSoundRecorder }
constructor TSfmlSoundRecorder.Create(OnStart: TSfmlSoundRecorderStartCallback;
OnProcess: TSfmlSoundRecorderProcessCallback;
OnStop: TSfmlSoundRecorderStopCallback; UserData: Pointer);
begin
FHandle := SfmlSoundRecorderCreate(OnStart, OnProcess, OnStop, UserData);
end;
destructor TSfmlSoundRecorder.Destroy;
begin
SfmlSoundRecorderDestroy(FHandle);
inherited;
end;
function TSfmlSoundRecorder.GetDevice: AnsiString;
begin
Result := SfmlSoundRecorderGetDevice(FHandle);
end;
function TSfmlSoundRecorder.GetSampleRate: Cardinal;
begin
Result := SfmlSoundRecorderGetSampleRate(FHandle);
end;
procedure TSfmlSoundRecorder.SetDevice(const Name: AnsiString);
begin
Assert(SfmlSoundRecorderSetDevice(FHandle, PAnsiChar(Name)));
end;
procedure TSfmlSoundRecorder.SetProcessingInterval(Interval: TSfmlTime);
begin
SfmlSoundRecorderSetProcessingInterval(FHandle, Interval);
end;
function TSfmlSoundRecorder.Start(SampleRate: Cardinal): Boolean;
begin
Result := SfmlSoundRecorderStart(FHandle, SampleRate);
end;
procedure TSfmlSoundRecorder.Stop;
begin
SfmlSoundRecorderStop(FHandle);
end;
{$IFDEF DynLink}
var
CSfmlAudioHandle: {$IFDEF FPC}TLibHandle{$ELSE}HINST{$ENDIF};
{$IFDEF INT64RETURNWORKAROUND}
sfMusic_getDuration: function (const Music: PSfmlMusic): Int64; cdecl;
sfMusic_getPlayingOffset: function (const Music: PSfmlMusic): Int64; cdecl;
sfSoundStream_getPlayingOffset: function (const SoundStream: PSfmlSoundStream): Int64; cdecl;
sfSound_getPlayingOffset: function (const Sound: PSfmlSound): Int64; cdecl;
sfSoundBuffer_getDuration: function (const SoundBuffer: PSfmlSoundBuffer): Int64; cdecl;
{$ENDIF}
procedure InitDLL;
function BindFunction(Name: AnsiString): Pointer;
begin
Result := GetProcAddress(CSfmlAudioHandle, PAnsiChar(Name));
Assert(Assigned(Result));
end;
begin
// dynamically load external library
{$IFDEF FPC}
CSfmlAudioHandle := LoadLibrary(CSfmlAudioLibrary);
{$ELSE}
CSfmlAudioHandle := LoadLibraryA(CSfmlAudioLibrary);
{$ENDIF}
if CSfmlAudioHandle <> 0 then
try
SfmlListenerSetGlobalVolume := BindFunction('sfListener_setGlobalVolume');
SfmlListenerGetGlobalVolume := BindFunction('sfListener_getGlobalVolume');
SfmlListenerSetPosition := BindFunction('sfListener_setPosition');
SfmlListenerGetPosition := BindFunction('sfListener_getPosition');
SfmlListenerSetDirection := BindFunction('sfListener_setDirection');
SfmlListenerGetDirection := BindFunction('sfListener_getDirection');
SfmlListenerSetUpVector := BindFunction('sfListener_setUpVector');
SfmlListenerGetUpVector := BindFunction('sfListener_getUpVector');
SfmlMusicCreateFromFile := BindFunction('sfMusic_createFromFile');
SfmlMusicCreateFromMemory := BindFunction('sfMusic_createFromMemory');
SfmlMusicCreateFromStream := BindFunction('sfMusic_createFromStream');
SfmlMusicDestroy := BindFunction('sfMusic_destroy');
SfmlMusicSetLoop := BindFunction('sfMusic_setLoop');
SfmlMusicGetLoop := BindFunction('sfMusic_getLoop');
SfmlMusicPlay := BindFunction('sfMusic_play');
SfmlMusicPause := BindFunction('sfMusic_pause');
SfmlMusicStop := BindFunction('sfMusic_stop');
SfmlMusicGetChannelCount := BindFunction('sfMusic_getChannelCount');
SfmlMusicGetSampleRate := BindFunction('sfMusic_getSampleRate');
SfmlMusicGetStatus := BindFunction('sfMusic_getStatus');
SfmlMusicSetPitch := BindFunction('sfMusic_setPitch');
SfmlMusicSetVolume := BindFunction('sfMusic_setVolume');
SfmlMusicSetPosition := BindFunction('sfMusic_setPosition');
SfmlMusicSetRelativeToListener := BindFunction('sfMusic_setRelativeToListener');
SfmlMusicSetMinDistance := BindFunction('sfMusic_setMinDistance');
SfmlMusicSetAttenuation := BindFunction('sfMusic_setAttenuation');
SfmlMusicSetPlayingOffset := BindFunction('sfMusic_setPlayingOffset');
SfmlMusicGetPitch := BindFunction('sfMusic_getPitch');
SfmlMusicGetVolume := BindFunction('sfMusic_getVolume');
SfmlMusicGetPosition := BindFunction('sfMusic_getPosition');
SfmlMusicIsRelativeToListener := BindFunction('sfMusic_isRelativeToListener');
SfmlMusicGetMinDistance := BindFunction('sfMusic_getMinDistance');
SfmlMusicGetAttenuation := BindFunction('sfMusic_getAttenuation');
SfmlSoundStreamCreate := BindFunction('sfSoundStream_create');
SfmlSoundStreamDestroy := BindFunction('sfSoundStream_destroy');
SfmlSoundStreamPlay := BindFunction('sfSoundStream_play');
SfmlSoundStreamPause := BindFunction('sfSoundStream_pause');
SfmlSoundStreamStop := BindFunction('sfSoundStream_stop');
SfmlSoundStreamGetStatus := BindFunction('sfSoundStream_getStatus');
SfmlSoundStreamGetChannelCount := BindFunction('sfSoundStream_getChannelCount');
SfmlSoundStreamGetSampleRate := BindFunction('sfSoundStream_getSampleRate');
SfmlSoundStreamSetPitch := BindFunction('sfSoundStream_setPitch');
SfmlSoundStreamSetVolume := BindFunction('sfSoundStream_setVolume');
SfmlSoundStreamSetPosition := BindFunction('sfSoundStream_setPosition');
SfmlSoundStreamSetRelativeToListener := BindFunction('sfSoundStream_setRelativeToListener');
SfmlSoundStreamSetMinDistance := BindFunction('sfSoundStream_setMinDistance');
SfmlSoundStreamSetAttenuation := BindFunction('sfSoundStream_setAttenuation');
SfmlSoundStreamSetPlayingOffset := BindFunction('sfSoundStream_setPlayingOffset');
SfmlSoundStreamSetLoop := BindFunction('sfSoundStream_setLoop');
SfmlSoundStreamGetPitch := BindFunction('sfSoundStream_getPitch');
SfmlSoundStreamGetVolume := BindFunction('sfSoundStream_getVolume');
SfmlSoundStreamGetPosition := BindFunction('sfSoundStream_getPosition');
SfmlSoundStreamIsRelativeToListener := BindFunction('sfSoundStream_isRelativeToListener');
SfmlSoundStreamGetMinDistance := BindFunction('sfSoundStream_getMinDistance');
SfmlSoundStreamGetAttenuation := BindFunction('sfSoundStream_getAttenuation');
SfmlSoundStreamGetLoop := BindFunction('sfSoundStream_getLoop');
SfmlSoundCreate := BindFunction('sfSound_create');
SfmlSoundCopy := BindFunction('sfSound_copy');
SfmlSoundDestroy := BindFunction('sfSound_destroy');
SfmlSoundPlay := BindFunction('sfSound_play');
SfmlSoundPause := BindFunction('sfSound_pause');
SfmlSoundStop := BindFunction('sfSound_stop');
SfmlSoundSetBuffer := BindFunction('sfSound_setBuffer');
SfmlSoundGetBuffer := BindFunction('sfSound_getBuffer');
SfmlSoundSetLoop := BindFunction('sfSound_setLoop');
SfmlSoundGetLoop := BindFunction('sfSound_getLoop');
SfmlSoundGetStatus := BindFunction('sfSound_getStatus');
SfmlSoundSetPitch := BindFunction('sfSound_setPitch');
SfmlSoundSetVolume := BindFunction('sfSound_setVolume');
SfmlSoundSetPosition := BindFunction('sfSound_setPosition');
SfmlSoundSetRelativeToListener := BindFunction('sfSound_setRelativeToListener');
SfmlSoundSetMinDistance := BindFunction('sfSound_setMinDistance');
SfmlSoundSetAttenuation := BindFunction('sfSound_setAttenuation');
SfmlSoundSetPlayingOffset := BindFunction('sfSound_setPlayingOffset');
SfmlSoundGetPitch := BindFunction('sfSound_getPitch');
SfmlSoundGetVolume := BindFunction('sfSound_getVolume');
SfmlSoundGetPosition := BindFunction('sfSound_getPosition');
SfmlSoundIsRelativeToListener := BindFunction('sfSound_isRelativeToListener');
SfmlSoundGetMinDistance := BindFunction('sfSound_isRelativeToListener');
SfmlSoundGetAttenuation := BindFunction('sfSound_getAttenuation');
SfmlSoundBufferCreateFromFile := BindFunction('sfSoundBuffer_createFromFile');
SfmlSoundBufferCreateFromMemory := BindFunction('sfSoundBuffer_createFromMemory');
SfmlSoundBufferCreateFromStream := BindFunction('sfSoundBuffer_createFromStream');
SfmlSoundBufferCreateFromSamples := BindFunction('sfSoundBuffer_createFromSamples');
SfmlSoundBufferCopy := BindFunction('sfSoundBuffer_copy');
SfmlSoundBufferDestroy := BindFunction('sfSoundBuffer_destroy');
SfmlSoundBufferSaveToFile := BindFunction('sfSoundBuffer_saveToFile');
SfmlSoundBufferGetSamples := BindFunction('sfSoundBuffer_getSamples');
SfmlSoundBufferGetSampleCount := BindFunction('sfSoundBuffer_getSampleCount');
SfmlSoundBufferGetSampleRate := BindFunction('sfSoundBuffer_getSampleRate');
SfmlSoundBufferGetChannelCount := BindFunction('sfSoundBuffer_getChannelCount');
SfmlSoundBufferRecorderCreate := BindFunction('sfSoundBufferRecorder_create');
SfmlSoundBufferRecorderDestroy := BindFunction('sfSoundBufferRecorder_destroy');
SfmlSoundBufferRecorderStart := BindFunction('sfSoundBufferRecorder_start');
SfmlSoundBufferRecorderStop := BindFunction('sfSoundBufferRecorder_stop');
SfmlSoundBufferRecorderGetSampleRate := BindFunction('sfSoundBufferRecorder_getSampleRate');
SfmlSoundBufferRecorderGetBuffer := BindFunction('sfSoundBufferRecorder_getBuffer');
SfmlSoundBufferRecorderSetDevice := BindFunction('sfSoundBufferRecorder_setDevice');
SfmlSoundBufferRecorderGetDevice := BindFunction('sfSoundBufferRecorder_getDevice');
SfmlSoundRecorderCreate := BindFunction('sfSoundRecorder_create');
SfmlSoundRecorderDestroy := BindFunction('sfSoundRecorder_destroy');
SfmlSoundRecorderStart := BindFunction('sfSoundRecorder_start');
SfmlSoundRecorderStop := BindFunction('sfSoundRecorder_stop');
SfmlSoundRecorderGetSampleRate := BindFunction('sfSoundRecorder_getSampleRate');
SfmlSoundRecorderIsAvailable := BindFunction('sfSoundRecorder_isAvailable');
SfmlSoundRecorderSetProcessingInterval := BindFunction('sfSoundRecorder_setProcessingInterval');
SfmlSoundRecorderGetAvailableDevices := BindFunction('sfSoundRecorder_getAvailableDevices');
SfmlSoundRecorderGetDefaultDevice := BindFunction('sfSoundRecorder_getDefaultDevice');
SfmlSoundRecorderSetDevice := BindFunction('sfSoundRecorder_setDevice');
SfmlSoundRecorderGetDevice := BindFunction('sfSoundRecorder_getDevice');
SfmlSoundRecorderSetChannelCount := BindFunction('sfSoundRecorder_setChannelCount');
SfmlSoundRecorderGetChannelCount := BindFunction('sfSoundRecorder_getChannelCount');
{$IFDEF INT64RETURNWORKAROUND}
sfMusic_getDuration := BindFunction('sfMusic_getDuration');
sfMusic_getPlayingOffset := BindFunction('sfMusic_getPlayingOffset');
sfSoundStream_getPlayingOffset := BindFunction('sfSoundStream_getPlayingOffset');
sfSound_getPlayingOffset := BindFunction('sfSound_getPlayingOffset');
sfSoundBuffer_getDuration := BindFunction('sfSoundBuffer_getDuration');
{$ELSE}
SfmlMusicGetDuration := BindFunction('sfMusic_getDuration');
SfmlMusicGetPlayingOffset := BindFunction('sfMusic_getPlayingOffset');
SfmlSoundStreamGetPlayingOffset := BindFunction('sfSoundStream_getPlayingOffset');
SfmlSoundGetPlayingOffset := BindFunction('sfSound_getPlayingOffset');
SfmlSoundBufferGetDuration := BindFunction('sfSoundBuffer_getDuration');
{$ENDIF}
except
FreeLibrary(CSfmlAudioHandle);
CSfmlAudioHandle := 0;
end;
end;
procedure FreeDLL;
begin
if CSfmlAudioHandle <> 0 then
FreeLibrary(CSfmlAudioHandle);
end;
{$ELSE}
{$IFDEF INT64RETURNWORKAROUND}
function sfMusic_getDuration(const Music: PSfmlMusic): Int64; cdecl; external CSfmlAudioLibrary;
function sfMusic_getPlayingOffset(const Music: PSfmlMusic): Int64; cdecl; external CSfmlAudioLibrary;
function sfSoundStream_getPlayingOffset(const SoundStream: PSfmlSoundStream): Int64; cdecl; external CSfmlAudioLibrary;
function sfSound_getPlayingOffset(const Sound: PSfmlSound): Int64; cdecl; external CSfmlAudioLibrary;
function sfSoundBuffer_getDuration(const SoundBuffer: PSfmlSoundBuffer): Int64; cdecl; external CSfmlAudioLibrary;
{$ENDIF}
{$ENDIF}
{$IFDEF INT64RETURNWORKAROUND}
function SfmlMusicGetDuration(const Music: PSfmlMusic): TSfmlTime; cdecl;
begin
Result.MicroSeconds := sfMusic_getDuration(Music);
end;
function SfmlMusicGetPlayingOffset(const Music: PSfmlMusic): TSfmlTime; cdecl;
begin
Result.MicroSeconds := sfMusic_getPlayingOffset(Music);
end;
function SfmlSoundStreamGetPlayingOffset(const SoundStream: PSfmlSoundStream): TSfmlTime; cdecl;
begin
Result.MicroSeconds := sfSoundStream_getPlayingOffset(SoundStream);
end;
function SfmlSoundGetPlayingOffset(const Sound: PSfmlSound): TSfmlTime; cdecl;
begin
Result.MicroSeconds := sfSound_getPlayingOffset(Sound);
end;
function SfmlSoundBufferGetDuration(const SoundBuffer: PSfmlSoundBuffer): TSfmlTime; cdecl;
begin
Result.MicroSeconds := sfSoundBuffer_getDuration(SoundBuffer);
end;
{$ENDIF}
{$IFDEF DynLink}
initialization
InitDLL;
finalization
FreeDLL;
{$ENDIF}
end.
| 47.628956 | 267 | 0.81743 |
f1b2b0c308ba19b6218aa95667b5a6d1a3213e09 | 340 | pas | Pascal | Library/Prerequisites/Lazarus/Generics.Collections/generics_collections.pas | Jeanmilost/Mels | 0384db41dd1ae365f72384857e3a3dbf0b688367 | [
"MIT"
]
| 3 | 2019-10-23T13:42:42.000Z | 2021-02-13T08:15:15.000Z | Library/Prerequisites/Lazarus/Generics.Collections/generics_collections.pas | Jeanmilost/Mels | 0384db41dd1ae365f72384857e3a3dbf0b688367 | [
"MIT"
]
| null | null | null | Library/Prerequisites/Lazarus/Generics.Collections/generics_collections.pas | Jeanmilost/Mels | 0384db41dd1ae365f72384857e3a3dbf0b688367 | [
"MIT"
]
| 3 | 2018-06-17T15:35:57.000Z | 2021-02-15T15:24:11.000Z | { This file was automatically created by Lazarus. Do not edit!
This source is only used to compile and install the package.
}
unit generics_collections;
interface
uses
Generics.Collections, Generics.Defaults, Generics.Hashes,
Generics.Helpers, Generics.MemoryExpanders, Generics.Strings;
implementation
end.
| 21.25 | 66 | 0.747059 |
c3c2f9533a87486bca8a74a6e08e0bd46a3489a3 | 70,347 | dfm | Pascal | Delphi/Unit1.dfm | ReneFGJr/pGDP | 0a2e360c6ca2b15d3c1f168b9e9bd496c299cbb0 | [
"MIT"
]
| null | null | null | Delphi/Unit1.dfm | ReneFGJr/pGDP | 0a2e360c6ca2b15d3c1f168b9e9bd496c299cbb0 | [
"MIT"
]
| null | null | null | Delphi/Unit1.dfm | ReneFGJr/pGDP | 0a2e360c6ca2b15d3c1f168b9e9bd496c299cbb0 | [
"MIT"
]
| null | null | null | object Form1: TForm1
Left = 218
Top = 147
Width = 1284
Height = 838
BorderIcons = [biSystemMenu, biMaximize]
Caption = 'Ferramentas PGD'
Color = clMaroon
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -19
Font.Name = 'Segoe UI Light'
Font.Style = []
OldCreateOrder = False
Position = poMainFormCenter
PixelsPerInch = 96
TextHeight = 25
object Panel3: TPanel
Left = 0
Top = 98
Width = 345
Height = 701
Align = alLeft
BevelOuter = bvNone
Color = clMaroon
TabOrder = 0
object Panel4: TPanel
Left = 312
Top = 19
Width = 33
Height = 662
Align = alRight
BevelOuter = bvNone
Color = clMaroon
TabOrder = 0
object Panel6: TPanel
Left = 0
Top = 0
Width = 33
Height = 662
Align = alRight
BevelOuter = bvNone
Color = 10485760
TabOrder = 0
end
end
object Panel5: TPanel
Left = 0
Top = 19
Width = 17
Height = 662
Align = alLeft
BevelOuter = bvNone
Color = 10485760
TabOrder = 1
end
object Panel7: TPanel
Left = 0
Top = 681
Width = 345
Height = 20
Align = alBottom
BevelOuter = bvNone
Color = 10485760
TabOrder = 2
end
object Panel8: TPanel
Left = 17
Top = 19
Width = 295
Height = 662
Align = alClient
BevelOuter = bvNone
Color = clMaroon
TabOrder = 3
object DirectoryListBox1: TDirectoryListBox
Left = 0
Top = 0
Width = 295
Height = 209
Align = alTop
Color = clMaroon
FileList = FLB
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -19
Font.Name = 'Segoe UI Light'
Font.Style = []
ItemHeight = 25
ParentFont = False
TabOrder = 0
end
object FLB: TFileListBox
Left = 0
Top = 217
Width = 295
Height = 404
Align = alClient
Color = clMaroon
FileEdit = ED
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -19
Font.Name = 'Segoe UI Light'
Font.Style = []
ItemHeight = 25
ParentFont = False
TabOrder = 1
OnDblClick = FLBDblClick
end
object Panel13: TPanel
Left = 0
Top = 621
Width = 295
Height = 41
Align = alBottom
BevelOuter = bvNone
Caption = 'Panel13'
Color = 10485760
TabOrder = 2
object DriveComboBox1: TDriveComboBox
Left = 0
Top = 10
Width = 297
Height = 31
Color = clMaroon
DirList = DirectoryListBox1
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -19
Font.Name = 'Segoe UI Light'
Font.Style = []
ParentFont = False
TabOrder = 0
end
end
object Panel14: TPanel
Left = 0
Top = 209
Width = 295
Height = 8
Align = alTop
BevelOuter = bvNone
Color = 10485760
TabOrder = 3
end
end
object Panel11: TPanel
Left = 0
Top = 0
Width = 345
Height = 19
Align = alTop
BevelOuter = bvNone
Color = 10485760
TabOrder = 4
end
end
object Panel12: TPanel
Left = 0
Top = 0
Width = 1268
Height = 1
Align = alTop
BevelOuter = bvNone
TabOrder = 1
end
object Panel15: TPanel
Left = 345
Top = 98
Width = 923
Height = 701
Align = alClient
BevelOuter = bvNone
Color = 10485760
TabOrder = 2
object Panel9: TPanel
Left = 903
Top = 0
Width = 20
Height = 681
Align = alRight
BevelOuter = bvNone
Color = 10485760
TabOrder = 0
end
object Panel16: TPanel
Left = 0
Top = 681
Width = 923
Height = 20
Align = alBottom
BevelOuter = bvNone
Color = 10485760
TabOrder = 1
end
object Metadados: TPageControl
Left = 0
Top = 0
Width = 903
Height = 681
ActivePage = TabSheet2
Align = alClient
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -16
Font.Name = 'Segoe UI Light'
Font.Style = []
ParentFont = False
TabOrder = 2
object TabSheet1: TTabSheet
Caption = 'Metadados'
object Panel17: TPanel
Left = 0
Top = 0
Width = 895
Height = 33
Align = alTop
Caption = 'Panel17'
TabOrder = 0
object ToolBar1: TToolBar
Left = 1
Top = 1
Width = 893
Height = 29
ButtonHeight = 24
Caption = 'ToolBar1'
DisabledImages = image
TabOrder = 0
object ToolButton3: TToolButton
Left = 0
Top = 2
Width = 8
Caption = 'ToolButton3'
ImageIndex = 2
Style = tbsSeparator
end
object ToolButton1: TToolButton
Left = 8
Top = 2
Caption = 'ToolButton1'
ImageIndex = 0
OnClick = ToolButton1Click
end
object ToolButton4: TToolButton
Left = 31
Top = 2
Width = 8
Caption = 'ToolButton4'
ImageIndex = 2
Style = tbsSeparator
end
object ToolButton2: TToolButton
Left = 39
Top = 2
Caption = 'ToolButton2'
ImageIndex = 1
end
end
end
object wb: TWebBrowser
Left = 0
Top = 33
Width = 895
Height = 612
Align = alClient
TabOrder = 1
ControlData = {
4C000000805C0000413F00000000000000000000000000000000000000000000
000000004C000000000000000000000001000000E0D057007335CF11AE690800
2B2E126208000000000000004C0000000114020000000000C000000000000046
8000000000000000000000000000000000000000000000000000000000000000
00000000000000000100000000000000000000000000000000000000}
end
end
object TabSheet2: TTabSheet
Caption = 'Preview'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -16
Font.Name = 'Segoe UI Light'
Font.Style = []
ImageIndex = 1
ParentFont = False
object img: TImage
Left = 0
Top = 0
Width = 895
Height = 645
Align = alClient
Center = True
Picture.Data = {
0A544A504547496D616765A1640000FFD8FFE000104A46494600010100000100
010000FFDB0043000302020302020303030304030304050805050404050A0707
06080C0A0C0C0B0A0B0B0D0E12100D0E110E0B0B1016101113141515150C0F17
1816141812141514FFDB00430103040405040509050509140D0B0D1414141414
1414141414141414141414141414141414141414141414141414141414141414
14141414141414141414141414FFC200110801C1024B03012200021101031101
FFC4001C0001000203010101000000000000000000000305010407060208FFC4
001A010100030101010000000000000000000000010203040506FFDA000C0301
0002100310000001FD4D964C3230C8C3230C8C3230C8C3230C8C3230C8C3230C
8C3230C8C33F08FA67E4CB43EAF4DD6B79BBE7EB5863BE58FA30A6B8BD32CA9A
619186461918646191864619186461918646191864619188E58CFBCE32000000
0000000000000AF9AEFB8FEDFA5E47A0AFF33F3E8F93DB2BB9C49C1EA74CF8E5
9EDF3D6C6936B4663EEED475B5DFC19EB7AD1D1E7EABC19EC000000000000000
0000239233EF38C800000000000000000C19F0BBBE1FD5F0F5A3D98FD9F9FCFA
5F3FF396F61A4B38997D4793B7E2F4362E6B3E39BB2DF1E5B7D3718D6D8CB693
675EDF1DFE949B35BD92A76AB6DC14D40000000000000000472467DE71900000
00000000000068EF7C5A9C6B3EABCC7D2FC7C31DCD469949F326262CABD6196D
B365F2E3F43EB6A87D3534DEE67ECF661AA58D35D1BDA1F55874495926E73F5C
AD356DBC29A800000000000000008E48CFBCE320000000000000000007CE858A
D4D6F15EF9AE1CB6A7B2F28F5FC3D3FAF9FAEDF3ACACBCF7A2E4ED9BE25D8E6E
C8ACA4F359EBB5BB5B677A7A2D95179BEB4B71A3F731F6CAB79C534000000000
000000011C919F79C64000000000000000000000790F5FE3FAB8BC5CDAFB9EFF
00CBD9CBA767C7DFB12FCD3E3D12FA2D0B2CF5D0B1C5EF3F5D259FDE9E5B6FE8
EE499EA15B800000000000000000239233EF38C8000000000000000000000AAB
55A9CF7CFF005AE4FED7CF4D6553EE2F9EB6FCB5BC1E9DA62E73C9DD497656F5
16E44856E0000000000000000000239233EF38C8000000000000000000000C66
9AD9F9DA2C6CFBFF00313D87D7ABE3F42BAF68EF383D3A3BC29A053400000000
0000000000000011C919F79C6400000000000000000000002825B8CEDCE658F4
000000000000000000000000000239233EF38C80000000000000000000000000
00000000000000000000000001AF8FAC1B11C919F79C64000000000000000000
000000000000000000000000000000000011C910499224A224A224A224A224A2
24A224A224A224A224A224A224A224A224A224A224A224A224A224A224A224A2
24A224A224A224A224A224A224A224A224A224A224A224A224A224A22F8D88CF
BA1BEF067BAF8F2156AF49737BE4FAA783D34F48782DE97AF78BDCABD43C2C28
E815FE27367451120000000000000000000000000000000000000000239233EF
CEFA2ADE69C6B583826AEC2414D3D90ABB09068ECCA22C4C2A37B64658196065
8196065819606581960658196065819606581960658196065819606581960658
196065819606581960658196306F45F1F7EC564AEB1AEF3E63AADCADF1AF3FC7
9DF4B78BE19480000000000000000000000000000000000000000000000C6704
924727D5672555AE71562CDC76AC598AC598AC598AC598AC598AC598AC598AC5
98AC598AC598AC598AC598AC598AC598AC598AC598AC598AC598AC598AC598AC
598AC598AC598AC598AC598AC598AC598AC598AC598AC598AC598AC598AC598A
CC5A110E658FD38FBCE320000000000000000000000000000000000000000000
00000000008E48CFBF2FEA39A27DA6BEBD34D3D8CBCF7D544DDEA78F893EFF00
E3C17A195BFC51D443D9C5E1F60F7FF5E0F411D033E3F7226F2EBCDFA4B40448
00000000000000000000000000000000000008E48CFBD1DEAEE49FA48F366348
2BF724263484686DC82348234823482348234823482348234823482348234823
4823482348234823482348234823482348234823482348234823482348234823
48234823C4B836FE2393DDAC95D635DE7CC7E4BD85178FA696D4F3DEB7231900
0000000000000000000000000000000000000000000018CE09248E4FAACE4AFB
0CE6AF5839A6BD602BD602BD602BD602BD602BD602BD602BD602BD602BD602BD
602BD602BD602BD602BD602BD602BD602BD602BD602BD602BD602BD602BD602B
D602BD602BD602BD602BD602BD602BD602BD602BD602BD602BF1629478962ED8
24C9125112511251125112511251125112511251125112511251125112511251
1251125112511251125112511251125112511251125112511251125112511251
125112511251125117C6C4449E4FD67E55EFE1EBEE0EF5FC9EF0E0E3BC3838EF
0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838E
F0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838
EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC3838EF0E0E3BC383
8EF0E0E3BC6E7E7B44FEC486B6C7E73E865FCA7FAB3F29FADE5548FA0F080000
000000000000000000DFD0F5D67CDD3CFB67A5E8D2FCE5D5B95EB8FC8DF10000
0000000000000000003F54DA55DA7C57D84BF94FF56FE55F57CCA61F41E10000
00000000000000000017F9F3ECB4F77A1E4D4BD9D6E1B6216800000000000000
000000003F54DA5758FC57D84DE4FD6653CCDD31BE1CCDD3073374C1CCDD3073
374C1CCDD3073374C1CCDD3073374C1CCDD3073374C1CCDD3073374C1CCDD307
3374C1CCDD3073374C1CCDD3073374C1CCDD3073374C1CCDD3073374C1CCDD2B
E8E66E98399BA16D1CCDD3073374C1CCDD2F525CFDD310E66E98399BA24C7357
4CF839B3A60E67B9D01128668B9BA64CE3200000000000000000000000000000
00000149A37B16B9D44D6B24D7C6ED7ADD299A15F488F29B3EA2029A1F452D66
6196A0799A6F77ABB65E63764B1B45067D1E61AB6FF1F79688E48EB6FBCE3200
0000000000000000000000000000000000000000000000000008E48CF9000000
000000000000000000000000000000000000000000000000C07FFFC4002E1000
0103030401040104030003000000000400020301051311121416311540506006
10213435202324223042FFDA0008010100010502FA4D7E028EA3AAAAEA3686CE
F8031267CC24F1B0A1C4D6D73D1D47528EA3955D46FE9752E70C76D756FBDAF9
F7CFBF90D56E9F8770D68AE01B2E228D0B4680C1A860B15B9915B62A7A75626F
A456D96D65AE0B85AE3B83EDA7C86BBDFD7CFBB28C60AAA4F365B8DCE9736CDB
342E8CD620D8717C26947CBA085924727F1FB5C5422C513A96E75BC2F4A0A0A5
3F20ADCAE9E9EEB6DCFD41C316C250573E617EF6BE7DDDF1F4A5D06959B5B2B3
1CD2B76BDD4B355907A898739B1CB13681C419349A22417967063FA5DBEDF736
5C43B65C9B7482D76EADB9974BA32D4CBADBEB711E19ABC8F7B5F3EE7C222FE3
6A217BAA315AD1A5FF00AE62BF628AD2A515A54DB9C7512DD364B911748459C5
25A60E41ED84C388A8D768A4F5CA931D6F0CB6DBE50EB740E63616D3468C14D0
9F711A42C3ACBE976E10A61A37B9AF9F72757685011AA0C8D6A311AD1A4FFAE6
23F6288D2B71B842E14A234741B856C37118998886488A1C988E1EB56B58196E
5F8C4B9206CEEB1220A75E9A69F15B0663E92323BA4129D56D1D4A368DA7B9AF
9F72F6D1ED96CE442E0E5D6B6B1273A26CDFEB9A5FD8A9BF72A5FDD84C309904
524C44EF8B2459E23DF151918504F08F59420E5124F436021114ACEFE7D1F0B2
68E03C7988A42CA4A6B269050993462FB9AF9F755A6EA36DC2B1423C4334BB21
1479B6F28688A7D7529F5D4A7D770A6E22249E0214434BC51E6742C26325C6CB
51219E09DB154A2E6B83621A281C87903A9AA79D834504EC262F735F3EF9CDA3
DB730671E8553F72A9FF0093617CD2871C31566710C359C529EC3449D712E64C
C1871C6AC61CE2550553B971850453B4B85D3CD0B088A18583C5EE6BE7DFFE4F
4D4029BFBCD0BE695B1B618FFF00986AE902838310764B7452096F3E47403092
5CA96C20B9E804A64934D3C63B295A3A8C020617EEEBE7DFFE50CC8015056B5D
D308489577AA911C74906AB8A12B6F822B8E39AD32FA750C57224B8244D958FA
9C04371858CA46CF795F3EFEE16E86E70DE2C90402142EAE1C064C5401520BA4
AC9E62E3B68E00D6F2E7242B59739635ACB9CB8D056C84097DF57CFC04F03098
AE4235A48E0308299152D96E88F7C96D0C6A5D25D7E0EBE7E02E57A936B4269A
65BC5A477A8E3DBF92BED4D7DD1156BA1477C157CFBFBA5BFD487BA8B50EA413
C981A1D6CD4108A1633EDCE75CFE12BE7E02F644435BADC2B636D69AFC3D7CFC
0569477C4D7CFD19D1B647E1631CABE7E8CEAD5AEA39CEAAAF9FA4D7CFD26BE7
1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B56
36AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC
6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58
DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1B5636AC6D58DAB1
B5636AC6D58DAB1B555B454FA4D7CD14B7B1629DAEDEDCCCCDFF00AE33A2926F
99AF9A780E331F76205E75C4582970BA03CC2D586273A13499A294BDD5088265
60A2C6E26EF73AC93DD6075D200891EA6182FF00C8F05CF69F6491D315F335F3
445DB6D73CEC78D1A921026A71ADDC964F044D221848B9C905BE52081ADC5CAD
987638A8C13A914A38F1E51F5C8351441DB207C751625CB8D72E35CB8D72E35C
B8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB
8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8
D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E35CB8D
72E35CB8D72E35CB8D72E35CB8D72E35CB8D72E2FD2BE68A3A7D1AB4FD87FE3D
7CD145E092630E07DF046526BE070547BCC645CFE843FF001EBE68A2F17219C6
0458C5B0F6D88B1011C59C6B8FD087FE3D7CD151ED8EB9E359E359E359E359E3
59E359E359E359E359E359E359E359E359E359E359E359E359E359E359E359E3
59E359E359E359E359E359E359E359E359E359E359E359E359E359E359E359E3
59E359E359E359E359E359E359E359E359E359E359E359E359E359E359E359E3
59E359E359E359E359E359E359E359E359E359E359E359E359E359E359E359E3
559E350B76C35F3F49AF9FA4D7CFD26BE68BD44D9CB9AEC206A7BE0635C69701
5C4C65C12C95222A31F7312222A4C54A38C818F2AE2280A7BA062C73DD031629
AF200ECE543B6B3C6DAC1730CA6BEE42471DB6E71DCFE5EBE69E2B10F1DDE38A
B21A1EF0E70A17D55885A0C1DC58F6DC8BA3A819F570CC045D2EC6971877E19E
48230CDA0C1C93CD1D0C82798AA0649221AEADCA62226814B356AF77CB57CD13
8876ECF2ACF2ACF2ACF2A7B6AF273CAB3CAB3CAB4AF2B3CAB3CAB3CAB3CAB3CA
B3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CA
B3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CA
B3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CAB3CA
B3CAB3CAB3CAB3CAB3CAB3CAB3CAB9125136BB9B5F345178FA30FF00C7AF9A28
BC144B031BB95AEB633BF2CB6DB4127F23044BCFD087FE3D7CD145E268584C3D
72D9E9A4D82DC68D2D9C29EE1F421FF8F5F345B5F1D757AD5EB57AD5EB57AD5E
B57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB
57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB5
7AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57AD5EB57
AD5EB57AD5EB57AD5EB57AD5EB57AFF65546DD91D7CD3E935F3BAAB7556EAADD
55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EAADD55BA
AB7556EAADD55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EAADD55BAAB75
56EAADD55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EA
ADD55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EAADD55BAAB7556EAADD5
5BAAAB554FA4D7CD3C5D7F270AD12F7E0177E0177E0177E0177E0177E0177E01
77E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0
177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E
0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177
E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E017
7E0177E0177E0177E0177E0177E0177E0177E0177E0177E0177E010BF9B5B899
957CD3C5E9D575E3E8D66755F68779A78BC7F6FF0000485208CFD22872B3E0AC
9FD33BCD3C5E3FB7F80BEFF1B352DB1F11A2B4DA8A4C8C919EB4EA6D77C0593F
A6779A78BC7F6FF00CBE98C8A1BE970B2DB70FF82EF71665F522685D6BAD7E02
C9FD33BCD3C5E9B56DE3E8D666D5968779A78BAFE3015DE5E8202E8202E8202E
8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202
E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E820
2E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E82
02E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8
202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E8202E
8202E820217F09B70D32AF9F90DD4D7F56930BDFFE3E150C82AFFF0009088A15
4AD1D454751D5FF1AF9F909FFB63279B75662232AC713A31038E42828CB9DE43
242F1FA8B866FA9151C04CE406A5A4CE9E08AA487FE0555F4BC4134CD8E79CEA
D1CE29D46EE28A08A3487DAEB2C81FE95F3F20407016AB6E16AB843E78C78A17
B18D8DB4B70947B6DC23194087A43823A3E304685B3890129B0C6DAFF86C6EF9
021E669767691236DF0F1AA10F58DA10EC99ADA31BFA57CFD26BE7E935F3F4AF
FFC4003D11000103020305050506030900000000000001021103141221523141
5161F004132240711032506281A1B1C1D1E1F105152334426070729192C2F2FF
DA0008010301013F01F238D31601F570392532EBA9F6A3D15CACE1E75CE46A4A
9FCC990AB1E9CFEC1DDAAA4A3D5663F5E43BB62D46C2D3945CB6FAF229F6A6D4
6BD8ADD883B0C31E891927FE7EBC46B7BAC3978B72704DF998A9A5786AC2EFE7
91DEB32CF6F9DED9DAA9BD3BB6ACFEE84A46DEA1398DA894E5DBFF007E62E056
BA573CFF00ED96D28546B1B8E613F1EB70D5A54FFADC7F119DA5EAEC132A9BB8
ECCF94098913BAA0909B97688DFEAAAA246CCF898DD815D873E0254455C2BB76
C79A724B5507537D27235F974DF98872351CBBFF004F9872E4B9F59FCC39DDE3
B358E9DCC6E2624A6CFBFD3D77149712AAA6CE1CFADC556AD6C2F55C3D722923
B0318DF7D3ECF549296376256AF8B8EEEB892AF85A6A9CCC5E3C31F5F36AD6BB
6A157B3D3AADC2A76CECAB45259B3EBCC74E7FAFCC5173DDE15D9D6C113386ED
4E3F7FEA3970674FC53F542977AE8A6BB17D7127AA8AA94D51A89B464B121F07
8F1FCBE77B6FF677919AE2D9E9FEAE43736CA75CFD4956A35CD49DD9EDCCA0C7
53446D34F126DE0BB37C14A9A23E1156536F3FD887369F8165799851D1893CF3
98D7B70B9323B7F666D3F135325FC97929D9E923BC4A9B37F4822331261F1397
8EE4EB381AC7261976CFB46355AD855918C6D34C2D4F3EF5735AAAD4952AB9D5
1EBDF6EDDFF2C8A1413263B2545C5F429370E2F0C67FEFCC6B1AC5554DFF0002
EEA6AF78BFE426E15613AE29F98BB605C85C8DF04ECE64F85553CF2104104104
10410410410410410410410410410410410410410411EC4F8349249249249249
24924924924924924924924924924924924924FC1F713965D6682ED817217283
7C099FB537F9C420820820820820820820820820820820820820820820820820
823D89ECCE3ADBF0492492492492492492492492492492492492492492492492
49249F83F6BAEEA2D45697D58BEAC5F562FAB17D58BEAC5F562FAB17D58BEAC5
F562FAB17D58BEAC5F562FAB17D58BEAC5F562FAB17D58BEAC5F562FAB17D58B
EAC5F562FAB17D58BEAC5F562FAB17D58BEAC276FAA22CA49FC47DC6F9175344
55E0888BF77E65BE15855DFF008C0EA785A8BE45BEEA1FC47DC6F91EF1FC4EF9
D87092ABE45BEEA0E635E90E42DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA
8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92
DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E92DA8E
92DE8E92DA8E92DA8E92DA8E92DA8E92DA8E913B3D24FEEF9A545118B8A446AA
408D72185DC456CAF5CBDAE62AAAAA75B087498544484FF067FFC40037110000
05020305050508030000000000000001020314115112215204314061F0132232
4171105081B1D105233391A1C1E1F1426070FFDA0008010201013F01E0701E1C
412DE223A6FF0069A4C924AE3488D47421055522A82D9D1434916FFE3982D949
0AAE3CCB3DDE817B3A90A4AC8F7982AD56933AE7D1851F698B3EEF99DED90A2C
D9AA8B2F2E43B356796EE3766D9D693C6AEB78CEBD73E40D06BA1797F5C81632
515B2FDB907506A3C34A9FEC144E2FEEEDFB05309C38B711FE9C81E1AF68E9D4
EDB862FBB2233FE0614E222C40D06458BCB8A49D0EA0968708CD3D6FE42A46A3
22EB7F20459EEEB2E4129C0591759720AA28F3DFF2F50E152847D106D44DE24D
31070CB12947E13FD7D320E614E1232CADE7D5850935C6429DDAD78B25196E30
DBCB6CEA4365DA3B53A2B784D32EB4870905DEF3067977BF4F97F01258B25F76
9F030E7669AAFCCBF2F80A1AEA66615DE3EED47770F3E3765FC648AE5975E1E6
1591D0FAE5E82846664674F4DC1E512CCD4BDC7BAE1C599A7322CF772154A97D
E2A1721532AD38E4A8D078923637CD7DD51E7FD7320F3869C88F7F5715553BD9
117CC1AD275EE851928EA4540A51ACEAAE3D24467451D03692424BB2F3F3FC83
AE9F88B32A503875C39D7206B351111F97B8BB4A3780BFE0859982CCE9D6E3FA
02CCAA0B3EBD3EBEC2CCAA2FC8533A1F591FD38E7DDEC93884E5584E5584E558
4E5584E5584E5584E5584E5584E5584E5584E5584E5584E5584E5584E5584E55
84E5584E5584E5584E5584E5584E5584E5584E5584E5584E5584E5584E5584E5
584E5584E5584E5584E5584E5584E3B7B36DFC32F50540649F2F71BAD13A9C26
20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6
E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A
6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6E20A6FEE72DE0B7E7D6460B
754167D7A75F01CC16EEB9FB7AF98B7C38CDA1C369154898E898E898E898E898
E898E898E898E898E898E898E898E898E898E898E898E898E898E898E898E898
E898E898E898E898E898E898E898E898E898E898E898E898E898E898EFB36DFC
32F50587CC7DDD7AF87B8DC6D2E951421B421B421B421B421B421B421B421B42
1B421B421B421B421B421B421B421B421B421B421B421B421B421B421B421B42
1B421B421B421B421B421B421B421B421B421B42235EE7D9184BEB325080C880
C880C880C880C880C880C880C880C880C880C880C880C880C880C880C880C880
C880C880C880C880C880C880C880C880C880C880C880C880C880C880C880C880
C83FB3D906543A0FB37C6AE049C3C2573A82DA316E2EB2FA84398CF815F88C7D
9BE35703D9A2C3B14E2C40888B7702AF1184AD483AA4C4A7B5094F6A129ED425
3DA84A7B5094F6A129ED4253DA84A7B5094F6A129ED4253DA84A7B5094F6A129
ED4253DA84A7B5094F6A129ED4253DA84A7B5094F6A129ED4253DA84A7B5092F
EA129ED4253DA8497CFF00C84A7B5094F6A125FD4253DA84A7B503DA5E3CB171
44A2222A835961A0C6475A90C693F218D3618E85ED4AC88888CBACC624835952
940A3A9D7FD33FFFC40048100000040305040509050702060300000000010203
04113312313291921321A1D2224151D1E105101423244250617152607281B120
345374B2C1F015700625436282A23073C2FFDA0008010100063F02FBD2644739
79A667220E3ACB7B65916E497586DD751B15994CD27D416851F4165233210F03
0EC9AE17799BDD82647321B8E6379CBCC95C3B1E90B354AC829EEF8EB9EC0E1D
976C17CCBB4462CE19F225BB2333DFF9F994C2D4694ABAD210D24E648296F0E3
2A334A5652990F4425A8D166CDAEB0CF92D0DBAEB2B4AA6F4EE0C793DA69D79B
76F7BEC83690B52C8D56BA61852D4B49B4AB4564EF0F1390EA6366722B5EF7C7
1B2399A96AB2444219D5A22666F9F5DD7064CE1DF6EC3B2E89888F5713FBD175
FD446FAB89ADD47F5116CFAE6AD59E928F7089879BC89A1256E7BAE20FD9F48B
4DB25D249DF705BA64E11A9A9C938836DCDC45A44BA588833E49938EED12AF5F
D9398D9DB53B299CD5786625497618E1DCC1F68305B153DB454BA3D41F2D8ADA
D9AACF4BAC2E532342AC9918886362B46C8E5695D7F1AF27CD6E174AE45C7F51
09EB626B9DFF00902F5D135C447AD88FDE8BFB876296A5C425E56E47D9118CA5
F79B354AFB884624DE88E8A1177E5704F9414EB8E37B322D9186DE2292567391
FCC1BA9885B4567676527C4595B8A7CDB499DA3BC7A4212A4A77EE3BC29C4A14
DC9567A41C4A9E53D6D56A6AEA08529B52EDAA5D1096D2F1B1255AB490A60DB5
15929ED3A95F19D924D666E12889692105ED910A9BA65BD37DD7EF10BED91073
7CCB7A6FBBE60BDB226BCB0F0BC447B5C417B49161BAFDD788CF6C88293DD49B
AFF988DF6B882959B937710E304E3C871B4A4CDD22DFBE4129DBBAEFA92E82CB
705B4B4AAD20B68722EAEC1B76D324A8F74EF2050CA256D1C2DD2B884196D5C6
D33A68DE930CC442BCE43B6CB9D244B1061C868A534942E6767AC3DB5885445B
3995AF74252CC41C3A8953997582EBF987DE5C41ADA5E16FEC871A69D3656AB9
442DBEB53BB24F495D6610FA276165329FC5220ED59936ADFD9B841FB619CC95
EE5E207DB0D5378FDCBEE109ED86737CFDCBEEDC0BDB4EBFD8E0223DB0CBDA48
B05D7EE11BED86527BEC5D7875B43A6D3ADCADB966F115ED86526D1EE5D704C7
3AFED2176645290436929ADC2B6532F77B01C4ED2C42B45D26881C4349E81DC6
7D41C9A246929F6C8429147AFA5112C17DC223D7EDFD65F29482D71D126E93AB
E87FDA16CC03E6CBACB856D52FA8275F33B38664412A2B94530B844ABD720A66
2465321222917C50D2771EE08525D6B62D928CE68DE20BDA993F5A77357DDF20
D2D98861696DE3B5EAE5D9F205ED6C57FE178088F6A64BDA7F8575FBAE119ED4
C97AEFE15D7FC846FB532587FE95DC03EA8879A719242268D9FC8BE409DB485C
0AD324B5642E199B0DC659E8746E20C43BF1285AAC1DB6ECE2E01C4A104DCAEF
FB429312A275D2F78834DB8DA1B5B8AF56563AC1A239E45A79DE85820EFA6AD1
109B569BDD84388F25BADB4FA1CF5A72BC125D4A5C2EC514C390CDACB68D5E90
6E120AD9EE35758712C2AC3A65D1330DA5F592DE22E928BE2B23DE413261B2B2
732E8DC2CB4DA5B2BE4921ECFB1346D2DF4905B883CB59B0949BE4A23B1D5BFE
4233D7C317AEEB47D7E4237D7437BB7A2EE022BD74397AB45E8FA7C816D625AD
82592559497107E8CA47A5AD136D465D5D42D3A4938D2296D257043116E11C62
BB3AC35B1324B05512A2DE194C459DAA8FD55BDE73163CAAF34E3BB5F55BAE05
FE98FA2685C9C0B36D048359CD52EBF33C96AC7A4FFD4916FF00329C7156509D
E6612E36AB4855C7F199194C8452D6DC3210B766935F588DFDD3DDBCFF005115
FBAD345E7F4BC2D084C2A946C14888C3285A5098D4A488C91D82D6E28322E9DA
3DF3051252709385DEC2EB1EA5E6D4E2F0F4AF106E4432CA94DB9333EB2298FF
0099B6CA1E53B36F7DE2276CD21AB6B9958EBF344FA4123613F5720B790D925D
5E257685324E24DD4DE8EB0A6DC4DA42AF23096DB4D9426E22F8D27A0D2FA773
A72211BEA617DDBD7FAEF1129443C32D46DA375ADE777CC5A650D17944912B16
BC46D6CB7FEA9630DAFF003AC1FA59125678CA7B81B4CADB9191D84DBBC2228D
86FD21A33B1B25F4423D34910EFACE4944F1025F94A1D24E34B9B720EFA5324C
C8FA32EB2110512DA508257AB32EB2169D5A5B4F6A8E4265BC8C2E252DC9E5EE
357C71244D13BD32DCA3908DF6541CECFBF788879A8741384DA2476FE4436CEB
696E6D119B9682E2999391767A1BEF21ED65B352F1A04136C3495C3C9456EDDC
19868186B50C7BD4A3EA10EF4624BD21A3B4562E210E50CCED52A574CFEC9798
C92A25195F21B27CAD227309495C452F8E934F4EC91CF7187DD6985BCB70CA69
B422BD854736D1EFDF70343B0AA69B530446BB41A26D8558437649E9FCC7A39B
2A542B85D376E08434DDB5333536467BE636AF439B4EFF000C1ADF60D85CE564
C2CE221CE1CC952223EBF33EE376AD3C769533FB80A6DC4DA42AF211C9285756
56525323C57036D70EE34953049359989B4953DB22E8A0AF31E906C9A5DB16B6
477887F293A85B0F2665B33FB8B16CA61DE2D9EEB682BFE81F6D5B76ADA11D35
5D710B05B63B2D4ADAB0183AB4EFF7022336AB234A6CD89EEF343C4ED54936BD
D2B8FEE1937B5533BE769022EDAE24D2AB32347F60B83421FB694A7A692DE739
0546ADE75D24356765786DE249A4965392AF088BDBAC89252D9757DC6714F5AB
17742F1B6B6B59B892C5D5BBEE4EF29FDF0E92495BBAC811A50949FC8BEE4CC9
06AFA02F56A4FCCE5FECBE12C8612C8612C8612C8612C8612C8612C8612C8612
C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C861
2C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C86
12C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8
612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C
8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612C8612
C85C5F731C67D7AD6D9C97B28671645BA77924128A723DFBCA409AB45B432B56
7AE5FF00C8DB456896B6F6A44A4996EFF0FE39E553878865A6F6E99A5C64D667
EAD3D768879412B7A2124DB6834134FAD123E97618F26443CA7768B80B6761E5
A48CE69EC3F986625097B6BB73DA2D511D0B36A465627D9F20B8871F79D59B8E
A64B5EE495B3EA11B044E2F68F38DEC8E7BD295EE397D2CA8C794E376EF14543
B8A26D24F289252C25667239FF0071FF00111ED549536466DF4B07AA2BBB3787
CD6FBD61A43464D12E499EF0887B0F2DBD8DB24B2FECA67395F32FF0C43A760C
BEE914966F3F64FE5724E7B87942DBCFA364D2148269F524927257618F26446D
5F57A43466F12DD52C8FA16A7233DDF90F27BAD938DC3C525472722D6E999599
96E3DC5F918F25AD6A35AD5E4F333528E667D24FC714B88828679E3BD4A60947
FA03B0824CC893B9BEA2B8344E43B6B2669DA66763E9BB70F48F456BD2273DAE
C3A53ED9C85941582BE49418858A397A84AA47B33B533F9E60A2170CDADF2B9D
533D2CE436AFC2B4F39295B71899CB206A4A64A3BCC907BC24A25843E49BB68D
5A970096DA4ECDB4EE24A5B32220B3B3BD7B947B33DE1BE853C1EAF0FD012DB8
3650B2399292C48E7904D86C9161361365B948BB2E179E93179E93179E93179E
93179E93179E93179E93179E93179E93179E93179E93179E93179E93179E9317
9E93179E93179E93179E93179E93179E93179E93179E93179E93179E93179E93
179E93179E93179E93179E93179E93179E93179E93179E93179E93179E93179E
93179E93179E93179E93179E93179E93179E93179E93179E93179E93179E9317
9E93179E93179E93179E93179E93179E93179E93179E93179E93179FE693FD85
7E23FD7EE3B7F84BCEAFC4AFD42DE79561A414D4AEC0939BC7688CE49616672E
D94AEF9829B8A5159259AD0DA9494A4EE33322917E62220B66F12DA974F62BB0
7BA78A52E3F70DAFC25E757E257EA1D650644A51758544C2A197768D134A4BCE
1A25233323B8FB43B04C6C5D69E874B2A71C5991A248B33948E61E51136A8674
93D2B7D2232295D2FEFF0070DAFC25E75128C92768CF78A89CC544E62A273151
398A89CC544E62A273151398A89CC544E62A273151398A89CC544E62A2731513
98A89CC544E62A273151398A89CC544E62A273151398A89CC544E62A27315139
8A89CC544E62A273151398A89CC544E62A273151398A89CC544E62A273151398
A89CC544E62A273151398A89CC544E62A273151398A89CC544E62A273151398A
89CC544E62A273151398A89CC544E62A273151398A89CC544E62A273151398A8
9CC544E62A273151398A89CC6323F9118411DE445FEF0C5350D08C2D0C2C906A
7620D067D123B8907DA1298A8A87877774D0B748BF50DC1BAFB6DB8B45B2B4B2
2EB9110F4628968E23F856CAD64366879B5AEFB295119F607166E2090DE355AD
C9FA8261714CA5F3B9B370AD1FE41D3375126AA74B075EFEC04853ED92CE4449
3514F7DC0BD26259879FF156490DADE8B61A439BD0A5B8444AFA043AF45B0D34
E605ADC22257D036B763A1DB4B8534294E91128BE416ADAA2CA37A8ED61EBDE0
88DC4919A6D16FEAED0B53314CBA96F7ACD0E11D9FA85AD514CA508392946E14
88C4429A5216DB6EECD2B42AD12B711FF7F8CF945714DF9408D4EA5483874C45
832B09FB1B879457B35587596ECDA4CA7B943C92E3CD3D2F42D89C9A52A4BE8E
E3916E0CC2C42DE42DB88DA48A11529DA339ED2EDFDBF30BF55B25ADE714AE8C
8CFA67BC2E0892AD9C7B8DAED4B76EA85924B31E5382D83C714FB8A36D44CA8D
273C276A52DDFD879718365F5B9149336B66CA964AF5449BC8A57908A794CC95
B2692970D3F5994C32A712E2BD9952D9B4A73DE2FB24621995EDE1985ED57365
8DA2D335CD29948E5B8FB04238A5C6C3C4B7B46C8D308A5CCAD7BC567E9D81B8
B338963CA2E3044A6DB84538DAA5394F76EBFED06DA5B0AB31EDB64FD94CD28B
2735119FCC8E422DB532E19C3B1E8C82514B69256F976CC8921D721D97892882
75B3B6CA913339488A65BEE31E4A73D195E8EC4ED25968D560ECEE3B25FE6F11
EE5871097222D2768834999584F51FC64C908B445BA6672148B5780A45ABC052
2D5E02916AF00DBE6D74DB234A7A7BB7CBE5F2148B5780A45ABC0522D5E00A23
65EB091631F5642916AF0148B5780A45ABC0522D5E02916AF0148B5780A45ABC
0522D5E02916AF0148B5780A45ABC0522D5E02916AF0148B5780A45ABC0522D5
E02916AF0148B5780A45ABC0522D5E02916AF0148B5780A45ABC0522D5E02916
AF0148B5780A45ABC0522D5E02916AF0148B5780A45ABC0522D5E02916AF0148
B5780A45ABC0522D5E02916AF0148B5780A45ABC0522D5E02916AF0148B5780A
45ABC0522D5E02916AF0148B5780A45ABC0522D5E02916AF0148B5780A45ABC0
522D5E02916AF0148B5780A45ABC0522D5E02916AF0148B5780A45ABC0522D5E
037B5BBE4A046571F9D5F895FAFDC76BF0979D5F895FA875F74E4DB4935A8FE4
40FCAFB657A092AC5BB0739CE570828B7DD52588C96C4C90673994C43F92DC70
CA31F2B484593DE5BFAFF2FB86D7E12F3ABF12BF50B69C4DB6D6469524FAC87F
A7FA1B7E853B5B1F76621E1DE846DC661E920EE406A39C8742A2DA2921D3BD3F
E4FEE1B5F84BCEAE81A8A73990A4AE1DE292B8778A4AE1DE292B8778A4AE1DE2
92B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8
778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A
4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1
DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE29
2B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B87
78A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4
AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1DE292B8778A4AE1D
E292B8778A4AE1DE292B8778A4AE1DE37347F99904A7B0A5F733098C063018C0
63018C063018C063018C063018C063018C063018C063018C063018C063018C06
3018C063018C063018C063018C063018C063018C063018C063018C063018C063
018C063018C063018C063018C063018C063018C063018C063018C063018C0630
18C063018C063018C063018C063018C063018C063018C063018C27F73364E9AD
C77AD0D14CC8508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B
4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A79850
8AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E6
1422B4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A
798508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A798508A
D29E61422B4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E614
22B4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A79
8508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A798508AD2
9E61422B4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E61422
B4A798508AD29E61422B4A798508AD29E61422B4A798508AD29E61422B4A7985
08AD29E61422B4A798508AD29E604D9ED589FBCE914B81FEC474CE7EBD65FF00
B7DC781519CCCD84199FFE3E78EFE61CFEA3F80B0A5CA4F22DA65D9E77156D09
B053928E46AFA7C0E03F976FFA4BCF1DFCC39FD47F01F257F2A5FA98F25B4D30
CAD2FA096E5B6C946B99DC23D307E8C875A8A91AE208A448EA29ABE63CAC6CB6
C1B6D329B06DA088A73299908680F4687F4771A4DA2D914CE689CE60CBB3E030
1FCBB7FD25E78EFE61CFEA3F80B6DDB41A10565369941C8BF320492521564E68
353693B07F2EC0F25316DC3C638EDB715109B44B4E460D30AB4C96CA50FA908B
2970C222769EBD04449548BB2427F0180FE5DBFE92F3C74CA5EBD67FFB7DC781
49948C9841197FE3E7DABA4B6DDEB5B4723315E2B52794578AD49E515E2B5279
4578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD4
9E515E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2
B52794578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B527945
78AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD49E
515E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B5
2794578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B52794578
AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD49E51
5E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B527
94578AD49E515E2B52794578AD49E515E2B52794578AD49E515E2B52794578AD
49E515E2B52794578AD49E515E2B52794578AD49E515E2B527941387B57E5EEB
A652E05F13229EF3EAFD8B09750A5FD9256FFDB4A09F6EDAB7A5368A67FB25B4
71089FDA390991CCBCC644646657FCBE2F09FF00D6E7FF00911AA4BE6C943209
494911495BA7BC129E53C8696B2246CEC58DFD47EF5E0ED3CB77A6BDCA96EE99
F6106DA287B2497CD5B75194B7393DDD61AD92DD521E4AEC6DAC4BE576F0E344
A7FD2A49549CD9DD3DF6645FA84AD6B74D295290E25E24CC8ECDA2C3FE6F0A4A
944710C36E29CDDB8E587F5E01D426214E9EC7684A5A53D139FC8BE6150E714E
1596B686A24A66A999FC87939992491B3438A5F5EE96E2EFFD96F66DA5D3F475
6E52A5EF10866994B844EA56F4A1AC747A587A7D93096ED3AD446C2D252D2527
35F5CEFF00907D0DAD4A36DD4919A6C92ECD82BBAA73106A2898841913893B44
89CC8CB75D20876CBBB251AAD5AD9D822DF294BA41A75E74DD5388255C4445BB
E285B761B7A576D12472089C333D0DC9E817446DB60DEDBF8964AD6616A43694
297BD4692BC594A4925D842D143336BB6C10520A199242B124905231B2D837B2
9CEC58294C2D7B34DB5EE52A5BCC292DC3B484AB1125045305B665B76CDD6D33
90499212564AC948AE2ECFD9B764ADCA56BAC1256C36B491DA92925789913068
B16128759B448FA6FF00F2412CB8DA5E222299B899DA32294C2106C37611BD29
B252206EA586C9D3F7C92530494912525B888BFDE2FFC4002C10000201030303
0305010101010100000000011121315141F0F161C1D171819110405060A1B120
E13070FFDA0008010100013F2149410B042C10B042C10B042C10B042C10B042C
10B042C10B042C10B042C10B042C10B042C10B042C10B042C10B042C10B042C1
0B042C10B042C10B042C10B042C10B042C10B042C10B042C10B042C10B042C10
B042C10B042C10B042C10B042C10B042C10B042C10B042C10B042C10B042C10B
042C10B042C10B042C10B042C170ACBEFD305AE49DBE91259195F05195C19B1A
E72B0D0673FA9894F57FE9111910A6549D1911049C29D7E8FC281D268A1D4630
926A5AC7DF8ACBEF2521B485318B5ED6C6D4FE943E9135AB7428B14AE432F259
0E8E479D5AADAAC927877515E4A95D8C4CB363A93AAF52A38D336EAC8CD52934
B9A782D2550FA18B9BCBCA8CAA7E04565F76E515A4B3EFE83E85A959F0DBFF00
4A6EEEAE7574B0B7660D7AD52C5C0EAD5AD94B0D438928B45694274924FA7629
D04593AC54907652E3A5659D0634C74DC1205ABAF204B16E6957428B44B3D10E
BD0836FAFA757F23184DE4A10C2D0862A8C2CE14FBF8ACBEED18CDD19041CAB4
AD42F8BAD8F459B7F2F617A3C228ACF4AAD89F382ED52F222432CD1AB4A924C2
0E34EBA8CFD155DAB13D0879A2506A16F4A8B72DB28D59F2312D09BAD610CB36
247A055399058B1464ABF804FE6874B1B824EA1D1D3FA514551BD0FBF1597DCB
691B74488F98C2926A567A15BFF8F2B009F0D00BC3C8897AC6C40956B52FB161
E056959EA685808F0366C2B584B6522D7A8BA966D0BDAB3372612B5A51F50B8C
24763A171320D3BF029C8F2BA935FB9722E3433A14C36A8C84F91C3A318CB617
F9092D07D360628DC92896A26AED5B040028D11890AA150A900587F762B2FB9A
AA988F52A7FEE62B34D21FE234571B6DB3D85C843696E16D18C73DDA047D1893
A9A8350B3EC57EFDC471324DBA5481FE6B8CC55E255B4C1EF223570C8BFAE234
45A966325ED3FBFD2E641EA22D55F4A93702613A5095440B5692A854B4DC4F46
3AE3804507349974D0A6922C92FBB1597DCA5D94B64F053FE47A1CB5646BB6AA
8BA4B431BC147563429BA8CF60132F8EBEA436B2AAB7AACBAF422B3A1567750F
5B21B1B5B3D37D43E20CA69D07EE12157653E0724934BD1256C8CCDCACEBAD66
810A944912A4BA40ACC52D5092D3413B88AA2BD6D4D09C13DEB734261D2A2AA3
DBD04A09F67087D2B528A70DC048FA4528D44211B2B80AA5EA2DDC6A544C80D2
1084DFDD8ACBEE96D448A1A7A98064A55943C305CA026C4E930B097A8ADFD195
A40AE336555516B23434AD0F212A146970BEA12B7ACB4A5E1EA38F51DAB5141A
2B559973F4649281EC70CFD852796D24A41B78C0D8D54A65A6821255E87B07EB
03F5A62AB542A2BD459BB5FE0982D058975FA51FC4BB87D1159693A21159694E
BF762B2FBE7C59F74C9139DA212EFD467F82F40CFE37C7C42213F28DBA7F07FA
8814AE9AE4801BE37A1DA0845781A7A1273EA2251A42BBE8550B4BB35575114B
C39C715BDE86216351D7E8C45219DF05A790DC21B94A9D02F32D164D0BCCB459
2FBB1597DFE041EACEA865C7E6D8210EC2CE85CB40BEB961B17F5822F69BC923
4FF9FDD9A8D37BF6D1979CC94F466C7FE992C7D6A2EAA422AD4EBD3E4919A35F
904061D7B5AFFC2BEA629122CB12129AD44E44AADD56D7DE8ACBEFDB863AB53D
584F4FA9D44A4D422E38CEE839B4E934911226D0F549FC8E2B30A91EA6BD3327
2994AB5B97B82D266266980B34D99F710C62BD22BFEFD292994698277604538A
A2906B27A2FBE1597DFAD97D2EA8A40CD3CA4C6DA33EDD3EDD868107CE152904
54D65DA8580C0FBAA2AA31067D836A752E30AA77109D3A6A2C987E1899FA6504
4AB5B7CFE00565F80454521821594E85168A14280A74A94B135C3DC2A34161BC
DAA40A966975155AA904E26BF841597E0117A60B31CFD0407529D0B0CA52F41A
D300952081548CF0099614353E8CAD9BFDDFC20ACBEFD8863ACCAFA0D8443352
AE96A2384C546AE5E7A88AD869DD4A90428D1085960B3AFAFE18565F805E5344
DE15BB34402EAA9D90D0424352B0C4A142B7E1C565F8059084C312850BF122B2
FD1AD5EA2B0A5245D0BEA2B2FD1A3A36A2B54F96259A1332763FA8ACBF4A1597
E9526AFD277BDEF7BDEF7BDEF7BDEF7BDEF7BDEF7BDEF7BDEF7BDEF7BDEF7BDE
F7BDEF7BDEF7BDEF7BDEF7BDEF7BDEF7BDEF26E8AF62C5FA51621AE4BCA7EB48
4A566B5D45A622524CDEE9D50D2C4D52752349BFEAFF00E8D4199B58B4AA9AA3
A28FF36581327CD21A2917C310837C0B949C2A6CAF822230E912D90A352B3D45
74A550237B394242BA57A8840B1B6AAD25668AAE5E930245A3775785A68561AD
046A5CB8A5D39F68CA3484A6AD7C874D4920EF7294DB4AAED6987AA23C9BBA3D
59B46385149FF04C5B5B550F06D44BA5498EDF36647084ECAEB42758B4F560E2
694EC573573D04E53B142AB2F04B5F240BADFE6CB1106549E74A4B9685CCA93A
9A096B222D291810B7B456C13EFC92A4F52F42B81296E5BB6ADB622F9AACA512
510B45BD50D6549C8A356D4A0BE8F87D06976559018A92534569A6839824AD73
A488EAD8706124A862A9540AAC9D2B762A0228454A22345294A146B626649FA9
FC8DDDD4837A3685454E86D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6
EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D
6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6
D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC
6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC6D6EC2C175417F9F5AC429A7D7BE2
1608582160858216085821608582160858216085821608582160858216085821
6085821608582160858216085821608582160858216085821608582160858216
0858216085821608582160858216085821608582160858216085821608582160
85821608582160858216085821608582160858216085821604B69457B6A178B1
1B16422ACC0B26463A08C5F70DD26B06A3D2492337A4C189779654AD85D1D113
7C04FF00D69FA13B3372C178B11B16422859276DD0D5CA41A2044F7CDAC864AE
5B34948CB0938955F91C0C26CCA9F5A69C2AC35FD09D99B960BC588BCBD0C4A6
E4E1670B3859C2CE1670B3859C2CE1670B3859C2CE1670B3859C2CE1670B3859
C2CE1670B3859C2CE1670B3859C2CE1670B3859C2CE1670B3859C2CE1670B385
9C2CE1670B3859C2CE1670B3859C2CE1670B3859C2CE1670B3859C2CE1670B38
59C2CE1670B3859C2CE1670B3859C2CE164070DF54D8EA5913F82F0ACBF4A159
7E942B2FD28B113BD25E5F9271DB3CA811BC50DABD60BB56CF5150E65CD330C7
9425D62EBAA4A29974509C9C7474F5256A12250BCB4822BBB0D92D129A88E0B8
69147F039AE836E6A04CEC25D61C16E2255517BB13106113966EB7562B584F50
E3753AB23DB933755D44C55E9A342454DA52BE83E1494D6AB13E852ABD50B7F9
06D33074131ACB06AC9B9A3E82974E4642BA57565EDF982C10742906A9D7AA6A
B81CD8A19BAA2AAEAA5155611AE667AA687574A31BBD5CAD929454A3D581332C
A4AAC6D9A4570506389DE71D94D3EB22D7DB897470D976A3DA5621A7D40988E4
A36B433CC03A289F0942AB4D72E5D161099144BD991A7ABB440BBB930ECE12F1
30EA3D04C9D56F9D60F3AA9089A9173DCE699652D56F02EC9DED958E67657D64
91352FD3F29B60B7B8BB4849063A816F2A8A819DB58C86604EE9FE60B1154112
B97C7FCCD34D327DBD0CAE38D547F7FE269A66F8990BA24D3FF0BF3B34D34D34
D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D34D
34D34D34D34D34D34D788F70FF00C13592257D2B11B165FA33B3372C178B11B1
6433E2DE5308974F4424A57AF8E09B9387035291292A51EA411EE9CBE015DFA1
3B3372C178B11B1642E759D0C50D090C93A68EA4CC7A9182648D850A3D911A16
752AD17CBE7F427666E582F162224993A356AE7567265C997265C997265C9972
65C997265C997265C997265C997265C997265C997265C997265C997265C99726
5C997265C997265C997265C997265C997265C997265C997265C997265C997265
C997265C997265C997265C997265C997265C997265C997265C997265C997265C
997265C997265C997265C997264DA2117989FE956E6297D2B17E9528BC7E4DCA
F26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF
26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF2
6E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26
E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E
579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E579372BC9B95E4DCAF26E5
79372BC9B95E4DCAF26E579372BC9B95E4DCAF26E579372BC9B95E46B763E0B1
7E9378B0294029A445DA65A5FA360C183060C183060C183060C183060C183060
C183060C183060C183060C183060C183060C183060C183060C183060C183060C
183060C183060C1830605AB3612A9F56C8FA5E2C7A0C473553C264BF47612691
AB8174B5E9F822148309D37457E3EB65FF00AF8884D5FE1385D2D7A7E0C8346C
6115A2D553534E86B901AB54511A9668201869E598596D4E0B526AA711613326
B8CA3F05C2E96BD3F04415D8EC73825AC4E89CE6B1CB73414A7730C27A49CB7A
0C39565D0B96D285158C584A7C40C941488B0C735DD5FE0B85D2C7A08473513C
366BF47612691A38174B029402924455A6535FA360C183060C183060C183060C
183060C183060C183060C183060C183060C183060C183060C183060C183060C1
83060C183060C183060C183060C1830607AB3653A9F5489FA5E1597E41A1D455
94AAFF00E3A6CC0FE1FF004DA46DB84B51BF294844BAA696BFF2E51AD8972F91
6526294D3A3FA3648C227744D7E7FEE565F90DF7267FE02D9294D371A522CC71
366464824A55574506CA66B4B5519620BF5F6819AA808931A09B9522C86C5031
AA94B28D1EBA0CA0918F5D5E09BC7A687511BD591234D0B8F243591176589414
F2E25568287960449631588455A8A3FB562E8CDFA2DBA4757EC4BAFF00CB33FF
0010CAC7F2A758CD3028953D64721CAA672352B4897AD2ABA8894D6392DD4AE3
5EB6A19D005F0687E8A6071B18EDA955292AF5184495E1A217FBFCFF0081597E
4112A3ED2A46731152D2689528759D3AA444EAB0D0F50D4DFABD4AA936E18557
2C6A54EDB6B34BBD63ABF9213EB6136951581095690F514C644944A140C2AC9B
D4B6A140F5E46AEC741F6A46236752ADD185454E9FF332D02185989C0FA70464
935DFAB2026AD2D26B4A2EBE053AB106412F58571B96F973394B4258B8DA279B
D45F9182849617FC0ACBF4A1597FF8A1FFDA000C03010002000300000010E30C
30C30C30C30C30C30C33C64053C70C30C30C30C30C30C30C30C2800000000000
00000001BA3F855C595280000000000000000000000A0000000000000000010A
AEA56FE74D020430000000000000000000280000000000000000116CF2C7D359
DE2F61C0000000000000000000A000000000000000000218C8F163BAB012BC00
00000000000000000280000000000000000000000158E4070E68000000000000
000000000A000000000000000000000112A2B528620000000000000000000000
280000000000000000000005EFF49000000000000000000000000000A0000000
0000000000000000F10000000000000000000000000000028000000000000000
0000000000000000000000000000000000000008000000000000000000000000
00000000000000000000000000000010C30C30C30C30C30C30C30C30C30C30C3
0C30C30C30C30C30C30C305E300000238F000000000000000000000000000000
0000000000000100B24A2020C800000000000000000000000000000000000000
0049007F482082082082082082082082082082082082082082082082096A9908
20820820820820820820820820820820820820820820820820C0800000000000
000000000000000000000000000000000000000000010D08628038E8E8000000
0000000000000000000000000000000000048106006104104104104104104104
1041041041041041041041057601710082082082082082082082082082082082
0820820820820825AA0C30C30C30C30C30C30C30C30C30C30C30C30C30C30C30
C30C30C0010C30C30C30C30C30C30C30C30C30C30C30C30C30C30C30C30C30C3
0431C71C71C71C71C71C71C71C71C71C71C71C71C71C71C71C71C7357D000000
00000000000000000010D18000000000000000000000002BC400000000000000
00000000012CA30000000000000000000000009D0C71C71C71C71C71C71C71C7
1C71C71C71C71C7BC71E31C77DF1CD4A00000000000000000000000000000000
000B65E31062000B0C2690280000000000000000000000000000000000000000
00000000000000F3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3CF3
CF3CF3FFC4002B11000201030303050001050100000000000111002131614151
917181A140B1C1D1F050103060E1F170FFDA0008010301013F10FEFB0212AA66
FCD3B149ABDBB5E104A9A3B964800202DBB523063103C6D09A155CD8DBD6931D
011C3541233B09C13CC2DCC6486B6D987ED4B4424E6370D961CE22AA3A8D8203
04342151990037B9162B70411BBAF1C0000455EB53612EBDB174195442B43830
8C8EAA1922BF1EB42066209208A2A170DBD20430DC4200068B162875AA0F4863
80019BBE84B352C9C534A406A46AF516CDF843842F69656CA5AA82FF00B004AC
66804D110AD0CC837862E4A801AB44B3B79B42B66A5045D44E8B742029068D30
655B15CF782A64632016F7A7AA308B9063352A5CDD253ABF6E49440285D0A0CB
54E51AFEBF763900F4368001195CF5EF656501AC6A4B226DA10A0E98B2A9A01A
1048000A595AD2F28D3176C1A9142C03A2D6B6DA18F804B750FD6162D53BC208
C242979A2520EE2D63300C64015AACC1011A171AF6CEC57B6EF5B2F56701115B
88141405951711CF2481772A5C41CD21AF7FE5FEE202A555CB77489DD5840812
9142A351469A95405AC1381CC1D8A81A5A858CB328510F6458546D13A3B88512
88D8505CB3B7DCB422494A80B248BEAAF99D0A32DBE12EEFD6D4ADBF687D8C22
503516AA5B7F7EC4184802424A83484FDB0840020335E02C01D0B36AA7169028
1235C68320597484DAA2205E28CAAA6D6B180F0BD22572EC481616B420100915
1AA3B8FBF5C64F15C1D65078A0801769EB3FDA8D208064D01D0B4929AB157631
A06E4104D21A2B4280AA4C2EC9446D552A697E9BC163C86A533C5250286C3353
E7D7AC1160D3EF0266CD85AD42CB31AE219B2D5EE42DFF00710447748DDD83B1
ED8811D1267252FE08D42080020AA0D6ADD6876A7FE09A8CA87EB104BF1BFD79
1DB4357EEC83D0807C4A00EEFC2FB86983E81F99520DCBB103E42F8887425E48
1EC7D703A4020212B2E1770BD4CAE2CAEFEBBFFF00FF00FEF8117DBDC3E0332A
86FAF8F7AF455FE0C15FE15FFF00FF00FF00FF0051D61BB57FA03E093DB82211
FAFF005E715D0FC016413C57A8E86925CBF85EFE2128F62F2017D0135E779EC7
D37B2677EA202C0EDE57C37D14D956FE003F3E2133D4786578F580CC48912245
64FEDBDA2448912244891224489122448912244891224489122448912244FE97
C290597C5177BE25C775EEF65DDFF060A8D1A3468D1A3468D1A3468D1A3468D1
A3468D1A3468D1A3468D1A3468D1A37F0E062A4CCC3899871330E2661C4CC389
9871330E2661C4CC3899871330E2661C4CC3899871330E2661C4CC3899871330
E2661C4CC3899871330E2661C4CC3899871330E2661C4CC3899871330E2661C4
CC3899871012CA3DA20DD3C8F8F435F1126A6A190EBC212055518355DD8BA6D2
B4B69E1804783E3D0F8C3DA791F1E840123A64CA0D9AD776EF77ADE111134FC3
DBD0F8C256106662CC598B31662CC598B31662CC598B31662CC598B31662CC59
8B31662CC598B31662C6E898B31611DC262CC595524C598B0B301EA88255BA91
8D200065A7AEFF008534DE044350BC7C75880BB64F9EFAED45AC2A43FD2DCB4B
BBBC2B5D1117DEAF63CF7FEA40135E007C11DDDC081C05A5BE00F765AED00882
F51AEDDBE9E2180097FE19FFC4002A1100010303020700030003010000000000
010011612131914151407181A1B1C1F01050D13060F170FFDA0008010201013F
10FF003B1575C85DAF57E57EA847151A68C0392EF786AA63F8286C5F5DA38D6C
2E5364505DED4BCD5D90AC60001BEFEC420040020DD79ED29E42C55AA09ABB3A
1AE80448B581BDEE36D514197B98ABB507B52CAF846E7DD560FA9DD53390C71A
6822181A31AB881B3221CA79DD060A2418D44AC42440726335B7BDDA0655BCC3
EDC8CC2DBA080ED7060FBAB7A39F9908422E81A917554ABB5D385BB1A4B6B80C
37441886F4B1B2AFABED5444C4C59CB1A3DE688802AE67D1FF00E71400968556
6C56C2D7FDF80AA620D435AB72D27269F3F75005D3AB33937B07C74F6EC00965
C50041B4D4A0098E5831141536C0924EB5A5130AE1D98D81AD412D57543E5AE6
CDD450DE836414884D74681DCB6B7D813D02824534BD89A54326DB5D9B5B5F66
D38B06C408ACCE4DDEA80C6050D60F51BF241D8DBD1535A2C1B67721ACF7452E
0706B03A403D4EC446918046E509D6F50C70A81AB0C28F7A166A06B280812835
353A537FE26BCF0003BD79DB4D973EBE8DE5DF8DA1FDFED47940803C3B067347
F8FAC442472402F7BEA2FF00D205B98496D804DDFA0845C1CCE4EE02AC19E809
BBA012C2C03A0D583D1E6E88136876780728351900D3989E38148C458AA9821A
926CE2307DA34184800D56A8BBBB95688BB056C58BB802CE1F50E09146421A01
CB8BD06C2BE51CB21D06994EC9CFF29C78BB06A59DBA225030BB66FADD8E92AB
ABB56D5D7EB2661680599AF49E68D0B8061CAFFA217002497AD08A51B4B6F5FF
00C102843F703DA0F96E0F9FF3E081FD8B1EBE0AF4A874645EA80A03CBB87FA5
131B9FB123C8F8D112C08EC7EAEDE0BF4BA05D63E5F3C708300E5DBEC2A8EDCA
603350035344C066A634A82A0A82A0A82A0A82A0A82A0A82A0A82A0A82A0A82A
0A82A0A82A0A82A0A82A0A82A0A8283B51FC764F05015EF58D3D9FB50392F715
6AE0DBB6BA36BFA128488D575254952549525495254952549525495254952549
52549525495254952549525495254952549525495254941DA9FE9D8586CDEC7A
740EDA2BE48D900756E75017D41FD9B4D2B0F9C8610325B9A880040E4F151D0D
1540777EC43BB7A44801E79EF9F31AA219C9B57B3D793B0064ECA4D2DDC87800
F5C90C393260FDF8C1CBC4B79520C290614830A4185419C63AF9520C29061483
0A418520C290614830A418520C290614830A418520C290614830A418520C2906
14830A418520C290614830A418520C290614830A418520C20E698FC764F05523
5DC5B67AF6B4A7D02CE76B7B3BBF6FD114C9A8A039501CA80E54072A039501CA
80E54072A039501CA80E54072A039501CA80E54072A039501CA80E54072A0395
01CA80E54072A039501CA80E54072A039501CA80E54072A039501CA023639FD3
9C1A00F4519CA8CE54672A339519CA8CE54672A339519CA8CE54672A339519CA
8CE54672A339519CA8CE54672A339519CA8CE54672A339519CA8CE54672A3395
19CA8CE54672A339519CA8CE510080E3AA72D8BB4F7C09C467200D2C4FA19402
D2A1CBAA26CAEE9E010D407A171EB81EECF95D87BE049DDC6B010178E9B01B3B
06A0D15501B81EF8F9549630A5A96A5A96A5A96A5A96A5A96A5A96A5A96A5A96
A5A96A5A96A5A96A5A96A5A22B9A96A5A1684A5A96A93BD4B52D04247C56B403
8B03A93AF36EE886435B41A7D7D764FAC0BB733F0B6D6AA2E81BB600452B81BD
5F4551CF35057F8069828001856F6170EDDC8E4DF974037CF20F4945B0400FB3
483E0333EB74598682052CE498DE59B57403806FF4CFFFC4002B100100020103
0304010501010101000000010011213161F1415191A1C1D1F0811040506071B1
20E130FFDA0008010100013F10ACC1A769B4F1369E26D3C4DA789B4F1369E26D
3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA78
9B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F136
9E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C
4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B
4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA78841E27A6F
DFBC2AA2156FFA3502D56823C3B59FA6B5C768A2CF1D9765F5EF9CC08E910322
9A6209FAA697142BB3F3063AE46B3CC7A1CD2DC5CD1B55CAB7637FD01364E954
71EC81F9957D5EE4993F7DAD3D37EF165283292D0BEF111A046B34BB55F0CC15
4F3422E91ABEEE120C1A039CB1CA130C6814B7DA02A81C9050AF78F074B813D4
5EB2FDDD66E666EAAF33568AB17A6EAAAEAC563598807925E8AA90A3FC8DB5E9
45028A0C40B10831D87E0CEA67BC3C25EA61320C60EFAFF01AD3D37EED438955
6A0AEC35561D2625035513FC68DA28A4F5274F809955A44CCF08EE4CC6E1D15B
5BA5FF00C4B06E345453A5A53345DA1EAC1EF383F98089E65AA0F597CCC28C5A
942C28C3B54D6683FB2CBBE95D3B152BA1C59EF18D4E99ED085EC6F599CA6F64
0597E065A798D909A9DE341C7B255BFCA013A9D9EE6E6621B43B625597A8EA24
10AAE2AE2D4EDB7729FDF6B4F4DFBBC195E07A56463CCA52E8073AF6A7FAC6E4
CAD937705937813BFA476312F75DA19A0568AD260B8DE520A3EEAA973A1E48A0
770BD7FD6128AB01A056EA3FF50D3D1F0634CBC0FF008954521AAF864AC51D3A
4C90F860056C1545C302684575D06B7D23576574AAACEFECE223017592815CB8
C4A2A4022D1AB710258D100B64C3FF0010584EC51C6099B3A8CBFDEEB4F4DFB9
72805ABA0430E99F6D1B438555467AD868D7D5285EB9D5C477D7D08D4DB85E1C
EAC77758F1B4DBF567D223EB20AFCB31D71A31DB47DD8EF95B0D71A18978D568
1C9FF55F5D35EB0DDBE75CA18E680E7BC20AA9F5F33DB975C75731A653322A25
D5A4D327C19618743EF14A60246A8BEE36EB18062984CD55FF008CEB28FBF285
148D67BB06790E35292D44A70E33FE42BC331C2DC2D7B9E212CDD6D172BFEFE3
31C798832AB5801305BBF1933B3D3ACEB6F496CEE0E96660603492D5AB5617F9
95BAD084B4C82D69FBAD69E9BF72C42412B68943AD6BF89DF5BCA31CEF6AD3F1
3B5B5A8D797B55EBBCBD6B9D468CDDAAF58B9AFC33F3F0DE5DF5D827DD98D62B
98C629EDBDFF00DDA0B22DC4ACABAE31F995AD1009CF03BE5F882A71E502134D
4BA7CC7840C53083596120E5558955AEA4B6515012A440E728F9974991520AA4
5CF45C47C05440B82F7D34671ABA44BEE38AA28A01D4C2FE664D1F4D1B36013C
4B0AC846942F5B41FC42ED5CA6B1E9F863CEA8694A027A301C4DECCB507B9679
8511E8644DC6144EA180FF0003F75AD3D37EE40E1A4B145257E619ED096C54B7
412EAAEA760DED41D1FF00D31A99C4C8100E10C01AEA31A99C628CB35A2AFC7E
8EB3BA81A3D538776ACE73D0DEF2C9BFD33A399D1A7BA1F96E9AD5F4820A270D
923AC5085B5669505904A96A9EB5303177B7ECEE6D15A374D76002FA20AD5E90
23C481B2C8A36B7F996AFC2965C8D588A5CB61D8004A25D5B4674D2C0552F01D
5CBB916346CE129A8C9D5B423B869EDA28B24676730CEAA0149AD27FB2C28910
D2C74430634C4380D0A0B41D485C60B4B27D1D66BA64B89D0FF28BEB57FBAD69
E9BF7413D20AC0E118E37D1C96D5E0C3833B4ADD3C5DE10EB88255944A1D0AAD
E9AAA0526A9A274AD59DBE7334E5017BCC5BB3A399A2354B1ABF39D35AC420CA
00C6F93AC3D0CD59A54BCA99CB57A0D0DBE7488D4C23B817620162CB5160F2F5
95A7B4A1900A62BE23CB12812EEB6FD61F24C8E481518CA0059CC0909D03039E
E468EEC168F42C7ADE4D65396155DFEEFD1DDB6062A60B56753F4CCB16B5DEC4
ADF3B5037579FF003F75AD3D37EF817CD0EC4DC804F6245E8E7D09EB178722B5
3AF7B1B7E23F1674507F23F0FC407AF629B14BFC7F1039C3419043962D52BF66
A00145CD5C60718D452B3609673C48E551576831470D229B192B014ABC0758A7
ADF49BA19247823814AFAC2DB45AE98FF7F4230F61554FB77D6EB105A9D58A31
AE7620F4011450453FC4F33C0273899D0738E6EE8F3FBAD69E9BF7EC53F077E4
3A9B5C56A73A2D7FE1AE9A74D601C559A2E856A034E301AC4A73D58C28AD0B04
4A0F17B577AD76B444904CFA4AC938B5DD81ED852A498330CEED30A8A384542C
2B55BBB83E69D418586ED50ACDE1EB1D9D81AAA08B4AEDE8F62315CD95DE6597
03A2DD9CB2734766B30281556342DEB8803C8B581C88C04051B240055D683A74
FDE6B4F4DFBF4A1098B632BB3C5CA26BA94183AFA6BF1A44A345066A90E20297
D6A0A59FC85C64C5F5AE934C1DBB334AEB31A434E01452BA4C6F2A1F58C07FDC
1746AE567BDE52AF55D88836622100D745114E91DDCA6AECF87E8CC82969F66B
484C36E77929B3FD607684D6E828F43F7BAD3D37EFCD3B09668219FCB0B433D5
4291AC5511CCCF82986063186BD7FD44C1044557ABA95AED28679C0601732D66
3B21C6A5856A1A12EA5465409055ADA769D3B3E835D2AF4BDE3F36C349C0353B
675AB311B63DC5442B3FB88964EC5A68C9615832FDFEB4F4DFC020AA97623167
867282192AA8BD746326B838DF9877DA652829514E75A42FE614C26D4BD01969
C563A93001FD016C20E46FF2440405A0BAFF0007AD3D37EFD4356A24BE690305
B2303AE62BE4DD7E01D83BDC0AA16EA7F916B5DFBCB7AEEB8736E8DF3DE21AD1
20CD535D0D6CEAD30034C472736A352FF836B4F4DFBF79F5E01D09D46330B84F
9406761B3235AC235D01680778C1BECCB5E725801A14BB32D7560AE525BBD118
00654CBD12C5D5E7B74FE175A7A6FE02C4DD2F1291D118ED46CA82406816AD7B
B11998A42C601000C01D3F86D69E9BF80D938B6402000C01D3F88D69E9BFA368
D1702B974B98364DF2A9EA1FA6B4F4DFD189E4041B0F5A3BF4826658A861EEBE
9FA6B4F4DFD275A7A6FE92B3831514CA89C2BE270AF89C2BE270AF89C2BE270A
F89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE27
0AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE
270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2
BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89
C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF
89C2BE270AF89C2BE270AF89C2BE270AF89C2BE270AF88BC00E819E88FE93AD3
D110EE700482B5DFACB085C02058965213B88268841494B60413B085EE7FF9E9
2CED610DD0924281CE98FE6B5A7A021C28F3FCD0E128A6A4BB748C024F9B08E9
5304C3128828F21D6F12953428D144CE120B634F4E008AB6A437F9C663D60100
260309DF2814CFF787619155033A75B55800ADBDD6E81DF08206FB7D42C353AD
CB798B19EA6594B58458855A7792A509BC5081BA5D81C5990E266C1659A986E1
7B249FA1CABAD0D2C86CF0C111AA98400A6695070AE7C9B3BA500B68624A2AC9
AA85557ABFCD6B4F444D1342FE05B4C002DD2A1E01035694D660A0680B519E12
5534C0E860C2A9D88DED357E86B66632BA9725ABAA558ADA07AAABAC49A44842
592176B654E93A9E650F62A1B34DE2F113F1C992BC5EF61A65EF3384FE490A2E
966874B6B58C970DC314B6A94C35A908C0A79FA0D01D8268DE858644E60001D2
DEF0A075107D2FA3D8631A4ADCBCB92A0147A8777765B74A9AF1C7A94A630C63
F98DDBB76EDDBB76EDDBB76EDDBB76EDDBB76EDDBB76EDDBB76EDDBB76EDDBB7
6EDDBB76EDDBB76EDDBB76EDDBB76EDDBB721043D82FF5407E608823631529E8
88C2055EBB14DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E2
6D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA
789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1
369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D
3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA789B4F1369E26D3C4DA78
9B4F1369E26D3C4DA78858289A544A56D555FF003FA2F447E86DE5E8B50EAA85
A8C5026E5B96F4C0072866081923C54784340A3A0B0B75D18A12B3AD465BDFD0
BD34FB9EDFD17A23F436EF94F42899417A768EC4AA03C4C5AC22EA3A0162D664
3EC097AE169A60C29BBC5688B905E0D17FD07D34FB9EDFD17A2252DC202E2117
5C2693ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDE
F3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3EC
DEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3
ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDE
F3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3EC
DEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3
ECDEF3ECDEF3ECDEF3ECDEF3ECDEF3ECDEF14551C019D80CAC0DE8D76403FA2F
4DFD275A7A6FE93AD3D37F49D69E8885CAE8489800003AF0E230749281A59705
10B0BA349626686A44809DA030A34967AF12D00AFA411718118FC1DE038E8AD0
ADE829CC6E6446A9B3655596EA8D624C72F369A58F4633D25913E934157BD05A
590E8C2E0DDC6541B5C01AD35A4297783702CAACB431DE629AD0A06901A4BB61
3BC17C007141110348E170DCD8C1796226D2C81A0A4BE916282CB3590E90FEE2
738A85CE6C60C9A931F9E84EB620285B68A180F42B482B51044596CAD6114206
661C185017FE7F97D69E808EAB53B444DB7593A1C0475DA0BDD249B2A52C5041
946178D630A3AD10664A8364D1BE1616CB4309536470D76659C51B362D6958A8
0706B1ED696C1AC8DA069A5231FDD9B4090B7AAFF4B3FAB46488856995D4824C
95F11688BA1683852E5B145B2BDB0842AD0168D71120BB6C121A8F6266A44A49
69BA71F18D833962A106E664E448DBEDBA0F40C66B283E8811A0B740B8E6EF0E
184004B11517634FDE96C346D17E089AD693541638FAF695D47238B472AA2A76
6A829643226A3FCBEB4F4444186E80461A05A367E27258E4B1C96392C02C7CB5
0FBA3007A0F73392C7258E4B0FBB3EBE75C755E69C96392C7258E4B1C96392C7
258E4B1C96392C7258E4B1C96392C7258E4B1C96392C7258E4B1C96392C7258E
4B1C96392C7258E4B1C96392C7258E4B1C96392C7258E4B1C96392C7258E4B1C
96392C7258E4B1C96392C7258E4B1C96392C7258E4B1C96392C7258E4B1C9639
2C7258E4B0870ECBA26C26FCC59681BB896454A7A23FA39BF4D3EE7B7F45E88F
D0DBFF00382DD7065A4C11C23B092A6F41750FAF54905A0DC1C0A82233D72420
D8D7A6FF00D0BD34FB9EDFD17A23F43646F67B5CBD914FCC171CBBB55A8D683F
EC23F2DE81D7BC5007F90FEED225D65E0FFABFA17A69F73DBFA2F444067773D4
42068AE97FD1B66CD9B366CD9B366CD9B366CD9B366CD9B366CD9B366CD9B366
CD9B366CD9B366CD9B366CD9B366CD9B366CD9B366CD9B366CD9B366CD9B366C
D9B36314328043BD36BFC27AF02280BF48339E88FE92B38005D8D465CACB9597
2B2E565CACB95972B2E565CACB95972B2E565CACB95972B2E565CACB95972B2E
565CACB95972B2E565CACB95972B2E565CACB95972B2E565CACB95972B2E565C
ACB95972B2E565CACB95972B2E565CACB95972B2E565CACB95972B2E565CACB9
5972B2E565CACB95972B2E565CACB95972B2E565CACB95972B2E565CACB95972
B2E5649551D97E53D11FD297A0217441902D322CCD5DD235497FD14B162C58B1
62C58B162C58B162C58B162C58B162C58B162C58B162C58B162C58B162C58B16
2C58B162C58B162C58B162C58B162C58B162C58B162C58B526509D4D06A17540
3AA1FA3A97A741F8C896809FE001F8FE8EBA9E1B51557BAC75F83FE4F46FE099
7579F5AE868C36B1FAA8C060360F62AED3B0BD3F8445FF0037FC9E8DFC1B2C4E
4DED721B803014A7BC339740E7E41C1832FC255D0C796605EE570B49801219BE
9D272113CE664EC9BD55D35FC122FF009BFE4F46FE0990A219C46828197563E7
8F76915C96E8C1D02295CE8276AC63DBB37AD6259D72FE7FB0A6616D9AD613A2
4E9D451AC8F7731CDB753BAFF048BFE6FF0093D3A2FC640A544FF111FCFF0047
1D4F0D20289DC61BFC1FF27A023744190281628C5D5D017415FD14B162C58B16
2C58B162C58B162C58B162C58B162C58B162C58B162C58B162C58B162C58B162
C58B162C58B162C58B162C58B162C58B162C58B162C58B526519D0D8EA174547
A89FA1B97A6FE4078C2A001568750B2FFD3F5112C6E2C30532E1A946F1FF00A3
200B534044A0D541645613226A7FE4FBA2B3035AB170D638720E889A9FA10211
E54001D1A0D3D11EB2CBABCBD3FF0022D4F4DFC89822708946D9A9317D23790D
519AE0A386916D9190B88B069C0559DACB64BD0310DD4FB75CB8223619735AA7
3B69DD772162AB3B64B9866CE15D72B404617902D80ECAE47034195514DB4550
00304E64B09582B112EDD2E36AAC408D068D35673A63157E08300832005E363A
A87C91A75A81A2F2106A13FF000210BB509D1732E0A6B5D66770EB7205AD0001
0301641A6FDD74164B44EA151592F614118DA15A0520E8101BC06B57434CBA4A
376B599E3A44142D0D55BBB8628E69B2D41424E6ED539D298FD75A7A6FE41F50
A916D5785ABA2EBB11915BCBA1BE841C81A3994FFF0032A032D177A626B4FD95
D922D65CBDD870540725128C5AAAF75586B7CAD822726407BDBBC726481D8BD2
2CC97A74832A41A01A63ACB37577986102C032515805A1D2E11000100BA08552
DABD2E59E42ED5AAF035747825AAAB83A84362630EC7FE5715420D1A28D5641A
D2C3B454D9B5153128455756DB888ADB6EB041B80819D52A14E186602D1BA875
5625EF3216768A965C9DD8E2253402249768B79CF5811820862803001D0FD75A
7A6FE93AD3D37F49D6869FD25D67FFD9}
end
end
object TabSheet3: TTabSheet
Caption = 'Ferramentas'
ImageIndex = 2
object ED: TEdit
Left = 816
Top = 16
Width = 65
Height = 29
CharCase = ecLowerCase
TabOrder = 0
Text = '*.*'
Visible = False
end
end
end
end
object Panel1: TPanel
Left = 0
Top = 1
Width = 1268
Height = 97
Align = alTop
BevelOuter = bvNone
Color = 10485760
TabOrder = 3
object Panel2: TPanel
Left = 0
Top = 0
Width = 225
Height = 97
Align = alLeft
BevelInner = bvLowered
BevelOuter = bvNone
Caption = 'CEDAP'
Color = clMaroon
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -40
Font.Name = 'Segoe UI Light'
Font.Style = []
ParentFont = False
TabOrder = 0
end
object Panel10: TPanel
Left = 225
Top = 0
Width = 271
Height = 97
Align = alLeft
BevelOuter = bvNone
Color = 10485760
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -19
Font.Name = 'Segoe UI Light'
Font.Style = []
ParentFont = False
TabOrder = 1
end
end
object image: TImageList
Left = 1201
Top = 106
end
end
| 60.331904 | 76 | 0.794049 |
c3ad2fe403aab992a3c7508492e1d412a580934a | 222 | pas | Pascal | ALG-1/lista_03/ex_52/media_n.pas | leommartin/ERE-2-UFPR | b6dfe367507566b4bd7fa10aa15ed7567880a4d2 | [
"MIT"
]
| null | null | null | ALG-1/lista_03/ex_52/media_n.pas | leommartin/ERE-2-UFPR | b6dfe367507566b4bd7fa10aa15ed7567880a4d2 | [
"MIT"
]
| null | null | null | ALG-1/lista_03/ex_52/media_n.pas | leommartin/ERE-2-UFPR | b6dfe367507566b4bd7fa10aa15ed7567880a4d2 | [
"MIT"
]
| null | null | null | program media;
var n,soma,i,q:longint;
begin
read(q);
i:=0;
soma:= 0;
while i<q do
begin
read(n);
soma:= n + soma;
i:=i+1;
end;
writeln(trunc(soma/q));
end.
| 12.333333 | 35 | 0.45045 |
fc47fa6e699d19c9d0143caa6ed63518c74745d6 | 47,143 | dfm | Pascal | Server/Unit1.dfm | ismailnguyen/Tchat | 7d5e96c046e8172890c31a766dd13f4ccc50f4bc | [
"Unlicense"
]
| null | null | null | Server/Unit1.dfm | ismailnguyen/Tchat | 7d5e96c046e8172890c31a766dd13f4ccc50f4bc | [
"Unlicense"
]
| null | null | null | Server/Unit1.dfm | ismailnguyen/Tchat | 7d5e96c046e8172890c31a766dd13f4ccc50f4bc | [
"Unlicense"
]
| null | null | null | object Form1: TForm1
Left = 1225
Top = 128
Width = 177
Height = 75
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
OnClose = FormClose
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Image1: TImage
Left = 0
Top = 0
Width = 169
Height = 41
Picture.Data = {
07544269746D617092510000424D92510000000000003600000028000000A900
00002900000001001800000000005C5100000000000000000000000000000000
00000000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF000000
FF433A3745403D45403D453C39473F3C473F3C413835413B39413B39453C3941
3B394741404B4543413B39433A374039373D3A38413B393D3735403634443D3C
3C3836403634433A373A312E403634403634433A373D3735443D3C403937443D
3C443D3C40393745403D433A37403634453C393D37353D3735443D3C45403D40
393745403D413B39413B39413B39413B393C3836453C39403634413835403634
433A374138354036343D3431403634403634352D2A3C3534453C3945403D4540
3D44403F34302E40393740393741383549403D3D3431473F3C473F3C433A3741
3835433A37473F3C4B4340433A37403634433A374943414943413C3836443D3C
443D3C3D37353D3735443D3C3731304036343D373545403D3D36343F37353D38
374038353C3230453C393D37354741403C38363D3735443D3C45403D433B3840
3937413A38473F3C433A37443D3C49403D433A37433A37403937453C39473F3C
473F3C413B39443D3C49403D413B393C3230433A374039373D3A384039374138
35453C3949403D453C39433A37433A37473F3C3D3A3844403F3C38363C353441
3B393C35344039373A3431473F3C453C39433A373A3431443D3C403937433B39
473F3D463D3A413B393D3431413835413B39403A38403836433D3B453F3D4741
40403937413B3947414044403F403634413B39413B390000FF000000FF413835
443D3C433A37453C39433A37433A373D34314036343D3735413B39403937473F
3C45403D4138353D3A383C38363D3735433A374036343C383645403D40393740
393745403D3A3431403937413B39473F3C4039374943414B43404B4340474140
453C3944403F413B39403937443D3C3D373540393745403D474140413B39443D
3C413B39443D3C413B3945403D3C383645403D403937413B39443D3C433A3740
36343D37354036344138353D3735372E2C403634443D3C443D3C443D3C474140
34302E3C38363D3735403937473F3C3D3431453C39473F3C413B393D3735413B
39443D3C4B43403D37353C353440393747414047414040393745403D45403D40
3937433A37474140403634413B393D3A3849403D433A37433C3A443D3B433A37
40363445403D40393745403D3D3A38433A37473F3C4B4340443D3B4039374038
3644403F4039373D3A384039374138354036343C3230433A374036344036343A
34313A312E3D3431373130352D2A3D34313C32303C32303C35343A312E403634
4036343D3431413835403634453C393D373544403F3D3A383C3534453C39413B
39473F3C3C3230453C39453C39453C39403634473F3C403937443C3A433B393D
36344039373D3735413835403937433C3A433C39463D3B4B4340504845473F3C
4B43404E44414B4340443D3C49403D4B43400000FF000000FF3D3735433A3743
3A37413B39443D3C443D3C3C35344039374138354138353C3836443D3C454140
3D3735403937403937453C39453C3941383540393745403D453C39403937453C
393D3431413835473F3C44403F403634443D3C4036343D3735453C3941383544
3D3C433A373D37354138353C35343C35344138354138353C32304036343D3431
433A374036344036343D3735453C393D3735413835413835433A37413B394039
37403937443D3C3C38363731303D3A3845403D45403D4741404B43403C353440
3937433A37473F3C474140413835473F3C494341443D3C403634473F3C4B4340
4E4441413B39413835453C394E44414F4643453C394B45434B454345403D453C
394B4543403634433A37403937494341413936443F3D47403D48403D443D3C49
4341453C394E4441473F3C453C3949403D4943414A413F443D3B483F3C4B4543
473F3C453C39453C39433A37473F3C453C394B43404B434049403D443D3C453C
39473F3C4138353C3230453C39403937443D3C473F3C413835413835413B3943
3A37453C39403937453C394039374541403D3A383C3534433A373D3A38443D3C
3C3230453C39443D3C413B394138354B4340413B39433B38433B39413A384039
373C35343C38363D37353D3A38403937433B39453D3A45403D413835443D3C45
41404B4340453C39433A37473F3C0000FF000000FF41383544403F413B39433A
37443D3C453C393C3230403937413B39413B39403937473F3C494341453C3941
3B39453C3949403D473F3C453C39453C394B45434B434049403D4B4543473F3C
4B43404E44414E4441453C394E4441473F3C453C39494341433A37473F3C4540
3D3D3A38443D3C403937413B3945403D44403F443D3C413B39413835433A3743
3A374036343C3534433A374036343C3534403634453C39453C394036343D3735
433A373D37353A312E3D3735443D3C45403D443D3C443D3C352D2A3C32304036
343D3735453C393C3230433A3745403D3D37353C3230413835433A3745403D3C
3230352D2A3A3431413B39413B393A3431433A374138353C3534373130403634
352D2A3A34313A343145403D3C3534403937403A383D37353C35344138353C32
30413B393C35343A3431413835453C39433A373C3431403634443D3C3C38363D
37354138354138354036343C3230433A374036343C35343A312E3A3431403634
3D34313C32304036343D37353D37353C38363D3735403937413835413B39443D
3C413835474140453C39474140413835403634433A37413B39473F3C4036344B
4340473F3C473F3C403937473F3C4039374039373F36344037343D37353A312E
3D37354036343C35343D3532403936403735453C393D3735413B39454140453C
39453C39413835473F3C0000FF000000FF413835454140403937443D3C45403D
45403D3A3431403937453C394138353D37353D3735443D3C4036343C32303C35
34403634433A37403634403634443D3C453C39403634433A373A312E4036343D
3431413B393A312E443D3C403634403634433A37403634453C39453C39413835
45403D403634403937473F3C49403D453C3945403D45403D45403D453C39453C
39453C3944403F453C39453C39473F3C4B43404B4340433A37443D3C49403D41
3B39413835453C3949434149403D45403D4741403A312E4039373D3735443D3C
45414040393745403D44403F4036343C3230443D3C443D3C4741403D37353C35
343D373549403D45403D3D3A38473F3C473F3C413835403937473F3C41383541
38353C38364943413F3A38433D3B463F3D4A413F45403D4E444145403D4F4643
453C39443D3C49403D4B434049413F433C3A403A3846403D3D3A383C38363D37
35403937403937403937443D3C4039374039374039373D3A3845403D3D3A3837
3130413B394036343D34313C35343C32303D37354138354138354036343C3534
413B393C3230413835373130342A27372E2C3731303C3230342A274036343D34
31373130372E2C3D34313B31303A34313C34313C34324036343C35343D373540
39373B36343B34313C36343D35323D34313B312E3C3230433A37453C39403937
3D3735443D3C0000FF000000FF49403D4F46434B43404B45434B4340473F3C3C
3230443D3C443D3C49403D413835413B39474140433A373D3735433A37453C39
49403D443D3C45403D4943414B454349403D4E484645403D4B434049403D4940
3D4138354B4340473F3C413B3949403D49403D49434149403D453C3947414047
3F3C413B39453C3949403D473F3C45403D443D3C443D3C413B39403937413B39
44403F413B39403937403937443D3C443D3C3D37353C3836473F3C413B393C35
34433A3747414049403D473F3C473F3C3D3431403634433A37453C3949403D41
3B39473F3C4741404138353D3431473F3C45403D4741404039373D37353D3A38
4541404943413D3A38443D3C45403D41383540363445403D3C35343D36343D37
35473F3C403634403A38403B394039373C3836413B393D37354741404036343C
3836443D3C45403D433D3B413835433936453C393F37353C3534403634403734
3D3735403734413B39413835403937403937413B3945403D4039373C32304840
3D403936403937413C3A403937433D3B453C39463D3B443B39453C394B434045
3C39484340463F3C433A37413B39403A38433A373D343145403D3F3836403937
403A38454140413A38413B39443C3944403F49434145403D4741404B4443463D
3B433D3A46403D48403F45403D413B39473F3C47403F4B434049403D453C3949
403D0000FF000000FF433A37474140433A37473F3C473F3C473F3C3731304039
37443D3C413B393D3A383C3836443D3C3D37353A3431413B39433A37443D3C40
393741383545403D443D3C3D3735413B39403937443D3C40393745403D403634
49403D433A373C3534413835433A37453C39453C39413B39443D3C413B39413B
39453C39453C39473F3C473F3C453C39413B3945403D413B3940393747414040
3937413B3940393745403D45403D433A37413B3949403D433A37403634413835
473F3C44403F413B39443D3C3731303D3431433A3741383545403D3D37354036
34443D3C3D34313A312E433A37443D3C443D3C4036344036343C35344741404B
43403D3735433A37413835403634403634443D3C403634433C3A403937474140
403937413B39403A38433A373C35344039374039374741404039373D3A384540
3D474140413B393F3735433A37443D3A4036343D36344036343D37353D373540
37344339363D37354036343D3735413B39443F3D413B393C3431463D3B3D3431
403937413B39403937403937433D3B433B38433B38403A3849403D453D3A473F
3C413835413835403937403C3A413B393C3431443D3B4038354036343D353245
3F3D3C35324036343C34313F35323D37353A312E3731304138353C35343C3230
403835413A384038353F36343F3634433D3B443D3C453C393D3A38413B390000
FF000000FF4B43404E484649403D4943414B43404B43404138354B45434B4543
4B434045403D45403D49403D49403D433A374B434049403D473F3C403937413B
3949434149403D413B39473F3C403937443D3C443D3C4039373C383649434144
403F3C3836413835433A37453C39453C39443D3C433A37433A37413835413835
413835453C39453C39433A37453C39433A373C35343D3735443D3C3D34313C35
343C3534433A37413B393731303A312E3C32303C3230342A273C32303D343141
38353A312E3D3431312926352D2A3C32303C32304138353A312E3A312E413B39
3731303A312E403634413835443D3C4138353D37353D37354741404E44413D37
35443D3C443D3C443D3C3D3A3845403D413835433D3B433C3A463F3D413A3743
3D3B403B39413B393D37354039374039374741403D37353D3A3845403D45403D
433D3B3F37353F3735433C3A3C36343D3534403835413C3A3F3634403735433B
38403936403734413835413A37433D3C433B383F3634473D3B413A37413B3944
3D3C45403D413D3B48434146403D453F3D453D3C4C434048403D46403D443D3C
443F3D413B39463F3D453D3A443B38443D3B433C393F3734403A38473D3B4038
364038353D34314037343D37354036343C3836453C394036343D343141383545
3F3C3D36344038363F3735403836413835403634403634453C390000FF000000
FF473F3C4B4543433A37473F3C473F3C473F3C3D3431494341473F3C433A3740
3937413835433A37443D3C3C3230443D3C443D3C443D3C403937413B3944403F
44403F403937453C39403937413B3949403D453C39413B394E44414E4441443D
3C433A3745403D473F3C473F3C474140453C39453C39433A37453C39453C3945
414045403D443D3C443D3C413B394036343C353445403D4036343D37353C3230
413835443D3C3A34313A34314036344036343C32303D3735443D3C44403F413B
39443D3C3C3230413835453C3949403D474140453C39453C39524946413B3944
3D3C4B45434E48464B45434B4340453C39453C394E4441524B4949403D4B4543
4B4340494341473F3C45403D3D3A38443F3D413A38443D3B3F3836433F3D4039
37413B394036344138354138354741403D37354039374741404F46434A413F43
3936433B3845403F403734403835403835473F3D3F3836453D3B453C393F3836
433936473D3B453C39453D3A4139363B34323F38363C353440383546403D4139
363D363446403F3F38363F3836403836433A37433A384139363F3836433C3A3D
3735433D3B413A38403835443D3B403836403734443F3D433C3A403A383D3735
3C35343D37353C35343D37353D3735453C393D3735403634443C39443D3C3F38
36443D3C403937433A37403937413B39433A37473F3C0000FF000000FF3D3735
44403F413B39443D3C403937433A37352D2A433A37433A374039373D37353D37
354138354138353A3431443D3C413835473F3C403937403937443D3C44403F3D
3A38413B39403937413B39443D3C4138353D373547414045403D4036343D3735
433A37413835433A37453C393D37354138353D37353D3431413835413B394138
353D3431453C3941383541383540363445403D40363440363440363444403F44
403F403937433A37494341453C39413B39473F3C4B43404943414B43404B4543
453C39473F3C4B43404E48464F464349403D474140534C4B49403D45403D4B45
434E48464B4543473F3C413B39443D3C4741404B4340413835474140473F3C47
3F3C433A3745403D40393748434048403D473F3C433A3747403F413835413B39
3D37353D37353C35344541404138354138354741404B434045403D433A37453C
394B44434039373D3A38433A374440403D3735433D3B403937403634403A3843
3A373D3735413B39403A383C32303D3734403634443B38484340443B38413835
4943413D3A38413835433A37443B38453D3A433B38433A3746403F413B394640
3F443D3B433D3B45403D3F37353D343146403F433A37433A374036343D36343C
35343C38363D37353C3534453C393D373541383545403D474140453C39484340
473F3C413835473F3C4B434049403D4B45430000FF000000FF3C383645414045
3C39443D3C443D3C453C393C3534413B394039374039373D3A383D3735403937
413B393C3230433A373D3735433A37403634413835443D3C453C393D3735413B
393D3735413B39433A3741383540363447414045403D413B39403937443D3C44
3D3C45403D443D3C403937413B39403937453C39473F3C494341473F3C453C39
494341453C39453C39413B3944403F443D3C3D373541383545403D443D3C3D37
353C35344138354036343C3534413835413835413B39403634453C393D34313D
3431433A37443D3C45403D3D37353D3735443D3C3D3735403634453C3944403F
413B394039373D37353C383645403D49403D3D373545403D45403D45403D443D
3C44403F3D3A38473F3C45403D3D37353D343145403D403634433A373D34313C
35343D343145403D403937403937443D3C44403F45403D413B39413B39494341
403937413835443D3C44403F403937413B393C38363D3735413B39473F3C413B
39473F3C473F3C403634443D3C443D3C4B43404E4441433A374036344946453C
38363D3431433A37413835413835413835413835453C393C3534413835413835
413835433A373D34313A312E45403D413B394039373C38363D3A384036343D3A
38403937413835473F3C413835413835473F3C474140433A37474140453C3941
3B39473F3C49403D473F3C4943410000FF000000FF443D3C49403D473F3C473F
3C49434149403D403937433A37433A37433A373D3A383C353445403D443D3C3C
3534443D3C3C3836453C39403634403937443D3C474140403634413B393C3836
413835443D3C40393740363445403D49403D453C39413835473F3C49403D4741
40473F3C443D3C49403D49403D4E444149403D4F46434B434049403D4F464347
3F3C49403D433A374B4543473F3C413835453C39473F3C4741403D3A383D3A38
453C39453C39403937453C39473F3C443D3C413B3945403D3D37353C38364540
3D45403D474140413835433A37494341413B39413B3949403D4B4340473F3C47
3F3C473F3C413B394741404E4441403937473F3C45403D45403D433A37494341
40363449403D453C394039374039374541403D3A3845403D3D3A383D3A383D37
35433A373D373540393745403D44403F443D3C41383540393744403F3C38363D
3735433A3745403D3C35344138354036343C3836413B3945403D3C3836433A37
433A373A34313C38363D3735473F3C4E48464138353A312E4B43403A312E352D
2A3C32303A312E3A312E3C32303D34314138353C3534403634433A37433A3743
3A373D34313C323045403D453C39433A373D37353C35343C3534403937403937
3D373549403D433A37453C394B4340494341453C3949403D453C39403634433A
37453C3940393745403D0000FF000000FF45403D4B45434B45434B45434F4947
4E4846443D3C4741404B45434741404741404741404B47464B4543453C394B43
40473F3C4E4846473F3C49403D4B45434F4643473F3C49403D443D3C453C3949
4341453C39433A3745403D49403D433A37433A3745403D433A37443D3C433A37
403634413B3940393744403F3D3A38454140403937403937474140413B39413B
39403937454140413B3940393745403D443D3C4943413D3A383C3836413B3941
38353D3735433A37413B39443D3C403937443D3C3D34313C3230433A37433A37
433A373A312E3A3431403937373130372E2C403634413B39413835433A374138
353D3431453C39473F3C3D3735453C39453C39413B393D3735453C393D343140
3634413835413835403634443D3C3D3735453C39403634403634403634413B39
40393740393745403D45403D443D3C40393740393744403F4138353D34314540
3D45403D3D37354036343D37353D3735403634443D3C403937413835453C3940
3634413B39403937453C394E48464039373C35344F49473D3A383C3534443D3C
403937413B39413B39433A3744403F413B39443D3C413B3945403D413B393D37
35373130474140494341473F3C4039373D37353D343140393740393740363447
3F3C403634413835473F3C474140433A3748403D473F3C403734433A37433A37
4039374943410000FF000000FF4741404E44414943414741404E48464B454345
3C3949403D49403D453C39413B3940363444403F413B393D3431433A373C3534
443D3C3D3735403634433A37443D3C3D34314036343A3431373130433A374036
343A312E4036344036343C32303A34314036343D3431413835453C3940363443
3A373C3836413B394039374541404039373D373544403F443D3C413B39413B39
474140413B39403937473F3C413B394B4340403937413835433A374039373D3A
38443D3C413B39433A37403937443D3C4036343D3431453C3944403F45403D3C
3534413B3945403D3C38363D3735443D3C45403D453C39413835413B39413835
443D3C494341413835453C3945403D443D3C453C3949403D413835403937443B
38453C3941383545414041383545403D403634413835403634433A37413B3947
3F3C49403D494341474140433A37433A37474140433A37403634413B39433D3B
3D37353F37353D37353D3735403937443D3C3C38364037344037343D34314037
343D3735413A384A4341403A383C35344C46443D39373B3431433D3B403A3843
3C3A413B39403836443D3C403A38433A37433A37443B38433A373D37353C3230
443F3C463D3A433D3B3C38363D34313A312E3D37353D37353C3534433A374036
34403634433A37443F3D3D36344036344138353C34314138353D37353C353444
3D3C0000FF000000FF403937453C3941383541383544403F45403D3D37353C38
36413835433A374039373C353445403D413B39403937413B393D3A3847414043
3A37473F3C4943414E4441473F3C49403D453C39453C3945403D433A37413835
45414047414040393740393749403D413835473F3C45403D3D3A38443D3C4039
37443D3C3D373549434140393740393744403F433A37433A3740363445403D41
38353C353444403F413B394541403D3A383D3A38413B393D37353D3735433A37
3D3735413B39403937443D3C3C38363C3534453C3945403D443D3C3D3431433A
3744403F3D3A383D3A38443D3C45403D453C39433A37453C39413835453C394B
43403D3735413B39433A37433A37413B3945403D3D3735403836433936453D3C
3F383545403F403A38413B393D37353D37353D37354036343C3836443D3C4540
3D49403D45403D403937433936463D3B403A383F3634433A37433A3740393740
3B38433A37433D3B453D3A46403F403A38463D3C453D3A3F3937443C39403A38
443D3B4C46443F38363D36344A44433F3A383D3431403835403A38413A37413A
373F3836433936403937403836403937433C394039373D38363C3431433D3B47
4140443D3C3F38364039373D37353D3A383D3A383D3735413B393D37353D3735
433C3A484140403A38433A37463D3C443C394138353C35343C35344039370000
FF000000FF413835443D3C403937433A3749434149403D433A37443D3C49403D
49403D433A37403634453C39453C39413B39453C39403937474140413B39453C
394B4340494341473F3C49403D433A37453C3945403D453C393D3A3845403D49
403D433A3740393745403D413835433A3749403D403937473F3C413835443D3C
3D3735494341403937443D3C47414045403D413B39413B3944403F4138354036
34453C3941383545403D4036343C32303D34313D37353C35344138353D373541
38354036344138353A34313C3230433A37413B394138353C3230403634433A37
4036343D3735413B3945403D443D3C443D3C45403D433A37473F3C4F46434138
35443D3C413B3945403D45403D45403D403937403735433B38473F3C40383548
403F453D3A443F3D4039373C38363D37354036343C3534433A37433A3745403D
453C393D3431413B39433A373F37343F35324138354037344037344039364138
353D34313C3230413A373A34324039364036343B34313F35323D34323D353443
3B393B312E3C3230433B383F37343C34313D3431443D3A4139374039373A312E
3B312E3A312E3A32303932313D34313D35323A312E352D2A3D3431453D3C4036
343B32303A313037302D3B312E3A34313A312E3D34313A312E3C3431433B3847
403D3F37343D3634443F3D433D3B433A373C38364039374741400000FF000000
FF49403D473F3C4138354039374541404039373D37353C3836413B39443D3C41
3B393D3431433A37473F3C413835413B39413835494341453C39453C3949403D
49403D44403F473F3C413835433A3749403D453C394039374E44414B4340453C
39453C394B4340433A37453C394541403D37354039374138354039373C35344B
4340403634413835474140433A3740363440393745403D4039373C3534453C39
3D373544403F4138354036344036343D3735403634443D3C3D3735413B394039
37443D3C3D3A383D373545403D45403D45403D4036344138354036344036343C
3230433A3745403D413835453C39433A37403634453C3949403D3D3735413B39
3D373544403F453C39474140453C39403937413A384A43413F3937463F3C433A
37463D3C413835403937413B39433A3740393745403D413B3945403D443D3C3C
3836443D3B433A383F36343D36344036343C3230403734403835403734393231
3C32304038353D3431433D3B4036343D3431433D3B3D37353F3835463F3D3F3B
39413835443C39453D3B4139363D3A3849434146403F45403D4039374038363D
3431403937403937413835473F3D4039373F3836403937494443413B39413936
403937403634433936433A37403937473F3C403937403A38463D3A49403D4037
343F3532463D3A443D3C473F3C453C394B43404F46430000FF000000FF494341
4B434049403D4741404F49474E484647414044403F4B45434E48464946454741
404B45434B47464943414B4340453C39524946473F3C473F3C4E44414E44414B
45434B434049403D453C394B454349403D433A374F4643474140433A37413835
453C393D3A38433A3744403F3D3735403634403937413B393D37354943414039
37443D3C454140473F3C3D37354039374541404039373C3534443D3C40393744
403F4039374039373C38363C3836413835453C393D3735413B39413B39403937
4036343C353445403D45403D413B393C32304036343D34313A3431372E2C3C32
30403937403634433A37433A37403634433A3745403D3C3534433A3740363443
3A37403937443D3C403634433A37473F3C4F4744433B3948403D433B38453C39
3D34313D3735403634403634403937443D3C413B3945403D443D3C3F37354640
3D47403D433B38433A37453C39433A384A413F4A4443484340473D3B413B3947
3F3C413B39484340453C394039374A413F443D3C443D3C4E444145403D443F3D
453F3D4A413F48403D443D3C4C44414B434047403F453C394138353C32314039
373D37353D3A38413B394039374039374138354B4543433B38433A374039373F
38364339364039373D3A38433A37413B394039374339364A413F403734413835
4B4340473F3C433A37403937433A374741400000FF000000FF3D34313D34313D
37353D3735443D3C4036343D3735403634443D3C413835453C393D3735443D3C
45403D403937413B39433A37524946443D3C443D3C4B45434E4441474140453C
39433A37433A37473F3C4138353D373547414044403F4039374036344036343C
3534433A374741403C35344036343D37353D3431372E2C453C393A312E403634
4039374036343C35343C3534433A373C35343A312E4138353D3735453C394036
343C3230413835403634403937473F3C403937433A37413B39443D3C40393740
393747414044403F44403F403634433A37413B393C38363D3431413835453C39
413835443D3C443D3C413835453C3945403D3D37354138353D37354138354036
34433A37403634453C39433A374C43403F3835433B393F3937433A374036343D
37353D37354138353D3735433A3749403D49403D443D3C3D3A38443F3D433C3A
3D3937403937403937403634453C3945403D44403F413B393D3735453C39413B
39494341453C39433A3745403D3C3836403937413B394039373D3A3840393744
3D3C413B393D3A3849434149403D49434140393740393735302E3D37353D3431
3C35343D37354036343C32303C3534473F3C4036344036343F36343D3734433B
39413835413B39453C39413B39413B38433936483F3C3D34313D343141383540
363449403D443D3C4B43404E44410000FF000000FF4036344138354036343C35
34443D3C3C32303A34313C3230413835403634433A373A312E453C39433A373D
373541383541383549403D4039373D3A384741404E44414B4340453C39453C39
473F3C494341473F3C45403D534A474E48464B4340473F3C4B4340453C394E44
414F49474741404B4340473F3C4B434045403D524946453C3949403D4B434047
3F3C403937413835473F3C473F3C403634433A37433A37473F3C453C39403634
443D3C453C39433A3745403D3D3A3840393740393745403D4039374036344940
3D494341494341413835453C39453C39443D3C403937413B3945403D45403D47
414044403F3D3735453C394741404036344039373C3836413B39433A3745403D
433A373D3735403937494340403937443D3B413A38453F3D3D37354036343D34
314036343C3431413835413835474140433A373C35344139364139373D38363D
36344039373A3431413835453C39433A374138353C3534413835373130413835
3A34313A34314036343D34313C32304138354036344036344036343D37354540
3D4138354E4441494341494341453C39403937403634473F3C443D3C443D3C49
403D45403D49403D474140534C4B4B4543484340463F3C413A38413835403734
3A34313D34313C35343D3634413835474140443D3C433A3749403D453C393D37
353D3735413B39453C390000FF000000FF403937413B394138353D3735443D3C
3D34313A34313D3431413835403634433A373A312E433A37443D3C3D37354138
35403634413B393A34313A3431413835453C39433A373D34313D34313D343141
38353C32303A312E45403D413B394036343D37353D37353C3534453C39473F3C
3C35343D34313A34313D34313C323045403D403634433A374138354138353D37
353D3735413835443D3C3A3431403937403937433A374039373A34313D373540
3937443D3C44403F3D3A38413B3940393745403D40393741383549403D44403F
45403D403937453C39443D3C3D3A383D3A38413835443D3C443D3C4741404440
3F40393744403F4741403D3735443D3C3D3735413B3945403D474140473F3C43
3A37433A374B4340443B38473F3C453D3C494341403634433A37413B39473F3C
403734473F3C49403D4B45434B4340413B39463D3A463D3B413A37403937413B
393D3534473F3C484340473F3C433A37413835443D3C3D3A38433D3C3D37353D
3735443F3D433A37403937453D3A403A38403A38433A37443D3C49403D433A37
4E4441494341494341433A374036343C3230413B39403937403634453C394138
35453C394039374B4340473F3C413B394039373F3A38403937413B3940393743
3A3741383540393740383544403D403A383D3735453C39413835403937413835
47414049403D0000FF000000FF3C32303D34313D34313A312E4036343A312E37
3130372E2C3C32303A312E403634312926403634413835352D2A3A312E3A3431
413835373130373130403937443D3C433A373D34313C32303D34314039373C35
343C3230443D3C45403D4036344039374036343D3735413835473F3C3C35343D
37353C35344039373C3836474140403634443D3C453C39413835403634403634
413835433A373C32303D37353D3735433A374138353C35343D3735403937413B
3945403D403937403937443D3C413B393D3A383D373545403D49403D49434145
3C3949403D473F3C413B39443D3C453C394B45434B4543524946494341453C39
494341494341403937473F3C413835473F3C49403D4E44414741403F3B393F3A
3845403F403A38433C39403836453F3D403634413B39413B39443C393C353440
393740393745403D413B393C3836403A384138353B35343B32303D3431352C29
3D3431433C3A4138353D37353F35324339363D36344037343F37343F35324038
364038363D3534443B383D35343D34313F38363D3735443D3C4036344B434045
3C39453C394138354036343C35344039373C38363D37354039373D3735413B39
3C3836474140453C39413835413A383D37353F35324036343D34314036343D37
353D34313D3634453D3C413A3840383649403D49403D403634403634453C3945
3C390000FF000000FF403634413B39443D3C3D373545403D4039373D37353C35
34443D3C413B39443D3C373130413B39443D3C3D343145403D3D373544403F3D
3A3841383549403D4B434049403D413835433A37473F3C45403D403937413835
47414049403D4039373D37353D3735403937443D3C4741404036344036344039
37413B393D3A3844403F3C3836443D3C453C394138354036343D37353D373540
36343C32303D37354036344138353D37353C32303D3735403634403937474140
4036343D3735433A374036343D37354036344741404741404541404039374540
3D453C39403937433A37413B394943414741404F464347414040393749403D47
4140413B39473F3C413835433A37473F3C49434144403F3C34313B3230403937
3C32303C34313F35324339363D34313C32303C32303D3431352E2B3A34313A34
31443D3C4036343D34313D34314037343D34313C34314036343A343140393641
3B39413B39443F3D41393749403D443D3B463D3A433B38433B38443B38473F3C
433C3A4C4441433B38403836463D3B443D3C474140433A374E44414943414940
3D473F3C403937403634443D3C453C39453C39473F3C403937433A3741383549
434145403D403937433C39433C39433B38463D3B473F3C49403D443D3C473F3C
463D3B4A4340433C3A403937443D3C443D3C49403D45403D4E48464B45430000
FF000000FF413B39473F3C49403D453C39494341473F3C433A37403634473F3C
45403D45403D3C3534413B39454140413835473F3C433A3745403D403937433A
374B434049403D4B43403D3A38413B3945403D45403D4138353D3431413B3945
403D413835403634403634413B39413B39494341413B393D37353C3836413835
3D3A384541403D3735443D3C45403D413B394039374039374039374039373D37
353C38363D37354039373D37353D34313D37353C3534403634443D3C4036343A
34313D34313C35343C3230372E2C4036344036344138353731303D34313A312E
352D2A3A312E3A312E4138353C3230453C39443D3C3C3534403634443D3C3D37
35433A3740363440363441383545403D443D3C4339363F3A38443F3D40393744
3B38413936473F3C3D37353D3735403937433A373C32303C38363D373545403D
403937403937433C3A403A38403937433A37453C39443B3848403D473D3B453C
394A413F443D3B484140453F3D403A38433B39403937413B39433D3B413A384A
4340443B38403835433C3A41383544403F3D3A38494341474140443D3C473F3C
4039373A34313C38363D37353D37354138353C35344036343A3431473F3C4138
353C35344038353F38363F37344138354036344036343D34313D37353D373543
3D3B403A383D3431413835413835433A3741383549403D473F3C0000FF000000
FF3D3A38473F3C49403D403937473F3C403937453C393D3431473F3C453C3945
3C39403634453C3949403D403634453C39433A3744403F413B39413B39494341
4741404B45433D3A3845403D45403D443D3C4138353D343145403D45403D4039
374138353D373540393740393745403D3C38363D37353C38363C383640363445
403D3D3735443D3C45403D403937403937403937433A37453C39403937403937
413835453C394039373D3431413835403937443D3C45403D4039373C3836413B
393D373541383540363444403F45414045403D3D37354039374039374036343D
37353D3431443D3C41383545403D45403D3D3735413835443D3C3D3431433A37
3C3230413835413B39474140453C39433C39413936463D3B403634433A374036
34443D3C3D3735403937443D3C433A37403634433A37413B39474140433A3745
3C3949403D433A37433A37403937443B384339364339363D3431433936443F3D
3D3937484340413A384138354138353D34314036343D34313C3230443D3B4039
363C353240383640373445403D4039374B434049403D45403D45403D3D3A3837
31304039373C38363D3735433A373D3735413B393C383649403D453C393C3534
4036343F3634403937403A384036344039373A34313D37353D37354339364037
343D34313C3534413835413B393C353445403D45403D0000FF000000FF3D3735
413835453C393C32304138353A34313C3230352D2A4036343D3431403634372E
2C403634433A37403634433A3740393745403D433A374138354B43404943414E
4846413B39473F3C4943414B4340473F3C433A374E48465249464943414B4543
4741404B45434B434052494649403D4B4340473F3C49403D473F3C4E4441473F
3C4943414B4543443D3C413B39413B39433A37473F3C443D3C40393740393747
3F3C413B394036343D3A383D3A38453C3949403D453C39413B39413835403937
443D3C3D373545403D44403F45403D403937413835433A37413835403937413B
39454140413B394E48464B45433C3836413B3944403F40393745403D40363440
3937473F3C49403D44403F433D3C403936433B39403634443D3C3D3735433A37
4036343D3735453C39433A373C35344039373D3A3845403D413835433A37413B
394138353C383640393741383540393745403D3C3534433A37473F3C443D3C52
49464B4340473F3C4B434045403D453C394B434045403D5048463B323039302D
4039373F3634443B383C3534474140474140443D3C45403D40393735302E4138
35413835453C39473F3C3D3A38453C394039374B434049403D433A37433A3743
3936413B39433A384039374138353D3431413B3940393746403D433D3C403937
433A37473F3C433A373C3230443D3C45403D0000FF000000FF41383549403D45
3C39403937443D3C40393741383540363449403D443D3C473F3C403937473F3C
473F3C413B3949403D4B4340473F3C473F3C473F3C4F46434943414F49474039
37433A3745403D443D3C3C383640393745403D4741404039374039373D373541
383540393749403D403634433A374039373D373540393745403D3D3A3845403D
45403D403937403937413835453C39453C39413B39413B39453C3949403D473F
3C433A37473F3C45403D4E444152494649403D49403D443D3C453C3949403D43
3A37473F3C45403D453C39403937413B39413B39403634413B3940363445403D
4138354E48464B45433C3836413B3945403D3D3A38453C394138354138354940
3D4943414741404A4140433A37453C39403937473F3C443D3C453C3941383540
393744403F473F3C403634433A3740393749403D403937453C39453C39413B39
3D3A383D3735403937443D3C45403D3C3534413B39433A373D373545403D443D
3C403937433A374036343C35343D37353C383645403D4039373C3532413C3A3D
3735463D3C403937474140474140453C394B4340433A373C3230413B39403937
453C39473F3C413835473F3C433A3749403D49403D453C39463D3B4039373D36
344039363A34313C3230352D2A403634403634433B384039373C34323C353440
3634453C393C323045403D45403D0000FF000000FF403937443D3C433A373C35
34433A373D37353D3735352D2A4138354138354138353C35343D37354036343D
3735443D3C413B39413B39413B39403634443D3C453C394E44413C3836403937
45403D4138354036343D373545403D474140413835413B394039374138354039
374B45433D3A38413B39413B393D37353D3735474140403634453C39453C393C
38364036343D34314036344138353D37353D34313D37353D34313C3534342A27
3D37353A3431403634443D3C4138354138353C35343D3735433A373D34314440
3F443D3C453C39433A37473F3C473F3C403634453C39443D3C4B454349403D54
4F4C534A47473F3C4B43404E4846443D3C4E444144403F4943414E48464F4643
4E48464E4441473F3C473F3C41383549403D413835433A37413835413B394940
3D494341403634433A37403937453C39413B39473F3C49403D4138354138353D
37353D3735413B3945403D3A3431433A37453C39433A374B4340473F3C433A37
49403D413B39403634403A3840393744403F453D3A403937433B38413835473F
3C413B394B43404B4340473F3C49403D453C393D3431403937433A37473F3C45
3C39403937473F3C413B3945414045403D3D3735413835403836403937433A38
4037344039373C3534403937413A38433D3B3F39373831303D3634413835413B
393A3431474140443D3C0000FF000000FF3D34314138354138353D3735433A37
403634413835352D2A413835453C394138353C3836403937413835403634453C
39433A37433A37413835433A3745403D443D3C4B454340363441383544403F40
39374039373C353444403F45403D433A37433A37433A37413B39433A374F4947
413B39453C39473F3C433A37433A374B4340413835453C39453C39403937433A
37433A3749403D49403D433A37403937403937413B393C3836372E2C3C35343C
3534403634453C393D3431433A373C35344036344036343D3431453C39403937
413B393C38364039374039373C32303D34313D343145403D4039374946454741
403D3735413835454140403937453C3941383540393744403F45403D45403D45
403D3D3A384039373D3735413B393D37354138354036343D3735453C3945403D
3C32304138353D37354036343C35344036344138353731303C35343C32303D35
34403634413835372E2C4138354139363F383645403D453D3A43393645403D40
3A38413936433C3A433D3B47403D443D3B413A38433B383F3A38413B393C3836
45403D474140403937413B39413B393A312E4036343C3230413835433A374036
34443D3C3D373545403D443D3C403937443D3C433936433936413A3741383541
38353D3735403937433A3745403F443D3C3D36343F3A38443D3C473F3C3C3230
4F4643473F3C0000FF000000FF413835453C39473F3C433A37473F3C453C3949
403D41383549403D4B454349403D45403D4943414943414741404B4746494341
4B43404B43404943414E44414B4340534C4B49403D4B43404B45434B4340453C
39413B394E44414F4643453C39433A37403937453C39453C394E44413D3A3844
3D3C4039373C38363D373545403D3D3735453C39473F3C403937433A37403634
453C39453C39453C39413835433A37453C393D3A3835302E3D3A38403937413B
3945403D40393745403D3D37354039374138353D3735443D3C433A37413B393D
37353D37353C38363D3735413B393A34314541404138354B454345403D403634
433A3745403D4036344036343D37353C383645403D45414045403D443B384039
37403937403634443D3B3D3A3845403D40393740393745403D443D3C3A343141
3B39433A3749403D413B39473F3C49403D413B39413835403734403B39413A38
413B393C3634403836433A37433A3746403D443C39403937473F3D413C3A433B
38453D3B40393746403D463D3B443B38463D3A473F3C49403D433A3747414047
4140433A37443D3C3C38363A34314039373D373545403D403937403634443D3C
3D3735453C39443D3C403634413B393D37354037343D35343C36343A312E3C32
303C3534403634433A37443D3A403734403936443F3D453C39352D2A4B434043
3A370000FF000000FF3C3534413835433A373D3735433A373A34313D3431352D
2A3D37354138353C35343C35344036343C35343C35344138354036344138353C
3534453C39443D3C4138354943413A34313D34314036343D34313731303C3230
413B39443D3C4138354138353C3836403634403634473F3C4036344138354138
353D37353C383645403D403634413835443D3C3D37354138353C3230433A3743
3A37433A374036343D37353D3431373130352D2A3C3534403634403634433A37
40393745403D3D37353D3735403937403634443D3C403937433A374036344138
35413835403634433A3740363449403D473F3C4F49474E4441453C3949403D47
4140403937443D3C4039373D3A38443D3C44403F45403D433B39403A38433D3B
403836433C3A3D3634433A373D3735403937454140413B393A3431443D3C443D
3C443D3C40393740393744403F3F3A38433936413835443C39433C3A433C3A43
3D3A413B39463F3D46403F49403D47403D443D3A484341474140453D3B4C4441
443C3948414047403D453C39453F3D413B39433A3741393644403F48403D433A
37433A374138354037343F3532403734443F3D403A383D3937433F3D40383644
3D3B443D3C3F3836443D3B4036343D37353D39373F39373D37353C35343D3735
403634403634433D3B3C3431403634413C3A413835372E2C494645443D3C0000
FF000000FF413B3949403D4B4340413B39494341453C39433A373D3431413835
443D3C413B39403937473F3C433A37433A37453C39433A37433A374138354541
40454140413B394E4A483D37353D3735443D3C413B3940393741383545403D44
403F45403D413B39413835453C39473F3C4E4441413B39403937403937403937
3D3A3844403F403937443D3C413B393D3735413B393C3534453C39473F3C4540
3D403937403937413B393C35343A312E3D37354138353D3431453C393D343141
38353D34313D37353C35343D3431433A37403634433A373A3431403634403634
3C32303C35343A312E413835403634473F3C443D3C403634403634443D3C4036
34433A374036343D3735433A37453C39433A373D36343D3735403C3A3D363443
3C3A3D3836453C393C323040393744403F413B393D3634433F3D453C3948403D
453C39413835473F3C403937403937433936443D3B413A38433B39433D3B3F38
36433C39433D3C45403D453C39433936463F3C433F3D3D393745403D3F383643
3C3A413B39413A38413B39413B39453C3A443C394741404A4340463D3B443C39
433A3741393640373441393646403F453D3B413B38463F3D413936433A38443B
383F3836463D3B4138354039374139363F38363D34313D343140393740393743
3A3745403D3F3634403734413A37413835372E2C4B43404036340000FF000000
FF433A374B43404B4340443D3C4F464349403D49403D433A37473F3C4B434047
3F3C453C39473F3C433A37433A37433A37413835453C39403937454140454140
45403D4F4947413835413835453C39433A374039373D3735433A37433A37443D
3C413B39403937413B394039374F4643413835433A3749403D41383540393747
414040393749403D473F3C433A37453C39403634433A37443D3C45403D403937
413B394039374039373D3735403634433A37413B3945403D4138354138353D34
313C35343731303A312E3D34313C35343C323031292635302E373130352D2A3C
3534352D2A3D343140363445403D443D3C4036343D37354138353D3735413835
3D3735403634443D3C443D3C443D3C413B394843404A4340443D3C464140413D
3B453F3D3D373545403D4B4340443D3C3F3937453D3C45403D45403D443D3C3D
3735413B39433936453C39433B3846403D433A37403B38413D3C403734433A37
443D3B463D3B433A37403734443C39433A383D3532413B393F35324038364037
344138354038363D34323C35343F39374039373F3A383C34313F38363F383541
3A383D3431403937453D3B433A38403A38443D3B433D3B433D3C443D3C3D3836
443F3D3F36343D38364037343D37353B312E3A312E3D37354036344138354540
3D3C35344036343D3735433A373A312E4B4543433A370000FF000000FF443D3C
4B4543473F3C41383544403F403937443D3C3731303D3735413B39413B394039
37413B393D37353D37354036343D3735413B3940393745403D45403D443D3C4F
49473D3A38443D3C413B394039373D3A38403937453C39453C39473F3C473F3C
433A37473F3C473F3C524946473F3C473F3C4B434047414045403D4F49474540
3D4E484649464549403D4E4846433A374B434049434149434149403D4B434047
3F3C49403D433A37453C3949403D49403D473F3C413835443D3C403937433A37
413835403937413B393D3735413B393A34314039373C38363D34314039373D34
31453C39473F3C49403D474140433A37413835473F3C433A3745403D3D37353D
3A3845403D45403D443D3C3D3431443D3A433D3C413936443B38403A38443D3C
40363445403D45403D413B393F3735433D3B433C3A433D3B413B39403634433A
373C36343F3836403836433B384339364039363D3937403835433C3A463F3C48
413F473F3C463D3A474140443C3A3F3836433D3C413937403C3A403B38413A37
453F3C403835413A3844403D403C3A3F3B393F3634433936403836433D3B3D34
313D36343F39373D37353C34313F3634403734453D3B453C393D3634453F3D3D
34313B34313C35343D37353A312E3C32303D37353D3431413835453C393C3230
413835403634433A37372E2C4B4340433A370000FF000000FF3C353441383541
38353C3534453C393C3534413835352D2A3D3735413B393D3735403937413B39
4036343C3534403634403634403937403937443D3C453C39453C39524B494039
37473F3C433A373D3A383D3A38403634413B39413B3945403D45403D3D3A383D
37354036344B4340403634413835433A373C38363D3735433A373C3534413835
433A373D3735453C39342A27413835433A37433A373C32304036343D37354138
353A312E3C3534403634413835433A3740393745403D403937433A37453C3940
3937453C39473F3C4B43404138354E444145403D433A37473F3C453C394E4441
4B4340534A474F49474B454349403D4E44414B43404E4441473F3C413B394940
3D494341453C39403937463F3D494140463D3C463F3D413B38453C3940363449
403D4B434049403D413B39443B38443B38413B39413B393C3836443D3C3D3A38
413835413836433C39453D3B443C393D3431413A38473F3C433A37454040473F
3C413B3946403F403C3A3D36344138354039374037344339363F3B3945403D43
3A37443B3847403F433C3A453D3C3D3431433A3741383546403F3D3431403937
413936433A37413835453C39473F3C4C4340473F3C3D3A3845403D443D3C3D37
354036344138353C32303C32303D3735403937413B3945403D3C353440393741
383545403D3C32304F494749403D0000FF000000FF443D3C4B4340473F3C4039
3745403D4039374039373A312E403937473F3C413835403937413B3940393741
3835403937413835403937403937413835453C394138354F4947413B39413B39
403937403937413B3941383549403D473F3C4B4340494341453C3949403D473F
3C4F4947473F3C4B4340494645473F3C473F3C4E4441473F3C4B454349403D44
3D3C4943413C3230474140473F3C44403F403937403937403937413B39403634
403937413B393D3735433A37403634433A373D37354036343C35343C32304138
35403634433A373C32304138353D3735372E2C3D37353D3431413835413B3947
4140474140403634403634403634403634433A373D37353D3431433A37453C39
453C393D38373D35343D37353F36344037343C34313D34313A312E403634443D
3C4138353C32303C35343C32304036343C32303C35344036343C35343D37353D
34313F3836433936413835342B283A34313D36343D3634413B39453F3D403634
4138353B34313D34313D34313C3534403634413B393C383644403F4036344039
3744403F3D37354036343A312E4036344036344741403A34313D37353D373540
393741383540393740393749403D433A373D373545403D433A373C3836413B39
4039373A34313C35343D3A38403937413B39443D3C4036344036344036344138
35372E2C4E48464138350000FF000000FF453C3949403D453C39433A3749403D
403937453C393D3431403937453C394039374138354138354039374036344036
34433A374039373D37353D3735443D3C413B394F4947413B39413B3940393740
36344036343C3230413835433A37403634443D3C3C35343D34313A343149403D
403634403634413B393C38363C3836413B393C3836413B393D37353D3735443D
3C372E2C443D3C433A37443D3C3D37354138353D3735413B393D373540393744
3D3C403937413B39413B39443D3C3C3836403937403634403634443D3C433A37
433A3740363441383540393735302E4039373D3735413B3945403D4B45434541
40403937403937403937413B39453C393C38363C3534443D3C45403D443D3C43
3D3B3C32304036343D3431443B3841383540393740393745403D47414045403D
403937403937433A37473F3C433A37433A37473F3C4039374138354138353D3A
3845403D413B3935302E3C3836403937433A374741404B4340453C3949403D44
3D3C413B39413835413B393D3735413B39403937473F3C403937433A37494341
4138354039374036343D3A383D3A384541404039374039374039373D3A38413B
39413835413B39474140443D3C3D3735443D3C433A373D3735443D3C3D37353D
34313D3431413835403937433A37453C393C35343D3A38413B39443D3C372E2C
4F49474039370000FF000000FF403937473F3C433A37403937453C3941383543
3A373C3230413835453C39403937453C394039373D373540393740393745403D
413B393C3836403937443D3C443D3C4F494745403D413B39473F3C3D3A383C38
363C3534413B39443D3C413B3944403F4039374036343D3735473F3C40363441
3835433A374036343C3534443D3C3C3836443D3C403937453C3945403D373130
453C39453C39454140403937413B393D3A38413B393D3735403937413B394039
37433A37433A37494341443D3C453C39453C393D3431453C39443D3C413B393D
3735413B39403634372E2C4036343D3431413835453C39473F3C443D3C3D3735
4138353C3836433A37433A373D34313A312E433A37453C39433A37433D3B3A31
2E3C3534403634453C394138354039373C3534443D3C45403D443D3C4036343D
373540393744403F413B39413B39443D3C3D3A384039373D34313C3836403937
4138353A312E403634403634403634433A37474140413B39443D3C413B393C38
363C38364039373D37353C32303A34314138353A34313C3230433A373C35343C
32304036343D37353D3735443D3C3C35343D34314037343D3735453C39403734
413B3948403D41383541383545403D413B39403634433A374138353D34314036
343D37353D37354036343D34313A312E3A3431403734413835352D2A4E4A483D
37350000FF000000FF433A3745403D413B39403937433A37403937413B393A34
31453C3949403D413B39433A37433A37403937413B39433A3749403D453C3941
3B39433A37473F3C473F3C4E484644403F453C39453C393D3A38403937403634
443D3C45403D413B394541404039374039373C383649403D433A37413B39473F
3C413B39443D3C49403D413B39473F3C433A37453C3944403F353130443D3C44
3D3C44403F3D3A38443D3C3D37354039373C38363D3735413B393D3735413835
403634443D3C3731304138353D37353C32304036344036344036343D34314036
344138353A312E4138353D3431433A37433A3745403D454140413835473F3C41
3835453C39453C394039373D343145403D45403D45403D4541403D3735403937
41383545403D473F3C413835403634473F3C49434149403D403937413B39453C
39474140413B39413B39413B393C38363D37353C35343D37353D37353D373537
3130413B393D3735433A37433A37443D3C433D3B4138354039373D37353D3937
3D37353C3230403A383D37353F38363F3836403836453F3D4037343D34313D34
313D3735403634433C3A3C35344037344038353C3534413835403835403B3943
3F3D3D3836443D3B45403D453D3B413835443B38443D3C403A38403A383C3836
403634413835413B394039373D3A38403A38443D3C3A3431524B494138350000
FF000000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF
0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000
FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00
00FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF00}
Stretch = True
end
object Edit1: TEdit
Left = 8
Top = 8
Width = 153
Height = 21
TabOrder = 0
Text = 'Edit1'
end
object ServerSocket1: TServerSocket
Active = False
Port = 0
ServerType = stNonBlocking
OnClientRead = ServerSocket1ClientRead
Left = 136
Top = 8
end
end
| 67.734195 | 70 | 0.896867 |
47fabf52de9e0aad54022425c7f00a847066e196 | 192 | pas | Pascal | Program2.pas | rt69/test | f15e3f2db32353b3b42d8f769f9f485f6738c0c8 | [
"MIT"
]
| null | null | null | Program2.pas | rt69/test | f15e3f2db32353b3b42d8f769f9f485f6738c0c8 | [
"MIT"
]
| null | null | null | Program2.pas | rt69/test | f15e3f2db32353b3b42d8f769f9f485f6738c0c8 | [
"MIT"
]
| null | null | null | program awesomeprogram;
var i,h:integer;
begin
write('write h: ');
readln(h);
//cycle from 1 to h
for i:= 1 to h do //
begin
write('hello world ');
writeln(i);
end;
end. | 12.8 | 26 | 0.588542 |
fcdd08fcd050cc5314042976bb466b72e994454e | 906 | pas | Pascal | sources/uBox.pas | devapromix-roguelikes/troll-hunter | c54ef35d4c8654f29bfcb9c8e1c9365cef5928af | [
"MIT"
]
| 29 | 2017-05-04T21:34:18.000Z | 2021-09-21T23:42:16.000Z | sources/uBox.pas | devapromix-roguelikes/troll-hunter | c54ef35d4c8654f29bfcb9c8e1c9365cef5928af | [
"MIT"
]
| 7 | 2017-08-22T15:34:45.000Z | 2018-07-07T11:36:55.000Z | sources/uBox.pas | devapromix-roguelikes/troll-hunter | c54ef35d4c8654f29bfcb9c8e1c9365cef5928af | [
"MIT"
]
| 6 | 2017-11-06T19:42:29.000Z | 2021-08-15T22:36:17.000Z | unit uBox;
interface
uses Windows, SysUtils;
procedure Box(); overload;
procedure Box(const BoxStrMessage: string); overload;
procedure Box(const BoxIntMessage: Integer); overload;
procedure Box(const BoxBoolMessage: Boolean); overload;
procedure Box(const BoxStrMessage, Title: string); overload;
implementation
procedure Box(); overload;
begin
MessageBox(0, '', 'Info', MB_OK);
end;
procedure Box(const BoxStrMessage: string); overload;
begin
MessageBox(0, PChar(BoxStrMessage), 'Info', MB_OK);
end;
procedure Box(const BoxIntMessage: Integer); overload;
begin
MessageBox(0, PChar(IntToStr(BoxIntMessage)), 'Info', MB_OK);
end;
procedure Box(const BoxBoolMessage: Boolean); overload;
begin
MessageBox(0, PChar(BoolToStr(BoxBoolMessage)), 'Info', MB_OK);
end;
procedure Box(const BoxStrMessage, Title: string);
begin
MessageBox(0, PChar(BoxStrMessage), PChar(Title), MB_OK);
end;
end.
| 22.097561 | 65 | 0.760486 |
f13de2833c307dbc5f0f6a7044e06702fc67593e | 349 | pas | Pascal | Projeto.Principal.pas | FranlleyGomes/TesteUnitario | d413bb709a4b746c687ae44711e05ea2f6de8cdd | [
"MIT"
]
| null | null | null | Projeto.Principal.pas | FranlleyGomes/TesteUnitario | d413bb709a4b746c687ae44711e05ea2f6de8cdd | [
"MIT"
]
| null | null | null | Projeto.Principal.pas | FranlleyGomes/TesteUnitario | d413bb709a4b746c687ae44711e05ea2f6de8cdd | [
"MIT"
]
| null | null | null | unit Projeto.Principal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
end.
| 13.96 | 98 | 0.713467 |
c3c365b7052eb6bc6a146d6ff3fad6276b2b4e46 | 233 | dpr | Pascal | ScrollDemo.dpr | Pasquina/FMXVertScrollBoxEtude | ee27879ce59d33ca94b23f4100a29adb293e2e11 | [
"Apache-2.0"
]
| 15 | 2016-08-14T11:49:10.000Z | 2022-01-28T07:59:28.000Z | ScrollDemo.dpr | Pasquina/FMXVertScrollBoxEtude | ee27879ce59d33ca94b23f4100a29adb293e2e11 | [
"Apache-2.0"
]
| null | null | null | ScrollDemo.dpr | Pasquina/FMXVertScrollBoxEtude | ee27879ce59d33ca94b23f4100a29adb293e2e11 | [
"Apache-2.0"
]
| 6 | 2017-03-31T21:32:36.000Z | 2021-11-23T21:26:05.000Z | program ScrollDemo;
uses
System.StartUpCopy,
FMX.Forms,
pScrollDemo in 'pScrollDemo.pas' {fScrollDemo};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TfScrollDemo, fScrollDemo);
Application.Run;
end.
| 15.533333 | 52 | 0.751073 |
c35541058f2fe6e50aa09de1a4dcfa5dc8849f9a | 414 | dpr | Pascal | Demos/RealtimeMoveDemo/RealtimeMoveDemo.dpr | landrix/DelphiGrpc | f7eb2234232fb7b7ce9185d722dd5392bf5b6571 | [
"Apache-2.0"
]
| 1 | 2020-10-17T04:44:02.000Z | 2020-10-17T04:44:02.000Z | Demos/RealtimeMoveDemo/RealtimeMoveDemo.dpr | landrix/DelphiGrpc | f7eb2234232fb7b7ce9185d722dd5392bf5b6571 | [
"Apache-2.0"
]
| null | null | null | Demos/RealtimeMoveDemo/RealtimeMoveDemo.dpr | landrix/DelphiGrpc | f7eb2234232fb7b7ce9185d722dd5392bf5b6571 | [
"Apache-2.0"
]
| 1 | 2020-09-12T09:54:47.000Z | 2020-09-12T09:54:47.000Z | program RealtimeMoveDemo;
uses
Vcl.Forms,
fClient in 'fClient.pas' {Form5},
demoservice.Client in 'demoservice.Client.pas',
Ultraware.Grpc.Client in '..\..\gRPC\Ultraware.Grpc.Client.pas',
demoservice.Proto in 'demoservice.Proto.pas';
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TForm5, Form5);
Application.Run;
end.
| 23 | 67 | 0.707729 |
c3d00dd262f26f4dfbe31e273b874decfe60ebb4 | 19,539 | pas | Pascal | Delphi/Clipper2Lib/Clipper.Offset.pas | AngusJohnson/Clipper2 | 9d7a666ccb400762621a2b17be7dbd31a339878d | [
"BSL-1.0"
]
| 30 | 2022-02-25T08:44:43.000Z | 2022-03-31T21:40:32.000Z | Delphi/Clipper2Lib/Clipper.Offset.pas | AngusJohnson/Clipper2 | 9d7a666ccb400762621a2b17be7dbd31a339878d | [
"BSL-1.0"
]
| 7 | 2022-03-02T15:27:15.000Z | 2022-03-31T22:47:30.000Z | Delphi/Clipper2Lib/Clipper.Offset.pas | AngusJohnson/Clipper2 | 9d7a666ccb400762621a2b17be7dbd31a339878d | [
"BSL-1.0"
]
| 8 | 2022-02-25T08:58:00.000Z | 2022-03-26T20:03:15.000Z | unit Clipper.Offset;
(*******************************************************************************
* Author : Angus Johnson *
* Version : 10.0 (beta) - aka Clipper2 *
* Date : 14 June 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : Offset paths and clipping solutions *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************)
{$I Clipper.inc}
interface
uses
Classes, Clipper.Core;
type
TJoinType = (jtSquare, jtRound, jtMiter);
TEndType = (etPolygon, etJoined, etButt, etSquare, etRound);
//etButt : offsets both sides of a path, with square blunt ends
//etSquare : offsets both sides of a path, with square extended ends
//etRound : offsets both sides of a path, with round extended ends
//etJoined : offsets both sides of a path, with joined ends
//etPolygon: offsets only one side of a closed path
TPathGroup = class
paths : TPaths64;
reversed : Boolean;
joinType : TJoinType;
endType : TEndType;
constructor Create(jt: TJoinType; et: TEndType);
end;
TClipperOffset = class
private
fDelta : Double;
fMinLenSqrd : double;
fJoinType : TJoinType;
fTmpLimit : Double;
fMiterLimit : Double;
fArcTolerance: Double;
fStepsPerRad : Double;
fNorms : TPathD;
fInGroups : TList;
fMergeGroups : Boolean;
fInPath : TPath64;
fOutPath : TPath64;
fOutPaths : TPaths64;
fOutPathLen : Integer;
fSolution : TPaths64;
fPreserveCollinear : Boolean;
fReverseSolution : Boolean;
procedure AddPoint(x,y: double); overload;
procedure AddPoint(const pt: TPoint64); overload;
{$IFDEF INLINING} inline; {$ENDIF}
procedure DoSquare(j, k: Integer);
procedure DoMiter(j, k: Integer; cosAplus1: Double);
procedure DoRound(j, k: integer; angle: double);
procedure OffsetPoint(j: Integer; var k: integer);
procedure BuildNormals;
procedure DoGroupOffset(pathGroup: TPathGroup; delta: double);
procedure OffsetPolygon;
procedure OffsetOpenJoined;
procedure OffsetOpenPath(endType: TEndType);
public
constructor Create(miterLimit: double = 2.0;
arcTolerance: double = 0.0; PreserveCollinear: Boolean = False);
destructor Destroy; override;
procedure AddPath(const path: TPath64;
joinType: TJoinType; endType: TEndType);
procedure AddPaths(const paths: TPaths64;
joinType: TJoinType; endType: TEndType);
procedure Clear;
function Execute(delta: Double): TPaths64;
//MiterLimit: needed for mitered offsets (see offset_triginometry3.svg)
property MiterLimit: Double read fMiterLimit write fMiterLimit;
//ArcTolerance: needed for rounded offsets (See offset_triginometry2.svg)
property ArcTolerance: Double read fArcTolerance write fArcTolerance;
//MergeGroups: A path group is one or more paths added via the AddPath or
//AddPaths methods. By default these path groups will be offset
//independently of other groups and this may cause overlaps (intersections).
//However, when MergeGroups is enabled, any overlapping offsets will be
//merged (via a clipping union operation) to remove overlaps.
property MergeGroups: Boolean read fMergeGroups write fMergeGroups;
property PreserveCollinear: Boolean
read fPreserveCollinear write fPreserveCollinear;
property ReverseSolution: Boolean
read fReverseSolution write fReverseSolution;
end;
implementation
uses
Math, Clipper.Engine;
const
TwoPi : Double = 2 * PI;
InvTwoPi : Double = 1/(2 * PI);
//------------------------------------------------------------------------------
// Miscellaneous offset support functions
//------------------------------------------------------------------------------
function DotProduct(const vec1, vec2: TPointD): double;
{$IFDEF INLINING} inline; {$ENDIF}
begin
result := (vec1.X * vec2.X + vec1.Y * vec2.Y);
end;
//------------------------------------------------------------------------------
function GetUnitNormal(const pt1, pt2: TPoint64): TPointD;
var
dx, dy, inverseHypot: Double;
begin
if (pt2.X = pt1.X) and (pt2.Y = pt1.Y) then
begin
Result.X := 0;
Result.Y := 0;
Exit;
end;
dx := (pt2.X - pt1.X);
dy := (pt2.Y - pt1.Y);
inverseHypot := 1 / Hypot(dx, dy);
dx := dx * inverseHypot;
dy := dy * inverseHypot;
Result.X := dy;
Result.Y := -dx
end;
//------------------------------------------------------------------------------
function GetLowestPolygonIdx(const paths: TPaths64): integer;
var
i,j: integer;
lp: TPoint64;
p: TPath64;
begin
Result := -1;
lp := Point64(0, -MaxInt64);
for i := 0 to High(paths) do
begin
p := paths[i];
for j := 0 to High(p) do
if (p[j].Y < lp.Y) then continue
else if ((p[j].Y > lp.Y) or (p[j].X < lp.X)) then
begin
Result := i;
lp := p[j];
end;
end;
end;
//------------------------------------------------------------------------------
function CopyPaths(const paths: TPathsD): TPathsD;
var
i, len: integer;
begin
len := Length(paths);
SetLength(Result, len);
for i := 0 to len -1 do
Result[i] := Copy(paths[i], 0, Length(paths[i]));
end;
//------------------------------------------------------------------------------
// TPathGroup methods
//------------------------------------------------------------------------------
constructor TPathGroup.Create(jt: TJoinType; et: TEndType);
begin
Self.joinType := jt;
Self.endType := et;
end;
//------------------------------------------------------------------------------
// TClipperOffset methods
//------------------------------------------------------------------------------
constructor TClipperOffset.Create(miterLimit: double;
arcTolerance: double; preserveCollinear: Boolean);
begin
fMiterLimit := MiterLimit;
fArcTolerance := ArcTolerance;
fInGroups := TList.Create;
fPreserveCollinear := preserveCollinear;
end;
//------------------------------------------------------------------------------
destructor TClipperOffset.Destroy;
begin
Clear;
fInGroups.Free;
inherited;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.Clear;
var
i: integer;
begin
for i := 0 to fInGroups.Count -1 do
TPathGroup(fInGroups[i]).Free;
fInGroups.Clear;
fSolution := nil;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPath(const path: TPath64;
joinType: TJoinType; endType: TEndType);
var
paths: TPaths64;
begin
if not assigned(path) then Exit;
SetLength(paths, 1);
paths[0] := path;
AddPaths(Paths, joinType, endType);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPaths(const paths: TPaths64;
joinType: TJoinType; endType: TEndType);
var
group: TPathGroup;
begin
if Length(paths) = 0 then Exit;
group := TPathGroup.Create(joinType, endType);
AppendPaths(group.paths, paths);
fInGroups.Add(group);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoGroupOffset(pathGroup: TPathGroup; delta: double);
var
i, len, lowestIdx: Integer;
absDelta, arcTol, area, steps: Double;
IsClosedPaths: Boolean;
begin
if pathgroup.endType <> etPolygon then
delta := Abs(delta) * 0.5;
IsClosedPaths := (pathgroup.endType in [etPolygon, etJoined]);
if IsClosedPaths then
begin
pathgroup.reversed := false;
//the lowermost polygon must be an outer polygon. So we can use that as the
//designated orientation for outer polygons (needed for tidy-up clipping)
lowestIdx := GetLowestPolygonIdx(pathgroup.paths);
if lowestIdx < 0 then Exit;
area := Clipper.Core.Area(pathgroup.paths[lowestIdx]);
if area = 0 then Exit;
{$IFDEF REVERSE_ORIENTATION}
if area < 0 then
begin
delta := -delta;
pathgroup.reversed := true;
end;
{$ELSE}
if area > 0 then
delta := -delta
else
pathgroup.reversed := true;
{$ENDIF}
end;
fDelta := delta;
absDelta := Abs(fDelta);
fJoinType := pathGroup.joinType;
if fArcTolerance > 0 then
arcTol := fArcTolerance else
arcTol := Log10(2 + absDelta) * 0.25; //empirically derived
//calculate a sensible number of steps (for 360 deg for the given offset
if (pathgroup.joinType = jtRound) or (pathgroup.endType = etRound) then
begin
//get steps per 180 degrees (see offset_triginometry2.svg)
steps := PI / ArcCos(1 - arcTol / absDelta);
fStepsPerRad := steps * InvTwoPi;
end;
fOutPaths := nil;
for i := 0 to High(pathgroup.paths) do
begin
fInPath := StripDuplicates(pathgroup.paths[i], IsClosedPaths);
len := Length(fInPath);
if (fInPath = nil) or
((pathGroup.endType in [etPolygon, etJoined]) and (len < 3)) then Continue;
fNorms := nil;
fOutPath := nil;
fOutPathLen := 0;
//if a single vertex then build a circle or a square ...
if len = 1 then
begin
if (pathgroup.endType = etRound) then
begin
SetLength(fNorms, 2);
fNorms[0] := PointD(1,0);
fNorms[1] := PointD(-1,0);
DoRound(0, 1, TwoPi);
dec(fOutPathLen);
SetLength(fOutPath, fOutPathLen);
end else
begin
fOutPathLen := 4;
SetLength(fOutPath, fOutPathLen);
with fInPath[0] do
begin
fOutPath[0] := Point64(X-fDelta,Y-fDelta);
fOutPath[1] := Point64(X+fDelta,Y-fDelta);
fOutPath[2] := Point64(X+fDelta,Y+fDelta);
fOutPath[3] := Point64(X-fDelta,Y+fDelta);
end;
end;
end else
begin
BuildNormals;
if pathgroup.endType = etPolygon then
begin
OffsetPolygon;
end
else if pathgroup.endType = etJoined then
begin
OffsetOpenJoined;
end else
OffsetOpenPath(pathgroup.endType);
end;
if fOutPathLen = 0 then Continue;
SetLength(fOutPath, fOutPathLen);
AppendPath(fOutPaths, fOutPath);
end;
if not fMergeGroups then
begin
//clean up self-intersections ...
with TClipper64.Create do
try
PreserveCollinear := fPreserveCollinear;
AddSubject(fOutPaths);
if pathgroup.reversed then
begin
ReverseSolution := not fReverseSolution;
Execute(ctUnion, frNegative, fOutPaths)
end else
begin
ReverseSolution := fReverseSolution;
Execute(ctUnion, frPositive, fOutPaths);
end;
finally
free;
end;
end;
//finally copy the working 'outPaths' to the solution
AppendPaths(fSolution, fOutPaths);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.BuildNormals;
var
i, len: integer;
begin
len := Length(fInPath);
SetLength(fNorms, len);
for i := 0 to len-2 do
fNorms[i] := GetUnitNormal(fInPath[i], fInPath[i+1]);
fNorms[len -1] := GetUnitNormal(fInPath[len -1], fInPath[0]);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.OffsetPolygon;
var
i,j: integer;
begin
j := high(fInPath);
for i := 0 to high(fInPath) do
OffsetPoint(i, j);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.OffsetOpenJoined;
begin
OffsetPolygon;
SetLength(fOutPath, fOutPathLen);
AppendPath(fOutPaths, fOutPath);
fOutPath := nil;
fOutPathLen := 0;
fInPath := ReversePath(fInPath);
BuildNormals;
OffsetPolygon;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.OffsetOpenPath(endType: TEndType);
procedure DoButtEnd(highI: integer);
begin
AddPoint(fInPath[highI].X + fNorms[highI-1].X *fDelta,
fInPath[highI].Y + fNorms[highI-1].Y * fDelta);
AddPoint(fInPath[highI].X - fNorms[highI-1].X *fDelta,
fInPath[highI].Y - fNorms[highI-1].Y * fDelta);
end;
procedure DoButtStart;
begin
AddPoint(fInPath[0].X + fNorms[1].X *fDelta,
fInPath[0].Y + fNorms[1].Y * fDelta);
AddPoint(fInPath[0].X - fNorms[1].X *fDelta,
fInPath[0].Y - fNorms[1].Y * fDelta);
end;
var
i, k, highI: integer;
begin
highI := high(fInPath);
k := 0;
for i := 1 to highI -1 do
OffsetPoint(i, k);
k := highI -1;
fNorms[highI].X := -fNorms[k].X;
fNorms[highI].Y := -fNorms[k].Y;
//cap the end first ...
case endType of
etButt: DoButtEnd(highI);
{$IFDEF REVERSE_ORIENTATION}
etRound: DoRound(highI, k, PI);
{$ELSE}
etRound: DoRound(highI, k, -PI);
{$ENDIF}
else DoSquare(highI, k);
end;
//reverse normals ...
for i := highI -1 downto 1 do
begin
fNorms[i].X := -fNorms[i-1].X;
fNorms[i].Y := -fNorms[i-1].Y;
end;
fNorms[0].X := -fNorms[1].X;
fNorms[0].Y := -fNorms[1].Y;
k := highI;
for i := highI -1 downto 1 do
OffsetPoint(i, k);
//now cap the start ...
case endType of
etButt: DoButtStart;
{$IFDEF REVERSE_ORIENTATION}
etRound: DoRound(0, 1, PI);
{$ELSE}
etRound: DoRound(0, 1, -PI);
{$ENDIF}
else doSquare(0, 1);
end;
end;
//------------------------------------------------------------------------------
function TClipperOffset.Execute(delta: Double): TPaths64;
var
i: integer;
group: TPathGroup;
begin
fSolution := nil;
Result := nil;
if fInGroups.Count = 0 then Exit;
fMinLenSqrd := 1;
if abs(delta) < Tolerance then
begin
//if delta ~= 0, just copy paths to Result
for i := 0 to fInGroups.Count -1 do
with TPathGroup(fInGroups[i]) do
AppendPaths(fSolution, paths);
Result := fSolution;
Exit;
end;
//Miter Limit: see offset_triginometry3.svg
if fMiterLimit > 1 then
fTmpLimit := 2 / Sqr(fMiterLimit) else
fTmpLimit := 2.0;
//nb: delta will depend on whether paths are polygons or open
for i := 0 to fInGroups.Count -1 do
begin
group := TPathGroup(fInGroups[i]);
DoGroupOffset(group, delta);
end;
if fMergeGroups and (fInGroups.Count > 0) then
begin
//clean up self-intersections ...
with TClipper64.Create do
try
PreserveCollinear := fPreserveCollinear;
AddSubject(fSolution);
if TPathGroup(fInGroups[0]).reversed then
begin
ReverseSolution := not fReverseSolution;
Execute(ctUnion, frNegative, fSolution)
end else
begin
ReverseSolution := fReverseSolution;
Execute(ctUnion, frPositive, fSolution);
end;
finally
free;
end;
end;
Result := fSolution;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPoint(x,y: double);
const
BuffLength = 32;
var
pt: TPoint64;
begin
pt := Point64(Round(x),Round(y));
if fOutPathLen = length(fOutPath) then
SetLength(fOutPath, fOutPathLen + BuffLength);
if (fOutPathLen > 0) and
PointsEqual(fOutPath[fOutPathLen-1], pt) then Exit;
fOutPath[fOutPathLen] := pt;
Inc(fOutPathLen);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPoint(const pt: TPoint64);
begin
AddPoint(pt.X, pt.Y);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoSquare(j, k: Integer);
begin
//Two vertices, one using the prior offset's (k) normal one the current (j).
//Do a 'normal' offset (by delta) and then another by 'de-normaling' the
//normal hence parallel to the direction of the respective edges.
if (fDelta > 0) then
begin
AddPoint(
fInPath[j].X + fDelta * (fNorms[k].X - fNorms[k].Y),
fInPath[j].Y + fDelta * (fNorms[k].Y + fNorms[k].X));
AddPoint(
fInPath[j].X + fDelta * (fNorms[j].X + fNorms[j].Y),
fInPath[j].Y + fDelta * (fNorms[j].Y - fNorms[j].X));
end else
begin
AddPoint(
fInPath[j].X + fDelta * (fNorms[k].X + fNorms[k].Y),
fInPath[j].Y + fDelta * (fNorms[k].Y - fNorms[k].X));
AddPoint(
fInPath[j].X + fDelta * (fNorms[j].X - fNorms[j].Y),
fInPath[j].Y + fDelta * (fNorms[j].Y + fNorms[j].X));
end;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoMiter(j, k: Integer; cosAplus1: Double);
var
q: Double;
begin
//see offset_triginometry4.svg
q := fDelta / cosAplus1;
AddPoint(fInPath[j].X + (fNorms[k].X + fNorms[j].X)*q,
fInPath[j].Y + (fNorms[k].Y + fNorms[j].Y)*q);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoRound(j, k: Integer; angle: double);
var
i, steps: Integer;
stepSin, stepCos: Extended;
pt: TPoint64;
pt2: TPointD;
begin
//even though angle may be negative this is a convex join
pt := fInPath[j];
pt2 := PointD(fNorms[k].X * fDelta, fNorms[k].Y * fDelta);
AddPoint(pt.X + pt2.X, pt.Y + pt2.Y);
steps := Round(fStepsPerRad * abs(angle) + 0.501);
Math.SinCos(angle / steps, stepSin, stepCos);
for i := 0 to steps -1 do
begin
pt2 := PointD(pt2.X * stepCos - stepSin * pt2.Y,
pt2.X * stepSin + pt2.Y * stepCos);
AddPoint(pt.X + pt2.X, pt.Y + pt2.Y);
end;
pt2 := PointD(fNorms[j].X * fDelta, fNorms[j].Y * fDelta);
AddPoint(pt.X + pt2.X, pt.Y + pt2.Y);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.OffsetPoint(j: Integer; var k: integer);
var
sinA, cosA: Double;
p1, p2: TPoint64;
begin
//A: angle between adjoining edges (on left side WRT winding direction).
//A == 0 deg (or A == 360 deg): collinear edges heading in same direction
//A == 180 deg: collinear edges heading in opposite directions (ie a 'spike')
//sin(A) < 0: convex on left.
//cos(A) > 0: angles on both left and right sides > 90 degrees
sinA := (fNorms[k].X * fNorms[j].Y - fNorms[j].X * fNorms[k].Y);
if (sinA > 1.0) then sinA := 1.0
else if (sinA < -1.0) then sinA := -1.0;
if sinA * fDelta < 0 then //ie a concave offset
begin
p1 := Point64(
fInPath[j].X + fNorms[k].X * fDelta,
fInPath[j].Y + fNorms[k].Y * fDelta);
p2:= Point64(
fInPath[j].X + fNorms[j].X * fDelta,
fInPath[j].Y + fNorms[j].Y * fDelta);
AddPoint(p1);
if not PointsEqual(p1, p2) then
begin
AddPoint(fInPath[j]); //this aids with clipping removal later
AddPoint(p2);
end;
end else
begin
cosA := DotProduct(fNorms[j], fNorms[k]);
//convex offsets here ...
case fJoinType of
jtMiter:
//see offset_triginometry3.svg
if (1 + cosA < fTmpLimit) then
DoSquare(j, k) else
DoMiter(j, k, 1 + cosA);
jtSquare:
begin
//angles >= 90 deg. don't need squaring
if cosA >= 0 then
DoMiter(j, k, 1 + cosA) else
DoSquare(j, k);
end
else
DoRound(j, k, ArcTan2(sinA, cosA));
end;
end;
k := j;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
end.
| 29.426205 | 81 | 0.562772 |
c3cc5867a5d3ccd44fe3237d3ee475102e3609fe | 6,089 | pas | Pascal | explore/Invers, Brigtness, Quantitation/utama.pas | ukayaj620/learn-image-processing | 4f68636db5f7007fa8172a4b0f85cacc2534e1c4 | [
"Apache-2.0"
]
| 1 | 2020-11-11T17:35:32.000Z | 2020-11-11T17:35:32.000Z | explore/Invers, Brigtness, Quantitation/utama.pas | ukayaj620/learn-image-processing | 4f68636db5f7007fa8172a4b0f85cacc2534e1c4 | [
"Apache-2.0"
]
| null | null | null | explore/Invers, Brigtness, Quantitation/utama.pas | ukayaj620/learn-image-processing | 4f68636db5f7007fa8172a4b0f85cacc2534e1c4 | [
"Apache-2.0"
]
| 2 | 2020-11-18T15:59:34.000Z | 2021-12-14T11:28:05.000Z | unit utama;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
ExtDlgs, ComCtrls;
type
{ TFormUtama }
TFormUtama = class(TForm)
ButtonColorInvers: TButton;
ButtonGrayInvers: TButton;
ButtonBinary: TButton;
ButtonSave: TButton;
ButtonGray: TButton;
ButtonBlue: TButton;
ButtonGreen: TButton;
ButtonRed: TButton;
ButtonColor: TButton;
ButtonLoadImage: TButton;
Image1: TImage;
OpenPictureDialog1: TOpenPictureDialog;
RadioGroupGray: TRadioGroup;
RadioGroupBinary: TRadioGroup;
SavePictureDialog1: TSavePictureDialog;
TrackBarBinary: TTrackBar;
procedure ButtonColorInversClick(Sender: TObject);
procedure ButtonGrayInversClick(Sender: TObject);
procedure ButtonBinaryClick(Sender: TObject);
procedure ButtonBlueClick(Sender: TObject);
procedure ButtonColorClick(Sender: TObject);
procedure ButtonGrayClick(Sender: TObject);
procedure ButtonGreenClick(Sender: TObject);
procedure ButtonLoadImageClick(Sender: TObject);
procedure ButtonRedClick(Sender: TObject);
procedure ButtonSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TrackBarBinaryChange(Sender: TObject);
private
procedure AssignBitmapBinary();
public
end;
var
FormUtama: TFormUtama;
implementation
{$R *.lfm}
{ TFormUtama }
uses
windows;
var
bitmapR, bitmapG, bitmapB : array[0..1000, 0..1000] of byte;
bitmapBinary : array[0..1000, 0..1000] of boolean;
procedure TFormUtama.ButtonLoadImageClick(Sender: TObject);
var
x, y : integer;
begin
if OpenPictureDialog1.Execute then
begin
Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
bitmapR[x,y] := GetRValue(Image1.Canvas.Pixels[x,y]);
bitmapG[x,y] := GetGValue(Image1.Canvas.Pixels[x,y]);
bitmapB[x,y] := GetBValue(Image1.Canvas.Pixels[x,y]);
end;
end;
end;
AssignBitmapBinary();
end;
procedure TFormUtama.ButtonRedClick(Sender: TObject);
var
x, y : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
Image1.Canvas.Pixels[x,y] := RGB(bitmapR[x,y], 0, 0);
end;
end;
end;
procedure TFormUtama.ButtonSaveClick(Sender: TObject);
begin
if SavePictureDialog1.Execute then
begin
Image1.Picture.SaveToFile(SavePictureDialog1.FileName);
end;
end;
procedure TFormUtama.FormShow(Sender: TObject);
begin
RadioGroupBinary.ItemIndex := 0;
RadioGroupGray.ItemIndex := 0;
TrackBarBinary.Position := 127;
end;
procedure TFormUtama.AssignBitmapBinary();
var
x, y, threshold, gray : integer;
begin
threshold := TrackBarBinary.Position;
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
gray := (bitmapR[x,y] + bitmapG[x,y] + bitmapB[x,y]) div 3;
if gray <= threshold then
begin
bitmapBinary[x,y] := false;
end
else
begin
bitmapBinary[x,y] := true;
end;
end;
end;
end;
procedure TFormUtama.TrackBarBinaryChange(Sender: TObject);
begin
AssignBitmapBinary();
end;
procedure TFormUtama.ButtonColorClick(Sender: TObject);
var
x, y : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
Image1.Canvas.Pixels[x,y] := RGB(bitmapR[x,y], bitmapG[x,y], bitmapB[x,y]);
end;
end;
end;
procedure TFormUtama.ButtonGrayClick(Sender: TObject);
var
x, y, gray : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
gray := (bitmapR[x,y] + bitmapG[x,y] + bitmapB[x,y]) div 3;
case(RadioGroupGray.ItemIndex) of
0 : Image1.Canvas.Pixels[x,y] := RGB(gray, gray, gray);
1 : Image1.Canvas.Pixels[x,y] := RGB(gray, 0, 0);
2 : Image1.Canvas.Pixels[x,y] := RGB(0, gray, 0);
3 : Image1.Canvas.Pixels[x,y] := RGB(0, 0, gray);
end;
end;
end;
end;
procedure TFormUtama.ButtonBlueClick(Sender: TObject);
var
x, y : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
Image1.Canvas.Pixels[x,y] := RGB(0, 0, bitmapB[x,y]);
end;
end;
end;
procedure TFormUtama.ButtonBinaryClick(Sender: TObject);
var
x, y : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
if bitmapBinary[x,y] = true then
begin
case(RadioGroupBinary.ItemIndex) of
0 : Image1.Canvas.Pixels[x,y] := RGB(0, 0, 0);
1 : Image1.Canvas.Pixels[x,y] := RGB(255, 0, 0);
2 : Image1.Canvas.Pixels[x,y] := RGB(0, 255, 0);
3 : Image1.Canvas.Pixels[x,y] := RGB(0, 0, 255);
end;
end
else
begin
Image1.Canvas.Pixels[x,y] := RGB(255, 255, 255);
end;
end;
end;
end;
procedure TFormUtama.ButtonGrayInversClick(Sender: TObject);
var
x, y, gray : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
gray := 255 - ((bitmapR[x,y] + bitmapG[x,y] + bitmapB[x,y]) div 3);
case(RadioGroupGray.ItemIndex) of
0 : Image1.Canvas.Pixels[x,y] := RGB(gray, gray, gray);
1 : Image1.Canvas.Pixels[x,y] := RGB(gray, 0, 0);
2 : Image1.Canvas.Pixels[x,y] := RGB(0, gray, 0);
3 : Image1.Canvas.Pixels[x,y] := RGB(0, 0, gray);
end;
end;
end;
end;
procedure TFormUtama.ButtonColorInversClick(Sender: TObject);
var
x, y : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
Image1.Canvas.Pixels[x,y] := RGB(255-bitmapR[x,y], 255-bitmapG[x,y], 255-bitmapB[x,y]);
end;
end;
end;
procedure TFormUtama.ButtonGreenClick(Sender: TObject);
var
x, y : integer;
begin
for y := 0 to Image1.Height-1 do
begin
for x := 0 to Image1.Width-1 do
begin
Image1.Canvas.Pixels[x,y] := RGB(0, bitmapG[x,y], 0);
end;
end;
end;
end.
| 23.600775 | 93 | 0.651338 |
47847fa7b581981deb2460dfdb5d1c7b7360c5a9 | 2,665 | pas | Pascal | gitlogparser.pas | skalogryz/gittools | 4e8b3097c735ab8f0ff0657d227b0abd0bd8964d | [
"MIT"
]
| 5 | 2022-02-16T06:57:53.000Z | 2022-02-16T13:47:21.000Z | gitlogparser.pas | skalogryz/gittools | 4e8b3097c735ab8f0ff0657d227b0abd0bd8964d | [
"MIT"
]
| null | null | null | gitlogparser.pas | skalogryz/gittools | 4e8b3097c735ab8f0ff0657d227b0abd0bd8964d | [
"MIT"
]
| null | null | null | unit gitlogparser;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, gitscanutils;
type
// see GitLog pretty formats https://git-scm.com/docs/pretty-formats
TGitLogEntry = (
gleCommit // always starts a new hash
,gleInfo
,gleGitAttr
,gleTitleStart
,gleTitle
,gleTitleEnd
,gleFileName
,gleUnknown
,gleCommitEnd
);
{ TGitLogScanner }
// scanns "fuller" pretty format
TGitLogScanner = class(TObject)
private
isTitle : Boolean;
isCommit : Boolean;
isTitleDone : Boolean;
public
Entry : TGitLogEntry;
CommitHash : string;
EntryName : string;
EntryValue : string;
FileMod : string;
function ConsumeLine(const s: string): TGitLogEntry;
procedure Reset;
end;
implementation
{ TGitLogScanner }
function TGitLogScanner.ConsumeLine(const s: string): TGitLogEntry;
var
i : integer;
t : string;
begin
try
if s = '' then begin
if isTitleDone and isCommit then begin
isCommit := false;
Result := gleCommitEnd;
end else begin
if not isTitle then begin
Result := gleTitleStart;
isTitleDone := false;
end else begin
Result := gleTitleEnd;
isTitleDone := true;
end;
isTitle := not isTitle;
end;
Exit;
end;
if isTitle then begin
EntryValue := s;
Result := gleTitle;
Exit;
end;
i:=1;
if (s[i] = ' ') then begin
Result := gleGitAttr;
ScanWhile(s, [#32], i);
EntryName := ScanTo(s, [':'], i);
inc(i, 2); // skip ': '
EntryValue := ScanTo(s, UnixEoln, i);
end else begin
t := ScanWhile(s, Alpha, i);
if (t = 'commit') then begin
EntryName := 'commit';
Result := gleCommit;
ScanWhile(s, WhiteSpace, i);
CommitHash := ScanTo(s, UnixEoln, i);
EntryValue := CommitHash;
isCommit := true;
isTitleDone := false;
end else if (i<=length(s)) and (s[i]=#9) then begin ;// else if (t='A' or
Result:=gleFileName;
FileMod := t;
ScanWhile(s, Tabs, i);
EntryValue := ScanTo(s, UnixEoln, i);
end else begin
Result:=gleInfo;
EntryName := t;
inc(i, 2);
ScanWhile(s, WhiteSpace, i);
EntryValue:=ScanTo(s, UnixEoln, i);
inc(i);
end;
end;
finally
Entry := Result;
end;
end;
procedure TGitLogScanner.Reset;
begin
isTitle:=false;
isCommit:=false;
isTitleDone:=false;
end;
end.
| 22.024793 | 80 | 0.549343 |
fcca1de14fec011b40613a8464d09cf03beb9966 | 655 | pas | Pascal | sorting/0004.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | sorting/0004.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | sorting/0004.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | {
> Does anyone know of a routine or code that would allow For a
> alphabetical sort?
Depends on what Type of sorting you want to do- For a very small list, a
simple BubbleSort will suffice.
}
Const
max = 50;
Var
i,j:Integer;
a : Array[1..max] of String;
temp : String;
begin
For i := 1 to 50 do
For j := 1 to 50 do
if a[i] < a[j] then
begin
temp := a[i];
a[i] := a[j];
a[j] := temp;
end; { if }
end.
{
If it's a bigger list than, say 100 or so elements, or it needs to be
sorted often, you'll probably need a better algorithm, like a shell sort
or a quicksort.
}
| 21.129032 | 73 | 0.584733 |
c3e1af4ebeea15581946118133ef6824febdb753 | 6,380 | pas | Pascal | Client/fProcessBaseOperationFieldEditFrame.pas | Sembium/Sembium3 | 0179c38c6a217f71016f18f8a419edd147294b73 | [
"Apache-2.0"
]
| null | null | null | Client/fProcessBaseOperationFieldEditFrame.pas | Sembium/Sembium3 | 0179c38c6a217f71016f18f8a419edd147294b73 | [
"Apache-2.0"
]
| null | null | null | Client/fProcessBaseOperationFieldEditFrame.pas | Sembium/Sembium3 | 0179c38c6a217f71016f18f8a419edd147294b73 | [
"Apache-2.0"
]
| 3 | 2021-06-30T10:11:17.000Z | 2021-07-01T09:13:29.000Z | unit fProcessBaseOperationFieldEditFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, fTreeOnlyNodeFieldEditFrame, DB, AbmesFields, DBClient,
AbmesClientDataSet, ActnList, ComCtrls, ToolWin, Buttons, JvExMask,
JvToolEdit, JvDBControls, StdCtrls, Mask, DBCtrls, ExtCtrls, uDocUtils;
type
TfrProcessBaseOperationFieldEditFrame = class(TTreeOnlyNodeFieldEditFrame)
cdsProcessBaseOperation: TAbmesClientDataSet;
cdsProcessBaseOperationPRC_BASE_OP_CODE: TAbmesFloatField;
cdsProcessBaseOperationPARENT_PRC_BASE_OP_CODE: TAbmesFloatField;
cdsProcessBaseOperationPRC_BASE_OP_LOCAL_NO: TAbmesFloatField;
cdsProcessBaseOperationPRC_BASE_OP_NAME: TAbmesWideStringField;
cdsProcessBaseOperationPRC_BASE_OP_SHORT_NAME: TAbmesWideStringField;
cdsProcessBaseOperationIS_GROUP: TAbmesFloatField;
cdsProcessBaseOperationPARENT_FULL_NO: TAbmesWideStringField;
cdsProcessBaseOperationDOC_BRANCH_CODE: TAbmesFloatField;
cdsProcessBaseOperationDOC_CODE: TAbmesFloatField;
cdsProcessBaseOperationHAS_DOC_ITEMS: TAbmesFloatField;
cdsProcessBaseOperationDOC_PRODUCT_CODE: TAbmesFloatField;
cdsProcessBaseOperationPRODUCT_DOC_BRANCH_CODE: TAbmesFloatField;
cdsProcessBaseOperationPRODUCT_DOC_CODE: TAbmesFloatField;
cdsProcessBaseOperationPRODUCT_HAS_DOCUMENTATION: TAbmesFloatField;
cdsProcessBaseOperation_PRC_BASE_OP_DISPLAY_NAME: TAbmesWideStringField;
procedure cdsProcessBaseOperationCalcFields(DataSet: TDataSet);
protected
procedure UpdateTreeNode; override;
function NoMatchingNodeErrorMsg: string; override;
function NodeNotAnInstanceErrorMsg: string; override;
function GetNodeCode(ANodeNo: string): Integer; override;
function GetEditTreeNodeButtonHint: string; override;
function DoEditTreeNodeCode(ANodeCode: Integer): Integer; override;
function IsInstance(ANodeCode: Integer): Boolean; override;
function TreeNodeIsInactiveErrorMsg: string; override;
function GetTreeNodeIsInactive(ANodeCode: Integer): Boolean; override;
function GetDocOwnerType: TDocOwnerType; override;
function RawNoWidth: Integer; override;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
fProcessBaseOperationsTree, uClientTypes, StrUtils, dMain;
resourcestring
SNoMatchingProcessBaseOperation = 'Не съществува Познавателен Оператор с такъв номер';
SEditTreeNodeButtonHint = 'Избор от Структура на Познавателни Оператори';
SNodeNotAnInstance = 'Избрания Процес трябва да бъде единичен';
SProcessBaseOperationIsInactive = 'Избрания Процес трябва да бъде активен';
{$R *.dfm}
{ TfrProcessBaseOperationFieldEditFrame }
function TfrProcessBaseOperationFieldEditFrame.RawNoWidth: Integer;
begin
Result:= 49;
end;
procedure TfrProcessBaseOperationFieldEditFrame.cdsProcessBaseOperationCalcFields(
DataSet: TDataSet);
begin
inherited;
cdsProcessBaseOperation_PRC_BASE_OP_DISPLAY_NAME.AsString:=
cdsProcessBaseOperationPRC_BASE_OP_SHORT_NAME.AsString +
' - ' +
cdsProcessBaseOperationPRC_BASE_OP_NAME.AsString;
end;
constructor TfrProcessBaseOperationFieldEditFrame.Create(AOwner: TComponent);
begin
inherited;
FieldNames:= 'PRC_BASE_OP_CODE';
end;
function TfrProcessBaseOperationFieldEditFrame.DoEditTreeNodeCode(
ANodeCode: Integer): Integer;
begin
Result:=
TfmProcessBaseOperationsTree.ShowForm(
nil,
nil,
emReadOnly,
doNone,
ANodeCode,
TreeDetailSelectionIfReadOnly);
end;
function TfrProcessBaseOperationFieldEditFrame.GetDocOwnerType: TDocOwnerType;
begin
if cdsProcessBaseOperationIS_GROUP.AsBoolean then
Result:= dotProcessBaseOperation
else
Result:= dotProduct;
end;
function TfrProcessBaseOperationFieldEditFrame.GetEditTreeNodeButtonHint: string;
begin
Result:= SEditTreeNodeButtonHint;
end;
function TfrProcessBaseOperationFieldEditFrame.GetNodeCode(
ANodeNo: string): Integer;
begin
if (RightStr(ANodeNo, 1) <> '.') then
ANodeNo:= ANodeNo + '.';
Result:= dmMain.SvrProcesses.GetProcessBaseOperationCodeByFullNo(ANodeNo);
end;
function TfrProcessBaseOperationFieldEditFrame.GetTreeNodeIsInactive(
ANodeCode: Integer): Boolean;
begin
Result:= False;
end;
function TfrProcessBaseOperationFieldEditFrame.IsInstance(
ANodeCode: Integer): Boolean;
begin
Result:= dmMain.SvrProcesses.GetProcessBaseOperationIsInstance(ANodeCode);
end;
function TfrProcessBaseOperationFieldEditFrame.NodeNotAnInstanceErrorMsg: string;
begin
Result:= SNodeNotAnInstance;
end;
function TfrProcessBaseOperationFieldEditFrame.NoMatchingNodeErrorMsg: string;
begin
Result:= SNoMatchingProcessBaseOperation;
end;
function TfrProcessBaseOperationFieldEditFrame.TreeNodeIsInactiveErrorMsg: string;
begin
Result:= SProcessBaseOperationIsInactive;
end;
procedure TfrProcessBaseOperationFieldEditFrame.UpdateTreeNode;
begin
inherited;
cdsProcessBaseOperation.Params.ParamByName('PRC_BASE_OP_CODE').AsInteger:= cdsTreeNodeNODE_CODE.AsInteger;
cdsProcessBaseOperation.Open;
try
cdsTreeNodeNODE_NAME.AsString:= cdsProcessBaseOperation_PRC_BASE_OP_DISPLAY_NAME.AsString;
if cdsProcessBaseOperationPRC_BASE_OP_LOCAL_NO.IsNull then
cdsTreeNodeNODE_NO.Clear
else
cdsTreeNodeNODE_NO.AsString:=
cdsProcessBaseOperationPARENT_FULL_NO.AsString +
cdsProcessBaseOperationPRC_BASE_OP_LOCAL_NO.AsString + '.';
if cdsProcessBaseOperationIS_GROUP.AsBoolean then
begin
cdsTreeNodeDOC_BRANCH_CODE.AsInteger:= cdsProcessBaseOperationDOC_BRANCH_CODE.AsInteger;
cdsTreeNodeDOC_CODE.AsInteger:= cdsProcessBaseOperationDOC_CODE.AsInteger;
cdsTreeNodeHAS_DOCUMENTATION.AsBoolean:= cdsProcessBaseOperationHAS_DOC_ITEMS.AsBoolean;
end
else
begin
cdsTreeNodeDOC_BRANCH_CODE.AsInteger:= cdsProcessBaseOperationPRODUCT_DOC_BRANCH_CODE.AsInteger;
cdsTreeNodeDOC_CODE.AsInteger:= cdsProcessBaseOperationPRODUCT_DOC_CODE.AsInteger;
cdsTreeNodeHAS_DOCUMENTATION.AsBoolean:= cdsProcessBaseOperationPRODUCT_HAS_DOCUMENTATION.AsBoolean;
end;
finally
cdsProcessBaseOperation.Close;
end; { try }
end;
end.
| 35.842697 | 109 | 0.797335 |
fcdef161bb56e389bb58dc8fe10863fab2ef6777 | 238 | dpr | Pascal | student_rooster_p.dpr | HendrikPrinsZA/uni-student-lecture-timetable-scheduler | 1996eb8e72587758ab881683be9728f2b72f058a | [
"MIT"
]
| null | null | null | student_rooster_p.dpr | HendrikPrinsZA/uni-student-lecture-timetable-scheduler | 1996eb8e72587758ab881683be9728f2b72f058a | [
"MIT"
]
| null | null | null | student_rooster_p.dpr | HendrikPrinsZA/uni-student-lecture-timetable-scheduler | 1996eb8e72587758ab881683be9728f2b72f058a | [
"MIT"
]
| 1 | 2021-12-15T11:29:12.000Z | 2021-12-15T11:29:12.000Z | program student_rooster_p;
uses
Forms,
student_rooster_u in 'student_rooster_u.pas' {Form1},
module_u in 'module_u.pas';
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
| 15.866667 | 55 | 0.743697 |
f1d7aef134c13b93e1f87e77d0ee4e0c0a025c71 | 1,505 | pas | Pascal | CryptoLib/src/Interfaces/ClpIDsaKeyParameters.pas | MarkG55/CryptoLib4Pascal | 740f1e7ac86ac9cf009a8010d4384368e7abe6fb | [
"MIT"
]
| 148 | 2018-02-08T23:36:43.000Z | 2022-03-16T01:33:20.000Z | CryptoLib/src/Interfaces/ClpIDsaKeyParameters.pas | tondrej/CryptoLib4Pascal | 33a540094aa24d22d84d502319e4d01f7c3e8163 | [
"MIT"
]
| 28 | 2018-08-09T04:14:18.000Z | 2022-03-31T05:23:51.000Z | CryptoLib/src/Interfaces/ClpIDsaKeyParameters.pas | tondrej/CryptoLib4Pascal | 33a540094aa24d22d84d502319e4d01f7c3e8163 | [
"MIT"
]
| 46 | 2018-03-18T17:25:59.000Z | 2022-02-07T16:52:15.000Z | { *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIDsaKeyParameters;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIDsaParameters,
ClpIAsymmetricKeyParameter;
type
IDsaKeyParameters = interface(IAsymmetricKeyParameter)
['{1E3454DF-DC9F-4EA0-91DA-0768A77387C5}']
function GetParameters: IDsaParameters;
function Equals(const other: IDsaKeyParameters): Boolean; overload;
property parameters: IDsaParameters read GetParameters;
end;
implementation
end.
| 35.833333 | 87 | 0.425914 |
c3d112fca0a35cb3cf8d8ed3ef4fae283d336640 | 954 | pas | Pascal | Tests/MainFormU.pas | ronaldhoek/SOAPStuff | 898acc163c83aa1b5f63f7bc5c7404ace0391330 | [
"MIT"
]
| 1 | 2022-03-14T18:14:07.000Z | 2022-03-14T18:14:07.000Z | Tests/MainFormU.pas | ronaldhoek/SOAPStuff | 898acc163c83aa1b5f63f7bc5c7404ace0391330 | [
"MIT"
]
| null | null | null | Tests/MainFormU.pas | ronaldhoek/SOAPStuff | 898acc163c83aa1b5f63f7bc5c7404ace0391330 | [
"MIT"
]
| null | null | null | unit MainFormU;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
mmResult: TMemo;
rgTests: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
uses
TestsU;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
GetTests(rgTests.Items);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
test: TTest;
begin
if rgTests.ItemIndex = -1 then
raise Exception.Create('No test selected');
mmResult.Lines.Clear;
test := TTestClass(rgTests.Items.Objects[rgTests.ItemIndex]).Create;
try
test.Run;
if Assigned(test.RequestData) then
mmResult.Lines.LoadFromStream(test.RequestData);
finally
test.Free;
end;
end;
end.
| 18 | 84 | 0.72327 |
c324e78fa6dcaa0a4d91809d873cb61a305d1c25 | 18,134 | pas | Pascal | Backup 13-5(13.05)/Main_Form.pas | gazzenger/multithread_queuer | 885ab83a269d63147b83aabd4ce59c3d3a9064bd | [
"MIT"
]
| null | null | null | Backup 13-5(13.05)/Main_Form.pas | gazzenger/multithread_queuer | 885ab83a269d63147b83aabd4ce59c3d3a9064bd | [
"MIT"
]
| null | null | null | Backup 13-5(13.05)/Main_Form.pas | gazzenger/multithread_queuer | 885ab83a269d63147b83aabd4ce59c3d3a9064bd | [
"MIT"
]
| null | null | null | unit Main_Form;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, ExtCtrls, Buttons;
const
TH_MESSAGE = WM_USER + 1; //Thread message
TH_FINISHED = 1; //Thread SubMessage : End of thread WParam = ThreadID
TH_NEWFILE = 2; //Thread Submessage : Started new file
TH_FOUND = 3; //Thread Submessage : Found searchString in File
TH_ERROR = 4; //Thread SubMessage : Error WParam = Error
MAX_THREADS = 4; //Max number of threads
ERROR_COULD_NOT_OPEN_FILE = 1; //Error file could not be opened
type
//Records for communication between Threads and MainForm, the pointer for the
//Record for found items, will occur when LParam = TH_FOUND, WParam will be PFoundRecord
PFoundRecord = ^TFoundRecord;
TFoundRecord = record
ThreadID: Cardinal;
Filename: string;
Position: Cardinal;
end;
//Record for new files, will occur when LParam = TH_NEWFILE, WParam will be PNewFileRecord
PNewFileRecord = ^TNewFileRecord;
TNewFileRecord = record
ThreadID: Cardinal;
Filename: string;
end;
//Record to hold the information from one thread
TThreadInfo = record
Active: Boolean;
ThreadHandle: integer;
ThreadId: Cardinal;
CurrentFile: string;
end;
//The Main form of the application
TMainForm = class(TForm)
btSearch: TButton;
OpenDialog: TOpenDialog;
edSearch: TEdit;
StringGrid: TStringGrid;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
append_btn: TButton;
Button2: TButton;
mvup_btn: TButton;
mvdwn_btn: TButton;
add_btn: TButton;
rmv_btn: TButton;
inlist_sg: TStringGrid;
outlist_sg: TStringGrid;
SpeedButton2: TSpeedButton;
Button3: TButton;
procedure btSearchClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edSearchChange(Sender: TObject);
procedure append_btnClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure InsertRow(Selected_SG: TObject; i: Integer; s: TStrings);
procedure add_btnClick(Sender: TObject);
procedure rmv_btnClick(Sender: TObject);
procedure mvup_btnClick(Sender: TObject);
procedure mvdwn_btnClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
private
ThreadInfo: array[0..4] of TThreadInfo; //Holds the information of the threads
procedure ThreadMessage(var Message: TMessage); message TH_MESSAGE;
function ThreadIDToIndex(ThreadID: Cardinal): integer; //MessageHandler
public
end;
var
MainForm: TMainForm;
implementation
var CriticalSection: TRTLCriticalSection; //Critical section protects the filelist
FileList: array[1..2] of TStrings; //List of filenames to be searched
InList_Header: TStrings;
SearchString: string; //String to be searched in every file
PauseThread: boolean;
FileListAccess: boolean;
{$R *.DFM}
//The threadFunction, this is actually the thread
function FindInFile(data: Pointer): Integer;
var FileStream: TFileStream;
Ch: char;
Current, Len: Integer;
FoundRecord: PFoundRecord;
NewFileRecord: PNewFileRecord;
Filename: string;
Search: string;
FilesDone: Boolean;
begin
Result := 0;
FilesDone := False;
while not FilesDone do //while there are still files
begin
Current := 1;
EnterCriticalSection(CriticalSection); //Try to catch the critical section
Search := SearchString; //Access the shared variables
//Are there still files available
if FileList[2].Count = 0 then
begin
//Leave the critical section, when there are no files left
LeaveCriticalSection(CriticalSection);
//Leave the while loop
break;
end
else
begin
while not (FileListAccess) do
begin
//nothing
end;
FileListAccess := false;
//Read the filename
Filename := FileList[2].Strings[0];
//Delete the file from the list
FileList[1].Delete(0);
FileList[2].Delete(0);
//Leave the critical section
LeaveCriticalSection(CriticalSection);
FileListAccess := true;
//Inform MainForm of New File
New(NewFileRecord);
NewFileRecord^.Filename := Filename;
NewFileRecord^.ThreadID := GetCurrentThreadID;
PostMessage(MainForm.Handle, TH_MESSAGE, TH_NEWFILE, Integer(NewFileRecord));
Len := Length(Search);
try
FileStream := TFileStream.Create(Filename, fmOpenRead or fmShareExclusive);
except
PostMessage(MainForm.Handle, TH_MESSAGE, TH_ERROR, ERROR_COULD_NOT_OPEN_FILE);
continue;
end;
//The search algorithm, pretty simple, the example is not about searching
while FileStream.Read(Ch, 1) = 1 do
begin
if Ch = Search[Current] then
begin
Inc(Current);
if Current > Len then
begin
//Found the search string, inform MainForm of our success
New(FoundRecord);
FoundRecord^.Filename := Filename;
FoundRecord^.Position := FileStream.Position;
FoundRecord^.ThreadID := GetCurrentThreadID;
PostMessage(MainForm.Handle, TH_MESSAGE, TH_FOUND, Integer(FoundRecord));
end;
end
else
begin
FileStream.Position := FileStream.Position - (Current - 1);
Current := 1;
end;
end;
FileStream.Free;
end;
end;
//All done inform MainForm of ending
PostMessage(MainForm.Handle, TH_MESSAGE, TH_FINISHED, GetCurrentThreadID);
end;
function TMainForm.ThreadIDToIndex(ThreadID: Cardinal): integer;
var Counter: integer;
begin
Result := -1;
for Counter := 0 to MAX_THREADS - 1 do //Search for the index of the thread
if ThreadInfo[Counter].ThreadID = ThreadID then
begin
Result := Counter;
break;
end;
end;
//functie voor het opvangen van de threadmessages
procedure TMainForm.ThreadMessage(var Message: TMessage);
var FoundRecord: PFoundRecord;
NewFileRecord: PNewFileRecord;
ThreadIndex: integer;
Counter: integer;
Ended: boolean;
begin
case Message.WParam of
TH_FINISHED:
begin
ThreadIndex := ThreadIDToIndex(Message.LParam);
if ThreadIndex = -1 then Exit; //Invalid threadID should never appear
CloseHandle(ThreadInfo[ThreadIndex].ThreadHandle); //Free the thread memoryspace
StringGrid.Cells[3, ThreadIndex + 1] := 'False'; //Update the stringgrid
Threadinfo[ThreadIndex].Active := False; //Update the ThreadInfo array
Ended := True;
for counter := 0 to MAX_THREADS - 1 do
if ThreadInfo[ThreadIndex].Active = True then
begin
Ended := False;
break;
end;
if Ended then btSearch.Enabled := True;
end;
TH_NEWFILE:
begin
NewFileRecord := PNewFileRecord(Message.LParam);
ThreadIndex := ThreadIDToIndex(NewFileRecord^.ThreadID);
if ThreadIndex = -1 then Exit; //Invalid threadID should never appear
StringGrid.Cells[2, ThreadIndex + 1] := ExtractFileName(NewFileRecord^.Filename) + ' (' + ExtractShortPathName(ExtractFilePath(NewFileRecord^.Filename)) + ')'; //Update StringGrid
ThreadInfo[ThreadIndex].CurrentFile := NewFileRecord^.Filename; //Update the ThreadInfo
while not (FileListAccess) do
begin
//Wait
end;
FileListAccess := false;
if FileList[1].Count > 0 then
begin
inlist_sg.RowCount := FileList[1].Count;
inlist_sg.Cols[0] := FileList[1];
inlist_sg.Cols[1] := FileList[2];
InsertRow(inlist_sg, 0, Inlist_header);
inlist_sg.FixedRows := 1;
end
else
begin
inlist_sg.RowCount := 2;
inlist_sg.Rows[1].Clear;
inlist_sg.Rows[0] := Inlist_header;
inlist_sg.FixedRows := 1;
end;
FileListAccess := true;
Dispose(NewFileRecord); //All information is used now free the pointer
end;
TH_FOUND:
begin
FoundRecord := PFoundRecord(Message.LParam);
ThreadIndex := ThreadIDToIndex(FoundRecord^.ThreadID);
if ThreadIndex = -1 then Exit; //Invalid threadID should never appear
if outlist_sg.RowCount = 2 then
begin
if outlist_sg.Cells[3, 1] <> '' then
outlist_sg.RowCount := outlist_sg.RowCount + 1;
end
else
outlist_sg.RowCount := outlist_sg.RowCount + 1;
outlist_sg.Cells[0, outlist_sg.RowCount - 1] := 'Project Name Here';
outlist_sg.Cells[1, outlist_sg.RowCount - 1] := FoundRecord^.Filename;
outlist_sg.Cells[3, outlist_sg.RowCount - 1] := 'Completed';
Dispose(FoundRecord); //All information is used now free the pointer
end;
TH_ERROR:
begin
ThreadIndex := ThreadIDToIndex(Message.LParam);
if ThreadIndex = -1 then Exit; //Invalid threadID should never appear
if outlist_sg.RowCount = 2 then
begin
if outlist_sg.Cells[3, 1] <> '' then
outlist_sg.RowCount := outlist_sg.RowCount + 1;
end
else
outlist_sg.RowCount := outlist_sg.RowCount + 1;
outlist_sg.Cells[0, outlist_sg.RowCount - 1] := 'Project Name Here';
outlist_sg.Cells[1, outlist_sg.RowCount - 1] := FoundRecord^.Filename;
outlist_sg.Cells[3, outlist_sg.RowCount - 1] := 'Error';
end;
end;
end;
procedure TMainForm.btSearchClick(Sender: TObject);
var Counter: Integer;
begin
inlist_sg.RowCount := 2;
outlist_sg.RowCount := 2;
inlist_sg.Rows[1].Clear;
outlist_sg.Rows[1].Clear;
PauseThread := false;
SearchString := EdSearch.Text;
if Opendialog.Execute then
begin
FileList[1].Clear;
FileList[2].Clear;
if OpenDialog.Files.Count > 0 then
begin
for Counter := 0 to OpenDialog.Files.Count - 1 do
begin
FileList[1].Add(Inttostr(Counter));
FileList[2].Add(OpenDialog.Files[Counter]);
end;
//Start all Threads
for Counter := 0 to MAX_THREADS - 1 do
begin
ThreadInfo[Counter].ThreadHandle :=
BeginThread(nil,
0,
@FindInFile,
nil,
0,
Threadinfo[Counter].ThreadId);
if ThreadInfo[Counter].ThreadHandle <> 0 then //Everything ok
begin
StringGrid.Cells[1, Counter + 1] := IntToStr(ThreadInfo[Counter].ThreadID);
StringGrid.Cells[3, Counter + 1] := 'True';
ThreadInfo[Counter].Active := True;
end;
end;
btSearch.Enabled := False;
end;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var x: byte;
begin
InitializeCriticalSection(CriticalSection);
FileList[1] := TStringList.Create;
FileList[2] := TStringList.Create;
Inlist_header := TStringList.Create;
StringGrid.Cells[1, 0] := 'ThreadID';
StringGrid.Cells[2, 0] := 'Handling File';
StringGrid.Cells[3, 0] := 'Active';
StringGrid.RowCount := MAX_THREADS + 1;
for x := 1 to MAX_THREADS do
StringGrid.Cells[0, x] := 'Thread ' + inttostr(x);
FileListAccess := true;
inlist_sg.Cells[0, 0] := 'Title';
inlist_sg.Cells[1, 0] := 'File Path';
outlist_sg.Cells[0, 0] := 'Title';
outlist_sg.Cells[1, 0] := 'File Path';
outlist_sg.Cells[2, 0] := 'Echo File';
outlist_sg.Cells[3, 0] := 'Status';
Inlist_header.Add('Title');
Inlist_header.Add('File Path');
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FileList[1].Free;
FileList[2].Free;
DeleteCriticalSection(CriticalSection);
end;
procedure TMainForm.edSearchChange(Sender: TObject);
begin
btSearch.Enabled := Length((Sender as TEdit).Text) > 0;
end;
procedure TMainForm.Button2Click(Sender: TObject);
var Counter: Integer;
FileCount: Integer;
AvailTh: array[0..MAX_THREADS - 1] of Integer;
AvailThCount: Integer;
begin
if PauseThread = false then
begin
PauseThread := true;
//Checkthreads and suspend
for Counter := 0 to MAX_THREADS - 1 do
begin
if ThreadInfo[Counter].Active then
begin
SuspendThread(ThreadInfo[Counter].ThreadHandle);
StringGrid.Cells[3, Counter + 1] := 'Suspended';
end;
end;
Button2.Caption := 'Resume Threads';
append_btn.Enabled := true;
add_btn.Enabled := true;
rmv_btn.Enabled := true;
mvup_btn.Enabled := true;
mvdwn_btn.Enabled := true;
end
else
begin
PauseThread := false;
FileCount := FileList[1].Count;
AvailThCount := 0;
for Counter := 0 to MAX_THREADS - 1 do
begin
if not (ThreadInfo[Counter].Active) then
begin
AvailTh[AvailThCount] := Counter;
AvailThCount := AvailThCount + 1;
end
end;
if (FileCount > 0) and (AvailThCount > 0) then
begin
//======================================================================
if AvailThCount > FileCount then AvailThCount := FileCount;
//Start all Threads
for Counter := 0 to AvailThCount - 1 do
begin
ThreadInfo[AvailTh[Counter]].ThreadHandle :=
BeginThread(nil,
0,
@FindInFile,
nil,
0,
Threadinfo[AvailTh[Counter]].ThreadId);
if ThreadInfo[AvailTh[Counter]].ThreadHandle <> 0 then //Everything ok
begin
StringGrid.Cells[1, AvailTh[Counter] + 1] := IntToStr(ThreadInfo[AvailTh[Counter]].ThreadID);
StringGrid.Cells[3, AvailTh[Counter] + 1] := 'True';
ThreadInfo[AvailTh[Counter]].Active := True;
end;
end;
//=======================================================================
end;
//Checkthreads and resume old threads
for Counter := 0 to MAX_THREADS - 1 do
begin
if ThreadInfo[Counter].Active then
begin
ResumeThread(ThreadInfo[Counter].ThreadHandle);
StringGrid.Cells[3, Counter + 1] := 'True';
end;
end;
Button2.Caption := 'Pause Threads';
append_btn.Enabled := false;
add_btn.Enabled := false;
rmv_btn.Enabled := false;
mvup_btn.Enabled := false;
mvdwn_btn.Enabled := false;
end;
end;
procedure TMainForm.InsertRow(Selected_SG: TObject; i: Integer; s: TStrings);
var r: Integer;
begin
with (Selected_SG as TStringGrid) do
begin
RowCount := RowCount + 1;
for r := RowCount downto i + 1 do begin
Rows[r] := Rows[r - 1];
end;
Rows[i] := s;
end;
end;
procedure TMainForm.append_btnClick(Sender: TObject);
begin
FileList[1].Append('3.1415');
FileList[2].Append('C:\Users\gary.namestnik\Desktop\test\test.txt');
inlist_sg.RowCount := FileList[1].Count;
inlist_sg.Cols[0] := FileList[1];
inlist_sg.Cols[1] := FileList[2];
InsertRow(inlist_sg, 0, Inlist_header);
inlist_sg.FixedRows := 1;
end;
procedure TMainForm.add_btnClick(Sender: TObject);
begin
FileList[1].Insert(inlist_sg.Row - 1, 'hello');
FileList[2].Insert(inlist_sg.Row - 1, 'C:\Users\gary.namestnik\Desktop\test\test.txt');
inlist_sg.RowCount := FileList[1].Count;
inlist_sg.Cols[0] := FileList[1];
inlist_sg.Cols[1] := FileList[2];
InsertRow(inlist_sg, 0, Inlist_header);
inlist_sg.FixedRows := 1;
end;
procedure TMainForm.rmv_btnClick(Sender: TObject);
var LastRowsSelected: boolean;
begin
if FileList[1].Count = 0 then exit;
LastRowsSelected := (inlist_sg.Row = inlist_sg.RowCount - 1) or (inlist_sg.Row = inlist_sg.RowCount - 2);
FileList[1].Delete(inlist_sg.Row - 1);
FileList[2].Delete(inlist_sg.Row - 1);
if FileList[1].Count > 0 then
begin
inlist_sg.RowCount := FileList[1].Count;
inlist_sg.Cols[0] := FileList[1];
inlist_sg.Cols[1] := FileList[2];
InsertRow(inlist_sg, 0, Inlist_header);
inlist_sg.FixedRows := 1;
end
else
begin
inlist_sg.RowCount := 2;
inlist_sg.Rows[1].Clear;
inlist_sg.Rows[0] := Inlist_header;
inlist_sg.FixedRows := 1;
end;
if LastRowsSelected and (inlist_sg.RowCount > 2) then
inlist_sg.Row := inlist_sg.Row + 1;
end;
procedure TMainForm.mvup_btnClick(Sender: TObject);
var LastRowsSelected: boolean;
begin
if inlist_sg.Row = 1 then exit;
LastRowsSelected := (inlist_sg.Row = inlist_sg.RowCount - 1);
FileList[1].Exchange(inlist_sg.Row - 1, inlist_sg.Row - 2);
FileList[2].Exchange(inlist_sg.Row - 1, inlist_sg.Row - 2);
inlist_sg.RowCount := FileList[1].Count;
inlist_sg.Cols[0] := FileList[1];
inlist_sg.Cols[1] := FileList[2];
InsertRow(inlist_sg, 0, Inlist_header);
inlist_sg.FixedRows := 1;
if not (LastRowsSelected) then
inlist_sg.Row := inlist_sg.row - 1;
end;
procedure TMainForm.mvdwn_btnClick(Sender: TObject);
begin
if inlist_sg.Row = inlist_sg.RowCount - 1 then exit;
FileList[1].Exchange(inlist_sg.Row - 1, inlist_sg.Row);
FileList[2].Exchange(inlist_sg.Row - 1, inlist_sg.Row);
inlist_sg.RowCount := FileList[1].Count;
inlist_sg.Cols[0] := FileList[1];
inlist_sg.Cols[1] := FileList[2];
InsertRow(inlist_sg, 0, Inlist_header);
inlist_sg.FixedRows := 1;
inlist_sg.Row := inlist_sg.Row + 1;
end;
procedure TMainForm.Button3Click(Sender: TObject);
var Counter: Integer;
begin
//Stop all Threads
for Counter := 0 to MAX_THREADS - 1 do
begin
TerminateThread(ThreadInfo[Counter].ThreadHandle, 0);
StringGrid.Cells[3, Counter + 1] := 'Terminated by user';
ThreadInfo[Counter].Active := False;
end;
end;
procedure TMainForm.SpeedButton2Click(Sender: TObject);
var i: integer;
begin
for i := 1 to outlist_sg.RowCount - 1
do
begin
outlist_sg.Rows[i].Clear;
outlist_sg.RowCount := 2;
end;
end;
end.
| 31.758319 | 188 | 0.637863 |
cd3e2a583ddeac8b80b504c74ff97298e00a8833 | 3,245 | dpr | Pascal | components/jcl/examples/common/unitversioning/UnitVersioningTestDLL.dpr | padcom/delcos | dc9e8ac8545c0e6c0b4e963d5baf0dc7d72d2bf0 | [
"Apache-2.0"
]
| 15 | 2016-08-24T07:32:49.000Z | 2021-11-16T11:25:00.000Z | components/jcl/examples/common/unitversioning/UnitVersioningTestDLL.dpr | CWBudde/delcos | 656384c43c2980990ea691e4e52752d718fb0277 | [
"Apache-2.0"
]
| 1 | 2016-08-24T19:00:34.000Z | 2016-08-25T19:02:14.000Z | components/jcl/examples/common/unitversioning/UnitVersioningTestDLL.dpr | CWBudde/delcos | 656384c43c2980990ea691e4e52752d718fb0277 | [
"Apache-2.0"
]
| 4 | 2016-10-16T17:52:49.000Z | 2020-11-24T11:36:05.000Z | {**************************************************************************************************}
{ }
{ 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 UnitVersioningTestDLL.dpr. }
{ }
{ The Initial Developer of the Original Code is Uwe Schuster. }
{ Portions created by Uwe Schuster are Copyright (C) Uwe Schuster. All rights reserved. }
{ }
{ Contributor(s): }
{ Uwe Schuster (uschuster) }
{ }
{**************************************************************************************************}
{ }
{ sample for TUnitVersioning }
{ }
{ Unit owner: Uwe Schuster }
{ }
{**************************************************************************************************}
// Last modified: $Date: 2009-08-10 17:00:08 +0200 (lun., 10 août 2009) $
library UnitVersioningTestDLL;
{$I jcl.inc}
uses
JclUnitVersioning;
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$Url:$';
Revision: '$Revision: 2936 $';
Date: '$Date: 2009-08-10 17:00:08 +0200 (lun., 10 août 2009) $';
LogPath: 'JCL\examples\common\unitversioning';
Extra: '';
Data: nil
);
begin
RegisterUnitVersion(HInstance, UnitVersioning);
end.
| 63.627451 | 101 | 0.286595 |
83039f59216168d1bc55b6f2229a718023b800d8 | 3,385 | dpr | Pascal | Examples/DUnitXExamples_XE4.dpr | lukaszsegiet/DUnitX | 808738bb8d27277b70f76e0b4f07f65e2cc108e2 | [
"Apache-2.0"
]
| 1 | 2021-03-26T02:37:32.000Z | 2021-03-26T02:37:32.000Z | Examples/DUnitXExamples_XE4.dpr | lukaszsegiet/DUnitX | 808738bb8d27277b70f76e0b4f07f65e2cc108e2 | [
"Apache-2.0"
]
| null | null | null | Examples/DUnitXExamples_XE4.dpr | lukaszsegiet/DUnitX | 808738bb8d27277b70f76e0b4f07f65e2cc108e2 | [
"Apache-2.0"
]
| null | null | null | program DUnitXExamples_XE4;
{$APPTYPE CONSOLE}
uses
SysUtils,
DUnitX.Examples.General in 'DUnitX.Examples.General.pas',
DUnitX.Loggers.Text in '..\DUnitX.Loggers.Text.pas',
DUnitX.Loggers.XML.NUnit in '..\DUnitX.Loggers.XML.NUnit.pas',
DUnitX.Loggers.XML.xUnit in '..\DUnitX.Loggers.XML.xUnit.pas',
DUnitX.MacOS.Console in '..\DUnitX.MacOS.Console.pas',
DUnitX.Test in '..\DUnitX.Test.pas',
DUnitX.TestFixture in '..\DUnitX.TestFixture.pas',
DUnitX.TestFramework in '..\DUnitX.TestFramework.pas',
DUnitX.TestResult in '..\DUnitX.TestResult.pas',
DUnitX.RunResults in '..\DUnitX.RunResults.pas',
DUnitX.TestRunner in '..\DUnitX.TestRunner.pas',
DUnitX.Utils in '..\DUnitX.Utils.pas',
DUnitX.Utils.XML in '..\DUnitX.Utils.XML.pas',
DUnitX.WeakReference in '..\DUnitX.WeakReference.pas',
DUnitX.Windows.Console in '..\DUnitX.Windows.Console.pas',
DUnitX.StackTrace.EurekaLog7 in '..\DUnitX.StackTrace.EurekaLog7.pas',
NonNamespacedExample in 'NonNamespacedExample.pas',
DUnitX.Examples.EqualityAsserts in 'DUnitX.Examples.EqualityAsserts.pas',
DUnitX.Loggers.Null in '..\DUnitX.Loggers.Null.pas',
DUnitX.MemoryLeakMonitor.Default in '..\DUnitX.MemoryLeakMonitor.Default.pas',
DUnitX.AutoDetect.Console in '..\DUnitX.AutoDetect.Console.pas',
DUnitX.ConsoleWriter.Base in '..\DUnitX.ConsoleWriter.Base.pas',
DUnitX.DUnitCompatibility in '..\DUnitX.DUnitCompatibility.pas',
DUnitX.Extensibility in '..\DUnitX.Extensibility.pas',
DUnitX.Extensibility.PluginManager in '..\DUnitX.Extensibility.PluginManager.pas',
DUnitX.FixtureProviderPlugin in '..\DUnitX.FixtureProviderPlugin.pas',
DUnitX.FixtureResult in '..\DUnitX.FixtureResult.pas',
DUnitX.Generics in '..\DUnitX.Generics.pas',
DUnitX.InternalInterfaces in '..\DUnitX.InternalInterfaces.pas',
DUnitX.IoC in '..\DUnitX.IoC.pas',
DUnitX.Loggers.Console in '..\DUnitX.Loggers.Console.pas',
DUnitX.CommandLine.OptionDef in '..\DUnitX.CommandLine.OptionDef.pas',
DUnitX.CommandLine.Options in '..\DUnitX.CommandLine.Options.pas',
DUnitX.CommandLine.Parser in '..\DUnitX.CommandLine.Parser.pas',
DUnitX.OptionsDefinition in '..\DUnitX.OptionsDefinition.pas',
DUnitX.Banner in '..\DUnitX.Banner.pas',
DUnitX.Filters in '..\DUnitX.Filters.pas';
var
runner : ITestRunner;
results : IRunResults;
logger : ITestLogger;
nunitLogger : ITestLogger;
begin
try
TDUnitX.CheckCommandLine;
//Create the runner
runner := TDUnitX.CreateRunner;
runner.UseRTTI := True;
//tell the runner how we will log things
if TDUnitX.Options.ConsoleMode <> TDunitXConsoleMode.Off then
begin
logger := TDUnitXConsoleLogger.Create(TDUnitX.Options.ConsoleMode = TDunitXConsoleMode.Quiet);
runner.AddLogger(logger);
end;
nunitLogger := TDUnitXXMLNUnitFileLogger.Create(TDUnitX.Options.XMLOutputFile);
runner.AddLogger(nunitLogger);
//Run tests
results := runner.Execute;
if not results.AllPassed then
System.ExitCode := EXIT_ERRORS;
{$IFNDEF CI}
if TDUnitX.Options.ExitBehavior = TDUnitXExitBehavior.Pause then
begin
System.Write('Done.. press <Enter> key to quit.');
System.Readln;
end;
{$ENDIF}
except
on E: Exception do
System.Writeln(E.ClassName, ': ', E.Message);
end;
end.
| 39.360465 | 101 | 0.712555 |
Subsets and Splits