text stringlengths 14 6.51M |
|---|
// parses Delphi code into a token collection
// Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html)
// Contributors: Thomas Mueller (http://www.dummzeuch.de)
// Jens Borrisholt (Jens@borrisholt.dk) - Cleaning up the code, and making it aware of several language features
unit GX_CodeFormatterParser;
{$I GX_CondDefine.inc}
interface
uses
SysUtils,
Classes,
GX_GenericUtils,
GX_CodeFormatterTokenList,
GX_CodeFormatterTypes,
GX_CodeFormatterSettings,
GX_CodeFormatterTokens;
type
TIdentifiersList = class(TStringList)
private
FSettings: TCodeFormatterSettings;
public
constructor Create(const _Settings: TCodeFormatterSettings); reintroduce;
function AddIdentifier(const _s: TGXUnicodeString): TGXUnicodeString;
end;
type
{: usage:
Tokens := TCodeFormatterParser.Execute(Text, Settings); }
TCodeFormatterParser = class
private
FSpacePerIndent: Integer;
FStartCommentOut: TGXUnicodeString;
FEndCommentOut: TGXUnicodeString;
private
FTokens: TPascalTokenList;
FReadingAsm: Boolean;
FAsmComment: TWordType;
FPrevLine: TLineFeed;
FPrevType: TWordType;
FLeftPointBracket: Integer;
FIdentifiers: TIdentifiersList;
{: ReadAsm does very simple parsing only to find comments because this
influences finding the matching "end". No formatting is done
later to asm code }
procedure ReadAsm(var _Buff: PGXUnicodeChar);
function ReadHalfComment(out _Dest: TGXUnicodeString; var _Source: PGXUnicodeChar): TWordType;
function ReadWord(out _Dest: TGXUnicodeString; var _Source: PGXUnicodeChar): TWordType;
{: Adds a single line of text to the parse tree }
procedure AddLine(_Buff: PGXUnicodeChar);
procedure DoExecute(_Text: TGXUnicodeStringList);
public
constructor Create(_Settings: TCodeFormatterSettings);
destructor Destroy; override;
function DetachTokens: TPascalTokenList;
{: parses the text and returns a parse tree }
class function Execute(_Text: TGXUnicodeStringList; _Settings: TCodeFormatterSettings): TPascalTokenList;
end;
implementation
uses
GX_CodeFormatterUnicode;
class function TCodeFormatterParser.Execute(_Text: TGXUnicodeStringList; _Settings: TCodeFormatterSettings): TPascalTokenList;
var
Parser: TCodeFormatterParser;
begin
Parser := TCodeFormatterParser.Create(_Settings);
try
Parser.DoExecute(_Text);
Result := Parser.DetachTokens;
finally
Parser.Free;
end;
end;
constructor TCodeFormatterParser.Create(_Settings: TCodeFormatterSettings);
begin
inherited Create;
FSpacePerIndent := _Settings.SpacePerIndent;
FStartCommentOut := _Settings.StartCommentOut;
FEndCommentOut := _Settings.EndCommentOut;
FLeftPointBracket := 0;
FReadingAsm := False;
FPrevLine := nil;
FPrevType := wtNothing;
FTokens := TPascalTokenList.Create;
FIdentifiers := TIdentifiersList.Create(_Settings);
end;
destructor TCodeFormatterParser.Destroy;
begin
FreeAndNil(FTokens);
FreeAndNil(FIdentifiers);
inherited;
end;
function TCodeFormatterParser.DetachTokens: TPascalTokenList;
begin
Result := FTokens;
FTokens := nil;
end;
procedure TCodeFormatterParser.DoExecute(_Text: TGXUnicodeStringList);
var
i: Integer;
s: TGXUnicodeString;
Buff: PGXUnicodeChar;
begin
for i := 0 to _Text.Count - 1 do begin
s := _Text[i];
Buff := PGXUnicodeChar(s);
AddLine(Buff);
end;
end;
procedure TCodeFormatterParser.AddLine(_Buff: PGXUnicodeChar);
var
s: TGXUnicodeString;
begin
FPrevLine := TLineFeed.Create(0, FSpacePerIndent);
FTokens.Add(FPrevLine);
if not Assigned(_Buff) or (_Buff^ = #0) then
Exit;
if FReadingAsm then
ReadAsm(_Buff);
while (_Buff^ <> #0) do begin
if FPrevType in [wtHalfComment, wtHalfStarComment, wtHalfOutComment] then
FPrevType := ReadHalfComment(s, _Buff)
else
FPrevType := ReadWord(s, _Buff);
if FPrevType = wtSpaces then begin
if (FPrevLine <> nil) and (FPrevLine.NoOfSpaces = 0) then begin
FPrevLine.NoOfSpaces := Length(s);
FPrevLine.OldNoOfSpaces := FPrevLine.NoOfSpaces;
end;
end else begin
FTokens.Add(TExpression.Create(FPrevType, s));
if FReadingAsm and (_Buff^ <> #0) then
ReadAsm(_Buff);
end;
end;
if FTokens.Count >= MaxCollectionSize - 100 then
raise ECodeFormatter.Create('File to large to reformat')
end;
function PCharPlus(_p: PGXUnicodeChar; _Offset: integer): PGXUnicodeChar;
begin
Result := _p;
while _Offset > 0 do begin
Inc(Result);
Dec(_Offset);
end;
while _Offset < 0 do begin
Dec(Result);
Inc(_Offset);
end;
end;
function PCharDiff(_p, _q: PGXUnicodeChar): integer;
begin
Result := (Integer(_p) - Integer(_q)) div SizeOf(_p^);
end;
procedure TCodeFormatterParser.ReadAsm(var _Buff: PGXUnicodeChar);
var
P: PGXUnicodeChar;
FirstNonWhitespace: PGXUnicodeChar;
s: TGXUnicodeString;
begin
P := _Buff;
FirstNonWhitespace := _Buff;
while CharInSet(FirstNonWhitespace^, [Tab, Space]) do
Inc(FirstNonWhitespace);
while p^ <> #0 do begin
case FAsmComment of
wtHalfComment: begin
if P^ = '}' then
FAsmComment := wtWord;
Inc(P);
end;
wtHalfStarComment: begin
if (P^ = '*') and (PCharPlus(P, 1)^ = ')') then begin
FAsmComment := wtWord;
Inc(P);
end;
Inc(P);
end;
else // case
if ((P = _Buff) or CharInSet(PCharPlus(p, -1)^, [' ', Tab]))
and (StrLIComp(P, 'end', 3) = 0)
and CharInSet(PCharPlus(P, 3)^, [#0, ';', ' ', Tab]) then begin // 'end' of assembler
FReadingAsm := False;
if FirstNonWhitespace <> P then begin
SetString(s, FirstNonWhitespace, PCharDiff(p, FirstNonWhitespace) - 1);
FTokens.Add(TExpression.Create(wtAsm, s));
end;
_Buff := P;
Exit;
end else if P^ = '{' then begin // '{' comment
Inc(P);
while (P^ <> '}') and (P^ <> #0) do
Inc(P);
if p^ = #0 then
FAsmComment := wtHalfComment
else
Inc(P);
end else if (P^ = '(') and (PCharPlus(P, 1)^ = '*') then begin // '(*' comment
Inc(p, 2);
while (P^ <> #0) and ((P^ <> '*') or (PCharPlus(P, 1)^ <> ')')) do
Inc(P);
if p^ = #0 then
FAsmComment := wtHalfStarComment
else
Inc(P, 2);
end else if (P^ = '/') and (PCharPlus(P, 1)^ = '/') then begin // '//' comment
Inc(p, 2);
while P^ <> #0 do begin
Inc(P);
end
end else
Inc(P);
end; // case
end; // while
SetString(s, _Buff, StrLen(_Buff));
FTokens.Add(TExpression.Create(wtAsm, s));
_Buff := P;
end;
function TCodeFormatterParser.ReadWord(out _Dest: TGXUnicodeString; var _Source: PGXUnicodeChar): TWordType;
const
IdentifierTerminators = [
'+', '-', '*', '/', '=',
'(', ')', '[', ']', '{', '}',
',', ';', ':', '.',
'<', '>', '@', '^',
Space, '''', Tab, #0];
{ TODO -otwm -cfixme : This allows strings like #a which is wrong, but there is no easy way to fix it. }
StringControlChars = ['0'..'9', 'a'..'z', 'A'..'Z', '#', '^', '$'];
var
P: PGXUnicodeChar;
{: Reads a string literal, on exit p points behind the last character of the string
@returns either wtString or wtErrorString }
function ReadString: TWordType;
begin
Result := wtString;
while True do begin
Inc(P);
case p^ of
#0: begin
// unterminated string (invalid Pascal code but we must deal with it anyway)
Result := wtErrorString;
Exit;
end;
#39: {// '} begin // we found either a quoted single quote or the end quote
Inc(p);
case p^ of
#39: begin // skip quoted single quote
; // do nothing, we just skipped it
end;
'#', '^': begin
// todo: this is not really correct code:
// 'hello'#^523 is not a valid string literal
while CharInSet(P^, StringControlChars) do
Inc(P);
if P^ <> #39 then begin
// we found the end of the string
Exit;
end;
end;
else
// we found the ending quote
Exit;
end;
end;
end; // case
end;
// we never get here, exiting the function is done via several Exit statements
end;
{: Reads an identifier, on exit p points behind the last character of the identifier }
procedure ReadIdentifier;
begin
Result := wtWord;
{ TODO -otwm -ccheck : Shouldn't that rather check for valid identifiers?
Note that Delphi 2005 allows non ascii characters for identifiers, e.g. "Müller" is a valid
identifier! }
while not CharInSet(p^, IdentifierTerminators) do
Inc(P);
end;
// this handles the formatting enabling / disabling strings
// default: '{(*}' ... '{*)}'
function CheckDisableComments(out AResult: TWordType): Boolean;
var
Len: Integer;
begin
Result := (FStartCommentOut <> '') and (FEndCommentOut <> '');
if not Result then
Exit;
Len := Length(FStartCommentOut);
Result := StrLIComp(P, FStartCommentOut, Len) = 0;
if not Result then
Exit;
AResult := wtHalfOutComment;
Inc(P, Len);
Len := Length(FEndCommentOut);
while P^ <> #0 do begin
if StrLIComp(P, FEndCommentOut, Len) = 0 then begin
Inc(P, Len - 1);
AResult := wtFullOutComment;
Break;
end;
Inc(P);
end;
end;
begin
P := _Source;
if CharInSet(P^, [Tab, Space]) then begin
Result := wtSpaces;
while CharInSet(P^, [Tab, Space]) do
Inc(P);
end else if CheckDisableComments(Result) then begin
end else
case P^ of
'{': begin
Result := wtHalfComment;
while not CharInSet(P^, ['}', #0]) do
Inc(P);
if (P^ = '}') then begin
Result := wtFullComment;
if PCharPlus(_Source, 1)^ = '$' then
Result := wtCompDirective;
Inc(p);
end;
end;
#39: begin
// single quote '
Result := ReadString;
end;
'^': begin // string starting with ^A or so or the ^ operator
Inc(p);
if CharInSet(P^, ['a'..'z', 'A'..'Z']) and CharInSet(PCharPlus(P, 1)^, [#39, '^', '#']) then begin
Result := wtString;
while CharInSet(P^, StringControlChars) do
Inc(P);
if P^ = #39 then
Result := ReadString;
end else begin
Result := wtOperator;
end;
end;
'+', '-', '*', '=',
')', '[', ']', '}',
',', ';',
'@': begin
Result := wtOperator;
Inc(p);
end;
'<': begin
Result := wtOperator;
Inc(p);
if CharInSet(p^, ['=', '>']) then // <= or <>
Inc(p);
end;
'>', ':': begin
Result := wtOperator;
Inc(p);
if p^ = '=' then // >= or :=
Inc(P);
end;
'.': begin // .. or .) { TODO -otwm -ccheck : What about .9 for a float? It works, but why? }
Result := wtOperator;
Inc(p);
case p^ of
'.':
Inc(P);
')': begin
Dec(FLeftPointBracket);
Inc(P);
end;
end;
end;
'(': begin // (. or (*
Result := wtOperator;
Inc(p);
case p^ of
'.': begin // (. (has precendence over .9, so '(.9)' is an error)
Inc(FLeftPointBracket);
Inc(P);
end;
'*': begin
Inc(p);
Result := wtHalfStarComment;
while (P^ <> #0) and ((P^ <> '*') or (PCharPlus(P, 1)^ <> ')')) do
Inc(P);
if p^ <> #0 then begin
Inc(P);
Result := wtFullComment;
if PCharPlus(_Source, 2)^ = '$' then
Result := wtCompDirective;
Inc(p);
end;
end;
end; // case
end;
'/': begin // / or //
if (PCharPlus(P, 1)^ = '/') then begin
Result := wtFullComment;
while P^ <> #0 do
Inc(P);
end else begin
Result := wtOperator;
Inc(p);
end;
end;
'$': begin
Result := wtHexNumber;
Inc(P);
while CharInSet(P^, ['0'..'9', 'A'..'F', 'a'..'f']) do
Inc(P);
end;
'#': begin
{ TODO -otwm -cfixme :
This is for upper casing hex numbers, but it is rather ugly.
It also misses those embedded in strings 'bla'#1d'blub' and will change #10^j to #10^J }
Result := wtHexNumber;
while CharInSet(P^, StringControlChars) do
Inc(P);
if P^ = #39 then begin
// single quote
Result := ReadString;
end;
end;
'0'..'9': begin
Result := wtNumber;
while CharInSet(P^, ['0'..'9', '.']) and not (StrLComp(P, '..', 2) = 0)
and not ((FLeftPointBracket > 0) and (StrLComp(P, '.)', 2) = 0)) do
Inc(P);
if StrLIComp(P, 'E', 1) = 0 then
if CharInSet(PCharPlus(P, 1)^, ['0'..'9', '-', '+']) then begin
Inc(P, 2);
while CharInSet(P^, ['0'..'9']) do
Inc(P);
end;
end;
else
ReadIdentifier;
end;
SetString(_Dest, _Source, PCharDiff(P, _Source));
// This is for changing the casing of identifiers without adding them to
// the global list.
if (Result <> wtString) and (not FReadingAsm) then
_Dest := FIdentifiers.AddIdentifier(_Dest);
if SameText(_Dest, AnsiString('asm')) then begin
FReadingAsm := True;
FAsmComment := wtWord;
end;
if (P^ = #0) then
_Source := P
else begin
if CharInSet(P^, [Tab, Space]) then
Inc(P);
_Source := P;
end;
end;
function TCodeFormatterParser.ReadHalfComment(out _Dest: TGXUnicodeString; var _Source: PGXUnicodeChar): TWordType;
var
Len: Integer;
P: PGXUnicodeChar;
FirstNonSpace: PGXUnicodeChar;
EndComment: TGXUnicodeString;
EndCommentType: TWordType;
begin
P := _Source;
FirstNonSpace := _Source;
while CharInSet(P^, [Tab, Space]) do
Inc(P);
if (FPrevLine <> nil) and (FPrevLine.NoOfSpaces = 0) then begin
FPrevLine.NoOfSpaces := PCharDiff(P, _Source);
FPrevLine.OldNoOfSpaces := PCharDiff(P, _Source);
FirstNonSpace := p;
end;
Result := FPrevType;
case FPrevType of
wtHalfComment: begin
EndComment := '}';
EndCommentType := wtFullComment;
end;
wtHalfStarComment: begin
EndComment := '*)';
EndCommentType := wtFullComment;
end;
wtHalfOutComment: begin
EndComment := FEndCommentOut;
EndCommentType := wtFullOutComment;
end;
else
raise ECodeFormatter.Create('internal error: ReadHalfComment should only be called if FPrevType in [wtHalfComment, wtHalfStarComment, wtHalfOutComment]');
end;
Len := Length(EndComment);
while (P^ <> #0) do begin
if StrLIComp(P, EndComment, Len) = 0 then begin
Result := EndCommentType;
Inc(P, Len);
Break;
end;
Inc(P);
end;
SetString(_Dest, FirstNonSpace, PCharDiff(P, FirstNonSpace));
_Source := P;
end;
{ TIdentifiersList }
function TIdentifiersList.AddIdentifier(const _s: TGXUnicodeString): TGXUnicodeString;
var
WordIndex : Integer;
begin
case FSettings.IdentifiersCase of
rfLowerCase:
Result := LowerCase(_s);
rfUpperCase:
Result := UpperCase(_s);
rfFirstUp: begin
Result := UpperCase(Copy(_s, 1, 1));
Result := Result + LowerCase(Copy(_s, 2, Length(_s) - 1));
end;
rfUnchanged:
Result := _s;
rfFirstOccurrence:
if not FSettings.CapNames.Find(_s, WordIndex) then
Result := Strings[Add(_s)]
else
Result := FSettings.CapNames[WordIndex];
end;
end;
constructor TIdentifiersList.Create(const _Settings: TCodeFormatterSettings);
begin
inherited Create;
FSettings := _Settings;
CaseSensitive := False;
Sorted := True;
Duplicates := dupIgnore;
end;
end.
|
unit rxDateRangeEditUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, types, Controls, Buttons, StdCtrls, Spin;
type
TRxDateRangeEditOption = (reoMonth, reoQuarter, reoHalfYear);
TRxDateRangeEditOptions = set of TRxDateRangeEditOption;
type
{ TRxCustomDateRangeEdit }
TRxCustomDateRangeEdit = class(TCustomControl)
private
FFlat: Boolean;
FOnEditChange: TNotifyEvent;
FOnEditClick: TNotifyEvent;
FOnEditEnter: TNotifyEvent;
FOnEditExit: TNotifyEvent;
FOptions: TRxDateRangeEditOptions;
FsbDecYear: TSpeedButton;
FsbDecMonth: TSpeedButton;
FsbIncYear: TSpeedButton;
FsbIncMonth: TSpeedButton;
FEditYear: TSpinEdit;
FEditMonth: TComboBox;
procedure DoIncMonth(Sender: TObject);
procedure DoIncYear(Sender: TObject);
procedure DoDecMonth(Sender: TObject);
procedure DoDecYear(Sender: TObject);
function GetHalfYear: word;
function GetMonth: word;
function GetPeriod: TDateTime;
function GetPeriodEnd: TDateTime;
function GetQuarter: word;
function GetYear: word;
procedure SetFlat(AValue: Boolean);
procedure SetHalfYear(AValue: word);
procedure SetMonth(AValue: word);
procedure SetOptions(AValue: TRxDateRangeEditOptions);
procedure SetPeriod(AValue: TDateTime);
procedure SetQuarter(AValue: word);
procedure SetYear(AValue: word);
procedure InternalOnEditChange(Sender: TObject);
procedure InternalOnEditClick(Sender: TObject);
procedure InternalOnEditEnter(Sender: TObject);
procedure InternalOnEditExit(Sender: TObject);
protected
class function GetControlClassDefaultSize: TSize; override;
procedure FillMonthNames;
procedure SetAutoSize(AValue: Boolean); override;
procedure EditChange; virtual;
procedure EditClick; virtual;
procedure EditEnter; virtual;
procedure EditExit; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Quarter:word read GetQuarter write SetQuarter;
property HalfYear:word read GetHalfYear write SetHalfYear;
property Flat: Boolean read FFlat write SetFlat default False;
property Year:word read GetYear write SetYear;
property Month:word read GetMonth write SetMonth;
property Period:TDateTime read GetPeriod write SetPeriod;
property PeriodEnd:TDateTime read GetPeriodEnd;
property Options:TRxDateRangeEditOptions read FOptions write SetOptions default [reoMonth];
property OnChange: TNotifyEvent read FOnEditChange write FOnEditChange;
property OnClick: TNotifyEvent read FOnEditClick write FOnEditClick;
property OnEnter: TNotifyEvent read FOnEditEnter write FOnEditEnter;
property OnExit: TNotifyEvent read FOnEditExit write FOnEditExit;
end;
type
TRxDateRangeEdit = class(TRxCustomDateRangeEdit)
published
property Align;
property Anchors;
property Autosize default True;
property BiDiMode;
property BorderSpacing;
property BorderStyle default bsNone;
property Color;
property Constraints;
property Cursor;
property Enabled;
property Flat;
property Hint;
property Month;
property Options;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Year;
property OnChange;
property OnClick;
property OnEnter;
property OnExit;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
end;
implementation
uses dateutil, rxconst;
{ TRxCustomDateRangeEdit }
procedure TRxCustomDateRangeEdit.DoIncMonth(Sender: TObject);
var
i:integer;
begin
if FEditMonth.ItemIndex>=0 then
begin
i:=PtrInt(FEditMonth.Items.Objects[FEditMonth.ItemIndex]);
if I in [17, 18] then
begin
if i = 18 then
begin
i:=17;
Year:=Year + 1;
end
else
i:=18;
end
else
if i in [13..16] then
begin
inc(i);
if i> 16 then
begin
i:=13;
Year:=Year + 1;
end;
end
else
begin
inc(i);
if i > 12 then
begin
i:=1;
Year:=Year + 1;
end;
end;
FEditMonth.ItemIndex := i - 1;
end
else
FEditMonth.ItemIndex := 0;
end;
procedure TRxCustomDateRangeEdit.DoIncYear(Sender: TObject);
begin
FEditYear.Value:=FEditYear.Value + 1;
end;
procedure TRxCustomDateRangeEdit.DoDecMonth(Sender: TObject);
var
i:integer;
begin
if FEditMonth.ItemIndex>=0 then
begin
i:=PtrInt(FEditMonth.Items.Objects[FEditMonth.ItemIndex]);
if I in [17, 18] then
begin
if i = 18 then
begin
i:=17;
Year:=Year - 1;
end
else
i:=18;
end
else
if i in [13..16] then
begin
Dec(i);
if i> 13 then
begin
i:=16;
Year:=Year - 1;
end;
end
else
begin
Dec(i);
if i < 1 then
begin
i:=12;
Year:=Year - 1;
end;
end;
FEditMonth.ItemIndex := i - 1;
end
else
FEditMonth.ItemIndex := 0;
end;
procedure TRxCustomDateRangeEdit.DoDecYear(Sender: TObject);
begin
FEditYear.Value:=FEditYear.Value - 1;
end;
function TRxCustomDateRangeEdit.GetHalfYear: word;
var
i:integer;
begin
Result:=0;
if reoHalfYear in FOptions then
begin
i:=PtrInt(FEditMonth.Items.Objects[FEditMonth.ItemIndex]);
if i in [17..18] then
Result:=i - 16;
end
end;
function TRxCustomDateRangeEdit.GetMonth: word;
var
i:integer;
begin
Result:=0;
if (reoMonth in FOptions) or (FOptions = []) then
begin
i:=PtrInt(FEditMonth.Items.Objects[FEditMonth.ItemIndex]);
if i in [1..12] then
Result:=i;
end
end;
function TRxCustomDateRangeEdit.GetPeriod: TDateTime;
begin
Result:=EncodeDate(Year, Month, 1);
end;
function TRxCustomDateRangeEdit.GetPeriodEnd: TDateTime;
begin
Result:=EncodeDate(Year, Month, DaysPerMonth(Year, Month));
end;
function TRxCustomDateRangeEdit.GetQuarter: word;
var
i:integer;
begin
Result:=0;
if reoQuarter in FOptions then
begin
i:=PtrInt(FEditMonth.Items.Objects[FEditMonth.ItemIndex]);
if i in [13..16] then
Result:=i - 12;
end
end;
function TRxCustomDateRangeEdit.GetYear: word;
begin
Result:=FEditYear.Value;
end;
procedure TRxCustomDateRangeEdit.SetFlat(AValue: Boolean);
begin
if FFlat=AValue then Exit;
FFlat:=AValue;
FsbDecMonth.Flat:=FFlat;
FsbDecYear.Flat:=FFlat;
FsbIncMonth.Flat:=FFlat;
FsbIncYear.Flat:=FFlat;
end;
procedure TRxCustomDateRangeEdit.SetHalfYear(AValue: word);
begin
end;
procedure TRxCustomDateRangeEdit.SetMonth(AValue: word);
begin
if (AValue>0) and (AValue < 13) then
FEditMonth.ItemIndex:=AValue-1;
end;
procedure TRxCustomDateRangeEdit.SetOptions(AValue: TRxDateRangeEditOptions);
begin
if FOptions=AValue then Exit;
FOptions:=AValue;
FillMonthNames;
end;
procedure TRxCustomDateRangeEdit.SetPeriod(AValue: TDateTime);
var
Y, M, D: word;
begin
DecodeDate(AValue, Y, M, D);
FEditMonth.ItemIndex:=M-1;
FEditYear.Value:=Y;
end;
procedure TRxCustomDateRangeEdit.SetQuarter(AValue: word);
begin
end;
procedure TRxCustomDateRangeEdit.SetYear(AValue: word);
begin
FEditYear.Value:=AValue;
end;
procedure TRxCustomDateRangeEdit.InternalOnEditChange(Sender: TObject);
begin
EditChange;
end;
procedure TRxCustomDateRangeEdit.InternalOnEditClick(Sender: TObject);
begin
EditClick;
end;
procedure TRxCustomDateRangeEdit.InternalOnEditEnter(Sender: TObject);
begin
EditEnter;
end;
procedure TRxCustomDateRangeEdit.InternalOnEditExit(Sender: TObject);
begin
EditExit;
end;
class function TRxCustomDateRangeEdit.GetControlClassDefaultSize: TSize;
begin
Result.CX := 80 + 70 + 23 * 4;
Result.CY := 23;
end;
procedure TRxCustomDateRangeEdit.FillMonthNames;
var
i, k: Integer;
begin
FEditMonth.Items.BeginUpdate;
FEditMonth.Items.Clear;
if (reoMonth in FOptions) or (FOptions = []) then
begin
for i:=1 to 12 do
begin
k:=FEditMonth.Items.Add(DefaultFormatSettings.LongMonthNames[i]);
FEditMonth.Items.Objects[K]:=TObject(Pointer(i));
end;
end;
if (reoQuarter in FOptions) or (FOptions = []) then
begin
k:=FEditMonth.Items.Add(sFirstQuarter);
FEditMonth.Items.Objects[K]:=TObject(Pointer(13));
k:=FEditMonth.Items.Add(sSecondQuarter);
FEditMonth.Items.Objects[K]:=TObject(Pointer(14));
k:=FEditMonth.Items.Add(sThirdQuarter);
FEditMonth.Items.Objects[K]:=TObject(Pointer(15));
k:=FEditMonth.Items.Add(sFourthQuarter);
FEditMonth.Items.Objects[K]:=TObject(Pointer(16));
end;
if (reoHalfYear in FOptions) or (FOptions = []) then
begin
k:=FEditMonth.Items.Add(sFirstHalfOfYear);
FEditMonth.Items.Objects[K]:=TObject(Pointer(17));
k:=FEditMonth.Items.Add(sSecondHalfOfYear);
FEditMonth.Items.Objects[K]:=TObject(Pointer(18));
end;
FEditMonth.ItemIndex:=0;
FEditMonth.Items.EndUpdate;
end;
procedure TRxCustomDateRangeEdit.SetAutoSize(AValue: Boolean);
begin
if AutoSize = AValue then
Exit;
inherited SetAutosize(AValue);
FEditMonth.AutoSize := AValue;
FEditYear.AutoSize := AValue;
end;
procedure TRxCustomDateRangeEdit.EditChange;
begin
if Assigned(FOnEditChange) then FOnEditChange(Self);
end;
procedure TRxCustomDateRangeEdit.EditClick;
begin
if Assigned(FOnEditClick) then FOnEditClick(Self);
end;
procedure TRxCustomDateRangeEdit.EditEnter;
begin
if Assigned(FOnEditEnter) then FOnEditEnter(Self);
end;
procedure TRxCustomDateRangeEdit.EditExit;
begin
if Assigned(FOnEditExit) then FOnEditExit(Self);
end;
constructor TRxCustomDateRangeEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOptions:=[reoMonth];
FEditYear:=TSpinEdit.Create(Self);
FEditMonth:=TComboBox.Create(Self);
FEditMonth.Style:=csDropDownList;
FEditMonth.DropDownCount:=12;
FEditYear.Width:=70;
FEditMonth.Width:=100;
FsbDecYear:=TSpeedButton.Create(Self);
FsbDecMonth:=TSpeedButton.Create(Self);
FsbIncYear:=TSpeedButton.Create(Self);
FsbIncMonth:=TSpeedButton.Create(Self);
FsbDecYear.OnClick:=@DoDecYear;
FsbDecMonth.OnClick:=@DoDecMonth;
FsbIncYear.OnClick:=@DoIncYear;
FsbIncMonth.OnClick:=@DoIncMonth;
FEditYear.Parent:=Self;
FsbDecYear.Parent:=Self;
FsbDecMonth.Parent:=Self;
FsbIncYear.Parent:=Self;
FsbIncMonth.Parent:=Self;
FEditMonth.Parent:=Self;
FsbDecYear.Caption:='<<';
FsbDecMonth.Caption:='<';
FsbIncYear.Caption:='>>';
FsbIncMonth.Caption:='>';
FsbDecYear.Left:=0;
FsbDecMonth.Left:=23;
FEditMonth.Left:=46;
FEditYear.Left:=126;
FsbIncMonth.Left:=206;
FsbIncYear.Left:=229;
ControlStyle := ControlStyle + [csNoFocus];
FsbDecYear.Align:=alLeft;
FsbDecMonth.Align:=alLeft;
FsbIncYear.Align:=alRight;
FsbIncMonth.Align:=alRight;
FEditYear.Align:=alRight;
FEditMonth.Align:=alClient;
FEditYear.MaxValue:=9999;
with GetControlClassDefaultSize do
SetInitialBounds(0, 0, CX, CY);
FillMonthNames;
SetPeriod(Now);
AutoSize := True;
FEditMonth.OnChange:=@InternalOnEditChange;
FEditYear.OnChange:=@InternalOnEditChange;
FEditMonth.OnClick:=@InternalOnEditClick;
FEditYear.OnClick:=@InternalOnEditClick;
FEditMonth.OnEnter:=@InternalOnEditEnter;
FEditYear.OnEnter:=@InternalOnEditEnter;
FEditMonth.OnExit:=@InternalOnEditExit;
FEditYear.OnExit:=@InternalOnEditExit;
end;
destructor TRxCustomDateRangeEdit.Destroy;
begin
inherited Destroy;
end;
end.
|
unit chart;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
VCLTee.TeEngine, VCLTee.Series, Vcl.ExtCtrls, VCLTee.TeeProcs, VCLTee.chart, VCLTee.DBChart,
VCLTee.TeeSpline, DateUtils;
type
TArrayLimit = array [0 .. 1] of integer;
// private
{ Private declarations }
// protected
// end;
var
TimestampLastLeft: TDateTime = 0;
TimestampLastRight: TDateTime = 0;
CountLeft: integer = 1;
CountRight: integer = 1;
//{$DEFINE DEBUG}
function ViewsCharts: bool;
function LimitMinMax(InTemperature, InSide: integer): TArrayLimit;
implementation
uses
main, settings, sql, logging;
function ViewsCharts: bool;
var
DateTimeLeft, TimeLeft, DateTimeRight, TimeRight: TDateTime;
i, q: integer;
LimitLeft, LimitRight: TArrayLimit;
begin
DateTimeLeft := NOW;
DateTimeRight := NOW;
for i := 0 to 4 do
begin
// -- left
Form1.chart_left_side.Series[i].XValues.DateTime := true;
// -- right
Form1.chart_right_side.Series[i].XValues.DateTime := true;
end;
// -- left
Form1.chart_left_side.BottomAxis.Automatic := false;
// -- right
Form1.chart_right_side.BottomAxis.Automatic := false;
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'ViewsCharts -> ' + timetostr(time));
{$ENDIF}
// -- left
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'TemperatureCurrentLeft -> '+inttostr(left.temperature));
{$ENDIF}
// LimitLeft[0] - min, LimitLeft[1] - max
LimitLeft := LimitMinMax(left.temperature, 0);
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LimitLeft min -> ' + inttostr(LimitLeft[0]));
SaveLog('debug' + #9#9 + 'LimitLeft max -> ' + inttostr(LimitLeft[1]));
{$ENDIF}
if NOW > Form1.chart_left_side.BottomAxis.Maximum then
begin
Form1.chart_left_side.BottomAxis.Maximum := DateTimeLeft;
// form1.Chart1.BottomAxis.Minimum := T - 10./(60*60*24);
Form1.chart_left_side.BottomAxis.Minimum := DateTimeLeft - (1 / 24 / 60);
end;
// построение оси с права
Form1.chart_left_side.Series[2].VertAxis := aRightAxis;
Form1.chart_left_side.RightAxis.SetMinMax(LimitLeft[0], LimitLeft[1]);
Form1.chart_left_side.LeftAxis.SetMinMax(LimitLeft[0], LimitLeft[1]);
// пределы red
Form1.chart_left_side.Series[4].AddXY(NOW, left.LowRed,
timetostr(DateTimeLeft), clRed); // min
Form1.chart_left_side.Series[0].AddXY(NOW, left.HighRed,
timetostr(DateTimeLeft), clRed); // max
// пределы green
if (left.LowGreen > left.LowRed) and (left.LowGreen < left.HighRed) and
(left.HighGreen > left.LowRed) then
Form1.chart_left_side.Series[3].AddXY(NOW, left.LowGreen,
timetostr(DateTimeLeft), clGreen); // min
if (left.HighGreen < left.HighRed) and (left.HighGreen > left.LowRed) and
(left.LowGreen < left.HighRed) then
Form1.chart_left_side.Series[1].AddXY(NOW, left.HighGreen,
timetostr(DateTimeLeft), clGreen); // max
if (left.LowGreen <> 0) and (left.LowRed >= left.LowGreen) and
(left.HighGreen > left.LowRed) then
Form1.chart_left_side.Series[3].AddXY(NOW, left.LowRed+3,
timetostr(DateTimeLeft), clGreen); // min +3 градуса от low красных
if (left.HighGreen <> 0) and (left.HighGreen >= left.HighRed) and
(left.LowGreen < left.HighRed) then
Form1.chart_left_side.Series[1].AddXY(NOW, left.HighRed-3,
timetostr(DateTimeLeft), clGreen); // max -3 градуса от high красных
if (left.LowGreen > left.HighRed) or (left.HighGreen < left.LowRed) then
begin
Form1.chart_left_side.Series[3].AddXY(NOW, 0,
timetostr(DateTimeLeft), clBlack); // min в 0
Form1.chart_left_side.Series[1].AddXY(NOW, 0,
timetostr(DateTimeLeft), clBlack); // max в 0
end;
// график температуры
Form1.chart_left_side.Series[2].AddXY(NOW, left.temperature,
timetostr(DateTimeLeft), clBlue);
try
// left chart clean old data
if CountLeft < Form1.chart_left_side.Series[2].Count then
begin
for i := Form1.chart_left_side.Series[2].Count - 101 downto 0 do
begin
for q := 0 to Form1.chart_left_side.SeriesCount - 1 do
Form1.chart_left_side.Series[q].Delete(i);
end;
CountLeft := Form1.chart_left_side.Series[2].Count + 100;
end;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
// -- right
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'TemperatureCurrentRight -> '+inttostr(right.temperature));
{$ENDIF}
// LimitRight[0] - min, LimitRight[1] - max
LimitRight := LimitMinMax(right.temperature, 1);
{$IFDEF DEBUG}
SaveLog('debug' + #9#9 + 'LimitRight min -> ' + inttostr(LimitRight[0]));
SaveLog('debug' + #9#9 + 'LimitRight max -> ' + inttostr(LimitRight[1]));
{$ENDIF}
if NOW > Form1.chart_right_side.BottomAxis.Maximum then
begin
Form1.chart_right_side.BottomAxis.Maximum := DateTimeRight;
// form1.Chart1.BottomAxis.Minimum := T - 10./(60*60*24);
Form1.chart_right_side.BottomAxis.Minimum := DateTimeRight - (1 / 24 / 60);
end;
// построение оси с права
Form1.chart_right_side.Series[2].VertAxis := aRightAxis;
Form1.chart_right_side.RightAxis.SetMinMax(LimitRight[0], LimitRight[1]);
Form1.chart_right_side.LeftAxis.SetMinMax(LimitRight[0], LimitRight[1]);
// пределы red
Form1.chart_right_side.Series[4].AddXY(NOW, right.LowRed,
timetostr(DateTimeRight), clRed); // min
Form1.chart_right_side.Series[0].AddXY(NOW, right.HighRed,
timetostr(DateTimeRight), clRed); // max
// пределы green
if (right.LowGreen > right.LowRed) and (right.LowGreen < right.HighRed) and
(right.HighGreen > right.LowRed) then
Form1.chart_right_side.Series[3].AddXY(NOW, right.LowGreen,
timetostr(DateTimeRight), clGreen); // min
if (right.HighGreen < right.HighRed) and (right.HighGreen > right.LowRed) and
(right.LowGreen < right.HighRed) then
Form1.chart_right_side.Series[1].AddXY(NOW, right.HighGreen,
timetostr(DateTimeRight), clGreen); // max
if (right.LowGreen <> 0) and (right.LowRed >= right.LowGreen) and
(right.HighGreen > right.LowRed) then
Form1.chart_right_side.Series[3].AddXY(NOW, right.LowRed+3,
timetostr(DateTimeRight), clGreen); // min +3 градуса от low красных
if (right.HighGreen <> 0) and (right.HighGreen >= right.HighRed) and
(right.LowGreen < right.HighRed) then
Form1.chart_right_side.Series[1].AddXY(NOW, right.HighRed-3,
timetostr(DateTimeRight), clGreen); // max -3 градуса от high красных
if (right.LowGreen > right.HighRed) or (right.HighGreen < right.LowRed) then
begin
Form1.chart_right_side.Series[3].AddXY(NOW, 0,
timetostr(DateTimeRight), clBlack); // min в 0
Form1.chart_right_side.Series[1].AddXY(NOW, 0,
timetostr(DateTimeRight), clBlack); // max в 0
end;
// график температуры
Form1.chart_right_side.Series[2].AddXY(NOW, right.temperature,
timetostr(DateTimeRight), clBlue);
try
// right chart clean old data
if CountRight < Form1.chart_right_side.Series[2].Count then
begin
for i := Form1.chart_right_side.Series[2].Count - 101 downto 0 do
begin
for q := 0 to Form1.chart_right_side.SeriesCount - 1 do
Form1.chart_right_side.Series[q].Delete(i);
end;
CountRight := Form1.chart_right_side.Series[2].Count + 100;
end;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
end;
function LimitMinMax(InTemperature, InSide: integer): TArrayLimit;
begin
// side left=0, side right=1
if (left.LowRed <> 0) and (InSide = 0) then
begin
Result[0] := left.LowRed-30;
Result[1] := left.HighRed+30;
exit;
end;
if (right.LowRed <> 0) and (InSide = 1) then
begin
Result[0] := right.LowRed-30;
Result[1] := right.HighRed+30;
exit;
end;
if InTemperature < 450 then
begin
Result[0] := 250;
Result[1] := 550;
end;
if (InTemperature < 650) and (InTemperature > 450) then
begin
Result[0] := 350;
Result[1] := 750;
end;
if (InTemperature < 850) and (InTemperature > 650) then
begin
Result[0] := 550;
Result[1] := 950;
end;
if (InTemperature < 1050) and (InTemperature > 850) then
begin
Result[0] := 750;
Result[1] := 1150;
end;
if (InTemperature < 1250) and (InTemperature > 1050) then
begin
Result[0] := 950;
Result[1] := 1250;
end;
end;
end.
|
unit ICDrecord;
interface
type TICDRecord = class
private
FId: integer;
FCodeICD10: string;
FFrDescription: string;
FNlDescription: string;
published
property id: integer read FId write FId;
property codeICD10: string read FCodeICD10 write FCodeICD10;
property frDescription: string read FFrDescription write FFrDescription;
property nlDescription: string read FNlDescription write FNlDescription;
public
constructor Create; overload;
constructor Create(const aCodeICD10: string;
const aFrDescription: string;
const aNlDescription: string); overload;
destructor Destroy; override;
end;
implementation
{ TICDRecord }
constructor TICDRecord.Create;
begin
codeICD10 := '';
frDescription := '';
nlDescription := '';
end;
constructor TICDRecord.Create(const aCodeICD10, aFrDescription,
aNlDescription: string);
begin
codeICD10 := aCodeICD10;
frDescription := aFrDescription;
nlDescription := aNlDescription;
end;
destructor TICDRecord.Destroy;
begin
//
inherited;
end;
end.
|
unit USQLScripts;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.StrUtils, System.Generics.Collections, UModel;
type
TSQLScripts = class
private
{ Private declarations }
class function BoolToStr(bool: boolean): string;
class function GetInsertOrderItemSQL(Order: TOrder): string;
class function GetOrderNo(OrderNo: string): string;
public
{ Public declarations }
class function GetInsertOrderSQL(Order: TOrder): string;
end;
implementation
{ TSQLScripts }
class function TSQLScripts.BoolToStr(bool: boolean): string;
begin
if bool then
result := '1'
else
result := '0';
end;
class function TSQLScripts.GetOrderNo(OrderNo: string): string;
begin
if OrderNo = '' then
result := '@OrderNo'
else
result := OrderNo;
end;
class function TSQLScripts.GetInsertOrderItemSQL(Order: TOrder): string;
var
i: integer;
OrderNo: string;
list: TList<TOrderItem>;
begin
list := Order.OrderItemList;
result := '';
OrderNo := GetOrderNo(Order.OrderNo);
for i := 0 to list.Count - 1 do
begin
result := result + 'INSERT INTO OrderI (' + 'SpecialOrder,' +
'OrderNo,ItemCode,Qty,PaidQty,Price,' +
'Discount,TaxRate,PrintFlag,Condition,PriceSelect,' +
'Seat,SentToKitchen,IDNo,VoidReason,' +
'CheckListPrinted,VoidFlag,OrderOperator,OriginalPrice,PresetDiscountCode,'
+ 'OriginalQty,ManuallyEnterWeight) VALUES (' + 'N' + Chr(39) +
list[i].SpecialOrder + Chr(39) + ',' +
format('''%s'',''%s'',%.2f,%.2f,%.2f,' + '%.2f,%.2f,%s,%d,%.2f,' +
'%d,%s,%d,''%s'',' + '%s,%s,''%s'',%f,''%s'',' +
'%.2f,%d); IF @@Error <> 0 ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION ',
[OrderNo, list[i].ItemCode, list[i].Qty, list[i].PaidQty, list[i].Price,
list[i].Discount, list[i].TaxRate, BoolToStr(list[i].PrintFlag),
list[i].Condition, list[i].PriceSelect, list[i].Seat,
BoolToStr(list[i].SentToKitchen), list[i].IDNo, list[i].VoidReason,
BoolToStr(list[i].CheckListPrinted), BoolToStr(list[i].VoidFlag),
list[i].OrderOperator, list[i].OriginalPrice, list[i].PresetDiscountCode,
list[i].OriginalQty, 0]);
end;
end;
class function TSQLScripts.GetInsertOrderSQL(Order: TOrder): string;
var
s: string;
settings: TFormatSettings;
begin
settings.DateSeparator := '-';
settings.TimeSeparator := ':';
settings.shortDateFormat := 'yyyy-MM-dd hh:mm:ss';
if Order.OrderNo = '' then
begin
s := 'INSERT INTO OrderH (' +
'OrderDate,OrderNo,Persons,TableNo,ServicePerson,' +
'Amount,GST,PaidAmount,VIPNo,OpName,' +
'Credit,OrderPrinted,MachineID,BillKind,DollarDiscount,' +
'DiscountKind,Delivery,PriceIncludesGST,CurrentGSTRate,' +
'SplitBill,DiscountOperator,ServiceCharge,Tips,Surcharge,' +
'OtherCharge,ServiceChargeRate,OtherChargeRate,AwardEffective,CurrentPoints,RedeemPoints) VALUES ('''
+ DateTimeToStr(Order.OrderDate, settings) + ''',''' +
GetOrderNo(Order.OrderNo) + ''',' + IntToStr(Order.Persons) + ',''' +
Order.TableNo + ''',''' + Order.ServicePerson + ''',';
s := s + format('%f,%f,%f,%d,''%s'',' + '%s,%s,''%s'',%d,%f,' +
'%d,%s,%s,%f,' + '%s,''%s'',%f,%f,%f,' +
'%f,%f,%f,%d,%d,%d); IF @@Error <> 0 ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION ',
[Order.Amount, Order.GST, Order.PaidAmount, Order.VipNo, Order.OpName,
BoolToStr(Order.Credit), BoolToStr(Order.OrderPrinted), Order.MachineID,
Order.BillKind, Order.DollarDiscount, Order.DiscountKind,
BoolToStr(Order.Delivery), BoolToStr(Order.PriceIncludeGST),
Order.CurrentGSTRate, BoolToStr(Order.SplitBill), Order.DiscountOperator,
Order.ServiceCharge, Order.Tips, Order.Surcharge, Order.OtherCharge,
Order.ServiceChargeRate, Order.OtherChargeRate, 0, 0, 0]);
end
else
begin
s := s + ' Begin Transaction Select * From Version (TabLockX) ' +
'UPDATE OrderH SET ' + 'Persons = ' + format('%d', [Order.Persons]) +
',TableNo = ' + format('''%s''', [Order.TableNo]) + ',ServicePerson = ' +
format('''%s''', [Order.ServicePerson]) + ',Amount = ' +
format('%.2f', [Order.Amount]) + ',GST = ' + format('%.2f', [Order.GST]) +
',OpName = ' + format('''%s''', [Order.OpName]) + ',DiscountKind = ' +
format('%d', [Order.DiscountKind]) + ' Where orderNo = ' +
format('''%s''', [Order.OrderNo]) +
'; IF @@Error <> 0 ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION ';
end;
result := s + GetInsertOrderItemSQL(Order);
end;
end.
|
unit debug;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SHFolder;
function GetCurrentFolderPath(): string;
procedure Print(Text : String; ClearFile: Boolean);
procedure Print(Text: String);
Procedure Print(Point: TPoint);
procedure Print(text: String; aRect: tRect);
procedure Print(text: String; number: Integer) ;
function GetSpecialFolderPath(folder : integer) : string;
implementation
function GetCurrentFolderPath() :String ;
var
folderExists: Boolean;
begin
GetcurrentfolderPath:= GetSpecialFolderPath(CSIDL_MYPICTURES)+ '\ScreenDumps\'
+ FormatDateTime('MMMM YYYY\DD MMMM YYYY',Now) ;
folderExists:=DirectoryExists(GetCurrentFolderPath);
IF NOT folderExists THEN
begin
forcedirectories(GetCurrentFolderPath);
end;
end;
function GetSpecialFolderPath(folder : integer) : string;
const
SHGFP_TYPE_CURRENT = 0;
{ Folder Types
CSIDL_ADMINTOOLS
CSIDL_APPDATA
CSIDL_COMMON_ADMINTOOLS
CSIDL_COMMON_APPDATA
CSIDL_COMMON_DOCUMENTS
CSIDL_COOKIES
CSIDL_FLAG_CREATE
CSIDL_FLAG_DONT_VERIFY
CSIDL_HISTORY
CSIDL_INTERNET_CACHE
CSIDL_LOCAL_APPDATA
CSIDL_MYPICTURES
CSIDL_PERSONAL
CSIDL_PROGRAM_FILES
CSIDL_PROGRAM_FILES_COMMON
CSIDL_SYSTEM
CSIDL_WINDOWS
}
var
path: array [0..MAX_PATH] of char;
begin
SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,@path[0]) ;
Result := path ;
end;
//DEBUG LOGGING
procedure Print(text: String; aRect: tRect);
begin
debug.Print (Text + chr(9)
+ chr(9) + ' TopLeft: ' + inttostr(arect.topleft.x) + ',' + inttostr(arect.topleft.y)
+ chr(9) + ' BottomRight: ' + inttostr(arect.BottomRight.x) + ',' + inttostr(arect.bottomright.y)
+ chr(9) + ' Width: ' + inttostr(arect.Right - arect.Left)
+ chr(9) + ' Height: ' + inttostr(arect.Bottom - arect.Top))
end;
procedure Print(text: String; number: Integer) ;
begin
Debug.Print(Text + inttoStr(number));
end;
procedure Print(Text: String);
begin
Debug.Print(Text, False);
end;
Procedure Print(Point: TPoint);
begin
Debug.print('x: ' + inttostr(Point.x) + ' y: ' + inttostr(Point.y));
end;
procedure Print(Text : String; ClearFile: Boolean);
var
file1: Textfile;
begin
if false then
begin
AssignFile(File1, Getcurrentfolderpath() + '\Debug.txt');
Try
begin
if (ClearFile) then
begin
rewrite(file1);
end
else
begin
append(File1);
end;
Writeln(File1,FormatDateTime('hh.mm.ss',Now) + ' - ' + Text);
end;
except
End;
CloseFile(File1);
end;
end;
end.
|
unit uFlashMemo;
interface
uses
cTranspMemo, uFormData, uFlashRect, Classes,
ExtCtrls, Messages, Controls;
type
TFlashMemo = class(TTransparentMemo)
private
FData: TPageData;
FShowNormalText: Boolean;
FOnMoved: TNotifyEvent;
procedure SetData(const Value: TPageData);
procedure SetShowNormalText(const Value: Boolean);
protected
procedure TextChanged(Sender: TObject);
procedure KeyPress(var Key: Char); override;
procedure Change; override;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
procedure WMKeyDown(var aMsg: TWMKeyDown); message WM_KEYDOWN;
procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU;
procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
function HideText(const aText: string): string;
public
procedure AfterConstruction;override;
procedure SpecialInvalidate;
function HeightNeeded: integer;
function WidthNeeded: integer;
property Data: TPageData read FData write SetData;
property ShowNormalText: Boolean read FShowNormalText write SetShowNormalText;
//positioning
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
var FFlashPos: TFlashRect;
FZoomBusy: Boolean;
property OnMoved: TNotifyEvent read FOnMoved write FOnMoved;
end;
implementation
uses
StrUtils, SysUtils, Character, Forms, Windows, Graphics, Math;
{ TFlashMemo }
procedure TFlashMemo.AfterConstruction;
begin
inherited;
Self.BorderStyle := bsNone;
Self.WordWrap := False;
// (Self.Lines as TMemoStrings).OnChange := Self.TextChanged;
end;
procedure TFlashMemo.Change;
begin
inherited;
if FData = nil then Exit;
TextChanged(nil);
end;
procedure TFlashMemo.CMMouseEnter(var Message: TMessage);
begin
if ReadOnly then
HideCaret(Self.Handle)
else
inherited
end;
procedure TFlashMemo.CMTextChanged(var Message: TMessage);
begin
inherited;
if FData = nil then Exit;
TextChanged(nil);
end;
function TFlashMemo.HideText(const aText: string): string;
var
i: Integer;
begin
Result := aText;
for i := 1 to Length(aText) do
begin
if not CharInSet(aText[i], [' ',#10,#13]) then
Result[i] := '#';//'*';
end;
end;
function TFlashMemo.WidthNeeded: integer;
Var
OldFont : HFont;
Hand : THandle;
TM : TTextMetric;
tempint : integer;
i: Integer;
begin
Hand := GetDC(Self.Handle);
try
OldFont := SelectObject(Hand, Self.Font.Handle);
try
GetTextMetrics(Hand, TM);
tempint := 0;
for i := 0 to Lines.Count - 1 do
tempint := Max(tempint,
(TM.tmAveCharWidth) * Length(Lines[i]));
finally
SelectObject(Hand, OldFont);
end;
finally
ReleaseDC(Self.Handle, Hand);
end;
Result := tempint;
end;
procedure TFlashMemo.WMContextMenu(var Message: TWMContextMenu);
begin
if ReadOnly then
Exit
else
inherited;
end;
procedure TFlashMemo.WMKeyDown(var aMsg: TWMKeyDown);
var
ks: TKeyboardState;
begin
if ReadOnly then
HideCaret(Self.Handle);
if not ReadOnly and
(aMsg.CharCode in [VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN,
VK_ADD, VK_SUBTRACT]) then
begin
if GetKeyboardState(ks) and
(ssCtrl in KeyboardStateToShiftState(ks)) then
begin
case aMsg.CharCode of
VK_LEFT : Left := Left - 1;
VK_RIGHT : Left := Left + 1;
VK_UP : Top := Top - 1;
VK_DOWN : Top := Top + 1;
VK_ADD :
begin
Data.FontSize := Data.FontSize + 1;
Font.Size := Round(Data.FontSize
* FFlashPos.Flash2ScreenRatio);
end;
VK_SUBTRACT :
begin
Data.FontSize := Data.FontSize - 1;
Font.Size := Round(Data.FontSize
* FFlashPos.Flash2ScreenRatio);
end;
end;
if (ssCtrl in KeyboardStateToShiftState(ks)) and
(ssShift in KeyboardStateToShiftState(ks)) then
case aMsg.CharCode of
VK_LEFT : Left := Left - 4;
VK_RIGHT : Left := Left + 4;
VK_UP : Top := Top - 4;
VK_DOWN : Top := Top + 4;
end;
//update pos: redraw background
SpecialInvalidate;
Exit;
end;
end;
inherited;
end;
procedure TFlashMemo.KeyPress(var Key: Char);
begin
if not ShowNormalText then
Key := #0;
inherited KeyPress(Key);
if FData = nil then Exit;
TextChanged(nil);
end;
procedure TFlashMemo.TextChanged(Sender: TObject);
begin
if FData = nil then Exit;
if ShowNormalText then
FData.AnswerText := Lines.Text;
end;
procedure TFlashMemo.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
Self.ShowNormalText := not Self.ShowNormalText;
end;
procedure TFlashMemo.WMLButtonDown(var Message: TWMLButtonDown);
begin
if ReadOnly then
HideCaret(Self.Handle)
else
inherited
end;
procedure TFlashMemo.WMNCHitTest(var Message: TWMNCHitTest);
begin
// if ReadOnly then
// HideCaret(Self.Handle);
// Message.Result := HTBORDER //HTTRANSPARENT
// else
inherited;
// Cursor := crDefault;
end;
procedure TFlashMemo.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
scrollb: TScrollBox;
begin
if not FZoomBusy then
begin
scrollb := Parent as TScrollBox;
if scrollb <> nil then
begin
FFlashPos.ScreenLeft := ALeft + scrollb.HorzScrollBar.Position;
FFlashPos.ScreenTop := ATop + scrollb.VertScrollBar.Position;
end
else
begin
FFlashPos.ScreenLeft := ALeft;
FFlashPos.ScreenTop := ATop;
end;
FFlashPos.ScreenWidth := AWidth;
FFlashPos.ScreenHeigth := AHeight;
end;
if FData <> nil then
begin
FData.AnswerPos.Top := FFlashPos.FlashTop;
FData.AnswerPos.Left := FFlashPos.FlashLeft;
FData.AnswerPos.Width := FFlashPos.FlashWidth;
FData.AnswerPos.Height := FFlashPos.FlashHeigth;
end;
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
SpecialInvalidate;
if Assigned(OnMoved) then
OnMoved(Self);
end;
procedure TFlashMemo.SetData(const Value: TPageData);
var
scrollb: TScrollBox;
begin
FData := Value;
if FData = nil then Exit;
ShowNormalText := False; //default no normal text but hidden text
//Lines.Text := FData.AnswerText;
FFlashPos.FlashTop := FData.AnswerPos.Top;
FFlashPos.FlashLeft := FData.AnswerPos.Left;
FFlashPos.FlashWidth := FData.AnswerPos.Width;
FFlashPos.FlashHeigth := FData.AnswerPos.Height;
scrollb := Parent as TScrollBox;
if scrollb <> nil then
begin
Self.SetBounds(Self.FFlashPos.ScreenLeft - scrollb.HorzScrollBar.Position,
Self.FFlashPos.ScreenTop - scrollb.VertScrollBar.Position,
Self.FFlashPos.ScreenWidth, Self.FFlashPos.ScreenHeigth)
end
else
Self.SetBounds(Self.FFlashPos.ScreenLeft, Self.FFlashPos.ScreenTop,
Self.FFlashPos.ScreenWidth, Self.FFlashPos.ScreenHeigth)
end;
procedure TFlashMemo.SetShowNormalText(const Value: Boolean);
begin
FShowNormalText := Value;
if ShowNormalText then
begin
Self.Lines.Text := FData.AnswerText;
end
else
Self.Lines.Text := HideText(FData.AnswerText)
end;
procedure TFlashMemo.SpecialInvalidate;
begin
if Parent <> nil then
PostMessage(Handle,TMWM__SpecialInvalidate,0,0);
Self.Invalidate;
end;
function TFlashMemo.HeightNeeded: integer;
Var
OldFont : HFont;
Hand : THandle;
TM : TTextMetric;
// Rect : TRect;
tempint : integer;
begin
Hand := GetDC(Self.Handle);
try
OldFont := SelectObject(Hand, Self.Font.Handle);
try
GetTextMetrics(Hand, TM);
//Self.Perform(EM_GETRECT, 0, longint(@Rect));
tempint := //(Rect.Bottom - Rect.Top) div
(TM.tmHeight + TM.tmExternalLeading) *
Lines.Count;
finally
SelectObject(Hand, OldFont);
end;
finally
ReleaseDC(Self.Handle, Hand);
end;
Result := tempint;
end;
end.
|
unit fSoundEffectEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, ValEdit, cMegaROM, cConfiguration;
type
TfrmSoundEffectEditor = class(TForm)
vleSoundEffects: TValueListEditor;
cmdOK: TButton;
cmdCancel: TButton;
procedure FormShow(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
_ROMData : TMegamanROM;
_EditorConfig : TRRConfig;
procedure SaveSoundEffects;
procedure FillListEditor;
procedure ClearItemProps;
{ Private declarations }
public
property ROMData : TMegamanROM read _ROMData write _ROMData;
property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig;
{ Public declarations }
end;
var
frmSoundEffectEditor: TfrmSoundEffectEditor;
implementation
uses uglobal, csound;
{$R *.dfm}
procedure TfrmSoundEffectEditor.SaveSoundEffects;
var
i : Integer;
begin
for i := 1 to _ROMData.SoundEffects.Count do
begin
_ROMData.SoundEffects[i - 1].SEIndex := _ROMData.SoundEffectList.IndexOf(vleSoundEffects.Values[vleSoundEffects.Keys[i]]);
end;
end;
procedure TfrmSoundEffectEditor.FillListEditor;
var
i : Integer;
begin
for i := 0 to _ROMData.SoundEffects.Count -1 do
begin
vleSoundEffects.InsertRow(_ROMData.SoundEffects[i].Name,_ROMData.SoundEffectList[_ROMData.SoundEffects[i].SEIndex],True);
vleSoundEffects.ItemProps[i].EditStyle := esPickList;
vleSoundEffects.ItemProps[i].PickList := _ROMData.SoundEffectList;
vleSoundEffects.ItemProps[i].ReadOnly := True;
end;
end;
procedure TfrmSoundEffectEditor.cmdOKClick(Sender: TObject);
begin
SaveSoundEffects;
end;
procedure TfrmSoundEffectEditor.ClearItemProps;
var
i : Integer;
begin
for i := 0 to _ROMData.SoundEffects.Count -1 do
begin
vleSoundEffects.ItemProps[i].Destroy;
end;
end;
procedure TfrmSoundEffectEditor.FormDestroy(Sender: TObject);
begin
ClearItemProps;
end;
procedure TfrmSoundEffectEditor.FormShow(Sender: TObject);
begin
FillListEditor;
end;
end.
|
unit Thermostat.EnabledState;
interface
uses
Thermostat.Classes;
type
TEnabledThermostatState = class(TThermostatState)
public
procedure Init; override;
procedure Finish; override;
procedure Execute; override;
end;
implementation
uses
Thermostat.HeatingState,
Thermostat.NotHeatingState,
Thermostat.DisabledState;
{ TEnabledThermostatState }
procedure TEnabledThermostatState.Execute;
begin
inherited;
if not Thermostat.Active or (Thermostat.WaterLevel = waterlevelLow) then
ChangeState(TDisabledThermostatState)
else State.Execute;
end;
procedure TEnabledThermostatState.Finish;
begin
inherited;
if State is THeatingState then
State.ChangeState(TNotHeatingState); // disable Heater
end;
procedure TEnabledThermostatState.Init;
var auxState: TThermostatState;
begin
inherited;
if Thermostat.SampleTemperature < Thermostat.TargetTemperature then
auxState := GetStateClass(THeatingState)
else auxState := GetStateClass(TNotHeatingState);
State := auxState;
auxState.Init;
end;
end.
|
program primoesercizio;
const
DMAX=25;
type
Tpunt=^Telemento;
Tinfo=char;
Telemento=record
info:Tinfo;
next:Tpunt;
end;
Tparola=String[DMAX];
var
PCoda:Tpunt;
procedure fill(var Pcoda:Tpunt);
var
parola:Tparola;
PAtt:Tpunt;
i:integer;
begin
PAtt:=Pcoda;
writeln('Inserisci una parola');
readln(parola);
for i:=1 to Length(parola) do
begin
PAtt^.info:=parola[i];
new(PAtt^.next);
PAtt:=PAtt^.next;
end;
end;
procedure print(Pcoda:Tpunt);
var
PAtt:Tpunt;
begin
PAtt:=Pcoda;
writeln('Qui di seguito il contenuto della sequenza');
while PAtt <> NIL do
begin
write(PAtt^.info, ' ');
PAtt:=PAtt^.next;
end;
writeln();
end;
procedure reverseprint(Pcoda:Tpunt);
type
TPila=record
corpo:array[1..DMAX] of Tinfo;
top:integer;
end;
var
PAtt:Tpunt;
Pila:Tpila;
i:integer;
begin
//Init della testa della pila
Pila.top:=0;
PAtt:=Pcoda;
writeln('Qui di seguito il contenuto inverso della sequenza');
//push in una pila di appoggio
while PAtt <> NIL do
begin
Pila.top:=Pila.top+1;
Pila.corpo[Pila.top]:=PAtt^.info;
PAtt:=PAtt^.next;
end;
//pop dalla pila sopra riempita
for i:=Pila.top downto 1 do
begin
write(Pila.corpo[i], ' ');
end;
end;
begin
new(Pcoda);
fill(Pcoda);
print(Pcoda);
reverseprint(Pcoda);
end.
|
unit IdIOHandlerWebsocket;
//The WebSocket Protocol, RFC 6455
//http://datatracker.ietf.org/doc/rfc6455/?include_text=1
interface
uses
Classes,
IdIOHandlerStack, IdGlobal, IdException, IdBuffer, SyncObjs;
type
TWSDataType = (wdtText, wdtBinary);
TWSDataCode = (wdcNone, wdcContinuation, wdcText, wdcBinary, wdcClose, wdcPing, wdcPong);
TWSExtensionBit = (webBit1, webBit2, webBit3);
TWSExtensionBits = set of TWSExtensionBit;
TIdIOHandlerWebsocket = class;
EIdWebSocketHandleError = class(EIdSocketHandleError);
TIdIOHandlerWebsocket = class(TIdIOHandlerStack)
private
FIsServerSide: Boolean;
FBusyUpgrading: Boolean;
FIsWebsocket: Boolean;
FWSInputBuffer: TIdBuffer;
FExtensionBits: TWSExtensionBits;
FLock: TCriticalSection;
FCloseReason: string;
FCloseCode: Integer;
FClosing: Boolean;
protected
FMessageStream: TMemoryStream;
FWriteTextToTarget: Boolean;
FCloseCodeSend: Boolean;
function InternalReadDataFromSource(var VBuffer: TIdBytes): Integer;
function ReadDataFromSource(var VBuffer: TIdBytes): Integer; override;
function WriteDataToTarget (const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override;
function ReadFrame(out aFIN, aRSV1, aRSV2, aRSV3: boolean; out aDataCode: TWSDataCode; out aData: TIdBytes): Integer;
function ReadMessage(var aBuffer: TIdBytes; out aDataCode: TWSDataCode): Integer;
public
function WriteData(aData: TIdBytes; aType: TWSDataCode;
aFIN: boolean = true; aRSV1: boolean = false; aRSV2: boolean = false; aRSV3: boolean = false): integer;
property BusyUpgrading : Boolean read FBusyUpgrading write FBusyUpgrading;
property IsWebsocket : Boolean read FIsWebsocket write FIsWebsocket;
property IsServerSide : Boolean read FIsServerSide write FIsServerSide;
property ClientExtensionBits : TWSExtensionBits read FExtensionBits write FExtensionBits;
public
procedure AfterConstruction;override;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
function TryLock: Boolean;
procedure Close; override;
property Closing : Boolean read FClosing;
property CloseCode : Integer read FCloseCode write FCloseCode;
property CloseReason: string read FCloseReason write FCloseReason;
//text/string writes
procedure Write(const AOut: string; AEncoding: TIdTextEncoding = nil); overload; override;
procedure WriteLn(const AOut: string; AEncoding: TIdTextEncoding = nil); overload; override;
procedure WriteLnRFC(const AOut: string = ''; AEncoding: TIdTextEncoding = nil); override;
procedure Write(AValue: TStrings; AWriteLinesCount: Boolean = False; AEncoding: TIdTextEncoding = nil); overload; override;
procedure Write(AStream: TStream; aType: TWSDataType); overload;
end;
//close frame codes
const
C_FrameClose_Normal = 1000; //1000 indicates a normal closure, meaning that the purpose for
//which the connection was established has been fulfilled.
C_FrameClose_GoingAway = 1001; //1001 indicates that an endpoint is "going away", such as a server
//going down or a browser having navigated away from a page.
C_FrameClose_ProtocolError = 1002; //1002 indicates that an endpoint is terminating the connection due
//to a protocol error.
C_FrameClose_UnhandledDataType = 1003; //1003 indicates that an endpoint is terminating the connection
//because it has received a type of data it cannot accept (e.g., an
//endpoint that understands only text data MAY send this if it
//receives a binary message).
C_FrameClose_Reserved = 1004; //Reserved. The specific meaning might be defined in the future.
C_FrameClose_ReservedNoStatus = 1005; //1005 is a reserved value and MUST NOT be set as a status code in a
//Close control frame by an endpoint. It is designated for use in
//applications expecting a status code to indicate that no status
//code was actually present.
C_FrameClose_ReservedAbnormal = 1006; //1006 is a reserved value and MUST NOT be set as a status code in a
//Close control frame by an endpoint. It is designated for use in
//applications expecting a status code to indicate that the
//connection was closed abnormally, e.g., without sending or
//receiving a Close control frame.
C_FrameClose_InconsistentData = 1007; //1007 indicates that an endpoint is terminating the connection
//because it has received data within a message that was not
//consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
//data within a text message).
C_FrameClose_PolicyError = 1008; //1008 indicates that an endpoint is terminating the connection
//because it has received a message that violates its policy. This
//is a generic status code that can be returned when there is no
//other more suitable status code (e.g., 1003 or 1009) or if there
//is a need to hide specific details about the policy.
C_FrameClose_ToBigMessage = 1009; //1009 indicates that an endpoint is terminating the connection
//because it has received a message that is too big for it to process.
C_FrameClose_MissingExtenstion = 1010; //1010 indicates that an endpoint (client) is terminating the
//connection because it has expected the server to negotiate one or
//more extension, but the server didn't return them in the response
//message of the WebSocket handshake. The list of extensions that
//are needed SHOULD appear in the /reason/ part of the Close frame.
//Note that this status code is not used by the server, because it
//can fail the WebSocket handshake instead.
C_FrameClose_UnExpectedError = 1011; //1011 indicates that a server is terminating the connection because
//it encountered an unexpected condition that prevented it from
//fulfilling the request.
C_FrameClose_ReservedTLSError = 1015; //1015 is a reserved value and MUST NOT be set as a status code in a
//Close control frame by an endpoint. It is designated for use in
//applications expecting a status code to indicate that the
//connection was closed due to a failure to perform a TLS handshake
//(e.g., the server certificate can't be verified).
implementation
uses
SysUtils, Math, IdStream, IdStack, IdWinsock2, IdExceptionCore,
IdResourceStrings, IdResourceStringsCore;
//frame codes
const
C_FrameCode_Continuation = 0;
C_FrameCode_Text = 1;
C_FrameCode_Binary = 2;
//3-7 are reserved for further non-control frames
C_FrameCode_Close = 8;
C_FrameCode_Ping = 9;
C_FrameCode_Pong = 10 {A};
//B-F are reserved for further control frames
{ TIdIOHandlerStack_Websocket }
procedure TIdIOHandlerWebsocket.AfterConstruction;
begin
inherited;
FMessageStream := TMemoryStream.Create;
FWSInputBuffer := TIdBuffer.Create;
FLock := TCriticalSection.Create;
end;
procedure TIdIOHandlerWebsocket.Close;
var
iaWriteBuffer: TIdBytes;
sReason: UTF8String;
iOptVal, iOptLen: Integer;
bConnected: Boolean;
begin
try
//valid connection?
bConnected := Opened and
SourceIsAvailable and
not ClosedGracefully;
//no socket error? connection closed by software abort, connection reset by peer, etc
iOptLen := SIZE_INTEGER;
bConnected := bConnected and
(IdWinsock2.getsockopt(Self.Binding.Handle, SOL_SOCKET, SO_ERROR, PAnsiChar(@iOptVal), iOptLen) = 0) and
(iOptVal = 0);
if bConnected then
begin
//close message must be responded with a close message back
//or initiated with a close message
if not FCloseCodeSend then
begin
FCloseCodeSend := True;
//we initiate the close? then write reason etc
if not Closing then
begin
SetLength(iaWriteBuffer, 2);
if CloseCode < C_FrameClose_Normal then
CloseCode := C_FrameClose_Normal;
iaWriteBuffer[0] := Byte(CloseCode shr 8);
iaWriteBuffer[1] := Byte(CloseCode);
if CloseReason <> '' then
begin
sReason := utf8string(CloseReason);
SetLength(iaWriteBuffer, Length(iaWriteBuffer) + Length(sReason));
Move(sReason[1], iaWriteBuffer[2], Length(sReason));
end;
end
else
begin
//just send normal close response back
SetLength(iaWriteBuffer, 2);
iaWriteBuffer[0] := Byte(C_FrameClose_Normal shr 8);
iaWriteBuffer[1] := Byte(C_FrameClose_Normal);
end;
WriteData(iaWriteBuffer, wdcClose); //send close + code back
end;
//we did initiate the close? then wait for close response
if not Closing then
begin
FClosing := True;
CheckForDisconnect();
//wait till client respond with close message back
//but a pending message can be in the buffer, so process this too
while ReadFromSource(False{no disconnect error}, 5 * 1000, False) > 0 do ; //response within 5s?
end;
end;
except
//ignore, it's possible that the client is disconnected already (crashed etc)
end;
IsWebsocket := False;
BusyUpgrading := False;
inherited Close;
end;
destructor TIdIOHandlerWebsocket.Destroy;
begin
FLock.Enter;
FLock.Free;
FWSInputBuffer.Free;
FMessageStream.Free;
inherited;
end;
function TIdIOHandlerWebsocket.InternalReadDataFromSource(
var VBuffer: TIdBytes): Integer;
begin
CheckForDisconnect;
if not Readable(IdTimeoutDefault) or
not Opened or
not SourceIsAvailable then
begin
CheckForDisconnect; //disconnected during wait in "Readable()"?
if not Opened then
EIdNotConnected.Toss(RSNotConnected)
else if not SourceIsAvailable then
EIdClosedSocket.Toss(RSStatusDisconnected);
GStack.CheckForSocketError(GStack.WSGetLastError); //check for socket error
EIdReadTimeout.Toss(RSIdNoDataToRead); //exit, no data can be received
end;
SetLength(VBuffer, RecvBufferSize);
Result := inherited ReadDataFromSource(VBuffer);
if Result = 0 then
begin
CheckForDisconnect; //disconnected in the mean time?
GStack.CheckForSocketError(GStack.WSGetLastError); //check for socket error
EIdNoDataToRead.Toss(RSIdNoDataToRead); //nothing read? then connection is probably closed -> exit
end;
SetLength(VBuffer, Result);
end;
procedure TIdIOHandlerWebsocket.WriteLn(const AOut: string;
AEncoding: TIdTextEncoding);
begin
FWriteTextToTarget := True;
try
inherited WriteLn(AOut, TIdTextEncoding.UTF8); //must be UTF8!
finally
FWriteTextToTarget := False;
end;
end;
procedure TIdIOHandlerWebsocket.WriteLnRFC(const AOut: string;
AEncoding: TIdTextEncoding);
begin
FWriteTextToTarget := True;
try
inherited WriteLnRFC(AOut, TIdTextEncoding.UTF8); //must be UTF8!
finally
FWriteTextToTarget := False;
end;
end;
procedure TIdIOHandlerWebsocket.Write(const AOut: string;
AEncoding: TIdTextEncoding);
begin
FWriteTextToTarget := True;
try
inherited Write(AOut, TIdTextEncoding.UTF8); //must be UTF8!
finally
FWriteTextToTarget := False;
end;
end;
procedure TIdIOHandlerWebsocket.Write(AValue: TStrings;
AWriteLinesCount: Boolean; AEncoding: TIdTextEncoding);
begin
FWriteTextToTarget := True;
try
inherited Write(AValue, AWriteLinesCount, TIdTextEncoding.UTF8); //must be UTF8!
finally
FWriteTextToTarget := False;
end;
end;
procedure TIdIOHandlerWebsocket.Write(AStream: TStream;
aType: TWSDataType);
begin
FWriteTextToTarget := (aType = wdtText);
try
inherited Write(AStream);
finally
FWriteTextToTarget := False;
end;
end;
function TIdIOHandlerWebsocket.WriteDataToTarget(const ABuffer: TIdBytes;
const AOffset, ALength: Integer): Integer;
begin
if not IsWebsocket then
Result := inherited WriteDataToTarget(ABuffer, AOffset, ALength)
else
begin
Lock;
try
if FWriteTextToTarget then
Result := WriteData(ABuffer, wdcText, True{send all at once},
webBit1 in ClientExtensionBits, webBit2 in ClientExtensionBits, webBit3 in ClientExtensionBits)
else
Result := WriteData(ABuffer, wdcBinary, True{send all at once},
webBit1 in ClientExtensionBits, webBit2 in ClientExtensionBits, webBit3 in ClientExtensionBits);
except
Unlock; //always unlock when socket exception
FClosedGracefully := True;
Raise;
end;
Unlock; //normal unlock (no double try finally)
end;
end;
function TIdIOHandlerWebsocket.ReadDataFromSource(
var VBuffer: TIdBytes): Integer;
var
wscode: TWSDataCode;
begin
//the first time something is read AFTER upgrading, we switch to WS
//(so partial writes can be done, till a read is done)
if BusyUpgrading then
begin
BusyUpgrading := False;
IsWebsocket := True;
end;
if not IsWebsocket then
Result := inherited ReadDataFromSource(VBuffer)
else
begin
Lock;
try
//we wait till we have a full message here (can be fragmented in several frames)
Result := ReadMessage(VBuffer, wscode);
//first write the data code (text or binary, ping, pong)
FInputBuffer.Write(LongWord(Ord(wscode)));
//we write message size here, vbuffer is written after this. This way we can use ReadStream to get 1 single message (in case multiple messages in FInputBuffer)
if LargeStream then
FInputBuffer.Write(Int64(Result))
else
FInputBuffer.Write(LongWord(Result))
except
Unlock; //always unlock when socket exception
FClosedGracefully := True; //closed (but not gracefully?)
Raise;
end;
Unlock; //normal unlock (no double try finally)
end;
end;
function TIdIOHandlerWebsocket.ReadMessage(var aBuffer: TIdBytes; out aDataCode: TWSDataCode): Integer;
var
iReadCount: Integer;
iaReadBuffer: TIdBytes;
bFIN, bRSV1, bRSV2, bRSV3: boolean;
lDataCode: TWSDataCode;
lFirstDataCode: TWSDataCode;
// closeCode: integer;
// closeResult: string;
begin
Result := 0;
(* ...all fragments of a message are of
the same type, as set by the first fragment's opcode. Since
control frames cannot be fragmented, the type for all fragments in
a message MUST be either text, binary, or one of the reserved
opcodes. *)
lFirstDataCode := wdcNone;
FMessageStream.Clear;
repeat
//read a single frame
iReadCount := ReadFrame(bFIN, bRSV1, bRSV2, bRSV3, lDataCode, iaReadBuffer);
if (iReadCount > 0) or
(lDataCode <> wdcNone) then
begin
Assert(Length(iaReadBuffer) = iReadCount);
//store client extension bits
if Self.IsServerSide then
begin
ClientExtensionBits := [];
if bRSV1 then ClientExtensionBits := ClientExtensionBits + [webBit1];
if bRSV2 then ClientExtensionBits := ClientExtensionBits + [webBit2];
if bRSV3 then ClientExtensionBits := ClientExtensionBits + [webBit3];
end;
//process frame
case lDataCode of
wdcText, wdcBinary:
begin
if lFirstDataCode <> wdcNone then
raise EIdWebSocketHandleError.Create('Invalid frame: specified data code only allowed for the first frame');
lFirstDataCode := lDataCode;
FMessageStream.Clear;
TIdStreamHelper.Write(FMessageStream, iaReadBuffer);
end;
wdcContinuation:
begin
if not (lFirstDataCode in [wdcText, wdcBinary]) then
raise EIdWebSocketHandleError.Create('Invalid frame continuation');
TIdStreamHelper.Write(FMessageStream, iaReadBuffer);
end;
wdcClose:
begin
FCloseCode := C_FrameClose_Normal;
//"If there is a body, the first two bytes of the body MUST be a 2-byte
// unsigned integer (in network byte order) representing a status code"
if Length(iaReadBuffer) > 1 then
begin
FCloseCode := (iaReadBuffer[0] shl 8) +
iaReadBuffer[1];
if Length(iaReadBuffer) > 2 then
FCloseReason := BytesToString(iaReadBuffer, 2, Length(iaReadBuffer), TEncoding.UTF8);
end;
FClosing := True;
Self.Close;
end;
//Note: control frames can be send between fragmented frames
wdcPing:
begin
WriteData(iaReadBuffer, wdcPong); //send pong + same data back
lFirstDataCode := lDataCode;
end;
wdcPong:
begin
//pong received, ignore;
lFirstDataCode := lDataCode;
end;
end;
end
else
Break;
until bFIN;
//done?
if bFIN then
begin
if (lFirstDataCode in [wdcText, wdcBinary]) then
begin
//result
FMessageStream.Position := 0;
TIdStreamHelper.ReadBytes(FMessageStream, aBuffer);
Result := FMessageStream.Size;
aDataCode := lFirstDataCode
end
else if (lFirstDataCode in [wdcPing, wdcPong]) then
begin
//result
FMessageStream.Position := 0;
TIdStreamHelper.ReadBytes(FMessageStream, aBuffer);
SetLength(aBuffer, FMessageStream.Size);
//dummy data: there *must* be some data read otherwise connection is closed by Indy!
if Length(aBuffer) <= 0 then
begin
SetLength(aBuffer, 1);
aBuffer[0] := Ord(lFirstDataCode);
end;
Result := Length(aBuffer);
aDataCode := lFirstDataCode
end;
end;
end;
procedure TIdIOHandlerWebsocket.Lock;
begin
FLock.Enter;
end;
function TIdIOHandlerWebsocket.TryLock: Boolean;
begin
Result := FLock.TryEnter;
end;
procedure TIdIOHandlerWebsocket.Unlock;
begin
FLock.Leave;
end;
function TIdIOHandlerWebsocket.ReadFrame(out aFIN, aRSV1, aRSV2, aRSV3: boolean;
out aDataCode: TWSDataCode; out aData: TIdBytes): Integer;
var
iInputPos: NativeInt;
function _GetByte: Byte;
var
temp: TIdBytes;
begin
while FWSInputBuffer.Size <= iInputPos do
begin
InternalReadDataFromSource(temp);
FWSInputBuffer.Write(temp);
end;
//Self.ReadByte copies all data everytime (because the first byte must be removed) so we use index (much more efficient)
Result := FWSInputBuffer.PeekByte(iInputPos);
inc(iInputPos);
end;
function _GetBytes(aCount: Integer): TIdBytes;
var
temp: TIdBytes;
begin
while FWSInputBuffer.Size < aCount do
begin
InternalReadDataFromSource(temp);
FWSInputBuffer.Write(temp);
end;
FWSInputBuffer.ExtractToBytes(Result, aCount);
end;
var
iByte: Byte;
i, iCode: NativeInt;
bHasMask: boolean;
iDataLength, iPos: Int64;
rMask: record
case Boolean of
True : (MaskAsBytes: array[0..3] of Byte);
False: (MaskAsInt : Int32);
end;
begin
iInputPos := 0;
SetLength(aData, 0);
aDataCode := wdcNone;
//wait + process data
iByte := _GetByte;
(* 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 (nr)
7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0 (bit)
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + *)
//FIN, RSV1, RSV2, RSV3: 1 bit each
aFIN := (iByte and (1 shl 7)) > 0;
aRSV1 := (iByte and (1 shl 6)) > 0;
aRSV2 := (iByte and (1 shl 5)) > 0;
aRSV3 := (iByte and (1 shl 4)) > 0;
//Opcode: 4 bits
iCode := (iByte and $0F); //clear 4 MSB's
case iCode of
C_FrameCode_Continuation: aDataCode := wdcContinuation;
C_FrameCode_Text: aDataCode := wdcText;
C_FrameCode_Binary: aDataCode := wdcBinary;
C_FrameCode_Close: aDataCode := wdcClose;
C_FrameCode_Ping: aDataCode := wdcPing;
C_FrameCode_Pong: aDataCode := wdcPong;
else
raise EIdException.CreateFmt('Unsupported data code: %d', [iCode]);
end;
//Mask: 1 bit
iByte := _GetByte;
bHasMask := (iByte and (1 shl 7)) > 0;
//Length (7 bits or 7+16 bits or 7+64 bits)
iDataLength := (iByte and $7F); //clear 1 MSB
//Extended payload length?
//If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length
if (iDataLength = 126) then
begin
iByte := _GetByte;
iDataLength := (iByte shl 8); //8 MSB
iByte := _GetByte;
iDataLength := iDataLength + iByte;
end
//If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the most significant bit MUST be 0) are the payload length
else if (iDataLength = 127) then
begin
iDataLength := 0;
for i := 7 downto 0 do //read 8 bytes in reverse order
begin
iByte := _GetByte;
iDataLength := iDataLength +
(Int64(iByte) shl (8 * i)); //shift bits to left to recreate 64bit integer
end;
Assert(iDataLength > 0);
end;
//"All frames sent from client to server must have this bit set to 1"
if IsServerSide and not bHasMask then
raise EIdWebSocketHandleError.Create('No mask supplied: mask is required for clients when sending data to server')
else if not IsServerSide and bHasMask then
raise EIdWebSocketHandleError.Create('Mask supplied but mask is not allowed for servers when sending data to clients');
//Masking-key: 0 or 4 bytes
if bHasMask then
begin
rMask.MaskAsBytes[0] := _GetByte;
rMask.MaskAsBytes[1] := _GetByte;
rMask.MaskAsBytes[2] := _GetByte;
rMask.MaskAsBytes[3] := _GetByte;
end;
//Payload data: (x+y) bytes
FWSInputBuffer.Remove(iInputPos); //remove first couple of processed bytes (header)
//simple read?
if not bHasMask then
aData := _GetBytes(iDataLength)
else
//reverse mask
begin
aData := _GetBytes(iDataLength);
iPos := 0;
while iPos < iDataLength do
begin
aData[iPos] := aData[iPos] xor
rMask.MaskAsBytes[iPos mod 4]; //apply mask
inc(iPos);
end;
end;
Result := Length(aData);
end;
function TIdIOHandlerWebsocket.WriteData(aData: TIdBytes;
aType: TWSDataCode; aFIN, aRSV1, aRSV2, aRSV3: boolean): integer;
var
iByte: Byte;
i: NativeInt;
iDataLength, iPos: Int64;
rLength: Int64Rec;
rMask: record
case Boolean of
True : (MaskAsBytes: array[0..3] of Byte);
False: (MaskAsInt : Int32);
end;
strmData: TMemoryStream;
bData: TBytes;
begin
Result := 0;
Assert(Binding <> nil);
strmData := TMemoryStream.Create;
try
(* 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 (nr)
7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0 (bit)
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + *)
//FIN, RSV1, RSV2, RSV3: 1 bit each
if aFIN then iByte := (1 shl 7);
if aRSV1 then iByte := iByte + (1 shl 6);
if aRSV2 then iByte := iByte + (1 shl 5);
if aRSV3 then iByte := iByte + (1 shl 4);
//Opcode: 4 bits
case aType of
wdcContinuation : iByte := iByte + C_FrameCode_Continuation;
wdcText : iByte := iByte + C_FrameCode_Text;
wdcBinary : iByte := iByte + C_FrameCode_Binary;
wdcClose : iByte := iByte + C_FrameCode_Close;
wdcPing : iByte := iByte + C_FrameCode_Ping;
wdcPong : iByte := iByte + C_FrameCode_Pong;
else
raise EIdException.CreateFmt('Unsupported data code: %d', [Ord(aType)]);
end;
strmData.Write(iByte, SizeOf(iByte));
iByte := 0;
//Mask: 1 bit; Note: Clients must apply a mask
if not IsServerSide then iByte := (1 shl 7);
//Length: 7 bits or 7+16 bits or 7+64 bits
if Length(aData) < 126 then //7 bit, 128
iByte := iByte + Length(aData)
else if Length(aData) < 1 shl 16 then //16 bit, 65536
iByte := iByte + 126
else
iByte := iByte + 127;
strmData.Write(iByte, SizeOf(iByte));
//Extended payload length?
if Length(aData) >= 126 then
begin
//If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length
if Length(aData) < 1 shl 16 then //16 bit, 65536
begin
rLength.Lo := Length(aData);
iByte := rLength.Bytes[1];
strmData.Write(iByte, SizeOf(iByte));
iByte := rLength.Bytes[0];
strmData.Write(iByte, SizeOf(iByte));
end
else
//If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the most significant bit MUST be 0) are the payload length
begin
rLength := Int64Rec(Int64(Length(aData)));
for i := 7 downto 0 do
begin
iByte := rLength.Bytes[i];
strmData.Write(iByte, SizeOf(iByte));
end;
end
end;
//Masking-key: 0 or 4 bytes; Note: Clients must apply a mask
if not IsServerSide then
begin
rMask.MaskAsInt := Random(MaxInt);
strmData.Write(rMask.MaskAsBytes[0], SizeOf(Byte));
strmData.Write(rMask.MaskAsBytes[1], SizeOf(Byte));
strmData.Write(rMask.MaskAsBytes[2], SizeOf(Byte));
strmData.Write(rMask.MaskAsBytes[3], SizeOf(Byte));
end;
//write header
strmData.Position := 0;
TIdStreamHelper.ReadBytes(strmData, bData);
Result := Binding.Send(bData);
//Mask? Note: Only clients must apply a mask
if IsServerSide then
begin
Result := Binding.Send(aData);
end
else
begin
iPos := 0;
iDataLength := Length(aData);
//in place masking
while iPos < iDataLength do
begin
iByte := aData[iPos] xor rMask.MaskAsBytes[iPos mod 4]; //apply mask
aData[iPos] := iByte;
inc(iPos);
end;
//send masked data
Result := Binding.Send(aData);
end;
finally
strmData.Free;
end;
end;
end.
|
unit ConsCheNeo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Cons07, JvAppStorage, JvAppIniStorage,
JvComponentBase, JvFormPlacement, wwfltdlg, Menus, Buttons,
Grids, ExtCtrls, ComCtrls, StdCtrls, Mask,
DBCtrls, ActnList, JvBaseDlg, JvProgressDialog, Provider, DB, DBClient,
StdActns, DBActns, ImgList, JvDBSearchComboBox, JvExStdCtrls, JvCombobox,
JvExMask, JvToolEdit, JvMaskEdit, JvDBFindEdit, ToolWin, JvDBGridFooter,
DBGrids, JvExDBGrids, JvDBGrid, JvEdit, JvDBSearchEdit, wwSpeedButton,
wwDBNavigator, wwclearpanel, vcl.wwlocate, vcl.wwIDlg, vcl.wwDialog,
vcl.Wwrcdvw, System.Actions;
resourcestring
rsTodosChe = '*** TODOS ***';
rsCanceChe = '*** CANCELADOS ***';
rsCarteChe = '*** EN CARTERA ***';
type
TFConsCheNeo = class(TFCons07)
ActionList1: TActionList;
Todos: TAction;
Cancel: TAction;
Activos: TAction;
mCheaFec: TAction;
actCheSinRec: TAction;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
DBEdit1: TDBEdit;
DBEdit2: TDBEdit;
DBEdit3: TDBEdit;
DBEdit4: TDBEdit;
DBEdit5: TDBEdit;
DBEdit6: TDBEdit;
DBEdit7: TDBEdit;
DBEdit8: TDBEdit;
DBEdit9: TDBEdit;
CdsNUMERO: TWideStringField;
CdsFECHAING: TDateTimeField;
CdsFECHADEP: TDateTimeField;
CdsNUMBCO: TWideStringField;
CdsNUMCHE: TWideStringField;
CdsIMPORTE: TFloatField;
CdsCLIENTE: TWideStringField;
CdsLOCALIDAD: TWideStringField;
CdsCODDEP: TWideStringField;
CdsCODCTE: TWideStringField;
CdsNUMCTE: TWideStringField;
CdsFIRMANTE: TWideStringField;
CdsCODIGO: TWideStringField;
CdsCANCELADO: TWideStringField;
CdsCODBAJA: TWideStringField;
CdsCTEBAJA: TWideStringField;
CdsNUMCTEBAJA: TWideStringField;
CdsFECBAJA: TDateTimeField;
CdsENDOSO: TWideStringField;
CdsNOMBAN: TWideStringField;
CdsNOMBRE: TWideStringField;
CdsIMAGEN: TWideStringField;
CdsRUTA: TStringField;
procedure TodosExecute(Sender: TObject);
procedure CancelExecute(Sender: TObject);
procedure ActivosExecute(Sender: TObject);
procedure mCheaFecExecute(Sender: TObject);
procedure actCheSinRecExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FrmCons1ImprimirExecute(Sender: TObject);
procedure FrmCons1VisPreExecute(Sender: TObject);
private
{ Private declarations }
FVieSQL: string;
FCan, FMen: string;
procedure SetCan(const Value: string);
public
{ Public declarations }
procedure Requeryconsulta; override;
property Can: string read FCan write SetCan;
end;
var
FConsCheNeo: TFConsCheNeo;
implementation
uses
DetChe, DMCons, SelFechas, SelFecHasta, funcsRb, informes;
{$R *.dfm}
procedure TFConsCheNeo.actCheSinRecExecute(Sender: TObject);
begin
inherited;
with TSelFechasDlg.create( self ) do
try
showmodal;
if modalresult = mrOK then
begin
DCons.TDatos.open;
DCons.qryCheSinRec.Parameters[0].Value := FecIni.date;
DCons.qryCheSinRec.Parameters[1].Value := Fecfin.date;
SetCadenaRb( 'LISTADO de CHEQUES ingresados sin recibo entre el ' + DateTimeToStr(FecIni.Date) + ' y el ' + DateTimeToStr(FecFin.Date));
VerInforme( 'Cheques_Sinrecibo.rtm', DCons.qryCheSinRec, nil, nil, nil, true );
DCons.TDatos.Close;
end;
finally
free;
end;
end;
procedure TFConsCheNeo.ActivosExecute(Sender: TObject);
begin
inherited;
FCan := 'S'; // Diferente de 'N';
FMen := rsCarteChe;
Requeryconsulta;
end;
procedure TFConsCheNeo.CancelExecute(Sender: TObject);
begin
inherited;
FCan := 'N'; // Diferente de 'N';
FMen := rsCanceChe;
Requeryconsulta;
end;
procedure TFConsCheNeo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
cds.Close;
DCons.QConsChe.CommandText := FVieSQL;
end;
procedure TFConsCheNeo.FormCreate(Sender: TObject);
var
x: integer;
FQuery: string;
begin
with DCons do
begin
FCan := 'S'; // diferente de ...
FQuery := QConsChe.CommandText;
x := Pos( 'ORDER', FQuery );
if x > 0 then
begin
FVieSQL := QConsChe.CommandText;
QConsChe.CommandText := Copy( QConsChe.CommandText, 1, x-1 ) + 'ORDER by FECHADEP';
end;
FIni := date-30;
FFin := date+365;
Cds.Params[ 0 ].value := FCan;
cds.Params[ 1 ].value := FIni;
cds.Params[ 2 ].value := FFin;
end;
inherited;
FIni := date-30;
FFin := date+365;
FMen := rsCarteChe;
end;
procedure TFConsCheNeo.FrmCons1ImprimirExecute(Sender: TObject);
begin
inherited;
ListarRegistroDeCheques( false, FMen );
end;
procedure TFConsCheNeo.FrmCons1VisPreExecute(Sender: TObject);
begin
inherited;
ListarRegistroDeCheques( true, FMen );
end;
procedure TFConsCheNeo.mCheaFecExecute(Sender: TObject);
var
Fec: TDateTime;
begin
inherited;
with TSelFecHastaDlg.create( self ) do
try
showmodal;
if modalresult = mrOK then
begin
DCons.TDatos.open;
fec := Fecha.Date;
DCons.QConsCheFec.Parameters.ParamByName( 'FECLIS' ).Value := Fec;
DCons.QConsCheFec.Parameters.ParamByName( 'FECBAJA' ).Value := Fec;
SetCadenaRb( 'LISTADO de CHEQUES al ' + DateTimeToStr(Fecha.date ));
VerInforme( 'Listado_cheques.rtm', DCons.QConsCheFec, nil, nil, nil, true );
DCons.TDatos.Close;
end;
finally
free;
end;
end;
procedure TFConsCheNeo.Requeryconsulta;
begin
// inherited;
with cds do
try
DisableControls;
Close;
Params.paramByName('CANCEL' ).value := FCan;
Params.paramByName('FECI' ).value := FIni;
Params.paramByName('FECF' ).value := FFin;
Open;
finally
EnableControls;
end;
end;
procedure TFConsCheNeo.SetCan(const Value: string);
begin
FCan := Value;
end;
procedure TFConsCheNeo.TodosExecute(Sender: TObject);
begin
inherited;
FCan := 'Z';
FMen := rsTodosChe;
Requeryconsulta;
end;
end.
|
unit qsound;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
timer_engine,sound_engine;
const
QSOUND_CLOCKDIV=166; // Clock divider
QSOUND_CHANNELS=16-1;
type
QSOUND_CHANNEL_def=record
bank, // bank (x16)
address, // start address
pitch, // pitch
reg3, // unknown (always 0x8000)
loop, // loop address
end_addr, // end address
vol, // master volume
pan, // Pan value
reg9:integer; // unknown
// Work variables
key:integer; // Key on / key off
lvol, // left volume
rvol, // right volume
lastdt, // last sample value
offset:integer; // current offset counter
end;
pQSOUND_CHANNEL_def=^QSOUND_CHANNEL_def;
qsound_state_def=record
// Private variables
channel:array[0..QSOUND_CHANNELS] of pQSOUND_CHANNEL_def;
data:word; // register latch data
sample_rom:pbyte; // Q sound sample ROM
sample_rom_length:dword;
pan_table:array[0..33-1] of integer; // Pan volume table
frq_ratio:single; // Frequency ratio
tsample:byte;
out_:array[0..1] of integer;
end;
pqsound_state_def=^qsound_state_def;
var
qsound_state:pqsound_state_def;
procedure qsound_init(sample_size:dword);
procedure qsound_close;
procedure qsound_reset;
procedure qsound_w(offset,data:byte);
function qsound_r:byte;
procedure qsound_sound_update;
implementation
procedure qsound_close;
var
f:byte;
begin
if qsound_state<>nil then begin
freemem(qsound_state.sample_rom);
qsound_state.sample_rom:=nil;
for f:=0 to QSOUND_CHANNELS do begin
freemem(qsound_state.channel[f]);
qsound_state.channel[f]:=nil;
end;
freemem(qsound_state);
qsound_state:=nil;
end;
end;
procedure qsound_reset;
var
f:byte;
begin
for f:=0 to QSOUND_CHANNELS do fillchar(qsound_state.channel[f]^,sizeof(QSOUND_CHANNEL_def),0);
qsound_state.data:=0;
qsound_state.out_[0]:=0;
qsound_state.out_[1]:=0;
end;
procedure qsound_set_command(data:byte;value:word);
var
ch,reg,pandata:byte;
chip:pqsound_state_def;
begin
chip:=qsound_state;
if (data<$80) then begin
ch:=data shr 3;
reg:=data and $07;
end else begin
if (data<$90) then begin
ch:=data-$80;
reg:=8;
end else begin
if ((data>=$ba) and (data<$ca)) then begin
ch:=data-$ba;
reg:=9;
end else begin
// Unknown registers
ch:=99;
reg:=99;
end;
end;
end;
case reg of
0:begin // Bank
ch:=(ch+1) and $0f; // strange...
chip.channel[ch].bank:=(value and $7f) shl 16;
end;
1:chip.channel[ch].address:=value; // start
2:begin // pitch
chip.channel[ch].pitch:=value*16;
if (value=0) then chip.channel[ch].key:=0; // Key off
end;
3:chip.channel[ch].reg3:=value; // unknown
4:chip.channel[ch].loop:=value; // loop offset
5:chip.channel[ch].end_addr:=value; // end
6:begin // master volume
if (value=0) then begin
// Key off
chip.channel[ch].key:=0;
end else if (chip.channel[ch].key=0) then begin
// Key on
chip.channel[ch].key:=1;
chip.channel[ch].offset:=0;
chip.channel[ch].lastdt:=0;
end;
chip.channel[ch].vol:=value;
end;
7:; // unused
8:begin
pandata:=(value-$10) and $3f;
if (pandata>32) then pandata:=32;
chip.channel[ch].rvol:=chip.pan_table[pandata];
chip.channel[ch].lvol:=chip.pan_table[32-pandata];
chip.channel[ch].pan:=value;
end;
9:chip.channel[ch].reg9:=value;
end;
end;
procedure qsound_w(offset,data:byte);
var
chip:pqsound_state_def;
begin
chip:=qsound_state;
case offset of
0:chip.data:=(chip.data and $ff) or (data shl 8);
1:chip.data:=(chip.data and $ff00) or data;
2:qsound_set_command(data, chip.data);
end;
end;
function qsound_r:byte;
begin
// Port ready bit (0x80 if ready)
qsound_r:=$80;
end;
procedure qsound_update_internal;
var
chip:pqsound_state_def;
i:byte;
rvol,lvol,count:integer;
ptemp:pbyte;
pC:pQSOUND_CHANNEL_def;
begin
chip:=qsound_state;
chip.out_[0]:=0;
chip.out_[1]:=0;
for i:=0 to QSOUND_CHANNELS do begin
pC:=chip.channel[i];
if (pC.key<>0) then begin
rvol:=(pC.rvol*pC.vol) div 256;
lvol:=(pC.lvol*pC.vol) div 256;
count:=(pC.offset) shr 16;
pC.offset:=pC.offset and $ffff;
if (count<>0) then begin
pC.address:=pC.address+count;
if (pC.address>= pC.end_addr) then begin
if (pC.loop<>0) then begin
pC.key:=0;
continue;
end;
pC.address:=(pC.end_addr-pC.loop) and $ffff;
end;
ptemp:=chip.sample_rom;
inc(ptemp,(pC.bank+pC.address) and chip.sample_rom_length);
pC.lastdt:=shortint(ptemp^);
end; //del if count
chip.out_[0]:=chip.out_[0]+((pC.lastdt*lvol) div 32);
if chip.out_[0]<-32767 then chip.out_[0]:=-32767
else if chip.out_[0]>32767 then chip.out_[0]:=32767;
chip.out_[1]:=chip.out_[1]+((pC.lastdt*rvol) div 32);
if chip.out_[1]<-32767 then chip.out_[1]:=-32767
else if chip.out_[1]>32767 then chip.out_[1]:=32767;
pC.offset:=pC.offset+pC.pitch;
end; //del if key
end; //del for
end;
procedure qsound_sound_update;
begin
tsample[qsound_state.tsample,sound_status.posicion_sonido]:=qsound_state.out_[0];
tsample[qsound_state.tsample,sound_status.posicion_sonido+1]:=qsound_state.out_[1];
end;
procedure qsound_init(sample_size:dword);
var
f:byte;
begin
getmem(qsound_state,sizeof(qsound_state_def));
for f:=0 to QSOUND_CHANNELS do getmem(qsound_state.channel[f],sizeof(QSOUND_CHANNEL_def));
getmem(qsound_state.sample_rom,sample_size);
qsound_state.frq_ratio:=16;
// Create pan table
for f:=0 to 32 do qsound_state.pan_table[f]:=round((256/sqrt(32))*sqrt(f));
qsound_state.sample_rom_length:=sample_size-1;
timers.init(1,sound_status.cpu_clock/(4000000/QSOUND_CLOCKDIV),qsound_update_internal,nil,true); //Aprox 24.096Hz
qsound_state.tsample:=init_channel;
end;
end.
|
unit WeatherTypeControl;
interface
uses
TypeControl;
const
_WEATHER_UNKNOWN_: LongInt = -1;
WEATHER_CLEAR : LongInt = 0;
WEATHER_CLOUD : LongInt = 1;
WEATHER_RAIN : LongInt = 2;
_WEATHER_COUNT_ : LongInt = 3;
type
TWeatherType = LongInt;
TWeatherTypeArray = TLongIntArray;
TWeatherTypeArray2D = TLongIntArray2D;
TWeatherTypeArray3D = TLongIntArray3D;
TWeatherTypeArray4D = TLongIntArray4D;
TWeatherTypeArray5D = TLongIntArray5D;
implementation
end.
|
unit V8AddIn;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, CTypes, Variants, LCLProc, contnrs;
type
TAppCapabilities = (
eAppCapabilitiesInvalid = -1,
eAppCapabilities1 = 1);
TAppType = (
eAppUnknown = -1,
eAppThinClient = 0,
eAppThickClient,
eAppWebClient,
eAppServer,
eAppExtConn);
TErrorCode = (
ADDIN_E_NONE = 1000,
ADDIN_E_ORDINARY = 1001,
ADDIN_E_ATTENTION = 1002,
ADDIN_E_IMPORTANT = 1003,
ADDIN_E_VERY_IMPORTANT = 1004,
ADDIN_E_INFO = 1005,
ADDIN_E_FAIL = 1006,
ADDIN_E_MSGBOX_ATTENTION = 1007,
ADDIN_E_MSGBOX_INFO = 1008,
ADDIN_E_MSGBOX_FAIL = 1009);
{ TAddIn }
TAddIn = class (Tobject)
public type
TGetMethod = function: Variant of object;
TSetMethod = procedure (AValue: Variant) of object;
TProcMethod = procedure (const Params: array of Variant) of object;
TProc0Method = procedure of object;
TProc1Method = procedure (P1: Variant) of object;
TProc2Method = procedure (P1, P2: Variant) of object;
TProc3Method = procedure (P1, P2, P3: Variant) of object;
TProc4Method = procedure (P1, P2, P3, P4: Variant) of object;
TProc5Method = procedure (P1, P2, P3, P4, P5: Variant) of object;
TFuncMethod = function (const Params: array of Variant): Variant of object;
TFunc0Method = function: Variant of object;
TFunc1Method = function (P1: Variant): Variant of object;
TFunc2Method = function (P1, P2: Variant): Variant of object;
TFunc3Method = function (P1, P2, P3: Variant): Variant of object;
TFunc4Method = function (P1, P2, P3, P4: Variant): Variant of object;
TFunc5Method = function (P1, P2, P3, P4, P5: Variant): Variant of object;
private
FConnection: Pointer;
FMemoryManager: Pointer;
FFactory: Pointer;
protected
class function AppCapabilities: TAppCapabilities; static;
{ IMemoryManager }
function AllocMemory(Size: SizeInt): Pointer;
procedure FreeMemory(var P: Pointer);
{ IAddInDefBase }
function AddError(Code: TErrorCode; const Source, Descr: String; HRes: HRESULT): Boolean;
function Read(const PropName: String; var Value: Variant; var ErrCode: LongWord; var ErrDescriptor: String): Boolean;
function Write(const PropName: PWideChar; const Value: Variant): Boolean;
function RegisterProfileAs(const ProfileName: String): Boolean;
function SetEventBufferDepth(const Depth: Integer): Boolean;
function GetEventBufferDepth: Integer;
function ExternalEvent(const Source, Message, Data: String): Boolean;
procedure CleanEventBuffer;
function SetStatusLine(const StatusLine: String): Boolean;
procedure ResetStatusLine;
{ IPlatformInfo }
function AppVersion: String;
function UserAgentInformation: String;
function ApplicationType: TAppType;
{ IMsgBox }
function Confirm(const QueryText: String; var RetValue: Variant): Boolean; overload;
function Confirm(const QueryText: String): Boolean; overload;
function Alert(const Text: String): Boolean;
public
constructor Create; virtual;
{ IInitDoneBase }
function Init: Boolean; virtual;
function GetInfo: Integer; virtual;
procedure Done; virtual;
{ ILanguageExtenderBase }
function RegisterExtensionAs(var ExtensionName: String): Boolean; virtual;
function GetNProps: Integer; virtual;
function FindProp(const PropName: String): Integer; virtual;
function GetPropName(const PropNum, PropAlias: Integer): String; virtual;
function GetPropVal(const PropNum: Integer; var Value: Variant): Boolean; virtual;
function SetPropVal(const PropNum: Integer; const Value: Variant): Boolean; virtual;
function IsPropReadable(const PropNum: Integer): Boolean; virtual;
function IsPropWritable(const PropNum: Integer): Boolean; virtual;
function GetNMethods: Integer; virtual;
function FindMethod(const AMethodName: String): Integer; virtual;
function GetMethodName(const MethodNum, MethodAlias: Integer): String; virtual;
function GetNParams(const MethodNum: Integer): Integer; virtual;
function GetParamDefValue(const MethodNum, ParamNum: Integer; var Value: Variant): Boolean; virtual;
function HasRetVal(const MethodNum: Integer): Boolean; virtual;
function CallAsProc(const MethodNum: Integer; const Params: array of Variant): Boolean; virtual;
function CallAsFunc(const MethodNum: Integer; var RetValue: Variant; const Params: array of Variant): Boolean; virtual;
{ ILocaleBase }
procedure SetLocale(const Locale: String); virtual;
{ Easy use }
class procedure RegisterAddInClass(const AddInExtensionName: String);
class procedure AddProp(const Name, NameAlias: String; const ReadMethod: TGetMethod = nil; const WriteMethod: TSetMethod = nil);
class procedure AddProc(const Name, NameAlias: String; const Method: TProcMethod; const NParams: Integer); overload;
class procedure AddProc(const Name, NameAlias: String; const Method: TProc0Method); overload;
class procedure AddProc(const Name, NameAlias: String; const Method: TProc1Method); overload;
class procedure AddProc(const Name, NameAlias: String; const Method: TProc2Method); overload;
class procedure AddProc(const Name, NameAlias: String; const Method: TProc3Method); overload;
class procedure AddProc(const Name, NameAlias: String; const Method: TProc4Method); overload;
class procedure AddProc(const Name, NameAlias: String; const Method: TProc5Method); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFuncMethod; const NParams: Integer); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFunc0Method); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFunc1Method); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFunc2Method); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFunc3Method); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFunc4Method); overload;
class procedure AddFunc(const Name, NameAlias: String; const Method: TFunc5Method); overload;
end;
TAddInClass = class of TAddIn;
procedure Unused(const AValue);
procedure RegisterAddInClass(const AddInClass: TAddInClass);
{****************************************************************************
1C binary data
****************************************************************************}
function StreamTo1CBinaryData(const Stream: TStream): Variant;
function Var1CBinaryData: TVarType;
function Is1CBinaryData(const Value: Variant): Boolean;
function Get1CBinaryDataSize(const Value: Variant): SizeInt;
function Get1CBinaryData(const Value: Variant): Pointer;
{****************************************************************************
Exported functions
****************************************************************************}
function GetClassNames: PWideChar; cdecl;
function GetClassObject(const wsName: PWideChar; var pIntf: Pointer): clong; cdecl;
function DestroyObject(var pIntf: Pointer): LongInt; cdecl;
function SetPlatformCapabilities(const Capabilities: TAppCapabilities): TAppCapabilities; cdecl;
implementation
// Use to hide "parameter not used" hints.
{$PUSH}{$HINTS OFF}
procedure Unused(const AValue);
begin
end;
{$POP}
type
TAddInFactory = class;
{$I types.inc}
{$I componentbase.inc}
{$I addindefbase.inc}
{$I imemorymanager.inc}
{$I strings.inc}
{$I binarydata.inc}
{$I variants.inc}
{$I bindings.inc}
var
ClassNames: PWideChar;
ComponentBase: TComponentBase;
AppCapabilities: TAppCapabilities;
FactoryList: TStringList;
{$I factory.inc}
procedure RegisterAddInClass(const AddInClass: TAddInClass);
var
Index: Integer;
Factory: TAddInFactory;
begin
Index := FactoryList.IndexOf(AddInClass.ClassName);
if Index >= 0 then
FactoryList.Delete(Index);
Factory := TAddInFactory.Create;
Factory.AddInClass := AddInClass;
FactoryList.AddObject(AddInClass.ClassName, Factory);
end;
{****************************************************************************
Exported functions
****************************************************************************}
function GetClassNames: PWideChar; cdecl;
begin
if ClassNames = nil then
ClassNames := StringToWideChar(FactoryList.DelimitedText, nil);
Result := ClassNames;
end;
function GetClassNamesS: String;
begin
Result := FactoryList.DelimitedText;
end;
function GetClassObject(const wsName: PWideChar; var pIntf: Pointer): clong;
cdecl;
var
ClassName: String;
Index: Integer;
AddInFactory: TAddInFactory;
begin
Result := 0;
if pIntf <> nil then
Exit;
ClassName := WideCharToString(wsName);
Index := FactoryList.IndexOf(ClassName);
if Index < 0 then
Exit;
AddInFactory := TAddInFactory(FactoryList.Objects[Index]);
pIntf := AddInFactory.New;
{$PUSH}
{$HINTS OFF}
Result := PtrInt(pIntf);
{$POP}
end;
function DestroyObject(var pIntf: Pointer): LongInt; cdecl;
begin
Result := -1;
if pIntf = nil then
Exit;
PComponentBase(pIntf)^.Factory.Delete(pIntf);
Result := 0;
end;
function SetPlatformCapabilities(const Capabilities: TAppCapabilities
): TAppCapabilities; cdecl;
begin
AppCapabilities := Capabilities;
Result := eAppCapabilities1;
end;
{****************************************************************************
TAddIn class
****************************************************************************}
{ TAddIn }
{$PUSH}
{$MACRO ON}
{$define ClassFactory := TAddInFactory(FFactory)}
class function TAddIn.AppCapabilities: TAppCapabilities;
begin
Result := V8AddIn.AppCapabilities;
end;
function TAddIn.AllocMemory(Size: SizeInt): Pointer;
begin
Result := nil;
if FMemoryManager = nil then
Exit;
if not P1CMemoryManager(FMemoryManager)^.__vfptr^.AllocMemory(FMemoryManager, Result, Size) then
Result := nil;
end;
procedure TAddIn.FreeMemory(var P: Pointer);
begin
P1CMemoryManager(FMemoryManager)^.__vfptr^.FreeMemory(FMemoryManager, P);
end;
function TAddIn.AddError(Code: TErrorCode; const Source, Descr: String;
HRes: HRESULT): Boolean;
var
S: PWideChar;
D: PWideChar;
begin
S := StringToWideChar(Source, nil);
D := StringToWideChar(Descr, nil);
Result := PAddInDefBase(FConnection)^.__vfptr^.AddError(FConnection, Ord(Code), S, D, HRes);
FreeMem(S);
FreeMem(D);
end;
function TAddIn.Read(const PropName: String; var Value: Variant;
var ErrCode: LongWord; var ErrDescriptor: String): Boolean;
var
wsPropName: PWideChar;
Val: T1CVariant;
E: culong;
wsDesc: PWideChar;
begin
wsPropName := StringToWideChar(PropName, nil);
Result := PAddInDefBase(FConnection)^.__vfptr^.Read(FConnection, wsPropName, @Val, @E, @wsDesc);
if Result then
begin
From1CVariant(Val, Value);
ErrCode := E;
ErrDescriptor := WideCharToString(wsDesc);
end
else
begin
Value := Unassigned;
ErrCode := 0;
ErrDescriptor := '';
end;
FreeMem(wsPropName);
end;
function TAddIn.Write(const PropName: PWideChar; const Value: Variant): Boolean;
var
wsPropName: PWideChar;
Val: T1CVariant;
begin
wsPropName := StringToWideChar(PropName, nil);
Val.vt := VTYPE_EMPTY;
To1CVariant(Value, Val, FMemoryManager);
Result := PAddInDefBase(FConnection)^.__vfptr^.Write(FConnection, wsPropName, @Val);
FreeMem(wsPropName);
end;
function TAddIn.RegisterProfileAs(const ProfileName: String): Boolean;
var
wsProfileName: PWideChar;
begin
wsProfileName := StringToWideChar(ProfileName, nil);
Result := PAddInDefBase(FConnection)^.__vfptr^.RegisterProfileAs(FConnection, wsProfileName);
FreeMem(wsProfileName);
end;
function TAddIn.SetEventBufferDepth(const Depth: Integer): Boolean;
begin
Result := PAddInDefBase(FConnection)^.__vfptr^.SetEventBufferDepth(FConnection, Depth);
end;
function TAddIn.GetEventBufferDepth: Integer;
begin
Result := PAddInDefBase(FConnection)^.__vfptr^.GetEventBufferDepth(FConnection);
end;
function TAddIn.ExternalEvent(const Source, Message, Data: String): Boolean;
var
wsSource, wsMessage, wsData: PWideChar;
begin
wsSource := StringToWideChar(Source, nil);
wsMessage := StringToWideChar(Message, nil);
wsData := StringToWideChar(Data, nil);
Result := PAddInDefBase(FConnection)^.__vfptr^.ExternalEvent(FConnection, wsSource, wsMessage, wsData);
FreeMem(wsSource);
FreeMem(wsMessage);
FreeMem(wsData);
end;
procedure TAddIn.CleanEventBuffer;
begin
PAddInDefBase(FConnection)^.__vfptr^.CleanEventBuffer(FConnection);
end;
function TAddIn.SetStatusLine(const StatusLine: String): Boolean;
var
wsStatusLine: PWideChar;
begin
wsStatusLine := StringToWideChar(StatusLine, nil);
Result := PAddInDefBase(FConnection)^.__vfptr^.SetStatusLine(FConnection, wsStatusLine);
FreeMem(wsStatusLine);
end;
procedure TAddIn.ResetStatusLine;
begin
PAddInDefBase(FConnection)^.__vfptr^.ResetStatusLine(FConnection);
end;
function TAddIn.AppVersion: String;
var
IFace: PPlatformInfo;
AppInfo: PAppInfo;
begin
IFace := PPlatformInfo(PAddInDefBaseEx(FConnection)^.__vfptr^.GetInterface(FConnection, eIPlatformInfo) - SizeOf(Pointer));
AppInfo := IFace^.__vfptr^.GetPlatformInfo(IFace);
Result := WideCharToString(AppInfo^.AppVersion);
end;
function TAddIn.UserAgentInformation: String;
var
IFace: PPlatformInfo;
AppInfo: PAppInfo;
begin
IFace := PPlatformInfo(PAddInDefBaseEx(FConnection)^.__vfptr^.GetInterface(FConnection, eIPlatformInfo) - SizeOf(Pointer));
AppInfo := IFace^.__vfptr^.GetPlatformInfo(IFace);
Result := WideCharToString(AppInfo^.UserAgentInformation);
end;
function TAddIn.ApplicationType: TAppType;
var
IFace: PPlatformInfo;
AppInfo: PAppInfo;
begin
IFace := PPlatformInfo(PAddInDefBaseEx(FConnection)^.__vfptr^.GetInterface(FConnection, eIPlatformInfo) - SizeOf(Pointer));
AppInfo := IFace^.__vfptr^.GetPlatformInfo(IFace);
Result := AppInfo^.Application;
end;
function TAddIn.Confirm(const QueryText: String; var RetValue: Variant
): Boolean;
var
wsQueryText: PWideChar;
RV: T1CVariant;
IFace: PMsgBox;
begin
RV.vt := VTYPE_EMPTY;
RetValue := Unassigned;
To1CVariant(RetValue, RV, nil);
wsQueryText := StringToWideChar(QueryText, nil);
IFace := PMsgBox(PAddInDefBaseEx(FConnection)^.__vfptr^.GetInterface(FConnection, eIMsgBox) - SizeOf(Pointer));
Result := IFace^.__vfptr^.Confirm(IFace, wsQueryText, @RV);
if Result then
From1CVariant(RV, RetValue);
FreeMem(wsQueryText);
end;
function TAddIn.Confirm(const QueryText: String): Boolean;
var
wsQueryText: PWideChar;
RV: T1CVariant;
IFace: PMsgBox;
RetValue: Variant;
begin
RV.vt := VTYPE_EMPTY;
RetValue := Unassigned;
To1CVariant(RetValue, RV, nil);
wsQueryText := StringToWideChar(QueryText, nil);
IFace := PMsgBox(PAddInDefBaseEx(FConnection)^.__vfptr^.GetInterface(FConnection, eIMsgBox) - SizeOf(Pointer));
Result := IFace^.__vfptr^.Confirm(IFace, wsQueryText, @RV);
if Result then
begin
From1CVariant(RV, RetValue);
Result := RetValue;
end;
FreeMem(wsQueryText);
end;
function TAddIn.Alert(const Text: String): Boolean;
var
wsText: PWideChar;
IFace: PMsgBox;
begin
wsText := StringToWideChar(Text, nil);
IFace := PMsgBox(PAddInDefBaseEx(FConnection)^.__vfptr^.GetInterface(FConnection, eIMsgBox) - SizeOf(Pointer));
Result := IFace^.__vfptr^.Alert(IFace, wsText);
FreeMem(wsText);
end;
constructor TAddIn.Create;
begin
// Do noting by default
end;
function TAddIn.Init: Boolean;
begin
Result := True;
end;
function TAddIn.GetInfo: Integer;
begin
Result := 2000;
end;
procedure TAddIn.Done;
begin
// Do noting by default
end;
function TAddIn.RegisterExtensionAs(var ExtensionName: String): Boolean;
begin
Result := ClassFactory.RegisterExtensionAs(ExtensionName);
end;
function TAddIn.GetNProps: Integer;
begin
Result := ClassFactory.GetNProps();
end;
function TAddIn.FindProp(const PropName: String): Integer;
begin
Result := ClassFactory.FindProp(PropName);
end;
function TAddIn.GetPropName(const PropNum, PropAlias: Integer): String;
begin
Result := ClassFactory.GetPropName(PropNum, PropAlias);
end;
function TAddIn.GetPropVal(const PropNum: Integer; var Value: Variant): Boolean;
begin
Result := False;
try
Result := ClassFactory.GetPropVal(Self, PropNum, Value);
except
on E: Exception do
AddError(ADDIN_E_FAIL, ClassName, E.Message, 0);
end;
end;
function TAddIn.SetPropVal(const PropNum: Integer; const Value: Variant
): Boolean;
begin
Result := False;
try
Result := ClassFactory.SetPropVal(Self, PropNum, Value);
except
on E: Exception do
AddError(ADDIN_E_FAIL, ClassName, E.Message, 0);
end;
end;
function TAddIn.IsPropReadable(const PropNum: Integer): Boolean;
begin
Result := ClassFactory.IsPropReadable(PropNum);
end;
function TAddIn.IsPropWritable(const PropNum: Integer): Boolean;
begin
Result := ClassFactory.IsPropWritable(PropNum);
end;
function TAddIn.GetNMethods: Integer;
begin
Result := ClassFactory.GetNMethods;
end;
function TAddIn.FindMethod(const AMethodName: String): Integer;
begin
Result := ClassFactory.FindMethod(AMethodName);
end;
function TAddIn.GetMethodName(const MethodNum, MethodAlias: Integer): String;
begin
Result := ClassFactory.GetMethodName(MethodNum, MethodAlias);
end;
function TAddIn.GetNParams(const MethodNum: Integer): Integer;
begin
Result := 0;
try
Result := ClassFactory.GetNParams(MethodNum);
except
on E: Exception do
AddError(ADDIN_E_FAIL, ClassName, E.Message, 0);
end;
end;
function TAddIn.GetParamDefValue(const MethodNum, ParamNum: Integer;
var Value: Variant): Boolean;
begin
Unused(MethodNum);
Unused(ParamNum);
Unused(Value);
Result := False;
end;
function TAddIn.HasRetVal(const MethodNum: Integer): Boolean;
begin
Result := False;
try
Result := ClassFactory.HasRetVal(MethodNum);
except
on E: Exception do
AddError(ADDIN_E_FAIL, ClassName, E.Message, 0);
end;
end;
function TAddIn.CallAsProc(const MethodNum: Integer;
const Params: array of Variant): Boolean;
begin
Result := False;
try
Result := ClassFactory.CallAsProc(Self, MethodNum, Params);
except
on E: Exception do
AddError(ADDIN_E_FAIL, ClassName, E.Message, 0);
end;
end;
function TAddIn.CallAsFunc(const MethodNum: Integer; var RetValue: Variant;
const Params: array of Variant): Boolean;
begin
Result := False;
try
Result := ClassFactory.CallAsFunc(Self, MethodNum, RetValue, Params);
except
on E: Exception do
AddError(ADDIN_E_FAIL, ClassName, E.Message, 0);
end;
end;
procedure TAddIn.SetLocale(const Locale: String);
begin
Unused(Locale);
// Do noting by default
end;
{$define ClassFactory := GetClassFactory(Self)}
class procedure TAddIn.RegisterAddInClass(const AddInExtensionName: String);
begin
V8AddIn.RegisterAddInClass(Self);
ClassFactory.AddInExtensionName := AddInExtensionName;
end;
class procedure TAddIn.AddProp(const Name, NameAlias: String;
const ReadMethod: TGetMethod; const WriteMethod: TSetMethod);
begin
ClassFactory.AddProp(Name, NameAlias, ReadMethod, WriteMethod);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProcMethod; const NParams: Integer);
begin
ClassFactory.AddProc(Name, NameAlias, Method, NParams);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProc0Method);
begin
ClassFactory.AddProc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProc1Method);
begin
ClassFactory.AddProc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProc2Method);
begin
ClassFactory.AddProc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProc3Method);
begin
ClassFactory.AddProc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProc4Method);
begin
ClassFactory.AddProc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddProc(const Name, NameAlias: String;
const Method: TProc5Method);
begin
ClassFactory.AddProc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFuncMethod; const NParams: Integer);
begin
ClassFactory.AddFunc(Name, NameAlias, Method, NParams);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFunc0Method);
begin
ClassFactory.AddFunc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFunc1Method);
begin
ClassFactory.AddFunc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFunc2Method);
begin
ClassFactory.AddFunc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFunc3Method);
begin
ClassFactory.AddFunc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFunc4Method);
begin
ClassFactory.AddFunc(Name, NameAlias, Method);
end;
class procedure TAddIn.AddFunc(const Name, NameAlias: String;
const Method: TFunc5Method);
begin
ClassFactory.AddFunc(Name, NameAlias, Method);
end;
{$undef ClassFactory}
{$POP}
{$I init.inc}
initialization
InitUnit;
finalization
ClearUnit;
end.
|
program lil;
{$MODE OBJFPC}{$H+}
uses SysUtils, fplil;
var
Running: Boolean = True;
function FncWriteChar(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue;
begin
if Length(Args)=0 then exit(nil);
Write(Chr(Args[0].IntegerValue));
Result:=nil;
end;
function FncReadLine(LIL: TLIL; Args: TLILFunctionProcArgs): TLILValue;
var
Line: string;
begin
Readln(Line);
Result:=TLIL.AllocString(Line);
end;
procedure REPL;
var
Command: string;
LIL: TLIL;
RetVal: TLILValue;
begin
LIL:=TLIL.Create(nil);
LIL.Register('writechar', @FncWriteChar);
LIL.Register('readline', @FncReadLine);
while Running do begin
Write('# ');
ReadLn(Command);
if Command='' then continue;
RetVal:=LIL.Parse(Command);
if LIL.Error then begin
WriteLn('Error: ' + LIL.ErrorMessage);
end;
if RetVal <> nil then begin
if (not LIL.Error) and (RetVal.Length > 0) then WriteLn(RetVal.StringValue);
RetVal.Free;
end;
end;
LIL.Free;
end;
procedure NonInteractive;
var
LIL: TLIL;
FileName: string;
ArgList: TLILList;
Args, Result: TLILValue;
TmpCode: string;
i: Integer;
begin
LIL:=TLIL.Create(nil);
LIL.Register('writechar', @FncWriteChar);
LIL.Register('readline', @FncReadLine);
FileName:=ParamStr(1);
ArgList:=TLILList.Create;
for i:=2 to ParamCount do ArgList.AddString(ParamStr(i));
Args:=ArgList.ToValue;
FreeAndNil(ArgList);
LIL.SetVar('argv', Args, lsvlGlobal);
FreeAndNil(Args);
TmpCode:='set __lilmain:code__ [read {' + FileName + '}]'#10'if [streq $__lilmain:code__ ''] {print There is no code in the file or the file does not exist} {eval $__lilmain:code__}'#10;
Result:=LIL.Parse(TmpCode);
FreeAndNil(Result);
if LIL.Error then WriteLn('lil: error at ', LIL.ErrorHead, ': ', LIL.ErrorMessage);
FreeAndNil(LIL);
end;
begin
if ParamCount=0 then begin
WriteLn('FreePascal implementation of LIL');
WriteLn('Type "exit" to exit');
WriteLn;
REPL;
end else NonInteractive;
end.
|
unit TTSNOTETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSNOTERecord = record
PLenderNumber: String[4];
PTrackCode: String[8];
PNoticeStage: String[1];
PModCount: Integer;
PLapse: Integer;
PStdLtr: String[1];
PTitle: String[25];
PCoMaker: Boolean;
PCustomer: Boolean;
End;
TTTSNOTEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSNOTERecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSNOTE = (TTSNOTEPrimaryKey);
TTTSNOTETable = class( TDBISAMTableAU )
private
FDFLenderNumber: TStringField;
FDFTrackCode: TStringField;
FDFNoticeStage: TStringField;
FDFModCount: TIntegerField;
FDFLapse: TIntegerField;
FDFStdLtr: TStringField;
FDFTitle: TStringField;
FDFCoMaker: TBooleanField;
FDFCustomer: TBooleanField;
FDFNoticeText: TBlobField;
procedure SetPLenderNumber(const Value: String);
function GetPLenderNumber:String;
procedure SetPTrackCode(const Value: String);
function GetPTrackCode:String;
procedure SetPNoticeStage(const Value: String);
function GetPNoticeStage:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPLapse(const Value: Integer);
function GetPLapse:Integer;
procedure SetPStdLtr(const Value: String);
function GetPStdLtr:String;
procedure SetPTitle(const Value: String);
function GetPTitle:String;
procedure SetPCoMaker(const Value: Boolean);
function GetPCoMaker:Boolean;
procedure SetPCustomer(const Value: Boolean);
function GetPCustomer:Boolean;
procedure SetEnumIndex(Value: TEITTSNOTE);
function GetEnumIndex: TEITTSNOTE;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSNOTERecord;
procedure StoreDataBuffer(ABuffer:TTTSNOTERecord);
property DFLenderNumber: TStringField read FDFLenderNumber;
property DFTrackCode: TStringField read FDFTrackCode;
property DFNoticeStage: TStringField read FDFNoticeStage;
property DFModCount: TIntegerField read FDFModCount;
property DFLapse: TIntegerField read FDFLapse;
property DFStdLtr: TStringField read FDFStdLtr;
property DFTitle: TStringField read FDFTitle;
property DFCoMaker: TBooleanField read FDFCoMaker;
property DFCustomer: TBooleanField read FDFCustomer;
property DFNoticeText: TBlobField read FDFNoticeText;
property PLenderNumber: String read GetPLenderNumber write SetPLenderNumber;
property PTrackCode: String read GetPTrackCode write SetPTrackCode;
property PNoticeStage: String read GetPNoticeStage write SetPNoticeStage;
property PModCount: Integer read GetPModCount write SetPModCount;
property PLapse: Integer read GetPLapse write SetPLapse;
property PStdLtr: String read GetPStdLtr write SetPStdLtr;
property PTitle: String read GetPTitle write SetPTitle;
property PCoMaker: Boolean read GetPCoMaker write SetPCoMaker;
property PCustomer: Boolean read GetPCustomer write SetPCustomer;
published
property Active write SetActive;
property EnumIndex: TEITTSNOTE read GetEnumIndex write SetEnumIndex;
end; { TTTSNOTETable }
procedure Register;
implementation
procedure TTTSNOTETable.CreateFields;
begin
FDFLenderNumber := CreateField( 'LenderNumber' ) as TStringField;
FDFTrackCode := CreateField( 'TrackCode' ) as TStringField;
FDFNoticeStage := CreateField( 'NoticeStage' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFLapse := CreateField( 'Lapse' ) as TIntegerField;
FDFStdLtr := CreateField( 'StdLtr' ) as TStringField;
FDFTitle := CreateField( 'Title' ) as TStringField;
FDFCoMaker := CreateField( 'CoMaker' ) as TBooleanField;
FDFCustomer := CreateField( 'Customer' ) as TBooleanField;
FDFNoticeText := CreateField( 'NoticeText' ) as TBlobField;
end; { TTTSNOTETable.CreateFields }
procedure TTTSNOTETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSNOTETable.SetActive }
procedure TTTSNOTETable.SetPLenderNumber(const Value: String);
begin
DFLenderNumber.Value := Value;
end;
function TTTSNOTETable.GetPLenderNumber:String;
begin
result := DFLenderNumber.Value;
end;
procedure TTTSNOTETable.SetPTrackCode(const Value: String);
begin
DFTrackCode.Value := Value;
end;
function TTTSNOTETable.GetPTrackCode:String;
begin
result := DFTrackCode.Value;
end;
procedure TTTSNOTETable.SetPNoticeStage(const Value: String);
begin
DFNoticeStage.Value := Value;
end;
function TTTSNOTETable.GetPNoticeStage:String;
begin
result := DFNoticeStage.Value;
end;
procedure TTTSNOTETable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSNOTETable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSNOTETable.SetPLapse(const Value: Integer);
begin
DFLapse.Value := Value;
end;
function TTTSNOTETable.GetPLapse:Integer;
begin
result := DFLapse.Value;
end;
procedure TTTSNOTETable.SetPStdLtr(const Value: String);
begin
DFStdLtr.Value := Value;
end;
function TTTSNOTETable.GetPStdLtr:String;
begin
result := DFStdLtr.Value;
end;
procedure TTTSNOTETable.SetPTitle(const Value: String);
begin
DFTitle.Value := Value;
end;
function TTTSNOTETable.GetPTitle:String;
begin
result := DFTitle.Value;
end;
procedure TTTSNOTETable.SetPCoMaker(const Value: Boolean);
begin
DFCoMaker.Value := Value;
end;
function TTTSNOTETable.GetPCoMaker:Boolean;
begin
result := DFCoMaker.Value;
end;
procedure TTTSNOTETable.SetPCustomer(const Value: Boolean);
begin
DFCustomer.Value := Value;
end;
function TTTSNOTETable.GetPCustomer:Boolean;
begin
result := DFCustomer.Value;
end;
procedure TTTSNOTETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNumber, String, 4, N');
Add('TrackCode, String, 8, N');
Add('NoticeStage, String, 1, N');
Add('ModCount, Integer, 0, N');
Add('Lapse, Integer, 0, N');
Add('StdLtr, String, 1, N');
Add('Title, String, 25, N');
Add('CoMaker, Boolean, 0, N');
Add('Customer, Boolean, 0, N');
Add('NoticeText, Memo, 0, N');
end;
end;
procedure TTTSNOTETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNumber;TrackCode;NoticeStage, Y, Y, N, N');
end;
end;
procedure TTTSNOTETable.SetEnumIndex(Value: TEITTSNOTE);
begin
case Value of
TTSNOTEPrimaryKey : IndexName := '';
end;
end;
function TTTSNOTETable.GetDataBuffer:TTTSNOTERecord;
var buf: TTTSNOTERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNumber := DFLenderNumber.Value;
buf.PTrackCode := DFTrackCode.Value;
buf.PNoticeStage := DFNoticeStage.Value;
buf.PModCount := DFModCount.Value;
buf.PLapse := DFLapse.Value;
buf.PStdLtr := DFStdLtr.Value;
buf.PTitle := DFTitle.Value;
buf.PCoMaker := DFCoMaker.Value;
buf.PCustomer := DFCustomer.Value;
result := buf;
end;
procedure TTTSNOTETable.StoreDataBuffer(ABuffer:TTTSNOTERecord);
begin
DFLenderNumber.Value := ABuffer.PLenderNumber;
DFTrackCode.Value := ABuffer.PTrackCode;
DFNoticeStage.Value := ABuffer.PNoticeStage;
DFModCount.Value := ABuffer.PModCount;
DFLapse.Value := ABuffer.PLapse;
DFStdLtr.Value := ABuffer.PStdLtr;
DFTitle.Value := ABuffer.PTitle;
DFCoMaker.Value := ABuffer.PCoMaker;
DFCustomer.Value := ABuffer.PCustomer;
end;
function TTTSNOTETable.GetEnumIndex: TEITTSNOTE;
var iname : string;
begin
result := TTSNOTEPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSNOTEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSNOTETable, TTTSNOTEBuffer ] );
end; { Register }
function TTTSNOTEBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..9] of string = ('LENDERNUMBER','TRACKCODE','NOTICESTAGE','MODCOUNT','LAPSE','STDLTR'
,'TITLE','COMAKER','CUSTOMER' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 9) and (flist[x] <> s) do inc(x);
if x <= 9 then result := x else result := 0;
end;
function TTTSNOTEBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
5 : result := ftInteger;
6 : result := ftString;
7 : result := ftString;
8 : result := ftBoolean;
9 : result := ftBoolean;
end;
end;
function TTTSNOTEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNumber;
2 : result := @Data.PTrackCode;
3 : result := @Data.PNoticeStage;
4 : result := @Data.PModCount;
5 : result := @Data.PLapse;
6 : result := @Data.PStdLtr;
7 : result := @Data.PTitle;
8 : result := @Data.PCoMaker;
9 : result := @Data.PCustomer;
end;
end;
end.
|
unit SDBFile;
{
Autor: Ulrich Hornung
Datum: 14.7.2007
1. Make a construtor Create, where you set the FHeaderSize and the FItemSize
}
interface
uses
Classes, SysUtils;
type
ESimpleDBStreamNROutOfRange = Exception;
TSimpleDBStream = class
private
FStream: TStream;
protected
FHeaderSize: Integer;
FItemSize: Integer;
procedure GetItem(const nr: Integer; var buf);
procedure SetItem(const nr: Integer; var buf);
function GetHeader(var buf): Boolean;
procedure SetHeader(var buf);
function GetCount: Integer; virtual;
procedure SetCount(newCount: Integer); virtual;
public
constructor Create;
destructor Destroy; override;
property Count: Integer read GetCount write SetCount;
end;
TSimpleDBFile = class(TSimpleDBStream)
private
FFilename: string;
public
constructor Create(aFilename: string);
destructor Destroy; override;
end;
TSimpleDBCachedFile = class(TSimpleDBFile)
protected
FPtrList: TList;
//-------- Umwandlung von buf -> ptr START ---------------------------------
function NewItemPtr: pointer; virtual; abstract;
procedure ItemToPtr(var Buf; const p: pointer); virtual; abstract;
procedure PtrToItem(const p: pointer; var Buf); virtual; abstract;
procedure DisposeItemPtr(const p: pointer); virtual; abstract;
//-------- Umwandlung von buf -> ptr ENDE ----------------------------------
procedure ClearList;
procedure LoadList;
function GetCachedItem(const nr: Integer): pointer;
procedure SetItem(const nr: Integer; const ptr: pointer);
procedure SetCount(newCount: Integer); override;
function GetCount: Integer; override;
public
constructor Create(aFilename: string; doLoad: Boolean = True);
destructor Destroy; override;
end;
implementation
uses Math;
constructor TSimpleDBStream.Create;
begin
inherited;
end;
destructor TSimpleDBStream.Destroy;
begin
inherited;
end;
constructor TSimpleDBFile.Create(aFilename: string);
begin
inherited Create();
FFilename := aFilename;
if FileExists(aFilename) then
FStream := TFileStream.Create(FFilename,fmOpenReadWrite or fmShareDenyWrite)
else
FStream := TFileStream.Create(FFilename,fmCreate or fmShareDenyWrite);
end;
destructor TSimpleDBFile.Destroy;
begin
FStream.Free;
inherited;
end;
procedure TSimpleDBStream.GetItem(const nr: Integer;
var buf);
begin
if (nr < Count)and(nr >= 0) then
begin
FStream.Position := FHeaderSize + (FItemSize * nr);
FStream.ReadBuffer(buf,FItemSize);
end else raise ESimpleDBStreamNROutOfRange.Create
('TSimpleDBStream.GetItem: nr(' + IntToStr(nr) + ') out of range!');
end;
procedure TSimpleDBStream.SetItem(const nr: Integer;
var buf);
begin
if (nr < Count+1)and(nr >= 0) then
begin
FStream.Position := FHeaderSize + (FItemSize * nr);
FStream.WriteBuffer(buf,FItemSize);
end else raise ESimpleDBStreamNROutOfRange.Create
('TSimpleDBStream.SetItem: nr(' + IntToStr(nr) + ') out of range!');
end;
function TSimpleDBStream.GetHeader(var buf): Boolean;
begin
FStream.Position := 0;
Result := (FStream.Read(buf,FHeaderSize) = FHeaderSize);
end;
procedure TSimpleDBStream.SetHeader(var buf);
begin
FStream.Position := 0;
FStream.WriteBuffer(buf,FHeaderSize);
end;
function TSimpleDBStream.GetCount: Integer;
begin
Result := (FStream.Size - FHeaderSize) div FItemSize;
end;
procedure TSimpleDBStream.SetCount(newCount: Integer);
begin
FStream.Size := FHeaderSize + (FItemSize * newCount);
end;
procedure TSimpleDBCachedFile.ClearList;
var i: Integer;
begin
for i := 0 to FPtrList.Count-1 do
begin
DisposeItemPtr(FPtrList[i]);
end;
FPtrList.Clear;
end;
constructor TSimpleDBCachedFile.Create(aFilename: string;
doLoad: Boolean = True);
begin
inherited Create(aFilename);
FPtrList := TList.Create;
if doLoad then
LoadList;
end;
destructor TSimpleDBCachedFile.Destroy;
begin
if FPtrList <> nil then
ClearList;
FPtrList.Free;
inherited;
end;
function TSimpleDBCachedFile.GetCachedItem(const nr: Integer): pointer;
begin
result := FPtrList[nr];
end;
function TSimpleDBCachedFile.GetCount: Integer;
begin
//Hier wird die geerbte Methode nicht aufgerufen,
//da diese direkt auf die Datei zugreift.
//Jedoch haben wir "Count" auch schon in der Liste gecached!
Result := FPtrList.Count;
end;
procedure TSimpleDBCachedFile.LoadList;
var i: Integer;
buf, p: pointer;
begin
FPtrList.Count := inherited GetCount;
GetMem(buf,FItemSize);
for i := 0 to FPtrList.Count-1 do
begin
p := NewItemPtr;
GetItem(i,buf^);
ItemToPtr(buf^,p);
FPtrList[i] := p;
end;
FreeMem(buf);
end;
procedure TSimpleDBCachedFile.SetCount(newCount: Integer);
var i, oldCount: Integer;
begin
oldCount := FPtrList.Count;
if (newCount > oldCount) then
begin
// organise capacity better than default behaviour:
if FPtrList.Capacity < newCount then
FPtrList.Capacity := newCount + 200;
FPtrList.Count := newCount;
for i := oldCount to newCount-1 do
FPtrList[i] := NewItemPtr;
end;
inherited;
if (newCount < oldCount) then
begin
for i := oldCount-1 downto newCount do
DisposeItemPtr(FPtrList[i]);
FPtrList.Count := newCount;
end;
end;
procedure TSimpleDBCachedFile.SetItem(const nr: Integer;
const ptr: pointer);
var buf: pointer;
begin
GetMem(buf,FItemSize);
PtrToItem(ptr,buf^);
inherited SetItem(nr, buf^);
ItemToPtr(buf^,FPtrList[nr]);
FreeMem(buf);
end;
end.
|
unit l3SysUtils;
{ Библиотека "L3 (Low Level Library)" }
{ Автор: Люлин А.В. © }
{ Модуль: l3SysUtils - }
{ Начат: 27.05.2005 14:22 }
{ $Id: l3SysUtils.pas,v 1.11 2015/12/11 21:19:47 lulin Exp $ }
// $Log: l3SysUtils.pas,v $
// Revision 1.11 2015/12/11 21:19:47 lulin
// - отлаживаем для удалённой сессии.
//
// Revision 1.10 2015/09/08 07:57:41 lulin
// - правим под XE.
//
// Revision 1.9 2014/10/27 14:48:04 lulin
// - bug fix: не падаем под Win 2000 при ненахождении функции.
//
// Revision 1.8 2011/11/02 15:27:29 lulin
// - переносим утилитную функцию в более подходящее место.
//
// Revision 1.7 2011/10/12 16:00:54 lulin
// {RequestLink:234363429}.
// - оставляем результаты НИР пока на память.
//
// Revision 1.6 2010/10/06 09:28:47 lulin
// {RequestLink:235864089}.
//
// Revision 1.5 2010/09/22 08:59:23 lulin
// {RequestLink:235053347}.
//
// Revision 1.4 2010/09/14 13:12:09 lulin
// {RequestLink:235048134}.
//
// Revision 1.3 2010/07/28 14:47:57 lulin
// {RequestLink:228692580}.
// - выделяем утилитную функию для узнавания того, что работает под 64-разрядной операционной системой.
//
// Revision 1.2 2008/09/10 13:12:27 lulin
// - <K>: 88080895.
//
// Revision 1.1 2005/05/27 12:06:04 lulin
// - убраны лишние зависимости.
//
{$Include l3Define.inc }
interface
uses
Windows,
l3Interfaces
;
function l3GetCursorPos(var lpPoint: TPoint): WinBOOL;
stdcall;
{-}
function l3RegisterDragDrop(wnd: HWnd; dropTarget: IDropTarget): HResult;
stdcall;
{-}
function l3DoDragDrop(dataObj: IDataObject; dropSource: IDropSource;
dwOKEffects: Longint; var dwEffect: Longint): HResult;
stdcall;
{-}
function l3RevokeDragDrop(wnd: HWnd): HResult;
stdcall;
{-}
procedure l3ReleaseStgMedium(var medium: Tl3StoragePlace);
stdcall;
{-}
function l3OleInitialize(pwReserved: Pointer = nil): HResult;
stdcall;
{-}
procedure l3OleUninitialize;
stdcall;
{-}
procedure OleCheck(Result: HResult);
{-}
function OleGetClipboard(out dataObj: IDataObject): HResult;
stdcall;
{-}
function l3Is64System: Boolean;
{-}
function l3NeedsHackFor64System: Boolean;
{-}
function l3IsRemoteSession: Boolean;
{-}
procedure ImmDisableIME;
{-}
function l3IsTimeElapsed(aStartTime : Longword; aTimeOut : Longword) : boolean;
{-}
function l3WTSGetActiveConsoleSessionId: DWORD; stdcall;
implementation
uses
ComObj,
//Windows,
SysUtils
;
const
{$IFDEF MSWINDOWS}
advapi32 = 'advapi32.dll';
kernel32 = 'kernel32.dll';
mpr = 'mpr.dll';
{$EXTERNALSYM version}
version = 'version.dll';
comctl32 = 'comctl32.dll';
gdi32 = 'gdi32.dll';
opengl32 = 'opengl32.dll';
user32 = 'user32.dll';
wintrust = 'wintrust.dll';
msimg32 = 'msimg32.dll';
{$ENDIF}
{$IFDEF LINUX}
advapi32 = 'libwine.borland.so';
kernel32 = 'libwine.borland.so';
mpr = 'libmpr.borland.so';
version = 'libversion.borland.so';
{$EXTERNALSYM version}
comctl32 = 'libcomctl32.borland.so';
gdi32 = 'libwine.borland.so';
opengl32 = 'libopengl32.borland.so';
user32 = 'libwine.borland.so';
wintrust = 'libwintrust.borland.so';
msimg32 = 'libmsimg32.borland.so';
{$ENDIF}
{$IFDEF MSWINDOWS}
ole32 = 'ole32.dll';
oleaut32 = 'oleaut32.dll';
olepro32 = 'olepro32.dll';
{$ENDIF}
{$IFDEF LINUX}
ole32 = 'libole32.borland.so';
oleaut32 = 'liboleaut32.borland.so';
olepro32 = 'libolepro32.borland.so';
{$ENDIF}
function l3RegisterDragDrop;
external ole32 name 'RegisterDragDrop';
{-}
function l3DoDragDrop;
external ole32 name 'DoDragDrop';
{-}
function l3RevokeDragDrop;
external ole32 name 'RevokeDragDrop';
{-}
function l3GetCursorPos;
external user32 name 'GetCursorPos';
{-}
procedure l3ReleaseStgMedium;
external ole32 name 'ReleaseStgMedium';
{-}
function l3OleInitialize;
external ole32 name 'OleInitialize';
{-}
procedure l3OleUninitialize;
external ole32 name 'OleUninitialize';
{-}
function OleGetClipboard;
{-}
external ole32 name 'OleGetClipboard';
procedure OleCheck(Result: HResult);
begin
ComObj.OleCheck(Result);
end;
function l3Is64System: Boolean;
type
TIsWow64Process = function (handle:THandle;var x64:Windows.BOOL): Windows.BOOL; stdcall;
{$WriteableConst On}
const
Inited : Boolean = false;
l_Is : Boolean = false;
{$WriteableConst Off}
var
l_DLL : THandle;
l_P : TIsWow64Process;
l_x64 : Windows.BOOL;
begin
if not Inited then
begin
Inited := true;
l_DLL := LoadLibrary('kernel32');
try
if (l_DLL <> 0) then
begin
l_P := GetProcAddress(l_DLL, 'IsWow64Process');
if Assigned(l_P) then
if l_P(GetCurrentProcess, l_x64) then
l_Is := l_x64
else
Assert(false);
end;//l_DLL <> 0
finally
FreeLibrary(l_DLL);
end;//try..finally
end;//not Inited
Result := l_Is;
end;
function l3NeedsHackFor64System: Boolean;
{-}
begin
Result := false;
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
if (Win32MajorVersion >= 5{6}) then
// ^ - потому что под терминалом почему-то возвращается 5
// "почему-то" - там и 3 может быть :-) если "режим совместимости"
// руками поставить
// - Vista
if l3Is64System then
Result := true;
end;
function l3IsRemoteSession: Boolean;
const
sm_RemoteSession = $1000;
begin
Result := GetSystemMetrics(sm_RemoteSession) <> 0;
end;
procedure ImmDisableIME;
{-}
function _ImmDisableIME(idThread: DWORD): BOOL;
type
TProcType = function (idThread: DWORD): BOOL; stdcall;
var
l_ProcAddress: Pointer;
l_Lib : THandle;
begin//_ImmDisableIME
l_Lib := LoadLibrary('Imm32.dll');
if (l_Lib <> 0) then
try
l_ProcAddress := GetProcAddress(l_Lib, 'ImmDisableIME');
if not Assigned(l_ProcAddress) then
Result := true
else
Result := TProcType(l_ProcAddress)(idThread);
finally
FreeLibrary(l_Lib);
end//try..finally
else
Result := true;
end;//_ImmDisableIME
begin
_ImmDisableIME({DWORD(-1)}GetCurrentThreadID);
end;
function l3IsTimeElapsed(aStartTime : Longword; aTimeOut : Longword) : boolean;
var
lCurTime : Longword;
begin
lCurTime := GetTickCount;
if aStartTime > lCurTime then // перевалили за High(Longword)
Result := (High(Longword) - aStartTime + lCurTime) > aTimeOut
else
Result := (lCurTime - aStartTime) > aTimeOut;
end;
procedure GetProcedureAddress(var P: Pointer; const ModuleName, ProcName: string);
var
ModuleHandle: HMODULE;
begin
if not Assigned(P) then
begin
{$IfDef XE}
ModuleHandle := GetModuleHandle(PChar(ModuleName));
{$Else XE}
ModuleHandle := GetModuleHandle(PAnsiChar(ModuleName));
{$EndIf XE}
if ModuleHandle = 0 then
begin
{$IfDef XE}
ModuleHandle := LoadLibrary(PChar(ModuleName));
{$Else XE}
ModuleHandle := LoadLibrary(PAnsiChar(ModuleName));
{$EndIf XE}
if ModuleHandle = 0 then raise {EJwaLoadLibraryError}Exception.Create('Library not found: ' + ModuleName);
end;
P := GetProcAddress(ModuleHandle, PAnsiChar(ProcName));
if not Assigned(P) then raise {EJwaGetProcAddressError}Exception.Create('Function not found: ' + ModuleName + '.' + ProcName);
end;
end;
var
_WTSGetActiveConsoleSessionId: Pointer;
function l3WTSGetActiveConsoleSessionId: DWORD; stdcall;
begin
GetProcedureAddress(_WTSGetActiveConsoleSessionId, kernel32, 'WTSGetActiveConsoleSessionId');
if (_WTSGetActiveConsoleSessionId = nil) then
begin
Result := 0;
Exit;
end;//_WTSGetActiveConsoleSessionId = nil
asm
mov esp, ebp
pop ebp
jmp [_WTSGetActiveConsoleSessionId]
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
{
Este é um clone para permitir compatibilidade com versões anteriors ao XE7;
Não é um clone completo, implmenta somente funcionalidade mais básicas;
Possui dependência de AsyncCalls (é free) - fácil entrar na net;
}
unit System.Threading;
{ Wrap for System.Threading }
interface
Uses SysUtils, Classes, System.SyncObjs,
WinApi.Windows;
type
TInteratorEvent = procedure(sender: TObject; index: integer) of object;
TThreadPool = Class // dummy para compatibilidade de codigo com XE7
public
MaxWorkerThreads: integer;
class function Default: TThreadPool; static;
end;
TParallel = class sealed
public type
TLoopResult = record
private
FCompleted: Boolean;
// FLowestBreakIteration: Variant;
public
property Completed: Boolean read FCompleted;
// property LowestBreakIteration: Variant read FLowestBreakIteration;
end;
public
class function &For(ALowInclusive, AHighInclusive: integer;
const Proc: TProc<integer>): TLoopResult; overload;
class function ForWorker(sender: TObject; AEvent: TInteratorEvent;
ALowInclusive, AHighInclusive: integer; const Proc: TProc<integer>)
: TLoopResult; overload;
end;
TTaskStatus = (Created, WaitingToRun, Running, Completed, WaitingForChildren,
Canceled, tsException);
{ TPDVCargaItem }
Type
TThreadTasked = class(TThread) // nao usar.... somente para compatibilidade
public
procedure Cancel;
function Status: TTaskStatus;
end;
ITask = interface
['{8E2DC915-6BA3-4500-8DF9-B603CA79CF8F}']
procedure Start;
function Handle: THandle;
function Status: TTaskStatus;
function WaitFor(Timeout: LongWord = INFINITE): Cardinal;
function Wait(Timeout: LongWord = INFINITE): Boolean;
end;
IFuture<T> = interface
['{8E2DC915-6BA3-4500-8DF9-B603CA79CF9F}']
function Value: T;
procedure StartFuture;
function WaitFor(Timeout: LongWord = INFINITE): Cardinal;
end;
TTask = record
private
type
TThreadLocal = class(TThread)
public
FProc: TProc;
procedure execute; override;
end;
TThreadTask<T> = class(TInterfacedObject, ITask, IFuture<T>)
private
AThread: TThread;
FTProc: TProc;
FEvent: TEvent;
FTaskStatus: TTaskStatus;
public
FResult: T;
FFunc: TFunc<T>;
FObject:TObject;
FObjectNotifyEvent:TNotifyEvent;
function Value: T;
procedure execute; virtual;
procedure Start;
procedure StartFuture;
function Handle: THandle;
constructor create;
destructor destroy; override;
function Status: TTaskStatus;
function WaitFor(Timeout: LongWord = INFINITE): Cardinal;
function Wait(Timeout: LongWord = INFINITE): Boolean;
procedure ExecuteFuture; virtual;
end;
private
public
class function create(Proc: TProc): ITask;overload; static;
class function create(AObj:TObject;AEvent:TNotifyEvent):ITask;overload;static;
class function Future<T>(func: TFunc<T>): IFuture<T>; static;
class function WaitForAll(const Tasks: array of ITask;
Timeout: LongWord = INFINITE): Boolean; static;
class function WaitForAny(const Tasks: array of ITask): Boolean; static;
// class procedure Run(Proc: TProc);overload; static;
class function Run(Proc: TProc): ITask; overload; static;
class function CurrentTask: TThreadTasked; static;
end;
implementation
Uses AsyncCalls;
procedure TThreadTasked.Cancel;
begin
Terminate
end;
{ TTask }
constructor TTask.TThreadTask<T>.create;
begin
inherited create;
FEvent := TEvent.create(nil, false, false, 'TaskThreading');
FTaskStatus := Created;
end;
destructor TTask.TThreadTask<T>.destroy;
begin
// FEvent.SetEvent;
FreeAndNil(AThread);
FreeAndNil(FEvent);
inherited destroy;
end;
procedure TTask.TThreadTask<T>.execute;
begin
FTaskStatus := Running;
try
if assigned(FTProc) then
FTProc
else
if assigned(FObjectNotifyEvent) then
FObjectNotifyEvent(FObject);
finally
if assigned(FEvent) then
FEvent.SetEvent;
FTaskStatus := TTaskStatus.Completed;
end;
end;
function TTask.TThreadTask<T>.Handle: THandle;
begin
result := FEvent.Handle;
end;
procedure TTask.TThreadTask<T>.Start;
//var
// A: TThread;
begin
// A := TThread.CreateAnonymousThread(execute); // testado - OK;
FTaskStatus := TTaskStatus.WaitingToRun;
// A.start;
TThread.Synchronize(nil,execute); // para forcar isolamento de acesso
end;
procedure TTask.TThreadTask<T>.StartFuture;
begin
AThread := TThreadTasked.CreateAnonymousThread(ExecuteFuture);
AThread.FreeOnTerminate := false;
FTaskStatus := TTaskStatus.WaitingToRun;
AThread.Start; // testado OK;
end;
function TTask.TThreadTask<T>.Status: TTaskStatus;
begin
result := FTaskStatus;
end;
function TTask.TThreadTask<T>.Wait(Timeout: LongWord): Boolean;
var
rt: Cardinal;
begin
rt := WaitForSingleObject(Handle, Timeout);
result := (rt = WAIT_OBJECT_0);
end;
function TTask.TThreadTask<T>.WaitFor(Timeout: LongWord = INFINITE): Cardinal;
begin
if assigned(AThread) then
begin
result := WaitForSingleObject(AThread.Handle, Timeout);
// if result<>WAIT_OBJECT_0 then -- verifica no XE7 qual o comportamento quando ocorre timeout. (termina ?)
// AThread.Terminate;
end;
end;
class function TTask.create(Proc: TProc): ITask;
var
FThread: TThreadTask<Boolean>;
begin
FThread := TThreadTask<Boolean>.create;
FThread.FTProc := Proc;
result := FThread;
end;
class function TTask.create(AObj: TObject; AEvent: TNotifyEvent): ITask;
var
FThread: TThreadTask<Boolean>;
begin
FThread := TThreadTask<Boolean>.create;
FThread.FObjectNotifyEvent := AEvent;
FThread.FObject := AObj;
{ FThread.FTProc := procedure
begin
AEvent(AObj);
end;
}
result := FThread;
end;
class function TTask.CurrentTask: TThreadTasked;
begin
result := TThreadTasked(TThread.CurrentThread);
end;
class function TTask.Future<T>(func: TFunc<T>): IFuture<T>;
var
FThread: TThreadTask<T>;
begin
FThread := TThreadTask<T>.create;
FThread.FFunc := func;
FThread.StartFuture;
result := FThread; // testado OK;
end;
class function TTask.Run(Proc: TProc): ITask;
begin
result := TTask.create(Proc);
result.Start;
end;
{ class Procedure TTask.Run(Proc: TProc);
begin
TThread.CreateAnonymousThread(
procedure
begin
Proc;
end).Start;
end;
}
class function TTask.WaitForAll(const Tasks: array of ITask;
Timeout: LongWord = INFINITE): Boolean;
var
i: integer;
n: integer;
r: word;
begin
result := false;
n := getTickCount;
r := Timeout;
for i := low(Tasks) to high(Tasks) do
if Tasks[i].Status in [TTaskStatus.WaitingToRun, TTaskStatus.Running] then
begin
Tasks[i].WaitFor(r);
r := r - (getTickCount - n);
if r < 0 then
break;
end;
result := true;
end;
class function TTask.WaitForAny(const Tasks: array of ITask): Boolean;
var
i: integer;
begin
result := false;
if Length(Tasks) > 0 then
while result = false do
for i := low(Tasks) to high(Tasks) do
if (Tasks[i].Status in [TTaskStatus.Completed]) then
begin
result := true;
exit;
end;
end;
{ TParallel }
type
TAsyncCallsHelper = class helper for TAsyncCalls
class function CreateAnonymousThreadInteger(AProc: TProc<integer>;
i: integer): IAsyncCall;
end;
class function TParallel.&For(ALowInclusive, AHighInclusive: integer;
const Proc: TProc<integer>): TLoopResult;
begin
result := TParallel.ForWorker(nil, TInteratorEvent(nil), ALowInclusive,
AHighInclusive, Proc); // testado OK
end;
// class function ForWorker(Sender: TObject; AEvent: TIteratorEvent; AStateEvent: TIteratorStateEvent; const AProc: TProc<Integer>; const AProcWithState: TProc<Integer, TLoopState>; ALowInclusive, AHighExclusive, AStride: Integer; APool: TThreadPool): TLoopResult; static;
class function TParallel.ForWorker(sender: TObject; AEvent: TInteratorEvent;
ALowInclusive, AHighInclusive: integer; const Proc: TProc<integer>)
: TLoopResult;
var
tsk: array of IAsyncCall;
i, n, k: integer;
cnt: integer;
A: IAsyncCall;
begin
result.FCompleted := false;
n := AHighInclusive - ALowInclusive + 1;
if n <= 0 then
exit;
SetLength(tsk, AHighInclusive - ALowInclusive + 1);
cnt := low(tsk);
for i := ALowInclusive to AHighInclusive do
begin
tsk[cnt] := TAsyncCalls.CreateAnonymousThreadInteger(
procedure(x: integer)
begin
Proc(x);
if assigned(AEvent) then
AEvent(sender, k);
end, i);
inc(cnt);
end;
AsyncMultiSync(tsk);
end;
{ TThreadHelper }
class function TAsyncCallsHelper.CreateAnonymousThreadInteger
(AProc: TProc<integer>; i: integer): IAsyncCall;
begin
result := TAsyncCalls.Invoke(
procedure
begin
AProc(i);
end);
end;
{ TTask.TThreadTaskFuture }
procedure TTask.TThreadTask<T>.ExecuteFuture;
begin
FTaskStatus := Running;
try
FResult := FFunc();
finally
FEvent.SetEvent;
FTaskStatus := TTaskStatus.Completed;
end;
end;
function TTask.TThreadTask<T>.Value: T;
begin
AThread.WaitFor;
result := FResult; // testado OK
end;
{ TThreadPool }
var
FThreadedPool: TThreadPool;
class function TThreadPool.Default: TThreadPool;
begin
if not assigned(FThreadedPool) then
begin
FThreadedPool := TThreadPool.create;
FThreadedPool.MaxWorkerThreads := GetMaxAsyncCallThreads;
end;
result := FThreadedPool;
end;
{ TTask.TThreadLocal }
procedure TTask.TThreadLocal.execute;
begin
inherited;
FProc;
end;
function TThreadTasked.Status: TTaskStatus;
begin
if Terminated then
result := TTaskStatus.Canceled;
if Suspended then
result := TTaskStatus.WaitingToRun;
if Finished then
result := TTaskStatus.Completed;
end;
initialization
finalization
FreeAndNil(FThreadedPool);
end.
|
unit clEnvioEMail;
interface
uses IdSMTP, IdMessage, IdText, IdAttachmentFile, IdSSLOpenSSL,
IdExplicitTLSClientServerBase, IdIOHandler, SysUtils, Classes,
dialogs;
type
TEnviarEmail = class(TObject)
private
protected
{ protected declarations }
public
{ public declarations }
function EnviarEmail(Dominio, Porta, Usuario, Senha, DeNome, DeEmail, Para,
Assunto, Corpo, CC: String; CorpoMIME, AnexoMIME: Integer;
AutoResposta: Boolean; Anexo: TStrings): Boolean;
function EmailTipoMIME(TipoMIME: Integer): String;
published
{ published declarations }
end;
implementation
{ TEnviarEmail }
uses
clUtil;
// ————————————————–
// Enviar E-mail via SMTP.
// ————————————————–
function TEnviarEmail.EnviarEmail(Dominio, Porta, Usuario, Senha, DeNome,
DeEmail, Para, Assunto, Corpo, CC: String; CorpoMIME, AnexoMIME: Integer;
AutoResposta: Boolean; Anexo: TStrings): Boolean;
var
i: Integer;
IdSMTP1: TIdSMTP;
IdMessage: TIdMessage;
IdCorpo: TIdText;
IdAnexo: TIdAttachmentFile;
IdSSL: TIdSSLIOHandlerSocketOpenSSL;
begin
try
IdMessage := TIdMessage.Create(nil);
try
// ——————————————————————————-
// Cria a Estrutura da Mensagem:
// ——————————————————————————-
IdMessage.Clear;
IdMessage.IsEncoded := True;
IdMessage.AttachmentEncoding := 'MIME';
IdMessage.Encoding := meMIME; // meDefault;
IdMessage.ConvertPreamble := True;
IdMessage.Priority := mpNormal;
IdMessage.ContentType := 'multipart/mixed'; // obrigatoriamente!
IdMessage.CharSet := 'ISO-8859-1';
IdMessage.Date := Now;
// ——————————————————————————-
// Define o Remetente e Destinatário:
// ——————————————————————————-
IdMessage.From.Address := DeEmail; // ou ‘[EMAIL PROTECTED]‘
IdMessage.From.Text := DeNome + '';
if (not TUtil.Empty(CC)) then
begin
IdMessage.CCList.EMailAddresses := CC;
end;
// IdMessage.BccList.EMailAddresses := lista de com cópia oculta
IdMessage.ReplyTo.EMailAddresses := DeEmail;
IdMessage.Recipients.EMailAddresses := Trim(Para);
if AutoResposta then
IdMessage.ReceiptRecipient.Text := DeEmail;
// auto-resposta (confirmação de leitura!)
IdMessage.Subject := Trim(Assunto);
// ——————————————————————————-
// Adiciona o CORPO da Mensagem:
// ——————————————————————————-
IdCorpo := TIdText.Create(IdMessage.MessageParts, nil);
IdCorpo.ContentType := EmailTipoMIME(CorpoMIME);
IdCorpo.ContentDescription := 'multipart-1';
IdCorpo.CharSet := 'ISO-8859-1'; // NOSSA LINGUAGEM PT-BR (Latin-1)!!!!
IdCorpo.ContentTransfer := '16bit';
// para SAIR ACENTUADO !!!! Pois, 8bit SAI SEM ACENTO !!!!
IdCorpo.ContentDescription := 'Corpo da Mensagem';
IdCorpo.Body.Clear;
IdCorpo.Body.Add(Corpo);
// ——————————————————————————-
// Define o ANEXO: (pode haver looping para vários anexos)
// ——————————————————————————-
for i := 0 to Pred(Anexo.Count) do
begin
if FileExists(Anexo.Strings[i]) then
begin
try
IdAnexo := TIdAttachmentFile.Create(IdMessage.MessageParts,
Anexo.Strings[i]);
IdAnexo.ContentType := EmailTipoMIME(AnexoMIME) + '; ' + 'name=' +
ExtractFileName(Anexo.Strings[i]);
IdAnexo.ContentDescription := 'Arquivo Anexo: ' +
ExtractFileName(Anexo.Strings[i]);
except
end;
end;
end;
//
IdSMTP1 := TIdSMTP.Create(nil);
// ——————————————————————————-
// Se a porta for diferente de 25 então abre o SSL para autenticação segura!
// ——————————————————————————-
// Gmail e Globo usam a porta 465 (smtp) e 995 (pop3) com SSL!!!
// Hotmail usam a porta 25 (smpt.live.com) e 995 (pop3.live.com) sem SSL!
// Bol usa a porta 25 (smtp.bol.com.br) e 110 (pop3.bol.com.br) sem SSL!
// ——————————————————————————-
if Porta <> '587' then
// ( Se Porta DIFERENTE de ’25’… o sinal de diferente está sumido aqui)
begin
With IdSMTP1 Do
try
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
IdSMTP1.IOHandler := IdSSL;
UseTLS := utUseImplicitTLS;
except
on E: Exception do
begin
IOHandler := TIdIOHandler.MakeDefaultIOHandler(nil);
UseTLS := utNoTLSSupport;
ShowMessage('SSL da Autenticação Segura Falhou.' + #13 + '' + #13
+ 'Pode ser uma instabilidade temporária na ' + #13 +
'conexão de sua Internet.' + #13 + '' + #13 +
'Tente de novo agora ou mais tarde.');
result := False;
end;
end;
IdSSL.SSLOptions.Method := sslvSSLv2;
IdSSL.SSLOptions.Mode := sslmClient;
end;
With IdSMTP1 Do
try
AuthType := satDefault;
ReadTimeout := 10000; // Leitura da Conexão em 10 segundos!
Host := Dominio; // ‘smtp.dominio.com.br';
Port := StrToInt(Porta); // padrão seria 25 ou autenticada 465;
UserName := Usuario; // ‘usuario';
Password := Senha; // ‘senha';
try
Connect;
Authenticate;
except
on E: Exception do
begin
ShowMessage('Autenticação Falhou.' + #13 + '' + #13 +
'Verifique seu Nome de Usuário e Senha ou ' + #13 +
'Tente de novo agora ou mais tarde.');
result := False;
end;
end;
if Connected then
begin
Send(IdMessage);
result := True;
end
else
begin
raise Exception.Create('A conexão com o Provedor foi interrompida.'
+ #13 + '' + #13 + 'Verifique se a sua Internet está ativa.');
result := False;
end;
finally
Disconnect;
end;
except
result := False;
end;
finally
FreeAndNil(IdMessage);
FreeAndNil(IdSMTP1);
end;
end;
// ———————————————————-
// Função que Retorna o Tipo MIME para Cabeçalho do Email:
// ———————————————————-
function TEnviarEmail.EmailTipoMIME(TipoMIME: Integer): String;
begin
case TipoMIME of
0:
result := 'text/plain';
1:
result := 'text/html';
2:
result := 'text/richtext';
3:
result := 'text/x-aiff';
4:
result := 'audio/basic';
5:
result := 'audio/wav';
6:
result := 'image/gif';
7:
result := 'image/jpeg';
8:
result := 'image/pjpeg';
9:
result := 'image/tiff';
10:
result := 'image/x-png';
11:
result := 'image/x-xbitmap';
12:
result := 'image/bmp';
13:
result := 'image/x-jg';
14:
result := 'image/x-emf';
15:
result := 'image/x-wmf';
16:
result := 'video/avi';
17:
result := 'video/mpeg';
18:
result := 'application/postscript';
19:
result := 'application/base64';
20:
result := 'application/macbinhex40';
21:
result := 'application/pdf'; // arquivos PDF !!!
22:
result := 'application/x-compressed';
23:
result := 'application/x-zip-compressed';
24:
result := 'application/x-gzip-compressed';
25:
result := 'application/java';
26:
result := 'application/x-msdownload';
27:
result := 'application/octet-stream'; // arquivos .dat !!!!
28:
result := 'multipart/mixed';
29:
result := 'multipart/relative';
30:
result := 'multipart/digest';
31:
result := 'multipart/alternative';
32:
result := 'multipart/related';
33:
result := 'multipart/report';
34:
result := 'multipart/signed';
35:
result := 'multipart/encrypted';
end;
end;
end.
|
unit Controller.Observer.Interfaces;
interface
type
TRecordItem = record
Descricao : String;
Quantidade : Currency;
Valor : Currency;
end;
iObserverItem = interface
['{654CF77E-EAE2-46D0-A0E2-A92CD9A0A7A9}']
function UpdateItem(Value : TRecordItem) : iObserverItem;
end;
iSubjectItem = interface
['{485CFDD0-F92B-41F4-80AB-B7E5AB6EF075}']
function Add(Value : iObserverItem) : iSubjectItem;
function Notify(Value : TRecordItem) : iSubjectItem;
end;
implementation
end.
|
PROGRAM SortMonth_b(INPUT, OUTPUT);
{Программа сравнивает введённые значения месяцев}
USES DateIO; {ReadMonth, WriteMonth}
VAR
F1: TEXT;
MonthNameFirst, MonthNameSecond: Month;
BEGIN {SortMonth}
Copy(INPUT, F1);
ReadMonth(F1, MonthNameFirst);
ReadMonth(F1, MonthNameSecond);
IF (MonthNameFirst = NoMonth) OR (MonthNameSecond = NoMonth)
THEN
WRITE('Входные данные записаны неверно')
ELSE
IF MonthNameFirst = MonthNameSecond
THEN
BEGIN
WRITE('Оба месяца ');
WriteMonth(OUTPUT, MonthNameFirst)
END
ELSE
BEGIN
WriteMonth(OUTPUT, MonthNameFirst);
IF MonthNameFirst < MonthNameSecond
THEN
BEGIN
WRITE(' предшедствует ');
WriteMonth(OUTPUT, MonthNameSecond)
END
ELSE
BEGIN
WRITE(' следует за ');
WriteMonth(OUTPUT, MonthNameSecond)
END
END;
WRITELN
END. {SortMonth}
|
unit DepWindow;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TDependencyWindow = class(TForm)
DepLines: TMemo;
Panel1: TPanel;
CloseBtn: TButton;
private
procedure SetLines(theLines : TStringList);
public
property Lines : TStringList write SetLines;
end;
var
DependencyWindow: TDependencyWindow;
implementation
{$R *.DFM}
procedure TDependencyWindow.SetLines(theLines : TStringList);
begin
DepLines.Lines := theLines;
end;
end.
|
unit RegisterAccountUnit;
interface
uses SysUtils, BaseExampleUnit, EnumsUnit;
type
TRegisterAccount = class(TBaseExample)
public
procedure Execute(Plan, Industry, FirstName, LastName, Email: String;
Terms: boolean; DeviceType: TDeviceType;
Password, PasswordConfirmation: String);
end;
implementation
uses NullableBasicTypesUnit;
procedure TRegisterAccount.Execute(
Plan, Industry, FirstName, LastName, Email: String;
Terms: boolean; DeviceType: TDeviceType;
Password, PasswordConfirmation: String);
var
ErrorString: String;
MemberId: NullableInteger;
begin
MemberId := Route4MeManager.User.RegisterAccount(Plan, Industry, FirstName, LastName,
Email, Terms, DeviceType, Password, PasswordConfirmation, ErrorString);
WriteLn('');
if (ErrorString = EmptyStr) then
begin
WriteLn(Format('Account registered successfully, MemberId = %d', [MemberId.Value]));
WriteLn('');
end
else
WriteLn(Format('RegisterAccount error: "%s"', [ErrorString]));
end;
end.
|
unit nscReminder;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Nemesis"
// Модуль: "w:/common/components/gui/Garant/Nemesis/nscReminder.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<GuiControl::Class>> Shared Delphi For F1::Nemesis::Reminders::TnscReminder
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Nemesis\nscDefine.inc}
interface
{$If defined(Nemesis)}
uses
Messages,
Classes,
nscCustomReminderModelPart
{$If not defined(NoVCM)}
,
vcmExternalInterfaces
{$IfEnd} //not NoVCM
,
afwInterfaces,
Controls {a}
;
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
type
_nsUnknownComponentWithIvcmState_Parent_ = TnscCustomReminderModelPart;
{$Include ..\Nemesis\nsUnknownComponentWithIvcmState.imp.pas}
TnscCustomReminder = class(_nsUnknownComponentWithIvcmState_)
private
// private fields
f_EntityName : AnsiString;
{* Поле для свойства EntityName}
f_OperationName : AnsiString;
{* Поле для свойства OperationName}
f_OnBecomeVisible : TNotifyEvent;
{* Поле для свойства OnBecomeVisible}
private
// private methods
procedure InitAction;
procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
protected
// property methods
procedure pm_SetEntityName(const aValue: AnsiString);
procedure pm_SetOperationName(const aValue: AnsiString);
protected
// overridden protected methods
procedure Loaded; override;
{$If defined(Nemesis) AND not defined(DesignTimeLibrary)}
procedure LoadSettings; override;
{$IfEnd} //Nemesis AND not DesignTimeLibrary
{$If defined(Nemesis) AND not defined(DesignTimeLibrary)}
procedure SaveSettings; override;
{$IfEnd} //Nemesis AND not DesignTimeLibrary
protected
// protected methods
{$If defined(Nemesis) AND not defined(DesignTimeLibrary)}
function MakeId(const anId: AnsiString): AnsiString;
{$IfEnd} //Nemesis AND not DesignTimeLibrary
function EntityNameStored: Boolean;
{* "Функция определяющая, что свойство EntityName сохраняется" }
function OperationNameStored: Boolean;
{* "Функция определяющая, что свойство OperationName сохраняется" }
public
// public properties
property EntityName: AnsiString
read f_EntityName
write pm_SetEntityName
stored EntityNameStored;
property OperationName: AnsiString
read f_OperationName
write pm_SetOperationName
stored OperationNameStored;
property OnBecomeVisible: TNotifyEvent
read f_OnBecomeVisible
write f_OnBecomeVisible;
end;//TnscCustomReminder
const
{ nscReminderConstants }
csidLeft = 'LeftDelta';
csidRight = 'RightDelta';
csidTop = 'TopDelta';
csidBottom = 'BottomDelta';
csidDefaultParams = 'DefaultParams';
type
TnscReminder = class(TnscCustomReminder)
end;//TnscReminder
{$IfEnd} //Nemesis
implementation
{$If defined(Nemesis)}
uses
afwConsts
{$If not defined(NoVCM)}
,
vcmUtils
{$IfEnd} //not NoVCM
;
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
{$Include ..\Nemesis\nsUnknownComponentWithIvcmState.imp.pas}
// start class TnscCustomReminder
procedure TnscCustomReminder.InitAction;
//#UC START# *4F9A820E03C8_4D90511700B2_var*
//#UC END# *4F9A820E03C8_4D90511700B2_var*
begin
//#UC START# *4F9A820E03C8_4D90511700B2_impl*
vcmUtils.vcmMakeControlAction(Self, f_EntityName, f_OperationName);
//#UC END# *4F9A820E03C8_4D90511700B2_impl*
end;//TnscCustomReminder.InitAction
{$If defined(Nemesis) AND not defined(DesignTimeLibrary)}
function TnscCustomReminder.MakeId(const anId: AnsiString): AnsiString;
//#UC START# *4F9A81E4031A_4D90511700B2_var*
//#UC END# *4F9A81E4031A_4D90511700B2_var*
begin
//#UC START# *4F9A81E4031A_4D90511700B2_impl*
Result := BaseId + g_afwPathSep + Name + g_afwPathSep + anId;
//#UC END# *4F9A81E4031A_4D90511700B2_impl*
end;//TnscCustomReminder.MakeId
{$IfEnd} //Nemesis AND not DesignTimeLibrary
procedure TnscCustomReminder.pm_SetEntityName(const aValue: AnsiString);
//#UC START# *4F9A800701C3_4D90511700B2set_var*
//#UC END# *4F9A800701C3_4D90511700B2set_var*
begin
//#UC START# *4F9A800701C3_4D90511700B2set_impl*
if (aValue = '')
then f_EntityName := ''
else f_EntityName := 'en' + aValue;
InitAction;
//#UC END# *4F9A800701C3_4D90511700B2set_impl*
end;//TnscCustomReminder.pm_SetEntityName
procedure TnscCustomReminder.pm_SetOperationName(const aValue: AnsiString);
//#UC START# *4F9A804B0065_4D90511700B2set_var*
//#UC END# *4F9A804B0065_4D90511700B2set_var*
begin
//#UC START# *4F9A804B0065_4D90511700B2set_impl*
if (aValue = '')
then f_OperationName := ''
else f_OperationName := 'op' + aValue;
InitAction;
//#UC END# *4F9A804B0065_4D90511700B2set_impl*
end;//TnscCustomReminder.pm_SetOperationName
procedure TnscCustomReminder.CMVisibleChanged(var Message: TMessage);
//#UC START# *4F9A82400387_4D90511700B2_var*
//#UC END# *4F9A82400387_4D90511700B2_var*
begin
//#UC START# *4F9A82400387_4D90511700B2_impl*
inherited;
if (not (csDestroying in ComponentState)) and
Visible and
Assigned(f_OnBecomeVisible) then
f_OnBecomeVisible(Self);
//#UC END# *4F9A82400387_4D90511700B2_impl*
end;//TnscCustomReminder.CMVisibleChanged
function TnscCustomReminder.EntityNameStored: Boolean;
//#UC START# *53950E25B942_4D90511700B2_var*
//#UC END# *53950E25B942_4D90511700B2_var*
begin
//#UC START# *53950E25B942_4D90511700B2_impl*
Result := (f_EntityName <> '');
//#UC END# *53950E25B942_4D90511700B2_impl*
end;//TnscCustomReminder.EntityNameStored
function TnscCustomReminder.OperationNameStored: Boolean;
//#UC START# *30649C70FFBF_4D90511700B2_var*
//#UC END# *30649C70FFBF_4D90511700B2_var*
begin
//#UC START# *30649C70FFBF_4D90511700B2_impl*
Result := (f_OperationName <> '');
//#UC END# *30649C70FFBF_4D90511700B2_impl*
end;//TnscCustomReminder.OperationNameStored
procedure TnscCustomReminder.Loaded;
//#UC START# *484516C00214_4D90511700B2_var*
//#UC END# *484516C00214_4D90511700B2_var*
begin
//#UC START# *484516C00214_4D90511700B2_impl*
inherited;
InitAction;
// Для интерактивных предупреждений рисуем руку:
if (Action <> nil) or Assigned(OnClick) then
Cursor := crHandPoint;
//#UC END# *484516C00214_4D90511700B2_impl*
end;//TnscCustomReminder.Loaded
{$If defined(Nemesis) AND not defined(DesignTimeLibrary)}
procedure TnscCustomReminder.LoadSettings;
//#UC START# *4F9A5C410274_4D90511700B2_var*
//#UC END# *4F9A5C410274_4D90511700B2_var*
begin
//#UC START# *4F9A5C410274_4D90511700B2_impl*
Assert(Name <> '');
if (BaseId <> '') then
begin
with Settings do
if not LoadBoolean(MakeId(csidDefaultParams), True) then
Self.WritePosition(LoadInteger(MakeId(csidLeft), 0),
LoadInteger(MakeId(csidRight), 0),
LoadInteger(MakeId(csidTop), 0),
LoadInteger(MakeId(csidBottom), 0));
end;//BaseId <> ''
//#UC END# *4F9A5C410274_4D90511700B2_impl*
end;//TnscCustomReminder.LoadSettings
{$IfEnd} //Nemesis AND not DesignTimeLibrary
{$If defined(Nemesis) AND not defined(DesignTimeLibrary)}
procedure TnscCustomReminder.SaveSettings;
//#UC START# *4F9A5C530398_4D90511700B2_var*
var
Left, Right, Top, Bottom: Integer;
//#UC END# *4F9A5C530398_4D90511700B2_var*
begin
//#UC START# *4F9A5C530398_4D90511700B2_impl*
Assert(Name <> '');
if (BaseId <> '') then
begin
Self.ReadPosition(Left, Right, Top, Bottom);
with Settings do
begin
SaveBoolean(MakeId(csidDefaultParams), False);
SaveInteger(MakeId(csidLeft), Left);
SaveInteger(MakeId(csidRight), Right);
SaveInteger(MakeId(csidTop), Top);
SaveInteger(MakeId(csidBottom), Bottom);
end;//with Settings
end;//BaseId <> ''
//#UC END# *4F9A5C530398_4D90511700B2_impl*
end;//TnscCustomReminder.SaveSettings
{$IfEnd} //Nemesis AND not DesignTimeLibrary
{$IfEnd} //Nemesis
end. |
unit Unit_Editors;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.ComCtrls,
VCLTee.Control, VCLTee.Grid, Tee.Grid.Columns;
type
TFormCellEditors = class(TForm)
TeeGrid1: TTeeGrid;
Panel1: TPanel;
Label1: TLabel;
Panel2: TPanel;
Label2: TLabel;
CBAutoEdit: TCheckBox;
Label3: TLabel;
CBAlwaysVisible: TCheckBox;
Label4: TLabel;
Label5: TLabel;
CBEnterKey: TComboBox;
CBCustomEditors: TCheckBox;
CBSelectedText: TCheckBox;
Label6: TLabel;
procedure FormCreate(Sender: TObject);
procedure CBAutoEditClick(Sender: TObject);
procedure CBAlwaysVisibleClick(Sender: TObject);
procedure CBEnterKeyChange(Sender: TObject);
procedure CBCustomEditorsClick(Sender: TObject);
procedure CBSelectedTextClick(Sender: TObject);
procedure TeeGrid1CellEditing(const Sender: TObject;
const AEditor: TControl; const AColumn: TColumn; const ARow: Integer);
procedure TeeGrid1CellEdited(const Sender: TObject; const AEditor: TControl;
const AColumn: TColumn; const ARow: Integer);
private
{ Private declarations }
procedure ResetCustomEditors;
procedure SetupCustomEditors;
public
{ Public declarations }
end;
var
FormCellEditors: TFormCellEditors;
implementation
{$R *.dfm}
uses
Unit_Example_Data, Tee.Grid, System.UITypes;
procedure TFormCellEditors.CBAlwaysVisibleClick(Sender: TObject);
begin
// When True, moving from one cell to another will keep the cell
// editor visible
TeeGrid1.Editing.AlwaysVisible:=CBAlwaysVisible.Checked;
end;
procedure TFormCellEditors.CBAutoEditClick(Sender: TObject);
begin
// When True, pressing any key will show the cell editor automatically.
// When False, pressing F2 or double-clicking the cell starts editing.
TeeGrid1.Editing.AutoEdit:=CBAutoEdit.Checked;
end;
procedure TFormCellEditors.CBCustomEditorsClick(Sender: TObject);
begin
if CBCustomEditors.Checked then
SetupCustomEditors
else
ResetCustomEditors;
end;
procedure TFormCellEditors.CBEnterKeyChange(Sender: TObject);
begin
TeeGrid1.Editing.EnterKey:=TEditingEnter(CBEnterKey.ItemIndex);
end;
procedure TFormCellEditors.CBSelectedTextClick(Sender: TObject);
begin
TeeGrid1.Editing.Text.Selected:=CBSelectedText.Checked;
end;
procedure TFormCellEditors.FormCreate(Sender: TObject);
begin
TeeGrid1.Data:=SampleData;
// Formatting
TeeGrid1.Columns['Height'].DataFormat.Float:='0.##';
TeeGrid1.Columns['BirthDate'].DataFormat.DateTime:='mm-dd-yyyy';
// Do not show cell editor with all text selected
TeeGrid1.Editing.Text.Selected:=False;
SetupCustomEditors;
end;
procedure TFormCelleditors.SetupCustomEditors;
begin
// Custom cell editor controls (default is TEdit)
TeeGrid1.Columns['Height'].EditorClass:=TTrackBar;
// TeeGrid1.Columns['BirthDate'].EditorClass:=TComboCalendar;
TeeGrid1.Columns['Vehicle'].EditorClass:=TComboBox;
// TeeGrid1.Columns['EyeColor'].EditorClass:=TComboColor;
TeeGrid1.Columns['EyeColor'].EditorClass:=TComboBox;
TeeGrid1.Columns['Holidays'].EditorClass:=TCheckBox;
TeeGrid1.Columns['Happiness'].EditorClass:=TUpDown;
end;
procedure TFormCellEditors.TeeGrid1CellEdited(const Sender: TObject;
const AEditor: TControl; const AColumn: TColumn; const ARow: Integer);
var tmp : TComboBox;
tmpValue : String;
begin
if AEditor is TComboBox then
begin
tmp:=TComboBox(AEditor);
if tmp.ItemIndex=-1 then
tmpValue:=''
else
tmpValue:=tmp.Items[tmp.ItemIndex];
// Bug with Rtti data:
// TeeGrid1.Data.SetValue(AColumn,ARow,tmpValue);
end;
end;
procedure TFormCellEditors.TeeGrid1CellEditing(const Sender: TObject;
const AEditor: TControl; const AColumn: TColumn; const ARow: Integer);
procedure FillCombo(const ACombo:TComboBox; const Values:Array of String);
var t : Integer;
begin
ACombo.Items.BeginUpdate;
try
ACombo.Clear;
for t:=Low(Values) to High(Values) do
ACombo.Items.Add(Values[t]);
finally
ACombo.Items.EndUpdate;
end;
end;
function FindValue(const ACombo:TComboBox; const AValue:String):Integer;
var t : Integer;
begin
for t:=0 to ACombo.Items.Count-1 do
if SameText(ACombo.Items[t],AValue) then
Exit(t);
result:=-1;
end;
function ColorOf(const AColor:TColor):String;
begin
case AColor of
TColors.Black : result:='Black';
TColors.Brown : result:='Brown';
TColors.Green : result:='Green';
else
result:='Blue';
end;
end;
var tmpValue : String;
begin
if AEditor is TComboBox then
begin
TComboBox(AEditor).Style:=csDropDownList;
tmpValue:=TeeGrid1.Data.AsString(AColumn,ARow);
if AColumn=TeeGrid1.Columns['Vehicle'] then
FillCombo(TComboBox(AEditor),
['None','Bicycle','MotorBike','Car','Caravan','Truck','Boat','Plane'])
else
if AColumn=TeeGrid1.Columns['EyeColor'] then
begin
FillCombo(TComboBox(AEditor),
['Black','Brown','Green','Blue']);
tmpValue:=ColorOf(StrToInt(tmpValue));
end;
TComboBox(AEditor).ItemIndex:=FindValue(TComboBox(AEditor),tmpValue);
end;
end;
procedure TFormCellEditors.ResetCustomEditors;
procedure ResetColumns(const AColumns:TColumns);
var t : Integer;
begin
for t:=0 to AColumns.Count-1 do
begin
AColumns[t].EditorClass:=nil; // <-- reset to default TEdit box
ResetColumns(AColumns[t].Items);
end;
end;
begin
ResetColumns(TeeGrid1.Columns);
end;
end.
|
unit Types;
uses System;
type
///Ключевой объект
KSCObject = abstract class
public const TypeName = 'object';
private _name: string;
public function GetName: string := _name;
public property Name: string read GetName;
public constructor (name: string);
begin
_name:=name;
end;
public function ToString: string; override := Self.GetType().ToString;
public procedure SetValue(s: object) := exit;
end;
KSCInt32 = class(KSCObject)
public const TypeName = 'int32';
private _value: Int32;
public procedure SetValue(a: Int32) := _value := a;
public procedure SetValue(a: KSCInt32) := _value := a._value;
public property Value: Int32 read _value write SetValue;
public constructor (name: string; a: Int32);
begin
_name:=name;
_value:=a;
end;
public constructor (name: string; a: KSCInt32);
begin
_name:=name;
_value := a._value;
end;
public function ToString: string; override := Value.ToString;
public function Parse(s: string): KSCInt32;
begin
Result:=new KSCInt32('<>localvariablename',Int32.Parse(s));
end;
public constructor (name: string; s: string);
begin
Create(name, Parse(s));
end;
public procedure SetValue(s: string) := SetValue(Parse(s));
end;
function IsTypeName(s: string): boolean;
var
tns: array of string =(
KSCInt32.TypeName,
KSCObject.TypeName
);
begin
Result:=false;
for var i:=0 to tns.Length-1 do
if s.ToLower = tns[i] then Result:=true;
end;
function StrToType(s: string): System.Type;
begin
case s.ToLower of
KSCInt32.TypeName: Result:=typeof(KSCInt32);
end;
end;
function GetNullVariable(name: string; &Type: System.Type): KSCObject;
begin
if &Type = typeof(KSCInt32) then Result:=new KSCInt32(name,0);
end;
function GetVariable(name, parse: string; &Type: System.Type): KSCObject;
begin
if &Type = typeof(KSCInt32) then Result:=new KSCInt32(name,parse);
end;
function GetAutoVariable(name, parse: string): KSCObject;
begin
var Auto001: Int32;
if Int32.TryParse(parse,Auto001) then Result:=new KSCInt32(name,parse);
end;
begin
end. |
End of preview. Expand
in Data Studio
- Downloads last month
- 15