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.
unit aeLoaderManager; interface uses windows, types, System.Generics.Collections, aeGeometry, ae3DModelLoaderBase, aeLoader3DS, sysutils, aeLoaderAionCGF; type TaeLoaderManagerResult = (AE_LOADERMANAGER_RESULT_SUCCESS, AE_LOADERMANAGER_RESULT_FAIL, AE_LOADERMANAGER_RESULT_FILE_NOT_SUPPORTED); type TaeLoaderManager = class public constructor Create; function loadFromFile(file_name: string; var geo: TaeGeometry): TaeLoaderManagerResult; private _loaders: TList<Tae3DModelLoaderBase>; function getLoaderForFile(file_ext: string): Tae3DModelLoaderBase; end; implementation { TaeLoaderManager } constructor TaeLoaderManager.Create; var loader: Tae3DModelLoaderBase; begin self._loaders := TList<Tae3DModelLoaderBase>.Create; loader := TaeLoader3DS.Create; self._loaders.Add(loader); loader := TaeLoaderAionCGF.Create; self._loaders.Add(loader); end; function TaeLoaderManager.getLoaderForFile(file_ext: string): Tae3DModelLoaderBase; var i: Integer; begin for i := 0 to self._loaders.Count - 1 do if (self._loaders[i].getHandledFileExtension() = file_ext) then begin Result := self._loaders[i]; exit; end; end; function TaeLoaderManager.loadFromFile(file_name: string; var geo: TaeGeometry): TaeLoaderManagerResult; var f_ext: string; loader: Tae3DModelLoaderBase; f_load_result: boolean; begin f_ext := ExtractFileExt(file_name); delete(f_ext, 1, 1); // remove dot loader := self.getLoaderForFile(f_ext); if (loader = nil) then begin Result := AE_LOADERMANAGER_RESULT_FILE_NOT_SUPPORTED; exit; end; case loader.getLoaderType of AE_LOADER_FILETYPE_3DS: f_load_result := TaeLoader3DS(loader).loadFromFile(file_name, geo); AE_LOADER_FILETYPE_AIONCGF: f_load_result := TaeLoaderAionCGF(loader).loadFromFile(file_name, geo); end; geo.SetNodeName(file_name); if (f_load_result) then Result := AE_LOADERMANAGER_RESULT_SUCCESS else Result := AE_LOADERMANAGER_RESULT_FAIL; end; end.
unit fSavedSearches; { Copyright 2012 Document Storage Systems, Inc.      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. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Trpcb, ORNet, ORFn, JvExControls, JvButton, JvTransparentButton; type TfrmSavedSearches = class(TForm) Image3: TImage; lbSavedSearches: TListBox; Image1: TImage; Bevel1: TBevel; buDeleteAllSearches: TJvTransparentButton; buCancel: TJvTransparentButton; buDeleteAllType: TJvTransparentButton; buDeleteSelectedSearch: TJvTransparentButton; buOpenSelectedSearch: TJvTransparentButton; //procedure buOpenSelectedSearchORIGClick(Sender: TObject); procedure lbSavedSearchesDblClick(Sender: TObject); //procedure buCancelORIGClick(Sender: TObject); //procedure buDeleteSelectedSearchORIGClick(Sender: TObject); //procedure buDeleteAllSearchesORIGClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); //procedure buDeleteAllTypeORIGClick(Sender: TObject); procedure buDeleteAllTypeORIGMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure buDeleteAllSearchesClick(Sender: TObject); procedure buCancelClick(Sender: TObject); procedure buDeleteAllTypeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure buDeleteAllTypeClick(Sender: TObject); procedure buDeleteSelectedSearchClick(Sender: TObject); procedure buOpenSelectedSearchClick(Sender: TObject); private FSelectedSearchName: string; public property SelectedSearchName: string read FSelectedSearchName write FSelectedSearchName; procedure DisplaySavedSearches(Sender: TObject); end; const CRLF = #13#10; var frmSavedSearches: TfrmSavedSearches; implementation uses fSearchCriteria; {$R *.dfm} var thisfrmSearchCriteria: fSearchCriteria.TfrmSearchCriteria; procedure TfrmSavedSearches.DisplaySavedSearches(Sender: TObject); var i: integer; begin try lbSavedSearches.Clear; thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR GET ALL FOR ENT', ['USR~DSIWA SEARCH TOOL TERMS~B']); //according to the RPC definition, 'B' is ALWAYS used thisfrmSearchCriteria.stUpdateContext(origContext); for i := 0 to thisfrmSearchCriteria.RPCBroker.Results.Count - 1 do begin //Load up the list box, eliminating the search name prefix for display purposes case thisfrmSearchCriteria.pcSearch.TabIndex of STANDARD_SEARCH_PAGE: begin frmSavedSearches.Caption := 'Standard Searches'; if Piece(thisfrmSearchCriteria.RPCBroker.Results[i], PREFIX_DELIM, 1) = STD then frmSavedSearches.lbSavedSearches.AddItem(Piece(Piece(thisfrmSearchCriteria.RPCBroker.Results[i],'^',1), PREFIX_DELIM, 2),nil); end; ADVANCED_SEARCH_PAGE: begin frmSavedSearches.Caption := 'Advanced Searches'; if Piece(thisfrmSearchCriteria.RPCBroker.Results[i], PREFIX_DELIM, 1) = ADV then frmSavedSearches.lbSavedSearches.AddItem(Piece(Piece(thisfrmSearchCriteria.RPCBroker.Results[i],'^',1), PREFIX_DELIM, 2),nil); end; end; end; except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' DisplaySavedSearches()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; procedure TfrmSavedSearches.buCancelClick(Sender: TObject); begin Close; end; { procedure TfrmSavedSearches.buCancelORIGClick(Sender: TObject); begin Close; end; } procedure TfrmSavedSearches.buDeleteAllSearchesClick(Sender: TObject); begin try if MessageDlg('You are about to permanently delete ALL your saved STANDARD and ADVANCED searches.' + CRLF + 'Once done, this action cannot be reversed.' + CRLF + CRLF + 'Are you sure?', mtWarning, [mbYes,mbNo], 0) = mrYes then begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR DEL ALL', ['USR~DSIWA SEARCH TOOL TERMS']); thisfrmSearchCriteria.stUpdateContext(origContext); DisplaySavedSearches(nil); end; except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' buDeleteAllSearchesClick()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; { procedure TfrmSavedSearches.buDeleteAllSearchesORIGClick(Sender: TObject); begin try if MessageDlg('You are about to permanently delete ALL your saved STANDARD and ADVANCED searches.' + CRLF + 'Once done, this action cannot be reversed.' + CRLF + CRLF + 'Are you sure?', mtWarning, [mbYes,mbNo], 0) = mrYes then begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR DEL ALL', ['USR~DSIWA SEARCH TOOL TERMS']); thisfrmSearchCriteria.stUpdateContext(origContext); DisplaySavedSearches(nil); end; except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' buDeleteAllSearchesClick()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; } procedure TfrmSavedSearches.buDeleteAllTypeClick(Sender: TObject); { Delete all the saved searches depending on the selected tab page } var i: integer; begin try //Loop thru lbSavedSearches and call DSIWA XPAR DEL for each one if thisfrmSearchCriteria.pcSearch.ActivePageIndex = 0 then //Standard Search page begin if MessageDlg('This action will delete ALL your Standard Searches.' + CRLF + 'Are you sure?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then begin for i := lbSavedSearches.Items.Count - 1 downto 0 do begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + STD_PREFIX + lbSavedSearches.Items[i]]); if Piece(thisfrmSearchCriteria.RPCBroker.Results[0],'^',1) = RPC_SUCCESS then begin thisfrmSearchCriteria.stUpdateContext(origContext); lbSavedSearches.ItemIndex := i; //Update the list one item at a time lbSavedSearches.DeleteSelected; // so that the list of saved searches does not lie to us if RPC Error end else begin MessageDlg('RPC Error while attempting to delete all Standard searches', mtError, [mbOk], 0); Break; end; end; end; end else begin if MessageDlg('This action will delete ALL your Advanced Searches.' + CRLF + 'Are you sure?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then begin for i := lbSavedSearches.Items.Count - 1 downto 0 do begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + ADV_PREFIX + lbSavedSearches.Items[i]]); if Piece(thisfrmSearchCriteria.RPCBroker.Results[0],'^',1) = RPC_SUCCESS then begin thisfrmSearchCriteria.stUpdateContext(origContext); lbSavedSearches.ItemIndex := i; //Update the list one item at a time lbSavedSearches.DeleteSelected; // so that the list of saved searches does not lie to us if RPC Error end else begin MessageDlg('RPC Error while attempting to delete all Advanced searches', mtError, [mbOk], 0); Break; end; end; end; end; except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' buDeleteAllTypeClick()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; procedure TfrmSavedSearches.buDeleteAllTypeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsStandardSearch then buDeleteAllType.Hint:= 'Delete all previously saved Standard searches.' else buDeleteAllType.Hint:= 'Delete all previously saved Advanced searches.'; end; { procedure TfrmSavedSearches.buDeleteAllTypeORIGClick(Sender: TObject); //Delete all the saved searches depending on the selected tab page var i: integer; begin try //Loop thru lbSavedSearches and call DSIWA XPAR DEL for each one if thisfrmSearchCriteria.pcSearch.ActivePageIndex = 0 then //Standard Search page begin if MessageDlg('This action will delete ALL your Standard Searches.' + CRLF + 'Are you sure?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then begin for i := lbSavedSearches.Items.Count - 1 downto 0 do begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + STD_PREFIX + lbSavedSearches.Items[i]]); if Piece(thisfrmSearchCriteria.RPCBroker.Results[0],'^',1) = RPC_SUCCESS then begin thisfrmSearchCriteria.stUpdateContext(origContext); lbSavedSearches.ItemIndex := i; //Update the list one item at a time lbSavedSearches.DeleteSelected; // so that the list of saved searches does not lie to us if RPC Error end else begin MessageDlg('RPC Error while attempting to delete all Standard searches', mtError, [mbOk], 0); Break; end; end; end; end else begin if MessageDlg('This action will delete ALL your Advanced Searches.' + CRLF + 'Are you sure?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then begin for i := lbSavedSearches.Items.Count - 1 downto 0 do begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + ADV_PREFIX + lbSavedSearches.Items[i]]); if Piece(thisfrmSearchCriteria.RPCBroker.Results[0],'^',1) = RPC_SUCCESS then begin thisfrmSearchCriteria.stUpdateContext(origContext); lbSavedSearches.ItemIndex := i; //Update the list one item at a time lbSavedSearches.DeleteSelected; // so that the list of saved searches does not lie to us if RPC Error end else begin MessageDlg('RPC Error while attempting to delete all Advanced searches', mtError, [mbOk], 0); Break; end; end; end; end; except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' buDeleteAllTypeClick()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; } procedure TfrmSavedSearches.buDeleteAllTypeORIGMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsStandardSearch then buDeleteAllType.Hint:= 'Delete all previously saved Standard searches.' else buDeleteAllType.Hint:= 'Delete all previously saved Advanced searches.'; end; procedure TfrmSavedSearches.buDeleteSelectedSearchClick(Sender: TObject); var i: integer; begin try if lbSavedSearches.ItemIndex = -1 then begin MessageDlg('No search selected.' + CRLF + 'Please select a search to delete.', mtInformation, [mbOk], 0); Exit; end; if MessageDlg('Delete the selected search.' + CRLF + 'Are you sure?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsStandardSearch then CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + STD_PREFIX + lbSavedSearches.Items[lbSavedSearches.ItemIndex]]); if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsAdvancedSearch then CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + ADV_PREFIX + lbSavedSearches.Items[lbSavedSearches.ItemIndex]]); thisfrmSearchCriteria.stUpdateContext(origContext); end; lbSavedSearches.Clear; DisplaySavedSearches(nil); except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' buDeleteSelectedSearchClick()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; { procedure TfrmSavedSearches.buDeleteSelectedSearchORIGClick(Sender: TObject); var i: integer; begin try if lbSavedSearches.ItemIndex = -1 then begin MessageDlg('No search selected.' + CRLF + 'Please select a search to delete.', mtInformation, [mbOk], 0); Exit; end; if MessageDlg('Delete the selected search.' + CRLF + 'Are you sure?', mtConfirmation, [mbYes,mbNo], 0) = mrYes then begin thisfrmSearchCriteria.stUpdateContext(SEARCH_TOOL_CONTEXT); if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsStandardSearch then CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + STD_PREFIX + lbSavedSearches.Items[lbSavedSearches.ItemIndex]]); if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsAdvancedSearch then CallV('DSIWA XPAR DEL', ['USR~DSIWA SEARCH TOOL TERMS~' + ADV_PREFIX + lbSavedSearches.Items[lbSavedSearches.ItemIndex]]); thisfrmSearchCriteria.stUpdateContext(origContext); end; lbSavedSearches.Clear; DisplaySavedSearches(nil); except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' buDeleteSelectedSearchClick()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; } procedure TfrmSavedSearches.buOpenSelectedSearchClick(Sender: TObject); begin if lbSavedSearches.ItemIndex = -1 then begin MessageDlg('No search selected.' + CRLF + 'Please select a search to open.', mtInformation, [mbOk], 0); Exit; end; //We'll use this value in frmSearchCriteria self.SelectedSearchName := lbSavedSearches.Items[lbSavedSearches.ItemIndex]; thisfrmSearchCriteria.sbStatusBar.Panels[2].Text := 'Current Search: ' + self.SelectedSearchName; Close; end; { procedure TfrmSavedSearches.buOpenSelectedSearchORIGClick(Sender: TObject); begin if lbSavedSearches.ItemIndex = -1 then begin MessageDlg('No search selected.' + CRLF + 'Please select a search to open.', mtInformation, [mbOk], 0); Exit; end; //We'll use this value in frmSearchCriteria self.SelectedSearchName := lbSavedSearches.Items[lbSavedSearches.ItemIndex]; thisfrmSearchCriteria.sbStatusBar.Panels[2].Text := 'Current Search: ' + self.SelectedSearchName; Close; end; } procedure TfrmSavedSearches.FormCreate(Sender: TObject); begin try thisfrmSearchCriteria := (self.Owner as TfrmSearchCriteria); //Get a pointer to the main form except on E: Exception do MessageDlg(GENERAL_EXCEPTION_MSG + ' frmSavedSearches.FormCreate()' + CRLF + E.Message, mtInformation, [mbOk], 0); end; end; procedure TfrmSavedSearches.FormShow(Sender: TObject); begin if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsStandardSearch then begin self.Caption := ' Standard Searches'; buDeleteAllType.Caption := 'Delete All &Std Searches'; end; if thisfrmSearchCriteria.pcSearch.ActivePage = thisfrmSearchCriteria.tsAdvancedSearch then begin self.Caption := ' Advanced Searches'; buDeleteAllType.Caption := 'Delete All Ad&v Searches'; end; end; procedure TfrmSavedSearches.lbSavedSearchesDblClick(Sender: TObject); begin //self.FSelectedSearchName := lbSavedSearches.Items[lbSavedSearches.ItemIndex]; //This is the user-selected search //self.SelectedSearchName := lbSavedSearches.Items[lbSavedSearches.ItemIndex]; buOpenSelectedSearchClick(nil); end; end.
(* * Task 1: Capital Detection * * GUEST LANGUAGE: THIS IS THE PASCAL VERSION OF ch-1.pl, suitable for * the Free Pascal compiler. *) uses sysutils; type strarray = array [0..100] of string; var debug : boolean; (* process_args_exactly_n( n, str[] ); * Process command line arguments, * specifically process the -d flag, * check that there are exactly n remaining arguments, * copy remaining args to str[n], a string array *) procedure process_args_exactly_n( n : integer; var str : strarray ); (* note: paramStr(i)); for i in 1 to paramCount() *) var nparams : integer; nel : integer; arg : integer; i : integer; p : string; begin nparams := paramCount(); arg := 1; if (nparams>0) and SameText( paramStr(arg), '-d' ) then begin debug := true; arg := 2; end; nel := 1+nparams-arg; if nel <> n then begin writeln( stderr, 'Usage: cap-det [-d] string' ); halt; end; // elements are in argv[arg..nparams], copy them to str[] for i := arg to nparams do begin p := paramStr(i); str[i-arg] := p; end; end; const Upper = ['A'..'Z']; Lower = ['a'..'z']; function capdetect( str : string ) : boolean; var alllower, allupper : boolean; len, i : integer; begin len := length(str); if debug then begin writeln( 'debug: capdetect(', str, '): entry, str1=', str[1] ); end; if str[1] in Upper then begin if debug then begin writeln( 'debug: capdetect(', str, '): starts with upper' ); end; alllower := true; allupper := true; for i := 2 to len do begin if not( str[i] in Lower) then begin if debug then begin writeln( 'debug: capdetect(', str, '): found ', str[i], ' not lower case' ); end; alllower := false; end; if not( str[i] in Upper) then begin if debug then begin writeln( 'debug: capdetect(', str, '): found ', str[i], ' not upper case' ); end; allupper := false; end; end; if alllower or allupper then exit( true ); end else if str[1] in Lower then begin if debug then begin writeln( 'debug: capdetect(', str, '): starts with lower' ); end; alllower := true; for i := 2 to len do begin if not( str[i] in Lower) then begin writeln( 'debug: capdetect(', str, '): found ', str[i], ' not lower case' ); alllower := false; end; end; if alllower then exit( true ); end; exit( false ); end; procedure main; var strarr : strarray; str : string; ok : boolean; begin debug := false; process_args_exactly_n( 1, strarr ); str := strarr[0]; if debug then begin writeln( 'debug: str=', str ); end; ok := capdetect( str ); if ok then begin writeln( 1 ); end else begin writeln( 0 ); end; end; begin main; end.
{ Utility functions for VOLATILE FOLLOWERS by dragonjet MOD: http://www.nexusmods.com/skyrim/mods/71998/ SOURCE: https://github.com/dragonjet/skyrim-volatilefollowers } unit vf_utils; uses mteFunctions; { MAKE ESP FILE Create an ESP file, or if exists, return the existing file } function MakeESPFile ( FileName:string ): IwbFile; var ExistingFile:IwbFile; begin try ExistingFile := FileByName(FileName); // Create file if not exist yet if GetFileName(ExistingFile) <> FileName then begin // Try creating our plugin file AddMessage('Creating ESP File...'); result := AddNewFileName(FileName); end else begin result := ExistingFile; end; // If ESP file was not created, use existing if GetFileName(result) <> FileName then begin AddMessage('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); AddMessage('['+FileName+'] ERROR. Not able to create ESP file.'); AddMessage('['+FileName+'] If you have executed this script before, make sure it is checked in plugin list when re-running.'); AddMessage('['+FileName+'] Alternatively, you can just delete the old '+FileName+' generated by this script.'); AddMessage('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); result := nil; end; except on TheCaughtException: Exception do // Exception thrown means it already exists, we just use it AddMessage('[ERROR] Problem while making ESP file: '+TheCaughtException.Message); end; end; { MAKE ESP FILE Create an ESP file, or if exists, return the existing file } function ResetGroup ( PluginFile:IwbFile; GroupName:string ): IwbElement; begin result := nil; try // Remove existing group to reset data inside plugin RemoveNode(GroupBySignature(PluginFile, GroupName)); // Re-add those nodes so we have containers later result := Add(PluginFile, GroupName, true); except on TheCaughtException: Exception do AddMessage('[ERROR] Cannot reset group '+GroupName+' on '+GetFileName(PluginFile)+' ('+TheCaughtException.Message+')'); end; end; { ADD MASTERS OF RECORD Adds all master files of this record, including those that override it } function AddRequiredElementMastersSilent ( PluginFile:IwbFile; MainRecord:IwbMainRecord ) : nil; var OverrideCtr : integer; CurrentOverride : IwbMainRecord; begin try if IsMaster(MainRecord) then begin AddMasterIfMissing(PluginFile, GetFileName(GetFile(MainRecord))); end else begin AddMasterIfMissing(PluginFile, GetFileName(GetFile(Master(MainRecord)))); for OverrideCtr := 0 to OverrideCount( MainRecord ) - 1 do begin CurrentOverride := OverrideByIndex( MainRecord, OverrideCtr ); AddMessage('Adding master '+ GetFileName(GetFile(CurrentOverride))); AddMasterIfMissing(PluginFile, GetFileName(GetFile(CurrentOverride))); end; end; except on TheCaughtException: Exception do AddMessage('Cannot add master for ' + Name(MainRecord) + ': '+ TheCaughtException.Message + '..'); AddRequiredElementMasters(MainRecord, PluginFile, false); end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Notification Center implementation for iOS } { } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.iOS.Notification; interface {$SCOPEDENUMS ON} uses System.Notification; /// <summary>Common ancestor used to instantiate platform implementation</summary> type TPlatformNotificationCenter = class(TBaseNotificationCenter) protected class function GetInstance: TBaseNotificationCenter; override; end; implementation uses System.Classes, System.SysUtils, System.Generics.Collections, System.Messaging, Macapi.ObjectiveC, Macapi.Helpers, iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit; type { TNotificationCenterCocoa } TNotificationCenterCocoa = class(TPlatformNotificationCenter) private class var FNotificationCenterSingleton: TNotificationCenterCocoa; FDelayedNotifications: TObjectList<TNotification>; FApplicationLoaded: Boolean; { Creation and manipulation with notifications } function CreateNativeNotification(const ANotification: TNotification): UILocalNotification; function ConvertNativeToDelphiNotification(const ANotification: UILocalNotification): TNotification; function FindNativeNotification(const AID: string; var ANotification: UILocalNotification): Boolean; { Global External event } procedure ReceiveLocalNotification(const Sender: TObject; const M: TMessage); { Delayed notifications } procedure SendDelayedNotifications; procedure ClearDelayedNotifications; procedure DidFormsLoad; function SharedApplication: UIApplication; inline; class destructor Destroy; class function GetNotificationCenter: TNotificationCenterCocoa; static; public constructor Create; destructor Destroy; override; { IFMXNotificationCenter } function GetCurrentNotifications: TNotifications; // Not accesible in base class because android doesn't have it function FindNotification(const AName: string): TNotification; // Not accesible in base class because android doesn't have it procedure DoScheduleNotification(const ANotification: TNotification); override; procedure DoPresentNotification(const ANotification: TNotification); override; procedure DoCancelNotification(const AName: string); overload; override; procedure DoCancelNotification(const ANotification: TNotification); overload; override; procedure DoCancelAllNotifications; override; procedure DoSetIconBadgeNumber(const ACount: Integer); override; function DoGetIconBadgeNumber: Integer; override; procedure DoResetIconBadgeNumber; override; procedure DoLoaded; override; class property NotificationCenter: TNotificationCenterCocoa read GetNotificationCenter; end; function RepeatIntervalToNSCalendarUnit(const AInterval: TRepeatInterval): NSCalendarUnit; begin case AInterval of TRepeatInterval.None: Result := 0; TRepeatInterval.Second: Result := NSSecondCalendarUnit; TRepeatInterval.Minute: Result := NSMinuteCalendarUnit; TRepeatInterval.Hour: Result := NSHourCalendarUnit; TRepeatInterval.Day: Result := NSDayCalendarUnit; TRepeatInterval.Weekday: Result := NSWeekdayCalendarUnit; TRepeatInterval.Week: Result := NSWeekCalendarUnit; TRepeatInterval.Month: Result := NSMonthCalendarUnit; TRepeatInterval.Quarter: Result := NSQuarterCalendarUnit; TRepeatInterval.Year: Result := NSYearCalendarUnit; TRepeatInterval.Era: Result := NSEraCalendarUnit; else Result := 0; end; end; function NSCalendarUnitToRepeatInterval(const AInterval: NSCalendarUnit): TRepeatInterval; begin case AInterval of NSEraCalendarUnit: Result := TRepeatInterval.Era; NSYearCalendarUnit: Result := TRepeatInterval.Year; NSQuarterCalendarUnit: Result := TRepeatInterval.Quarter; NSMonthCalendarUnit: Result := TRepeatInterval.Month; NSWeekCalendarUnit: Result := TRepeatInterval.Week; NSWeekdayCalendarUnit: Result := TRepeatInterval.Weekday; NSDayCalendarUnit: Result := TRepeatInterval.Day; NSHourCalendarUnit: Result := TRepeatInterval.Hour; NSMinuteCalendarUnit: Result := TRepeatInterval.Minute; NSSecondCalendarUnit: Result := TRepeatInterval.Second; else Result := TRepeatInterval.None; end; end; {$REGION 'TNotificationCenterCocoa'} procedure TNotificationCenterCocoa.DoCancelAllNotifications; begin SharedApplication.cancelAllLocalNotifications; end; function TNotificationCenterCocoa.FindNativeNotification(const AID: string; var ANotification: UILocalNotification): Boolean; function FindInScheduledNotifications: UILocalNotification; var Notifications: NSArray; NativeNotification: UILocalNotification; Found: Boolean; I: NSUInteger; UserInfo: NSDictionary; begin Notifications := SharedApplication.scheduledLocalNotifications; Found := False; if Notifications <> nil then begin I := 0; while (I < Notifications.count) and not Found do begin NativeNotification := TUILocalNotification.Wrap(Notifications.objectAtIndex(I)); UserInfo := NativeNotification.userInfo; if (UserInfo <> nil) and (UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(StrToNSStr('id'))).UTF8String) = AID) then Found := True else Inc(I); end; end; if Found then Result := NativeNotification else Result := nil; end; begin // We are searching notification in two list: // 1. Notifications, which have not displayed in Notification Center // 2. Notifications, which already displayed ANotification := FindInScheduledNotifications; Result := ANotification <> nil; end; function TNotificationCenterCocoa.FindNotification(const AName: string): TNotification; var NativeNotification: UILocalNotification; begin if FindNativeNotification(AName, NativeNotification) then Result := ConvertNativeToDelphiNotification(NativeNotification) else Result := nil; end; function TNotificationCenterCocoa.GetCurrentNotifications: TNotifications; var Notifications: NSArray; NativeNotification: UILocalNotification; I: Integer; begin Notifications := SharedApplication.scheduledLocalNotifications; SetLength(Result, Notifications.count); for I := 0 to Integer(Notifications.count) - 1 do begin NativeNotification := TUILocalNotification.Wrap(Notifications.objectAtIndex(I)); Result[I] := ConvertNativeToDelphiNotification(NativeNotification) end; end; procedure TNotificationCenterCocoa.DoCancelNotification(const AName: string); var NativeNotification: UILocalNotification; begin if not AName.IsEmpty and FindNativeNotification(AName, NativeNotification) then SharedApplication.cancelLocalNotification(NativeNotification); end; procedure TNotificationCenterCocoa.DoCancelNotification(const ANotification: TNotification); begin if ANotification <> nil then DoCancelNotification(ANotification.Name); end; procedure TNotificationCenterCocoa.ClearDelayedNotifications; begin FDelayedNotifications.Clear; end; constructor TNotificationCenterCocoa.Create; begin TMessageManager.DefaultManager.SubscribeToMessage(TMessageReceivedNotification, ReceiveLocalNotification); FDelayedNotifications := TObjectList<TNotification>.Create; FApplicationLoaded := False; end; function TNotificationCenterCocoa.SharedApplication: UIApplication; var App: Pointer; begin Result := nil; App := TUIApplication.OCClass.sharedApplication; if App <> nil then Result := TUIApplication.Wrap(App); end; function TNotificationCenterCocoa.CreateNativeNotification(const ANotification: TNotification): UILocalNotification; var NativeNotification: UILocalNotification; UserInfo: NSDictionary; GMTDateTime: TDateTime; begin NativeNotification := TUILocalNotification.Create; if not ANotification.Name.IsEmpty then begin // Set unique identificator UserInfo := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject( (StrToNSStr(ANotification.Name) as ILocalObject).GetObjectID, (StrToNSStr('id') as ILocalObject).GetObjectID)); NativeNotification.setUserInfo(UserInfo); end; // Get GMT time and set notification fired date GMTDateTime := GetGMTDateTime(ANotification.FireDate); NativeNotification.setTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone)); NativeNotification.setFireDate(DateTimeToNSDate(GMTDateTime)); NativeNotification.setApplicationIconBadgeNumber(ANotification.Number); NativeNotification.setAlertBody(StrToNSStr(ANotification.AlertBody)); NativeNotification.setAlertAction(StrToNSStr(ANotification.AlertAction)); NativeNotification.setHasAction(ANotification.HasAction); NativeNotification.setRepeatInterval(RepeatIntervalToNSCalendarUnit(ANotification.RepeatInterval)); if ANotification.EnableSound then if ANotification.SoundName.IsEmpty then NativeNotification.setSoundName(UILocalNotificationDefaultSoundName) else NativeNotification.setSoundName(StrToNSStr(ANotification.SoundName)) else NativeNotification.setSoundName(nil); Result := NativeNotification; end; destructor TNotificationCenterCocoa.Destroy; begin { Unsibscribe } TMessageManager.DefaultManager.Unsubscribe(TMessageReceivedNotification, ReceiveLocalNotification); { Destroying } ClearDelayedNotifications; FDelayedNotifications.Free; inherited Destroy; end; procedure TNotificationCenterCocoa.DidFormsLoad; begin FApplicationLoaded := True; SendDelayedNotifications; end; class destructor TNotificationCenterCocoa.Destroy; begin FNotificationCenterSingleton.Free; end; procedure TNotificationCenterCocoa.ReceiveLocalNotification(const Sender: TObject; const M: TMessage); procedure SendNotification(Notification: TNotification); begin TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification)); // Sending Delayed notifications if FDelayedNotifications.Count > 0 then SendDelayedNotifications; end; var NativeNotification: UILocalNotification; Notification: TNotification; begin if M is TMessageReceivedNotification then begin NativeNotification := (M as TMessageReceivedNotification).Value; // iOS doesn't provide list of presented notification. So we need to store it // in our list for cancelling in future with using ID Notification := ConvertNativeToDelphiNotification(NativeNotification); try if not FApplicationLoaded then FDelayedNotifications.Add(Notification) else SendNotification(Notification); finally Notification.Free; end; end; end; function TNotificationCenterCocoa.ConvertNativeToDelphiNotification(const ANotification: UILocalNotification): TNotification; var UserInfo: NSDictionary; NotificationTmp: TNotification; begin NotificationTmp := nil; if ANotification <> nil then begin NotificationTmp := TNotification.Create; UserInfo := ANotification.userInfo; if UserInfo <> nil then NotificationTmp.Name := UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(StrToNSStr('id'))).UTF8String); if ANotification.AlertBody <> nil then NotificationTmp.AlertBody := UTF8ToString(ANotification.AlertBody.UTF8String); if ANotification.AlertAction <> nil then NotificationTmp.AlertAction := UTF8ToString(ANotification.AlertAction.UTF8String);; NotificationTmp.Number := ANotification.ApplicationIconBadgeNumber; NotificationTmp.FireDate := NSDateToDateTime(ANotification.FireDate); NotificationTmp.EnableSound := ANotification.SoundName <> nil; if (ANotification.soundName = nil) or (ANotification.soundName.compare(UILocalNotificationDefaultSoundName) = NSOrderedSame) then NotificationTmp.SoundName := '' else NotificationTmp.SoundName := NSStrToStr(ANotification.soundName); NotificationTmp.HasAction := ANotification.HasAction; NotificationTmp.RepeatInterval := NSCalendarUnitToRepeatInterval(ANotification.repeatInterval); end; Result := NotificationTmp; end; procedure TNotificationCenterCocoa.DoPresentNotification(const ANotification: TNotification); var NativeNatification: UILocalNotification; begin DoCancelNotification(ANotification); NativeNatification := CreateNativeNotification(ANotification); SharedApplication.presentLocalNotificationNow(NativeNatification); end; procedure TNotificationCenterCocoa.DoScheduleNotification(const ANotification: TNotification); var NativeNatification: UILocalNotification; begin DoCancelNotification(ANotification); NativeNatification := CreateNativeNotification(ANotification); SharedApplication.scheduleLocalNotification(NativeNatification); end; procedure TNotificationCenterCocoa.SendDelayedNotifications; var Notification: TNotification; begin for Notification in FDelayedNotifications do TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification)); ClearDelayedNotifications; end; function TNotificationCenterCocoa.DoGetIconBadgeNumber: Integer; begin Result := SharedApplication.ApplicationIconBadgeNumber; end; procedure TNotificationCenterCocoa.DoLoaded; begin inherited; DidFormsLoad; end; class function TNotificationCenterCocoa.GetNotificationCenter: TNotificationCenterCocoa; begin if FNotificationCenterSingleton = nil then FNotificationCenterSingleton := TNotificationCenterCocoa.Create; Result := FNotificationCenterSingleton; end; procedure TNotificationCenterCocoa.DoSetIconBadgeNumber(const ACount: Integer); begin SharedApplication.setApplicationIconBadgeNumber(ACount); end; procedure TNotificationCenterCocoa.DoResetIconBadgeNumber; begin SharedApplication.setApplicationIconBadgeNumber(0); end; {$ENDREGION} { TPlatformNotificationCenter } class function TPlatformNotificationCenter.GetInstance: TBaseNotificationCenter; begin Result := TBaseNotificationCenter(TNotificationCenterCocoa.NotificationCenter) end; end.
{ Clever Internet Suite Copyright (C) 2017 Clever Components All Rights Reserved www.CleverComponents.com } unit clCryptPemEncryptor; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$ELSE} System.Classes, {$ENDIF} clUtils, clConfig, clCryptDataHeader; type TclRsaKeyPemEncryptor = class private FConfig: TclConfig; function GetDecryptKey(AKeySize: Integer; const AIV: TclByteArray; const APassPhrase: string): TclByteArray; public constructor Create(AConfig: TclConfig); function Decrypt(APemHeader: TclCryptDataHeader; const AKey: TclByteArray; const APassPhrase: string): TclByteArray; end; implementation uses clTranslator, clCryptUtils, clCryptHash, clCryptCipher; { TclRsaKeyPemEncryptor } constructor TclRsaKeyPemEncryptor.Create(AConfig: TclConfig); begin inherited Create(); FConfig := AConfig; end; function TclRsaKeyPemEncryptor.GetDecryptKey(AKeySize: Integer; const AIV: TclByteArray; const APassPhrase: string): TclByteArray; var hash: TclHash; passBytes, hn, tmp: TclByteArray; ind, hSize, hnSize: Integer; begin hash := TclHash(FConfig.CreateInstance('md5')); try hash.Init(); SetLength(Result, AKeySize); passBytes := TclTranslator.GetBytes(APassPhrase); hSize := hash.GetBlockSize(); hnSize := Length(Result) div hSize * hSize; if (Length(Result) mod hSize) <> 0 then begin hnSize := hnSize + hSize; end; SetLength(hn, hnSize); tmp := nil; ind := 0; while (ind + hSize <= hnSize) do begin if (tmp <> nil) then begin hash.Update(tmp, 0, Length(tmp)); end; hash.Update(passBytes, 0, Length(passBytes)); hash.Update(AIV, 0, Length(AIV)); tmp := hash.Digest(); System.Move(tmp[0], hn[ind], Length(tmp)); ind := ind + Length(tmp); end; System.Move(hn[0], Result[0], Length(Result)); finally hash.Free(); end; end; function TclRsaKeyPemEncryptor.Decrypt(APemHeader: TclCryptDataHeader; const AKey: TclByteArray; const APassPhrase: string): TclByteArray; var params: TStrings; cipher: TclCipher; iv, key: TclByteArray; begin {$IFNDEF DELPHI2005}iv := nil; key := nil; Result := nil;{$ENDIF} if (APemHeader.ProcType <> '4,ENCRYPTED') then begin Result := AKey; Exit; end; if (System.Pos('DES-CBC', APemHeader.DekInfo) = 0) and (System.Pos('DES-EDE3-CBC', APemHeader.DekInfo) = 0) then begin RaiseCryptError(UnknownKeyFormat, UnknownKeyFormatCode); end; params := nil; cipher := nil; try params := TStringList.Create(); SplitText(APemHeader.DekInfo, params, ','); if (params.Count <> 2) then begin RaiseCryptError(CryptInvalidArgument, CryptInvalidArgumentCode); end; cipher := TclCipher(FConfig.CreateInstance('3des-cbc')); iv := HexToBytes(params[1]); if (Length(iv) <> cipher.GetIVSize()) then begin RaiseCryptError(UnknownKeyFormat, UnknownKeyFormatCode); end; key := GetDecryptKey(cipher.GetBlockSize(), iv, APassPhrase); cipher.Init(cmDecrypt, key, iv); Result := System.Copy(AKey, 0, Length(AKey)); cipher.Update(Result, 0, Length(Result)); if (Length(Result) = 0) or (Result[0] <> $30) then begin RaiseCryptError(UnknownKeyFormat, UnknownKeyFormatCode); end; finally cipher.Free(); params.Free(); end; end; end.
PROGRAM Last(INPUT, OUTPUT); VAR Ch: CHAR; BEGIN {Last} IF NOT EOLN THEN BEGIN WHILE NOT EOLN DO READ(Ch); WRITE(Ch) END ELSE WRITE('You wrote nothing') END. {Last} PROGRAM WithoutLast(INPUT, OUTPUT); VAR Ch: CHAR; BEGIN {WithoutLast} IF NOT EOLN THEN BEGIN READ(Ch); WHILE NOT EOLN DO BEGIN WRITE(Ch); READ(Ch) END END ELSE WRITE('You wrote nothing') END. {WithoutLast} PROGRAM Copy(INPUT, OUTPUT); VAR Ch: CHAR; BEGIN {Copy} WHILE NOT EOLN DO BEGIN READ(Ch); WRITE(Ch) END END. {Copy} PROGRAM Last(INPUT, OUTPUT); VAR Ch: CHAR; BEGIN {Last} IF NOT EOLN THEN BEGIN WHILE NOT EOLN AND (Ch1 <> Ch2) DO BEGIN Ch2 := Ch1; READ(Ch1) END; RESET(INPUT); END ELSE WRITE('You wrote nothing') END. {Last}
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit ooFactory.Item.Intf; interface type TFactoryKey = String; IFactoryItem<TClassType> = interface ['{47E95B9B-25E7-491B-895E-F75E2B297F76}'] function Key: TFactoryKey; function ClassType: TClassType; end; implementation end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerIA5String; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpDerStringBase, ClpAsn1Tags, ClpAsn1OctetString, ClpAsn1Object, ClpStringUtils, ClpIProxiedInterface, ClpDerOutputStream, ClpCryptoLibTypes, ClpIAsn1TaggedObject, ClpIDerIA5String, ClpConverters; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SIllegalCharacters = 'String Contains Illegal Characters "str"'; SStrNil = '"str"'; type /// <summary> /// Der IA5String object - this is an ascii string. /// </summary> TDerIA5String = class(TDerStringBase, IDerIA5String) strict private var FStr: String; function GetStr: String; inline; property Str: String read GetStr; strict protected function Asn1GetHashCode(): Int32; override; function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public /// <summary> /// basic constructor - with bytes. /// </summary> constructor Create(const Str: TCryptoLibByteArray); overload; /// <summary> /// basic constructor - without validation. /// </summary> constructor Create(const Str: String); overload; /// <summary> /// Constructor with optional validation. /// </summary> /// <param name="Str"> /// the base string to wrap. /// </param> /// <param name="validate"> /// whether or not to check the string. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if validate is true and the string contains characters that should /// not be in an IA5String. /// </exception> constructor Create(const Str: String; validate: Boolean); overload; function GetString(): String; override; function GetOctets(): TCryptoLibByteArray; inline; procedure Encode(const derOut: TStream); override; /// <summary> /// return a DerIA5String from the passed in object /// </summary> /// <param name="obj"> /// a DerIA5String or an object that can be converted into one. /// </param> /// <returns> /// return a DerIA5String instance, or null. /// </returns> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerIA5String; overload; static; inline; /// <summary> /// return a DerIA5String from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// true if the object is meant to be explicitly tagged false otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerIA5String; overload; static; inline; /// <summary> /// return true if the passed in String can be represented without loss /// as an IA5String, false otherwise. /// </summary> /// <param name="Str"> /// true if in printable set, false otherwise. /// </param> class function IsIA5String(const Str: String): Boolean; static; inline; end; implementation { TDerIA5String } function TDerIA5String.GetStr: String; begin result := FStr; end; function TDerIA5String.GetOctets: TCryptoLibByteArray; begin result := TConverters.ConvertStringToBytes(Str, TEncoding.ASCII); end; class function TDerIA5String.IsIA5String(const Str: String): Boolean; var ch: Char; begin for ch in Str do begin if (Ord(ch) > $007F) then begin result := false; Exit; end; end; result := true; end; function TDerIA5String.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerIA5String; begin if (not Supports(asn1Object, IDerIA5String, other)) then begin result := false; Exit; end; result := Str = other.Str; end; function TDerIA5String.Asn1GetHashCode: Int32; begin result := TStringUtils.GetStringHashCode(FStr); end; constructor TDerIA5String.Create(const Str: TCryptoLibByteArray); begin Create(TConverters.ConvertBytesToString(Str, TEncoding.ASCII), false); end; constructor TDerIA5String.Create(const Str: String); begin Create(Str, false); end; constructor TDerIA5String.Create(const Str: String; validate: Boolean); begin Inherited Create(); if (Str = '') then begin raise EArgumentNilCryptoLibException.CreateRes(@SStrNil); end; if (validate and (not IsIA5String(Str))) then begin raise EArgumentCryptoLibException.CreateRes(@SIllegalCharacters); end; FStr := Str; end; procedure TDerIA5String.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.IA5String, GetOctets()); end; class function TDerIA5String.GetInstance(const obj: TObject): IDerIA5String; begin if ((obj = Nil) or (obj is TDerIA5String)) then begin result := obj as TDerIA5String; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerIA5String.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerIA5String; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerIA5String))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := TDerIA5String.Create(TAsn1OctetString.GetInstance(o as TAsn1Object) .GetOctets()); end; function TDerIA5String.GetString: String; begin result := Str; end; end.
unit fpvelectricalelements; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpimage, fpcanvas, // fpvectorial; const WIRE_SUBPART_DEST = 1; type { TWire } TvWire = class(TvEntity) public DestPos: T3DPoint; // procedure Assign(ASource: TPath); function TryToSelect(APos: TPoint; var ASubpart: Cardinal): TvFindEntityResult; override; procedure MoveSubpart(ADeltaX, ADeltaY: Double; ASubpart: Cardinal); override; procedure Render(ADest: TFPCustomCanvas; var ARenderInfo: TvRenderInfo; ADestX: Integer=0; ADestY: Integer=0; AMulX: Double=1.0; AMulY: Double=1.0); override; end; implementation { TvWire } function TvWire.TryToSelect(APos: TPoint; var ASubpart: Cardinal): TvFindEntityResult; begin if (APos.X = X) and (APos.Y = Y) then Result := vfrFound else if (Apos.X = DestPos.X) and (APos.Y = DestPos.Y) then begin Result := vfrSubpartFound; ASubpart := WIRE_SUBPART_DEST; end else Result := vfrNotFound; end; procedure TvWire.MoveSubpart(ADeltaX, ADeltaY: Double; ASubpart: Cardinal); begin if ASubpart = WIRE_SUBPART_DEST then begin DestPos.X := DestPos.X + ADeltaX; DestPos.Y := DestPos.Y + ADeltaY; end; end; procedure TvWire.Render(ADest: TFPCustomCanvas; var ARenderInfo: TvRenderInfo; ADestX: Integer; ADestY: Integer; AMulX: Double; AMulY: Double); function CoordToCanvasX(ACoord: Double): Integer; begin Result := Round(ADestX + AmulX * ACoord); end; function CoordToCanvasY(ACoord: Double): Integer; begin Result := Round(ADestY + AmulY * ACoord); end; begin ADest.Line( CoordToCanvasX(X), CoordToCanvasY(Y), CoordToCanvasX(DestPos.X), CoordToCanvasY(DestPos.Y)); end; end.
{ Double Commander ------------------------------------------------------------------------- Support for popup menu to help to enter variable parameters. Copyright (C) 2015-2018 Alexander Koblov (alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit uVariableMenuSupport; {$mode objfpc}{$H+} interface uses //Lazarus, Free-Pascal, etc. Classes, Menus, StdCtrls, //DC dmHelpManager; type TSupportForVariableHelperMenu = class(TObject) public constructor Create; destructor Destroy; override; procedure PopulateMenuWithVariableHelper(pmToPopulate: TComponent; ParamAssociatedComponent: TComponent); end; TVariableMenuItem = class(TMenuItem) private FAssociatedTComponent: TComponent; FSubstitutionText: string; public constructor MyCreate(TheOwner: TComponent; ParamTComponent: TComponent; ParamCaption, ParamSubstitutionText: string); procedure VariableHelperClick(Sender: TObject); procedure HelpOnVariablesClick(Sender: TObject); end; procedure LoadVariableMenuSupport; implementation uses //Lazarus, Free-Pascal, etc. SysUtils, Dialogs, //DC uGlobs, uLng; procedure LoadVariableMenuSupport; begin gSupportForVariableHelperMenu := TSupportForVariableHelperMenu.Create; end; { TVariableMenuItem.MyCreate } constructor TVariableMenuItem.MyCreate(TheOwner: TComponent; ParamTComponent: TComponent; ParamCaption, ParamSubstitutionText: string); begin inherited Create(TheOwner); Caption := ParamCaption; if ParamCaption <> rsVarHelpWith then begin if ParamSubstitutionText <> '' then begin FAssociatedTComponent := ParamTComponent; FSubstitutionText := ParamSubstitutionText; OnClick := @VariableHelperClick; end; end else begin OnClick := @HelpOnVariablesClick; end; end; { TVariableMenuItem.VariableHelperClick } //Our intention: //-If something is selected, we replace what's selected by the helper string //-If nothing is selected, we insert our helper string at the current cursor pos //-If nothing is there at all, we add, simply procedure TVariableMenuItem.VariableHelperClick(Sender: TObject); begin TCustomEdit(FAssociatedTComponent).SelText := FSubstitutionText; end; { TVariableMenuItem.HelpOnVariablesClick } procedure TVariableMenuItem.HelpOnVariablesClick(Sender: TObject); begin ShowHelpForKeywordWithAnchor('/variables.html'); end; { TSupportForVariableHelperMenu.Create } constructor TSupportForVariableHelperMenu.Create; begin inherited Create; end; { TSupportForVariableHelperMenu.Destroy } destructor TSupportForVariableHelperMenu.Destroy; begin inherited Destroy; end; { TSupportForVariableHelperMenu.PopulateMenuWithVariableHelper } procedure TSupportForVariableHelperMenu.PopulateMenuWithVariableHelper(pmToPopulate: TComponent; ParamAssociatedComponent: TComponent); type tHelperMenuDispatcher = set of (hmdNothing, hmdSeparator, hmdListLevel); tFunctionHelper = record sLetter: string; sDescription: string; HelperMenuDispatcher: tHelperMenuDispatcher; end; tFirstSubLevelHelper = record sLetter: string; sDescription: string; HelperMenuDispatcher: tHelperMenuDispatcher; end; const NbOfFunctions = 10; FunctionHelper: array[1..NbOfFunctions] of tFunctionHelper = ( (sLetter: 'f'; sDescription: rsVarOnlyFilename; HelperMenuDispatcher: []), (sLetter: 'd'; sDescription: rsVarPath; HelperMenuDispatcher: []), (sLetter: 'p'; sDescription: rsVarFullPath; HelperMenuDispatcher: []), (sLetter: 'o'; sDescription: rsVarFilenameNoExt; HelperMenuDispatcher: []), (sLetter: 'e'; sDescription: rsVarOnlyExtension; HelperMenuDispatcher: []), (sLetter: 'v'; sDescription: rsVarRelativePathAndFilename; HelperMenuDispatcher: [hmdSeparator]), (sLetter: 'D'; sDescription: rsVarCurrentPath; HelperMenuDispatcher: [hmdSeparator]), (sLetter: 'L'; sDescription: rsVarListFullFilename; HelperMenuDispatcher: [hmdListLevel]), (sLetter: 'F'; sDescription: rsVarListFilename; HelperMenuDispatcher: [hmdListLevel]), (sLetter: 'R'; sDescription: rsVarListRelativeFilename; HelperMenuDispatcher: [hmdListLevel,hmdSeparator])); NbOfSubListLevel = 4; SubListLevelHelper: array[1..NbOfSubListLevel] of tFirstSubLevelHelper = ( (sLetter: 'U'; sDescription: rsVarListInUTF8; HelperMenuDispatcher: []), (sLetter: 'W'; sDescription: rsVarListInUTF16; HelperMenuDispatcher: []), (sLetter: 'UQ'; sDescription: rsVarListInUTF8Quoted; HelperMenuDispatcher: []), (sLetter: 'WQ'; sDescription: rsVarListInUTF16Quoted; HelperMenuDispatcher: [])); NbOfSubLevel = 6; SubLevelHelper: array[1..NbOfSubLevel] of tFirstSubLevelHelper = ( (sLetter: 's'; sDescription: rsVarSourcePanel; HelperMenuDispatcher: []), (sLetter: 't'; sDescription: rsVarTargetPanel; HelperMenuDispatcher: [hmdSeparator]), (sLetter: 'l'; sDescription: rsVarLeftPanel; HelperMenuDispatcher: []), (sLetter: 'r'; sDescription: rsVarRightPanel; HelperMenuDispatcher: [hmdSeparator]), (sLetter: 'b'; sDescription: rsVarBothPanelLeftToRight; HelperMenuDispatcher: []), (sLetter: 'p'; sDescription: rsVarBothPanelActiveToInactive; HelperMenuDispatcher: [])); NbOfSubLevelExamples = 15; SubLevelHelperExamples: array[1..NbOfSubLevelExamples] of tFirstSubLevelHelper = ( (sLetter: '%?'; sDescription: rsVarShowCommandPrior; HelperMenuDispatcher: []), (sLetter: '%%'; sDescription: rsVarPercentSign; HelperMenuDispatcher: []), (sLetter: '%#'; sDescription: rsVarPercentChangeToPound; HelperMenuDispatcher: []), (sLetter: '#%'; sDescription: rsVarPoundChangeToPercent; HelperMenuDispatcher: [hmdSeparator]), (sLetter: '%"0'; sDescription: rsVarWillNotBeQuoted; HelperMenuDispatcher: []), (sLetter: '%"1'; sDescription: rsVarWillBeQuoted; HelperMenuDispatcher: []), (sLetter: '%/0'; sDescription: rsVarWillNotHaveEndingDelimiter; HelperMenuDispatcher: []), (sLetter: '%/1'; sDescription: rsVarWillHaveEndingDelimiter; HelperMenuDispatcher: []), (sLetter: '%t0'; sDescription: rsVarWillNotDoInTerminal; HelperMenuDispatcher: []), (sLetter: '%t1'; sDescription: rsVarWillDoInTerminal; HelperMenuDispatcher: [hmdSeparator]), (sLetter: rsVarSimpleMessage; sDescription: rsVarSimpleShowMessage; HelperMenuDispatcher: []), (sLetter: rsVarPromptUserForParam; sDescription: rsVarInputParam; HelperMenuDispatcher: [hmdSeparator]), (sLetter: '%f{-a }'; sDescription: rsVarPrependElement; HelperMenuDispatcher: []), (sLetter: '%f{[}{]} '; sDescription: rsVarEncloseElement; HelperMenuDispatcher: []), (sLetter: '%pr2'; sDescription: rsVarSecondElementRightPanel; HelperMenuDispatcher: [])); var miMainTree, miSubTree, miSubListTree: TVariableMenuItem; iFunction, iSubLevel, iSubListLevel: integer; procedure InsertSeparatorInMainMenu; begin miMainTree := TVariableMenuItem.MyCreate(pmToPopulate, nil, '-', ''); TPopupMenu(pmToPopulate).Items.Add(miMainTree); end; procedure InsertSeparatorInSubMenu; begin miSubTree := TVariableMenuItem.MyCreate(miMainTree, nil, '-', ''); miMainTree.Add(miSubTree); end; procedure InsertSeparatorInSubListMenu; begin miSubTree := TVariableMenuItem.MyCreate(miSubListTree, nil, '-', ''); miSubListTree.Add(miSubTree); end; begin //Add the automatic helper for iFunction := 1 to NbOfFunctions do begin miMainTree := TVariableMenuItem.MyCreate(pmToPopulate, nil, '%' + FunctionHelper[iFunction].sLetter + ' - ' + FunctionHelper[iFunction].sDescription, ''); TPopupMenu(pmToPopulate).Items.Add(miMainTree); miSubTree := TVariableMenuItem.MyCreate(miMainTree, ParamAssociatedComponent, '%' + FunctionHelper[iFunction].sLetter + ' - ' + FunctionHelper[iFunction].sDescription, '%' + FunctionHelper[iFunction].sLetter); miMainTree.Add(miSubTree); InsertSeparatorInSubMenu; for iSubLevel := 1 to NbOfSubLevel do begin miSubTree := TVariableMenuItem.MyCreate(miMainTree, ParamAssociatedComponent, '%' + FunctionHelper[iFunction].sLetter + SubLevelHelper[iSubLevel].sLetter + ' - ' + '...' + SubLevelHelper[iSubLevel].sDescription, '%' + FunctionHelper[iFunction].sLetter + SubLevelHelper[iSubLevel].sLetter); miMainTree.Add(miSubTree); if hmdSeparator in SubLevelHelper[iSubLevel].HelperMenuDispatcher then InsertSeparatorInSubMenu; end; if hmdListLevel in FunctionHelper[iFunction].HelperMenuDispatcher then begin InsertSeparatorInSubMenu; for iSubListLevel:=1 to NbOfSubListLevel do begin miSubListTree := TVariableMenuItem.MyCreate(miMainTree, ParamAssociatedComponent, '%' +FunctionHelper[iFunction].sLetter + SubListLevelHelper[iSubListLevel].sLetter + ' - ' + '...' + SubListLevelHelper[iSubListLevel].sDescription + '...', ''); miMainTree.Add(miSubListTree); miSubTree := TVariableMenuItem.MyCreate(miSubListTree, ParamAssociatedComponent, '%' +FunctionHelper[iFunction].sLetter + SubListLevelHelper[iSubListLevel].sLetter + ' - ' + SubListLevelHelper[iSubListLevel].sDescription, '%' +FunctionHelper[iFunction].sLetter + SubListLevelHelper[iSubListLevel].sLetter); miSubListTree.Add(miSubTree); InsertSeparatorInSubListMenu; for iSubLevel := 1 to NbOfSubLevel do begin miSubTree := TVariableMenuItem.MyCreate(miSubListTree, ParamAssociatedComponent, '%' +FunctionHelper[iFunction].sLetter + SubListLevelHelper[iSubListLevel].sLetter + SubLevelHelper[iSubLevel].sLetter + ' - ' + '...' + SubLevelHelper[iSubLevel].sDescription, '%' +FunctionHelper[iFunction].sLetter + SubListLevelHelper[iSubListLevel].sLetter + SubLevelHelper[iSubLevel].sLetter); miSubListTree.Add(miSubTree); if hmdSeparator in SubLevelHelper[iSubLevel].HelperMenuDispatcher then InsertSeparatorInSubListMenu; end; end; end; if hmdSeparator in FunctionHelper[iFunction].HelperMenuDispatcher then InsertSeparatorInMainMenu; end; //Add the more complex-not-so-complex other examples miMainTree := TVariableMenuItem.MyCreate(pmToPopulate, nil, rsVarOtherExamples, ''); TPopupMenu(pmToPopulate).Items.Add(miMainTree); for iSubLevel := 1 to NbOfSubLevelExamples do begin miSubTree := TVariableMenuItem.MyCreate(miMainTree, ParamAssociatedComponent, SubLevelHelperExamples[iSubLevel].sLetter + ' - ' + SubLevelHelperExamples[iSubLevel].sDescription, SubLevelHelperExamples[iSubLevel].sLetter); miMainTree.Add(miSubTree); if hmdSeparator in SubLevelHelperExamples[iSubLevel].HelperMenuDispatcher then InsertSeparatorInSubMenu; end; //Add link for the help at the end InsertSeparatorInMainMenu; miMainTree := TVariableMenuItem.MyCreate(pmToPopulate, nil, rsVarHelpWith, ''); TPopupMenu(pmToPopulate).Items.Add(miMainTree); end; end.
unit uAguarde; interface uses System.SysUtils, System.UITypes, FMX.Types, FMX.Controls, FMX.StdCtrls, FMX.Objects, FMX.Forms, FMX.Effects, FMX.Graphics; type TAguarde = class private class var FAguarde: TRectangle; class var FFundo: TPanel; class procedure TrocaCorPFundo(Sender: TObject); public class procedure ChangeMessage(const AMsg: string); class procedure Show(AParent: TFMXObject; AMsg: string = ''; ATitle: string = ''); class procedure Hide; end; implementation { TAguarde } class procedure TAguarde.ChangeMessage(const AMsg: string); var LLbl: TLabel; begin LLbl := TLabel(FAguarde.FindComponent('lblMessage')); if (LLbl <> nil) then LLbl.Text := AMsg; end; class procedure TAguarde.Hide; begin if (Assigned(FAguarde)) then begin FFundo.AnimateFloat('opacity', 0); FAguarde.AnimateFloat('opacity', 0); FFundo.DisposeOf; FAguarde.DisposeOf; FFundo := nil; FAguarde := nil; end; end; class procedure TAguarde.Show(AParent: TFMXObject; AMsg, ATitle: string); begin FFundo := TPanel.Create(AParent); FFundo.Parent := AParent; FFundo.Visible := true; FFundo.Align := TAlignLayout.Contents; FFundo.OnApplyStyleLookup := TrocaCorPFundo; FAguarde := TRectangle.Create(AParent); FAguarde.Parent := AParent; FAguarde.Visible := true; FAguarde.Height := 75; FAguarde.Width := 275; FAguarde.XRadius := 10; FAguarde.YRadius := 10; FAguarde.Position.X := (TForm(AParent).ClientWidth - FAguarde.Width) / 2; FAguarde.Position.Y := (TForm(AParent).ClientHeight - FAguarde.Height) / 2; FAguarde.Stroke.Kind := TBrushKind.None; if (ATitle.Trim.IsEmpty) then ATitle := 'Por favor, aguarde!'; with TLabel.Create(FAguarde) do begin Parent := FAguarde; Align := TAlignLayout.Top; Margins.Left := 10; Margins.Top := 10; Margins.Right := 10; Height := 28; StyleLookup := 'embossedlabel'; Text := ATitle; Trimming := TTextTrimming.ttCharacter; end; with TLabel.Create(FAguarde) do begin Parent := FAguarde; Align := TAlignLayout.Client; Margins.Left := 10; Margins.Top := 10; Margins.Right := 10; Height := 28; Font.Size := 12; Name := 'lblMessage'; StyledSettings := [TStyledSetting.ssFamily, TStyledSetting.ssStyle, TStyledSetting.ssFontColor]; StyleLookup := 'embossedlabel'; Text := AMsg; VertTextAlign := TTextAlign.Leading; Trimming := TTextTrimming.ttCharacter; end; with TShadowEffect.Create(FAguarde) do begin Parent := FAguarde; Enabled := true; end; FFundo.Opacity := 0; FAguarde.Opacity := 0; FFundo.Visible := true; FAguarde.Visible := true; FFundo.AnimateFloat('opacity', 0.5); FAguarde.AnimateFloat('opacity', 1); FAguarde.BringToFront; if FAguarde.Canfocus then FAguarde.SetFocus; end; class procedure TAguarde.TrocaCorPFundo(Sender: TObject); var Rectangle: TRectangle; begin Rectangle := (Sender as TFMXObject).Children[0] as TRectangle; Rectangle.Fill.Color := TAlphaColors.Black; end; end.
unit uPessoa; interface uses System.Generics.Collections; type TPessoa = class strict private FNaturalidade: String; FId: Integer; FNome: String; FProfissao: String; procedure SetId(const Value: Integer); procedure SetNaturalidade(const Value: String); procedure SetNome(const Value: String); procedure SetProfissao(const Value: String); public property Id: Integer read FId write SetId; property Nome: String read FNome write SetNome; property Profissao: String read FProfissao write SetProfissao; property Naturalidade: String read FNaturalidade write SetNaturalidade; end; TPessoas = TObjectList<TPessoa>; TPessoaList = class public Pessoas: TPessoas; constructor Create(); destructor Destroy; override; class function CreateInit(APessoas: TPessoas): TPessoaList; end; implementation { TPessoa } procedure TPessoa.SetId(const Value: Integer); begin FId := Value; end; procedure TPessoa.SetNaturalidade(const Value: String); begin FNaturalidade := Value; end; procedure TPessoa.SetNome(const Value: String); begin FNome := Value; end; procedure TPessoa.SetProfissao(const Value: String); begin FProfissao := Value; end; { TPessoList } constructor TPessoaList.Create(); begin Pessoas := TPessoas.Create; end; class function TPessoaList.CreateInit(APessoas: TPessoas): TPessoaList; begin Result := TPessoaList.Create(); Result.Pessoas := APessoas; end; destructor TPessoaList.Destroy; begin Pessoas.Free(); inherited; end; end.
{ Subroutine SST_R_PAS_DATA_TYPE (DTYPE_P) * * Read in a DATA_TYPE syntax and return DTYPE_P pointing to the corresponding * data type descriptor. If DTYPE_P is NIL on entry to this routine, then * a new data type descriptor is either created or an existing one found. If * DTYPE_P is no NIL, then DTYPE_P will not be altered, and the resulting data * type will be overwritten into the block DTYPE_P^. * * This is used when a previously referenced but undefined data type is finally * declared. } module sst_r_pas_DATA_TYPE; define sst_r_pas_data_type; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_data_type ( {process DATA_TYPE} in out dtype_p: sst_dtype_p_t); {returned pointer to new or reused data type} const max_msg_parms = 3; {max parameters we can pass to a message} var tag: sys_int_machine_t; {syntax tags from .syn file} str_h, str2_h: syo_string_t; {handle to string for a tag} dt_p: sst_dtype_p_t; {scratch data type pointer} dt_set_p: sst_dtype_p_t; {points to original data type for a SET} dt_original_p: sst_dtype_p_t; {save copy of DTYPE_P on entry} dt_id: sst_dtype_k_t; {scratch data type ID} dt_align: sys_int_machine_t; {alignment for this data type} dt_enum: sst_dtype_t; {data type for enumerated type elements} sym_p: sst_symbol_p_t; {scratch symbol pointer} prev_sym_p: sst_symbol_p_t; {previous symbol pointer for chaining} exp_p: sst_exp_p_t; {scratch expression pointer} i, j: sys_int_machine_t; {scratch integer and loop counter} bits: sys_int_machine_t; {number of bits required} token: string_var32_t; {scratch string for number conversion} dt_ar_p: sst_dtype_p_t; {pointer to next data type of array remainder} range_start, range_end: {subscript start/end ordinal values} sys_int_max_t; n_ele: sys_int_conv32_t; {total number of elements in array} sz: sys_int_adr_t; {scratch for saving amount of memory} n_subscr: sys_int_machine_t; {scratch number of subscripts} func: boolean; {TRUE if routine is a function} pointer: boolean; {TRUE if data type is a pointer} created: boolean; {TRUE if we created new dtype descriptor} reusing: boolean; {TRUE if re-using dtype (DTYPE_P <> NIL)} enum_dtype_set: boolean; {TRUE when enum dtype explicitly set} set_size_set: boolean; {TRUE when bit size of set given explicitly} fnam: string_treename_t; {file name passed to a message} lnum: sys_int_machine_t; {line number passed to a message} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {completion status code} label loop_tag_start, do_enum_dtype_set, enum_loop, done_enum, set_dtype_bad, loop_ar_dtype, got_set_size; { *********************************************** * * Local function BITS_MIN (V1, V2) * * Return the minimum number of bits that can be used to represent the * subrange of ordinal values from V1 to V2. A negative value is returned to * indicate that no target language integer is capable of holding the subrange. * It is assumed that V1 <= v2. } function bits_min ( in v1, v2: sys_int_max_t) {limits of the integer subrange} :sys_int_machine_t; var imin, imax: sys_int_max_t; {min/max values of current integer size} bmin: sys_int_machine_t; {internal BITS_MIN value} unsig: boolean; {TRUE if could match unsigned data type} label got_bmin; begin unsig := (v1 >= 0) and (v2 >= 0); {TRUE if range limits allow unsigned integer} bits_min := -1; {init to no suitable target size exists} if unsig then begin {test for fit as unsigned integer} imax := 1; {init value limit for 1 bit integer} for bmin := 1 to sst_dtype_int_max_p^.bits_min do begin {loop to max size} if imax >= v2 then goto got_bmin; {this size integer is big enough ?} imax := ~lshft(~imax, 1); {update to max value for next size integer} end; {back and check this new size int for fit} end else begin {test for fit as signed integer} imin := -1; {init value limits for 1 bit integer} imax := 0; for bmin := 1 to sst_dtype_int_max_p^.bits_min do begin {loop to max size} if (imin <= v1) and (imax >= v2) then goto got_bmin; {this size fits ?} imin := lshft(imin, 1); {update value limits for next bigger size} imax := ~lshft(~imax, 1); end; {back and check this new size int for fit} end ; return; {didn't fit into largest target integer} got_bmin: {found minimum BMIN value that works} if {used max int as unsigned with wrong lang ?} (bmin = sst_dtype_int_max_p^.bits_min) and {used max size integer ?} unsig and {assumed integer could be unsigned ?} (sst_config.lang <> sst_lang_c_k) {language doesn't support this ?} then return; {no suitable integer found} bits_min := bmin; {return minimum bits value} end; { *********************************************** * * Local subroutine DTYPE_CREATE (P) * * Create a new data type descriptor. P will be returned pointing to the * new descriptor. CREATED will also be set to TRUE, to indicate that * a new data type descriptor was created instead of an old one referenced. } procedure dtype_create ( out p: sst_dtype_p_t); begin if reusing then begin {re-using caller's data type descriptor ?} if created then begin {can't re-use same data type twice} sys_message_bomb ('sst_pas_read', 'dtype_reuse_twice', nil, 0); end; created := true; {a new data type descriptor was created} dtype_p := dt_original_p; {make sure we are pointing to callers desc} return; end; created := true; {a new data type descriptor was created} util_mem_grab (sizeof(p^), sst_scope_p^.mem_p^, false, p); {allocate the memory} p^.symbol_p := nil; {init mandatory fields} p^.dtype := sst_dtype_undef_k; p^.bits_min := 0; p^.align_nat := 0; p^.align := dt_align; p^.size_used := 0; p^.size_align := 0; end; { *********************************************** * * Start of main routine. } begin token.max := sizeof(token.str); {init var strings} fnam.max := sizeof(fnam.str); dt_original_p := dtype_p; {save DTYPE_P as passed in from caller} reusing := false; {init to not reusing descriptor at DTYPE_P} if dtype_p <> nil then begin {caller wants us to fill in DTYPE_P^ ?} if dtype_p^.dtype <> sst_dtype_undef_k then begin sys_message_bomb ('sst_pas_read', 'dtype_not_undefined', nil, 0); end; reusing := true; end; dt_align := sst_align; {default our alignment rule to curr rule} created := false; {init to no new dtype descriptor created} syo_level_down; {down into DATA_TYPE syntax} loop_tag_start: {back here for each new tag at syntax start} syo_get_tag_msg ( {get starting tag in DATA_TYPE syntax} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of 1: begin {data type is not a pointer} pointer := false; end; 2: begin {data type is a pointer} pointer := true; end; 3: begin {tag is for DATA_TYPE_ATTRIBUTE syntax} syo_level_down; {down into DATA_TYPE_ATTRIBUTE syntax} syo_get_tag_msg ( {get tag for this attribute} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of 1: dt_align := sst_align_natural_k; {NATURAL} 2: ; {ATOMIC} 3: dt_align := 1; {ALIGNED or ALIGNED(0)} 4: dt_align := 2; {ALIGNED(1)} 5: dt_align := 4; {ALIGNED(2)} 6: dt_align := 8; {ALIGNED(3)} syo_tag_end_k: ; {nothing here at all (this is legal)} otherwise syo_error_tag_unexp (tag, str_h); end; syo_level_up; {back up from DATA_TYPE_ATTRIBUTE syntax} goto loop_tag_start; {back for another tag at start of DATA_TYPE} end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of pointer yes/no tag cases} enum_dtype_set := false; {init to enum data type not explicitly set} syo_get_tag_msg ( {get tag for basic data type class} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of { * The code for each of the cases is responsible for making sure DTYPE_P is * pointing to a valid data type descriptor. CREATED must be set to TRUE * if DTYPE_P is pointing to a data type descriptor that was newly created * here. This is used later to decide whether the data type descriptor may * be edited, or whether a copy must be created first. * * When CREATED is TRUE, the ALIGN and SIZE_ALIGN fields of the data type * descriptor will be set later. * * CREATED is automatically set to TRUE by the local subroutine DTYPE_CREATE. * ************************************************* * * SIMPLE_DATA_TYPE } 1: begin syo_level_down; {down into SIMPLE_DATA_TYPE syntax} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); str2_h := str_h; {save handle to original simple data type} do_enum_dtype_set: {back here after ele data types determined} case tag of { ******************************* * * SIMPLE_DATA_TYPE > INTEGER16 } 1: begin dtype_p := dtype_i16_p; end; { ******************************* * * SIMPLE_DATA_TYPE > INTEGER32 } 2: begin dtype_p := dtype_i32_p; end; { ******************************* * * SIMPLE_DATA_TYPE > REAL } 12: begin dtype_p := sst_config.float_machine_p; end; { ******************************* * * SIMPLE_DATA_TYPE > SINGLE } 3: begin dtype_p := sst_config.float_single_p; end; { ******************************* * * SIMPLE_DATA_TYPE > DOUBLE } 4: begin dtype_p := sst_config.float_double_p; end; { ******************************* * * SIMPLE_DATA_TYPE > BOOLEAN } 5: begin dtype_p := sst_dtype_bool_p; end; { ******************************* * * SIMPLE_DATA_TYPE > CHAR } 6: begin dtype_p := sst_dtype_char_p; end; { ******************************* * * SIMPLE_DATA_TYPE > UNIV_PTR } 7: begin dtype_p := sst_dtype_uptr_p; end; { ******************************* * * SIMPLE_DATA_TYPE > STRING } 8: begin dtype_p := dtype_str_p; end; { ******************************* * * SIMPLE_DATA_TYPE > enumerated type } 9: begin i := 0; {init value of next enumerated name} if enum_dtype_set { * DTYPE_P is pointing to the explicit data type to use for all * elements of this enumerated type. We will make a copy for reference * in DT_ENUM. DTYPE_P will then be set to a data type descriptor that * the final enumerated type can be written in. All the alignment, etc., * fields will already be set, so we just return when done. } then begin dt_p := dtype_p; {resolve base elements data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; dt_enum := dt_p^; {save copy of data type for the elements} case dt_enum.dtype of {what kind of data type will elements have} sst_dtype_int_k, {all the legal element data types} sst_dtype_bool_k, sst_dtype_char_k: ; sst_dtype_range_k: begin {need to determine starting name value} i := dt_enum.range_ord_first; {first name will have first value of range} end; otherwise syo_error (str2_h, 'sst_pas_read', 'dtype_enum_ele_bad', nil, 0); end; if not created then begin {can't re-use DTYPE_P^ ?} dtype_create (dtype_p); {point to new data type descriptor} dtype_p^.bits_min := dt_enum.bits_min; {init final enum data type} dtype_p^.align_nat := dt_enum.align_nat; dtype_p^.size_used := dt_enum.size_used; end; end { * This is a regular enumerated type without the explicit elements * data type field. } else begin j := 1; {init index to integer size info for enum} while sst_config.size_int[j].size <> sst_config.size_enum do j := j + 1; dt_enum := {data type name values must be convertable to} sst_config.size_int[j].dtype_p^; dtype_create (dtype_p); {create new data type descriptor} dtype_p^.align_nat := sst_config.size_enum; dtype_p^.size_used := sst_config.size_enum; end ; syo_level_down; {down into ENUMERATED_DATA_TYPE syntax} dtype_p^.dtype := sst_dtype_enum_k; dtype_p^.enum_first_p := nil; prev_sym_p := nil; {init to no previous symbol exists} enum_loop: {back here each new tag} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'dtype_enum_bad', nil, 0); if tag = syo_tag_end_k then goto done_enum; {no more enumerated names ?} sst_symbol_new (str_h, syo_charcase_down_k, sym_p, stat); syo_error_abort (stat, str_h, '', '', nil, 0); sym_p^.symtype := sst_symtype_enum_k; {symbol is enumerated name} sym_p^.flags := [sst_symflag_def_k]; sym_p^.enum_next_p := nil; {init to this symbol is last in chain} if prev_sym_p = nil then begin {this is first symbol in chain} dtype_p^.enum_first_p := sym_p; sym_p^.enum_prev_p := nil; end else begin {new symbol is not first of chain} prev_sym_p^.enum_next_p := sym_p; sym_p^.enum_prev_p := prev_sym_p; end ; sym_p^.enum_dtype_p := dtype_p; {point symbol to its parent data type} prev_sym_p := sym_p; {new symbol becomes previous symbol} syo_get_tag_msg ( {get optional value tag for this name} tag, str_h, 'sst_pas_read', 'dtype_enum_bad', nil, 0); case tag of 1: begin {explicit value was given for this name} sst_r_pas_exp (str_h, true, exp_p); {get explicit name value expression} sst_exp_useage_check (exp_p^, [sst_rwflag_read_k], dt_enum); {check expression} sst_ordval (exp_p^.val, i, stat); {get expression ordinal value in I} syo_error_abort (stat, str_h, '', '', nil, 0); end; 2: ; {default value for this name, I already set} otherwise syo_error_tag_unexp (tag, str_h); end; sym_p^.enum_ordval := i; {set ordinal value of this enumerated name} i := i + 1; {make default value for next enumerated name} goto enum_loop; {back and process next enumerated name} done_enum: {jump here when no more enumerated names} dtype_p^.enum_last_p := prev_sym_p; {set pointer to end of symbols chain} syo_level_up; {back up from ENUMERATED_DATA_TYPE syntax} if not enum_dtype_set then begin {explicit data type not already set ?} bits := 1; {init number of bits needed} j := 2; {number of states for current BITS value} while j < i do begin {still need more bits ?} bits := bits + 1; j := j + j; end; dtype_p^.bits_min := bits; {set minumum bits needed for this type} end; end; { ******************************* * * SIMPLE_DATA_TYPE > subrange type } 10: begin dtype_create (dtype_p); {make sure DTYPE_P points to dtype desc} syo_level_down; {down into SUBRANGE_DATA_TYPE syntax} dtype_p^.dtype := sst_dtype_range_k; {indicate this is a subrange data type} { * Process range start expression. This sets the final data type fields * RANGE_DTYPE_P and RANGE_FIRST_P. The variable RANGE_START is also set to * the ordinal value of the range start expression. } syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'dtype_range_bad', nil, 0); if tag <> 1 then syo_error_tag_unexp (tag, str_h); sst_r_pas_exp (str_h, true, dtype_p^.range_first_p); {process range start value} sst_dtype_resolve ( {get pointer to root data type descriptor} dtype_p^.range_first_p^.dtype_p^, {raw dtype of range start expression} dtype_p^.range_dtype_p, {will point to root data type descriptor} dt_id); {unused root data type ID} sst_ordval ( {get ordinal value of subrange start} dtype_p^.range_first_p^.val, {input constant value descriptor} range_start, {returned ordinal value} stat); syo_error_abort (stat, str_h, 'sst_pas_read', 'dtype_range_illegal', nil, 0); { * Process the range end expression. It is verified to conform to the * data type established by the start range expression. This also sets * the final data type field RANGE_LAST_P. The variable RANGE_END * is also set to the ordinal value of the range end expression. } syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'dtype_range_bad', nil, 0); if tag <> 1 then syo_error_tag_unexp (tag, str_h); sst_r_pas_exp (str_h, true, dtype_p^.range_last_p); {process range end value} if not sst_dtype_convertable ( {data type incompatible with start range ?} dtype_p^.range_last_p^.dtype_p^, dtype_p^.range_first_p^.dtype_p^) then begin syo_error (str_h, 'sst_pas_read', 'dtype_range_not_match', nil, 0); end; sst_ordval ( {get ordinal value of subrange end} dtype_p^.range_last_p^.val, {input constant value descriptor} range_end, {returned ordinal value} stat); syo_error_abort (stat, str_h, 'sst_pas_read', 'dtype_range_illegal', nil, 0); if range_end < range_start then begin {subrange is inverted ?} syo_error (str_h, 'sst_pas_read', 'dtype_range_inverted', nil, 0); end; syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'dtype_range_bad', nil, 0); if tag <> syo_tag_end_k then syo_error_tag_unexp (tag, str_h); syo_level_up; {done with SUBRANGE_DATA_TYPE syntax level} { * All done parsing the input stream for this subrange. All the data has * been collected. Now use that information to fill in the remaining fields. } dtype_p^.range_ord_first := range_start; dtype_p^.range_n_vals := {set number of values in subrange} range_end - range_start + 1; dtype_p^.bits_min := {set minimum number of bits required} bits_min(range_start, range_end); if dtype_p^.bits_min < 0 then begin {right size integer not available ?} syo_error (dtype_p^.range_first_p^.str_h, 'sst_pas_read', 'dtype_range_int_nosize', nil, 0); end; if dtype_p^.range_first_p^.val.dtype = sst_dtype_int_k then begin {range of int ?} for i := 1 to sst_config.n_size_int do begin {once for each target int size} dtype_p^.range_dtype_p := sst_config.size_int[i].dtype_p; {init this size fits} if dtype_p^.range_dtype_p^.bits_min >= dtype_p^.bits_min {really does fit ?} then exit; end; {back and try next target language integer} end; {done setting base subrange integer data type} dtype_p^.align_nat := dtype_p^.range_dtype_p^.align_nat; dtype_p^.size_used := dtype_p^.range_dtype_p^.size_used; end; { ******************************* * * SIMPLE_DATA_TYPE > symbol_name } 11: begin sst_symbol_lookup (str_h, sym_p, stat); {look up data type name} if pointer and then sys_stat_match (sst_subsys_k, sst_stat_sym_not_found_k, stat) then begin {pointing to undefined data type} sst_symbol_new {create symbol that will be defined later} (str_h, syo_charcase_down_k, sym_p, stat); syo_error_abort (stat, str_h, '', '', nil, 0); sst_dtype_new (dt_p); {create data type block for new symbol} sym_p^.symtype := sst_symtype_dtype_k; {new symbol is a data type} sym_p^.dtype_dtype_p := dt_p; {point symbol to its data type block} dt_p^.symbol_p := sym_p; {point data type to its symbol block} end {done handling pointer to undef data type} else begin {not pointing to undefined data type} syo_error_abort (stat, str_h, '', '', nil, 0); if sym_p^.symtype <> sst_symtype_dtype_k then begin if sym_p^.char_h.crange_p = nil then begin {no source char, internally created} syo_error (str_h, 'sst_pas_read', 'symbol_not_dtype_internal', nil, 0); end else begin {symbol has know source character} sst_charh_info (sym_p^.char_h, fnam, lnum); sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^); sys_msg_parm_int (msg_parm[2], lnum); sys_msg_parm_vstr (msg_parm[3], fnam); syo_error (str_h, 'sst_pas_read', 'symbol_not_dtype', msg_parm, 3); end ; end; end ; if pointer then begin {new data type is pointing to old data type} dtype_p := sym_p^.dtype_dtype_p; {pointed-to data type descriptor} end else begin {new data type is copy of old data type} dtype_create (dtype_p); {create new data type descriptor} dtype_p^.dtype := sst_dtype_copy_k; dtype_p^.copy_dtype_p := sym_p^.dtype_dtype_p; while {loop until hit true copied data type} dtype_p^.copy_dtype_p^.dtype = sst_dtype_copy_k do begin dtype_p^.copy_dtype_p := dtype_p^.copy_dtype_p^.copy_dtype_p; end; if dtype_p^.copy_dtype_p^.dtype = sst_dtype_undef_k then begin sst_charh_info (sym_p^.char_h, fnam, lnum); sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^); sys_msg_parm_int (msg_parm[2], lnum); sys_msg_parm_vstr (msg_parm[3], fnam); syo_error (str_h, 'sst_pas_read', 'dtype_undefined', msg_parm, 3); end; dtype_p^.copy_symbol_p := sym_p; dtype_p^.bits_min := sym_p^.dtype_dtype_p^.bits_min; dtype_p^.align_nat := sym_p^.dtype_dtype_p^.align_nat; dtype_p^.size_used := sym_p^.dtype_dtype_p^.size_used; end {done with new data type is copy of old} ; {done with new data type is pointer Y/N} end; {end of SIMPLE_DATA_TYPE is symbol name} { ******************************* * * SIMPLE DATA TYPE > *** unexpected *** } otherwise syo_error_tag_unexp (tag, str_h); end; {end of SIMPLE_DATA_TYPE cases} { ******************************* * * Done processing this simple data type tag. This data type may have * been just the explicit data type for enumerated elements. If so, * the next tag is for the ENUMERATED_DATA_TYPE syntax. } syo_get_tag_msg ( {get optional enumerated data type tag} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of 9: begin {now at enumerated data type} enum_dtype_set := true; {indicate explicit enum data type exists} if created then begin {need to set final alignment ?} if dt_align = sst_align_natural_k then begin {desired alignment is NATURAL ?} dt_align := dtype_p^.align_nat; {resolve what natural alignment means} end; {DT_ALIGN is now set to hard alignment rule} sst_dtype_align (dtype_p^, dt_align); end; goto do_enum_dtype_set; {back to handle enum with explicit data type} end; syo_tag_end_k: ; {the previous data type stands by itself} otherwise syo_error_tag_unexp (tag, str_h); end; syo_level_up; {back up from SIMPLE_DATA_TYPE} end; {end of SIMPLE_DATA_TYPE case} { ************************************************* * * SET DATA TYPE } 2: begin if pointer then begin syo_error (str_h, 'sst_pas_read', 'dtype_pnt_not_allowed', nil, 0); end; dtype_create (dtype_p); {create new data type descriptor} syo_level_down; {down into SET_DATA_TYPE syntax} syo_get_tag_msg ( {get tag for optional BITSIZE keyword} tag, str2_h, 'sst_pas_read', 'dtype_set_syerr', nil, 0); case tag of 1: begin {tag is for explicit set size expression} sst_r_pas_exp (str2_h, true, exp_p); {get bit size expression} sst_exp_useage_check ( {make sure proper kind of expression} exp_p^, [sst_rwflag_read_k], sst_dtype_int_max_p^); sst_ordval (exp_p^.val, j, stat); {get min required bits in J} syo_error_abort (stat, str2_h, '', '', nil, 0); set_size_set := true; {indicate explicit set size was given} end; 2: begin {no explicit bit size given} set_size_set := false; end; otherwise syo_error_tag_unexp (tag, str2_h); end; syo_get_tag_msg ( {get tag for elements data type} tag, str_h, 'sst_pas_read', 'dtype_set_syerr', nil, 0); if tag <> 1 then begin syo_error_tag_unexp (tag, str_h); end; dt_set_p := nil; {indicate to return pointer to new data type} sst_r_pas_data_type (dt_set_p); {get pointer to base data type descriptor} dt_p := dt_set_p; {init pointer to base data type descriptor} while dt_p^.dtype = sst_dtype_copy_k do begin {loop until hit original data type} dt_p := dt_p^.copy_dtype_p; {point to copied data type descriptor} end; case dt_p^.dtype of {what data type is the base type ?} sst_dtype_enum_k: begin {set of enumerated data type} dtype_p^.bits_min := 0; {init min required bits} sym_p := dt_p^.enum_first_p; {init curr enum name to first in list} while sym_p <> nil do begin {loop thru all the enumerated names} i := sym_p^.enum_ordval; {get ordinal value of this enumerated name} if i < 0 then begin {can't make set of negative element values} sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^); sys_msg_parm_int (msg_parm[2], i); syo_error (str_h, 'sst_pas_read', 'dtype_set_enum_negative', msg_parm, 2); end; dtype_p^.bits_min := max( {take this enumerated value into account} dtype_p^.bits_min, i + 1); sym_p := sym_p^.enum_next_p; {advance to next enumerated name in list} end; {back to process new enumerated name} end; sst_dtype_bool_k: begin {set of BOOLEAN} dtype_p^.bits_min := 2; end; sst_dtype_char_k: begin {set of CHAR} dtype_p^.bits_min := 256; end; sst_dtype_range_k: begin {set of subrange data type} if dt_p^.range_ord_first < 0 then goto set_dtype_bad; {start val is in range ?} dtype_p^.bits_min := max(dt_p^.range_ord_first, dt_p^.range_n_vals) + 1; end; otherwise goto set_dtype_bad; {complain about illegal base data type} end; {end of base data type cases} if set_size_set then begin {min number of bits explicitly set ?} if j < dtype_p^.bits_min then begin {specified less than min required bits ?} sys_msg_parm_int (msg_parm[1], dtype_p^.bits_min); sys_msg_parm_int (msg_parm[2], j); syo_error (str2_h, 'sst_pas_read', 'set_bitsize_too_small', msg_parm, 2); end; dtype_p^.bits_min := j; {set min required bits to specified value} end; if dtype_p^.bits_min > 256 then begin {too many elements in set ?} set_dtype_bad: {jump here if base data type not useable} sys_msg_parm_vstr (msg_parm[1], dt_p^.symbol_p^.name_in_p^); syo_error (str_h, 'sst_pas_read', 'dtype_set_bad', msg_parm, 1); end; dtype_p^.dtype := sst_dtype_set_k; {output data type is definately SET} sz := {minimum amount of memory needed} (dtype_p^.bits_min + sst_config.bits_adr - 1) div sst_config.bits_adr; if set_size_set then begin {user explicitly specified bits in set} for i := 1 to sst_config.n_size_int do begin {look for smallest int that fits} if sst_config.size_int[i].size >= sz then begin {found right int to use ?} dtype_p^.size_used := sst_config.size_int[i].dtype_p^.size_used; dtype_p^.align_nat := sst_config.size_int[i].dtype_p^.align_nat; goto got_set_size; end; end; {back to inspect next integer size} end else begin {no explicit set size was specified} for i := 1 to sst_config.n_size_set do begin {look thru all the SET sizes} if sst_config.size_set[i].size >= sz then begin {found a best fit size ?} dtype_p^.size_used := sst_config.size_set[i].dtype_p^.size_used; dtype_p^.align_nat := sst_config.size_set[i].dtype_p^.align_nat; goto got_set_size; end; end; {back and check out next possible SET size} end ; { * The number of elements in the SET is greater than the number of bits in * the largest integer we are allowed to use as a whole for a set. We must * now use multiples of one of the integer sizes. This integer size is * specified by the config file command SIZE_SET_MULTIPLE. } j := (sz + sst_config.size_set_multiple.size - 1) div {num multiple words needed} sst_config.size_set_multiple.size; dtype_p^.size_used := j * sst_config.size_set_multiple.size; dtype_p^.align_nat := sst_config.size_set_multiple.dtype_p^.align_nat; got_set_size: {all done with SIZE_USED and ALIGN_NAT fields} dtype_p^.set_dtype_p := dt_p; dtype_p^.set_n_ent := {number of array elements for constant value} (dtype_p^.bits_min + sst_set_ele_per_word - 1) div sst_set_ele_per_word; dtype_p^.set_dtype_final := true; {final data type is definately known} syo_level_up; {back up from SET_DATA_TYPE syntax} end; { ************************************************* * * RECORD_DATA_TYPE } 3: begin if pointer then begin syo_error (str_h, 'sst_pas_read', 'dtype_pnt_not_allowed', nil, 0); end; dtype_create (dtype_p); {create new data type descriptor} sst_r_pas_dtype_record (dtype_p^); {separate routine does all the work} end; { ************************************************* * * ARRAY_DATA_TYPE } 4: begin if pointer then begin syo_error (str_h, 'sst_pas_read', 'dtype_pnt_not_allowed', nil, 0); end; dtype_create (dtype_p); {create new data type descriptor} syo_level_down; {down into ARRAY_DATA_TYPE syntax} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); {get PACKED tag} dtype_p^.ar_n_subscr := 0; {init number of subscripts} dtype_p^.ar_dtype_rem_p := nil; {init pointer to array "remainder" data type} n_ele := 1; {init total number of elements accumulator} dt_ar_p := nil; {init to not curr dtype for this subscript} loop_ar_dtype: {back here each new tag in ARRAY_DATA_TYPE} syo_get_tag_msg (tag, str2_h, 'sst_pas_read', 'dtype_bad', nil, 0); {get next tag} case tag of { * Tag is for a new ARRAY_INDEX_RANGE syntax. This declares the conditions * for one subscript. } 1: begin if dt_ar_p = nil then begin {no curr subscr data type, init to first} dt_ar_p := dtype_p; end else begin {curr subscr dtype exists, make new one} sst_dtype_new (dt_ar_p^.ar_dtype_rem_p); {create new data type descriptor} dt_ar_p := dt_ar_p^.ar_dtype_rem_p; {make new descriptor current} dt_ar_p^.dtype := sst_dtype_array_k; dt_ar_p^.ar_dtype_rem_p := nil; {init to this is last subscript in array} end ; dtype_p^.ar_n_subscr := dtype_p^.ar_n_subscr + 1; {one more subscript in array} syo_level_down; {down into ARRAY_INDEX_RANGE syntax} syo_get_tag_msg ( {get tag for min subscript value expression} tag, str_h, 'sst_pas_read', 'subscript_range_bad', nil, 0); if tag <> 1 then syo_error_tag_unexp (tag, str_h); sst_r_pas_exp (str_h, true, dt_ar_p^.ar_ind_first_p); {get min value exp} sst_ordval {get ordinal value of subscript range min} (dt_ar_p^.ar_ind_first_p^.val, range_start, stat); syo_error_abort (stat, str_h, 'sst_pas_read', 'subscript_dtype_bad', nil, 0); syo_get_tag_msg ( {get tag for max subscript value expression} tag, str_h, 'sst_pas_read', 'subscript_range_bad', nil, 0); case tag of 1: begin {tag is expression for max subscript value} sst_r_pas_exp (str_h, true, dt_ar_p^.ar_ind_last_p); {get max val exp} if {first/last exp data types incompatible ?} (not sst_dtype_convertable( dt_ar_p^.ar_ind_first_p^.dtype_p^, dt_ar_p^.ar_ind_last_p^.dtype_p^)) or (not sst_dtype_convertable( dt_ar_p^.ar_ind_last_p^.dtype_p^, dt_ar_p^.ar_ind_first_p^.dtype_p^)) then begin syo_error (str_h, 'sst_pas_read', 'subscript_dtype_different', nil, 0); end; sst_ordval {get ordinal value of subscript range max} (dt_ar_p^.ar_ind_last_p^.val, range_end, stat); syo_error_abort ( stat, str_h, 'sst_pas_read', 'subscript_dtype_bad', nil, 0); if range_end < range_start then begin syo_error (str_h, 'sst_pas_read', 'subscript_range_order', nil, 0); end; dt_ar_p^.ar_ind_n := range_end - range_start + 1; {num of subscript vals} end; 2: begin {tag indicates max subscript is unlimited} dt_ar_p^.ar_ind_last_p := nil; {indicate subscript max value is unlimited} dt_ar_p^.ar_ind_n := 1; {otherwise treat as if just one value allowed} end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of subscript max value cases} n_ele := n_ele * dt_ar_p^.ar_ind_n; {accumulate total number of array elements} syo_get_tag_msg ( {this tag should be end of syntax} tag, str_h, 'sst_pas_read', 'subscript_range_bad', nil, 0); if tag <> syo_tag_end_k then syo_error_tag_unexp (tag, str_h); syo_level_up; {up from ARRAY_INDEX_RANGE to ARRAY_DATA_TYPE} goto loop_ar_dtype; end; {end of tag is ARRAY_INDEX_RANGE case} 2: ; {tag is for data type of array elements} { * Unexepected TAG value. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of ARRAY_DATA_TYPE syntax tag cases} { * The last tag read is for the data type of the array elements. } dtype_p^.ar_dtype_ele_p := nil; {indicate to create a new data type descr} sst_r_pas_data_type (dtype_p^.ar_dtype_ele_p); {get data type of the array eles} sz := dtype_p^.ar_dtype_ele_p^.size_align; {allocated size for each array element} dtype_p^.dtype := sst_dtype_array_k; dtype_p^.bits_min := sz * n_ele * sst_config.bits_adr; dtype_p^.align_nat := dtype_p^.ar_dtype_ele_p^.align_nat; dtype_p^.size_used := sz * n_ele; { * Loop over each chained data type of this array. There is a new data type * descriptor for the "rest" of the array after each subscript. * * SZ is set to the array element size in machine addresses, and N_ELE is the * total number of elements in the whole array. } dt_ar_p := dtype_p^.ar_dtype_rem_p; {init to data type after first subscript} n_ele := n_ele div dtype_p^.ar_ind_n; {init number of elements at curr subscript} n_subscr := dtype_p^.ar_n_subscr; {init number of remaining subscripts} while dt_ar_p <> nil do begin {once for each subscript} n_subscr := n_subscr - 1; {one less subscript left in array} dt_ar_p^.bits_min := sz * n_ele * sst_config.bits_adr; dt_ar_p^.align_nat := dtype_p^.align_nat; dt_ar_p^.align := dtype_p^.align; dt_ar_p^.size_used := sz * n_ele; dt_ar_p^.size_align := sz * n_ele; dt_ar_p^.ar_dtype_ele_p := dtype_p^.ar_dtype_ele_p; dt_ar_p^.ar_n_subscr := n_subscr; n_ele := n_ele div dt_ar_p^.ar_ind_n; {number of elements after this subscript} dt_ar_p := dt_ar_p^.ar_dtype_rem_p; {to array subset after this subscript} end; dt_ar_p := dtype_p^.ar_dtype_ele_p; while dt_ar_p^.dtype = sst_dtype_copy_k do begin {resolve base ele dtype desc} dt_ar_p := dt_ar_p^.copy_dtype_p; end; dtype_p^.ar_string := {TRUE if array is a string of characters} (dt_ar_p^.dtype = sst_dtype_char_k) and {element data type is CHAR ?} (dtype_p^.ar_n_subscr = 1); {one-dimensional array ?} syo_level_up; {up from ARRAY_DATA_TYPE syntax} end; { ************************************************* * * ROUTINE_TYPE } 5: begin if not pointer then begin syo_error (str_h, 'sst_pas_read', 'dtype_proc_not_pointer', nil, 0); end; dtype_create (dtype_p); {create new data type descriptor} dtype_p^.dtype := sst_dtype_proc_k; {data type is a procedure} dtype_p^.size_used := sst_config.int_adr_p^.size_align; dtype_p^.bits_min := dtype_p^.size_used * sst_config.bits_adr; dtype_p^.align_nat := dtype_p^.size_used; sst_mem_alloc_scope ( {alloc routine descriptor} sizeof(dtype_p^.proc_p^), dtype_p^.proc_p); dtype_p^.proc_p^.sym_p := nil; {this template has no associated symbol} dtype_p^.proc_p^.dtype_func_p := nil; {init to routine is not a function} dtype_p^.proc_p^.n_args := 0; {init number of routine arguments} dtype_p^.proc_p^.flags := []; {init to no special flags apply} dtype_p^.proc_p^.first_arg_p := nil; {init args chain to empty} syo_level_down; {down into ROUTINE_TYPE syntax} syo_get_tag_msg ( {get routine type tag} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of {what type of routine is this} 1: begin {routine is a procedure} func := false; end; 2: begin {routine is a function} func := true; end; otherwise syo_error_tag_unexp (tag, str_h); end; {done with routine type keyword cases} syo_get_tag_msg ( {get args definition tag} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); if tag <> 1 then begin syo_error_tag_unexp (tag, str_h); end; sst_r_pas_proc_args (dtype_p^.proc_p^); {read routine arg declarations, if any} syo_get_tag_msg ( {get function value data type tag} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of 1: begin {no function data type present} if func then begin syo_error (str_h, 'sst_pas_read', 'func_no_data_type', nil, 0); end; end; 2: begin {function data type is present} if not func then begin syo_error (str_h, 'sst_pas_read', 'proc_data_type', nil, 0); end; sst_r_pas_data_type (dtype_p^.proc_p^.dtype_func_p); {get func return dtype} end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of function data type cases} syo_get_tag_msg ( {get VAL_PARAM tag, if present} tag, str_h, 'sst_pas_read', 'dtype_bad', nil, 0); case tag of syo_tag_end_k: ; {VAL_PARAM not present} 1: begin {VAL_PARAM was specified} sst_r_pas_vparam (dtype_p^.proc_p^); {adjust argument list accordingly} end; otherwise syo_error_tag_unexp (tag, str_h); end; syo_level_up; {up from ROUTINE_TYPE to DATA_TYPE syntax} end; { ************************************************* * * Unexpected tag value. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of DATA_TYPE tag cases} { ************************************************* * * Done filling in the basic info in the data type block pointed to by * DTYPE_P. Now set the final alignment, cleanup, and leave. } syo_level_up; {pop back from DATA_TYPE syntax} if created and pointer then begin {set alignment of pointed-to data type ?} sst_dtype_align (dtype_p^, sst_align); {use default alignment rule} end; if pointer then begin {need to create and pass back pointer dtype ?} if created and reusing then begin {not allowed to alter DTYPE_P} sst_dtype_new (dt_p); {create new data type descriptor} dt_p^ := dtype_p^; {make copy of pointed-to data type} dt_p^.symbol_p := nil; {new descriptor not linked to a symbol} end else begin {OK to call DTYPE_CREATE} dt_p := dtype_p; {save pointer to pointed-to data type} dtype_create (dtype_p); {create pointer data type descriptor} end ; {DTYPE_P^ is new block, DT_P^ is base dtype} sym_p := dtype_p^.symbol_p; {save pointer to data type's symbol, if any} dtype_p^ := sst_dtype_uptr_p^; {init from universal pointer template} dtype_p^.symbol_p := sym_p; {restore symbol pointer} dtype_p^.pnt_dtype_p := dt_p; {set pointer to pointed-to data type} end; if dt_align = sst_align_natural_k then begin {desired alignment is NATURAL ?} dt_align := dtype_p^.align_nat; {resolve what natural alignment means} end; {DT_ALIGN is now set to hard alignment rule} if {need to make COPY data type ?} (not created) and ((dtype_p^.align <> dt_align) or reusing) then begin dt_p := dtype_p; {save pointer to base data type} dtype_create (dtype_p); {create new data type descriptor} dtype_p^.dtype := sst_dtype_copy_k; dtype_p^.bits_min := dt_p^.bits_min; dtype_p^.align_nat := dt_p^.align_nat; dtype_p^.size_used := dt_p^.size_used; dtype_p^.copy_symbol_p := dt_p^.symbol_p; dtype_p^.copy_dtype_p := dt_p; end; if created then begin {need to fix alignment ?} sst_dtype_align (dtype_p^, dt_align); end; end;
{ mytoolbar.pas Toolbar controller class. Creates and manages the toolbar. This example project is released under public domain AUTHORS: Felipe Monteiro de Carvalho } unit mytoolbar; {$mode delphi}{$STATIC ON} interface uses SysUtils, MacOSAll, objc, appkit, foundation; type { TMyToolbarController } TMyToolbarController = class(NSObject) public { Extra binding functions } constructor Create; override; procedure AddMethods; override; { Toolbar items } OpenToolbarItem, SaveToolbarItem, CloseToolbarItem: NSToolbarItem; { Objective-c Methods } class function toolbarAllowedItemIdentifiers(_self: objc.id; _cmd: SEL; toolbar: objc.id {NSToolbar}): CFArrayRef; cdecl; {$ifndef VER2_2_2}static;{$endif} class function toolbarDefaultItemIdentifiers(_self: objc.id; _cmd: SEL; toolbar: objc.id {NSToolbar}): CFArrayRef; cdecl; {$ifndef VER2_2_2}static;{$endif} end; const Str_toolbarAllowedItemIdentifiers = 'toolbarAllowedItemIdentifiers:'; Str_toolbarDefaultItemIdentifiers = 'toolbarDefaultItemIdentifiers:'; Str_toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar = 'toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:'; var OpenToolbarItemIdentifier, SaveToolbarItemIdentifier, CloseToolbarItemIdentifier: CFStringRef; myToolbarController: TMyToolbarController; function toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar (_self: objc.id; _cmd: SEL; toolbar: objc.id; itemIdentifier: CFStringRef; flag: objc.BOOL): objc.id; cdecl;// static; implementation uses model, controller; { TMyToolbar } constructor TMyToolbarController.Create; begin { The class is registered on the Objective-C runtime before the NSObject constructor is called } if not CreateClassDefinition(ClassName(), Str_NSObject) then WriteLn('Failed to create objc class ' + ClassName()); inherited Create; { Prepare CFStringRefs for the constants } OpenToolbarItemIdentifier := CFStringCreateWithPascalString(nil, 'OpenID', kCFStringEncodingUTF8); SaveToolbarItemIdentifier := CFStringCreateWithPascalString(nil, 'SaveID', kCFStringEncodingUTF8); CloseToolbarItemIdentifier := CFStringCreateWithPascalString(nil, 'CloseID', kCFStringEncodingUTF8); { Create toolbar items } OpenToolbarItem := NSToolbarItem.initWithItemIdentifier(OpenToolbarItemIdentifier); OpenToolbarItem.setToolTip(CFStringCreateWithPascalString(nil, 'Open', kCFStringEncodingUTF8)); OpenToolbarItem.setImage(myModel.imgOpen.Handle); OpenToolbarItem.setTarget(myController.Handle); OpenToolbarItem.setAction(sel_registerName(PChar('doOpenFile:'))); SaveToolbarItem := NSToolbarItem.initWithItemIdentifier(SaveToolbarItemIdentifier); SaveToolbarItem.setToolTip(CFStringCreateWithPascalString(nil, 'Save', kCFStringEncodingUTF8)); SaveToolbarItem.setImage(myModel.imgSave.Handle); SaveToolbarItem.setTarget(myController.Handle); SaveToolbarItem.setAction(sel_registerName(PChar('doSaveFile:'))); CloseToolbarItem := NSToolbarItem.initWithItemIdentifier(CloseToolbarItemIdentifier); CloseToolbarItem.setToolTip(CFStringCreateWithPascalString(nil, 'Exit', kCFStringEncodingUTF8)); CloseToolbarItem.setImage(myModel.imgClose.Handle); CloseToolbarItem.setTarget(myController.Handle); CloseToolbarItem.setAction(sel_registerName(PChar('doClose:'))); end; procedure TMyToolbarController.AddMethods; begin AddMethod(Str_toolbarAllowedItemIdentifiers, '@@:@', Pointer(toolbarAllowedItemIdentifiers)); AddMethod(Str_toolbarDefaultItemIdentifiers, '@@:@', Pointer(toolbarDefaultItemIdentifiers)); AddMethod(Str_toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar, '@@:@@c', @toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar); end; {@@ Lists all of the items in the toolbar by their identifiers. This method is necessary to implement a toolbar. } class function TMyToolbarController.toolbarAllowedItemIdentifiers(_self: objc.id; _cmd: SEL; toolbar: objc.id): CFArrayRef; cdecl; var toolbarItems: array[0..4] of CFStringRef; begin { WriteLn('OpenToolbarItemIdentifier: ', IntToHex(Cardinal(OpenToolbarItemIdentifier), 8)); WriteLn('SaveToolbarItemIdentifier: ', IntToHex(Cardinal(SaveToolbarItemIdentifier), 8)); WriteLn('NSToolbarSpaceItemIdentifier: ', IntToHex(Cardinal(NSToolbarSpaceItemIdentifier), 8)); WriteLn('CloseToolbarItemIdentifier: ', IntToHex(Cardinal(CloseToolbarItemIdentifier), 8));} toolbarItems[0] := OpenToolbarItemIdentifier; toolbarItems[1] := SaveToolbarItemIdentifier; toolbarItems[2] := NSToolbarSpaceItemIdentifier; toolbarItems[3] := CloseToolbarItemIdentifier; toolbarItems[4] := nil; Result := CFArrayCreate(nil, @toolbarItems[0], 4, nil); end; {@@ Returns which items are available by default in the toolbar. Other items exist in the toolbar but are optional. We simply return the same items from toolbarAllowedItemIdentifiers. } class function TMyToolbarController.toolbarDefaultItemIdentifiers(_self: objc.id; _cmd: SEL; toolbar: objc.id): CFArrayRef; cdecl; begin Result := toolbarAllowedItemIdentifiers(_self, _cmd, toolbar); end; {@@ Returns the NSToolbarItem for each item. Note that we should return an item in our cache instead of creating a new one everytime this routine is called. } function toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar(_self: objc.id; _cmd: SEL; toolbar: objc.id {NSToolbar}; itemIdentifier: CFStringRef; flag: objc.BOOL): objc.id {NSToolbarItem}; cdecl; begin // WriteLn('toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar: ', IntToHex(Cardinal(itemIdentifier), 8)); with myToolbarController do begin if CFStringCompare(itemIdentifier, OpenToolbarItemIdentifier, kCFCompareCaseInsensitive) = kCFCompareEqualTo then Result := OpenToolbarItem.autorelease else if CFStringCompare(itemIdentifier, SaveToolbarItemIdentifier, kCFCompareCaseInsensitive) = kCFCompareEqualTo then Result := SaveToolbarItem.autorelease else if CFStringCompare(itemIdentifier, CloseToolbarItemIdentifier, kCFCompareCaseInsensitive) = kCFCompareEqualTo then Result := CloseToolbarItem.autorelease else Result := nil; end; end; end.
unit ResequenceAllRoutesRequestUnit; interface uses HttpQueryMemberAttributeUnit, GenericParametersUnit, EnumsUnit; type TResequenceAllRoutesRequest = class(TGenericParameters) private [HttpQueryMember('route_id')] FRouteId: String; [HttpQueryMember('disable_optimization')] FDisableOptimization: boolean; [HttpQueryMember('optimize')] FOptimize: String; public constructor Create(RouteId: String; DisableOptimization: boolean; Optimize: Toptimize); reintroduce; end; implementation { TResequenceAllRoutesRequest } constructor TResequenceAllRoutesRequest.Create(RouteId: String; DisableOptimization: boolean; Optimize: TOptimize); begin Inherited Create; FRouteId := RouteId; FDisableOptimization := DisableOptimization; FOptimize := TOptimizeDescription[Optimize]; end; end.
{$include lem_directives.inc} unit LemDosMainDat; interface uses Classes, GR32, SysUtils, LemTypes, LemDosStructures, LemDosCmp, LemDosBmp; type {------------------------------------------------------------------------------- Tool to extract data from the dos main dat file -------------------------------------------------------------------------------} TMainDatExtractor = class private fFileName: string; fDecompressor: TDosDatDecompressor; fSections: TDosDatSectionList; fPlanar: TDosPlanarBitmap; {$ifdef flexi}fSysDat: TSysDatRec; fSysDatLoaded: Boolean;{$endif} procedure EnsureLoaded; procedure EnsureDecompressed(aSection: Integer); protected public constructor Create; destructor Destroy; override; procedure ExtractBrownBackGround(Bmp: TBitmap32); procedure ExtractLogo(Bmp: TBitmap32); procedure ExtractBitmap(Bmp: TBitmap32; aSection, aPosition, aWidth, aHeight, BPP: Integer; aPal: TArrayOfColor32); procedure ExtractAnimation(Bmp: TBitmap32; aSection, aPos, aWidth, aHeight, aFrameCount: Integer; BPP: Byte; aPal: TArrayOfColor32); {$ifdef flexi} function GetSysData: TSysDatRec; procedure LoadSysData; {$endif} property FileName: string read fFileName write fFileName; end; implementation { TMainDatExtractor } constructor TMainDatExtractor.Create; begin inherited Create; fSections := TDosDatSectionList.Create; fPlanar := TDosPlanarBitmap.Create; fDecompressor := TDosDatDecompressor.Create; end; destructor TMainDatExtractor.Destroy; begin fSections.Free; fPlanar.Free; fDecompressor.Free; inherited; end; procedure TMainDatExtractor.EnsureDecompressed(aSection: Integer); var Sec: TDosDatSection; begin EnsureLoaded; Sec := fSections[aSection]; if Sec.DecompressedData.Size = 0 then fDecompressor.DecompressSection(Sec.CompressedData, Sec.DecompressedData) end; procedure TMainDatExtractor.EnsureLoaded; var DataStream: TStream; begin if fSections.Count = 0 then begin {$ifdef external}if FileExists(fFileName) then DataStream := TFileStream.Create(fFileName, fmOpenRead) else{$endif} DataStream := CreateDataStream(fFileName, ldtLemmings); try fDecompressor.LoadSectionList(DataStream, fSections, False); finally DataStream.Free; end; end; end; procedure TMainDatExtractor.ExtractAnimation(Bmp: TBitmap32; aSection, aPos, aWidth, aHeight, aFrameCount: Integer; BPP: Byte; aPal: TArrayOfColor32); begin EnsureDecompressed(aSection); {$ifdef flexi} LoadSysData; if fSysDat.Options2 and 2 <> 0 then begin if (aSection = 0) or (aSection = 6) then begin aPal[1] := $D02020; aPal[4] := $F0F000; aPal[5] := $4040E0; end else if (aSection > 2) and (aSection < 6) then begin aPal := GetDosMainMenuPaletteColors32(true); end; end; {$endif} fPlanar.LoadAnimationFromStream(fSections[aSection].DecompressedData, Bmp, aPos, aWidth, aHeight, aFrameCount, BPP, aPal); end; procedure TMainDatExtractor.ExtractBitmap(Bmp: TBitmap32; aSection, aPosition, aWidth, aHeight, BPP: Integer; aPal: TArrayOfColor32); begin EnsureDecompressed(aSection); {$ifdef flexi} LoadSysData; if fSysDat.Options2 and 2 <> 0 then begin if (aSection = 0) or (aSection = 6) then begin aPal[1] := $D02020; aPal[4] := $F0F000; aPal[5] := $4040E0; end else if (aSection > 2) and (aSection < 6) then begin aPal := GetDosMainMenuPaletteColors32(true); end; end; {$endif} fPlanar.LoadFromStream(fSections[aSection].DecompressedData, Bmp, aPosition, aWidth, aHeight, BPP, aPal); end; procedure TMainDatExtractor.ExtractBrownBackGround(Bmp: TBitmap32); {------------------------------------------------------------------------------- Extract hte brown background, used in several screens -------------------------------------------------------------------------------} begin EnsureDecompressed(3); {$ifdef flexi} LoadSysData; {$endif} fPlanar.LoadFromStream(fSections[3].DecompressedData, Bmp, 0, 320, 104, 2, GetDosMainMenuPaletteColors32{$ifdef flexi}(fSysDat.Options2 and 2 <> 0){$endif}); end; procedure TMainDatExtractor.ExtractLogo(Bmp: TBitmap32); {------------------------------------------------------------------------------- Extract the LemmingLogo -------------------------------------------------------------------------------} begin EnsureDecompressed(3); {$ifdef flexi} LoadSysData; {$endif} fPlanar.LoadFromStream(fSections[3].DecompressedData, Bmp, $2080, 632, 94, 4, GetDosMainMenuPaletteColors32{$ifdef flexi}(fSysDat.Options2 and 2 <> 0){$endif}); end; {$ifdef flexi} function TMainDatExtractor.GetSysData(): TSysDatRec; begin LoadSysData; Result := fSysDat; end; procedure TMainDatExtractor.LoadSysData; var TempRec : TSysDatRec; TempStream : TStream; begin if fSysDatLoaded then exit; //EnsureDecompressed(7); //fSections[7].DecompressedData.SaveToFile('sys2.dat'); {$ifdef external} if FileExists(ExtractFilePath(ParamStr(0)) + 'system.dat') then TempStream := TFileStream.Create(ExtractFilePath(ParamStr(0)) + 'system.dat', fmOpenRead) else{$endif} TempStream := CreateDataStream('system.dat', ldtLemmings); TempStream.Seek(0, soFromBeginning); TempStream.ReadBuffer(fSysDat, SYSDAT_SIZE); fSysDatLoaded := true; TempStream.Free; end; {$endif} end.
unit xSpeedButton; interface uses SysUtils, Classes, Controls, Buttons, Windows, Types, Graphics, CommCtrl, Messages, ImgList, ActnList; type TxSpeedButton = class; TssButtonStyle = (ssbsFlat, ssbsUser); TssButtonState = (ssbsUp, ssbsDown, ssbsDisabled); TssButtonType = (ssbtStandard, ssbtChecked); TssButtonViewStyle = (ssvsCaptionGlyph, ssvsCaptionOnly, ssvsGlyphOnly); TxSpeedButtonActionLink = class(TControlActionLink) protected FClient: TxSpeedButton; procedure AssignClient(AClient: TObject); override; function IsCheckedLinked: Boolean; override; function IsGroupIndexLinked: Boolean; override; procedure SetGroupIndex(Value: Integer); override; procedure SetChecked(Value: Boolean); override; end; TxSpeedButton = class(TGraphicControl) private FColor: TColor; FHotBorderColor: TColor; FImageRect: TRect; FTextRect: TRect; FOver: boolean; FHotTrackColor: TColor; FStyle: TssButtonStyle; FImages: TImageList; FImagesChangeLink: TChangeLink; FImageIndex: TImageIndex; FOffset: integer; FButtonType: TssButtonType; FChecked: boolean; FGroupIndex: Integer; FAllwaysShowFrame: boolean; FViewStyle: TssButtonViewStyle; procedure PaintFrame; procedure SetColor(const Value: TColor); procedure SetBorderColor(const Value: TColor); procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE; procedure SetHotTrackColor(const Value: TColor); procedure SetStyle(const Value: TssButtonStyle); procedure SetImages(const Value: TImageList); procedure ImageListChange(Sender: TObject); procedure SetImageIndex(const Value: TImageIndex); procedure DrawImage; procedure SetButtonType(const Value: TssButtonType); procedure SetChecked(const Value: boolean); procedure SetGroupIndex(const Value: Integer); procedure SetAllwaysShowFrame(const Value: boolean); procedure SetViewStyle(const Value: TssButtonViewStyle); protected FState: TssButtonState; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public procedure Loaded; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Action; property AllwaysShowFrame: boolean read FAllwaysShowFrame write SetAllwaysShowFrame; property Anchors; property BiDiMode; property ButtonType: TssButtonType read FButtonType write SetButtonType; property Checked: boolean read FChecked write SetChecked; property Constraints; property Caption; property Color: TColor read FColor write SetColor default clBtnFace; property Enabled; property Font; property GroupIndex: Integer read FGroupIndex write SetGroupIndex; property Height default 25; property HotBorderColor: TColor read FHotBorderColor write SetBorderColor; property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Images: TImageList read FImages write SetImages; property Offset: integer read FOffset write FOffset; property ParentFont; property ParentShowHint; property ParentBiDiMode; property PopupMenu; property ShowHint; property Style: TssButtonStyle read FStyle write SetStyle; property ViewStyle: TssButtonViewStyle read FViewStyle write SetViewStyle; property Visible; property Width default 25; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; TflSpeedButton = class(TxSpeedButton) end; implementation uses ExtCtrls; { TxSpeedButton } procedure TxSpeedButton.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin inherited ActionChange(Sender, CheckDefaults); if Sender is TCustomAction then with TCustomAction(Sender) do begin if Self.ImageIndex<>ImageIndex then Self.ImageIndex:=ImageIndex; if Self.Checked<>Checked then Self.Checked:=Checked; if Self.GroupIndex<>GroupIndex then Self.GroupIndex:=GroupIndex; Invalidate; end; end; procedure TxSpeedButton.CMMouseEnter(var Msg: TMessage); begin inherited; FOver:=True; Invalidate; end; procedure TxSpeedButton.CMMouseLeave(var Msg: TMessage); begin inherited; FOver:=False; FState:=ssbsUp; Invalidate; end; constructor TxSpeedButton.Create(AOwner: TComponent); begin inherited; FImagesChangeLink:=TChangeLink.Create; FImagesChangeLink.OnChange:=ImageListChange; FColor:=clBtnFace; Width:=25; Height:=25; FOffset:=1; FHotBorderColor:=clGray; FHotTrackColor:=clSkyBlue; FViewStyle:=ssvsGlyphOnly; end; destructor TxSpeedButton.Destroy; begin FImagesChangeLink.Free; inherited; end; procedure TxSpeedButton.DrawImage; begin if FImages<>nil then begin if FOver and Enabled and not (csDesigning in ComponentState) then begin // FImages.Draw(Canvas, FImageRect.Left, FImageRect.Top, FImageIndex, False); // OffsetRect(FImageRect, -1, -1); end; if (FState=ssbsDown) and not FChecked then OffsetRect(FImageRect, FOffset, FOffset); FImages.Draw(Canvas, FImageRect.Left, FImageRect.Top, FImageIndex, Enabled); end; end; function TxSpeedButton.GetActionLinkClass: TControlActionLinkClass; begin Result := TxSpeedButtonActionLink; end; procedure TxSpeedButton.ImageListChange(Sender: TObject); begin Invalidate; end; procedure TxSpeedButton.Loaded; begin inherited; end; procedure TxSpeedButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if FOver and (Button = mbLeft) then begin FState:=ssbsDown; end; Invalidate; end; procedure TxSpeedButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if FOver and (Button=mbLeft) then begin FState:=ssbsUp; if (FButtonType=ssbtChecked) then begin if Assigned(Action) then begin if not FChecked or (GroupIndex=0) then TCustomAction(Action).Checked:=not FChecked; end else begin if not FChecked or (GroupIndex=0) then FChecked:=not FChecked; end; end; end; Invalidate; end; procedure TxSpeedButton.Paint; var R: TRect; TH, TW: integer; clTemp: TColor; begin R := GetClientRect; if not Enabled then FState:=ssbsDisabled; with Canvas do begin TH:=TextHeight(Caption); TW:=TextWidth(Caption); Brush.Color:=FColor; if FChecked and (FState<>ssbsDisabled) then begin Brush.Bitmap := AllocPatternBitmap(clBtnFace, clBtnHighlight); end; FillRect(R); Brush.Style:=bsSolid; if not (csDesigning in ComponentState) and not (FState=ssbsDisabled) then begin if (FStyle=ssbsUser) and FOver then begin Brush.Color:=FHotTrackColor; if FState=ssbsDown then InflateRect(R, -1, -1); FillRect(R); end else if (FStyle in [ssbsFlat]) and FChecked and FOver then begin Brush.Color:=FColor; FillRect(R); end; end; clTemp:=Brush.Color; if csDesigning in ComponentState then begin Brush.Color := clBlack; FrameRect(R); end; if FViewStyle in [ssvsCaptionGlyph, ssvsGlyphOnly] then begin if FImages<>nil then begin case FViewStyle of ssvsGlyphOnly: begin FImageRect.Left := (Width-FImages.Width) div 2; FImageRect.Right := FImageRect.Left + FImages.Width; FImageRect.Top := (Height-FImages.Height) div 2; FImageRect.Bottom := FImageRect.Top + FImages.Height; end; ssvsCaptionGlyph: begin FImageRect.Left := (Width-FImages.Width-TW) div 2; FImageRect.Right := FImageRect.Left + FImages.Width; FImageRect.Top := (Height-FImages.Height) div 2; FImageRect.Bottom := FImageRect.Top + FImages.Height; end; end; end; if FChecked then OffsetRect(FImageRect, Offset, Offset); DrawImage; end; if (FViewStyle in [ssvsCaptionGlyph, ssvsCaptionOnly]) and (Length(Caption)>0) then begin Brush.Color:=clTemp; Font:=Self.Font; FTextRect.Top:=(Self.Height-TH) div 2; if FViewStyle=ssvsCaptionGlyph then FTextRect.Left:=FImageRect.Right+4 else FTextRect.Left:=(Self.Width-TW) div 2; if FChecked or (FState=ssbsDown) then begin FTextRect.Top:=FTextRect.Top+1; FTextRect.Left:=FTextRect.Left+1; end; TextOut(FTextRect.Left, FTextRect.Top, Caption); end; end; PaintFrame; { draw text } { if Length(Caption) > 0 then begin if FOver then Canvas.Font := FHighlightFont else Canvas.Font := Font; // W := FSpacing + W; SetBkMode(Canvas.Handle, Windows.Transparent); R := GetClientRect; if (ImageSize = isLarge) and Assigned(FLargeImages) then R.Top := R.Top + FLargeImages.Height + (FSpacing * 2) else if (ImageSize = isSmall) and Assigned(FSmallImages) then R.Left := R.Left + FSmallImages.Width + (FSpacing * 3) else Flags := DT_END_ELLIPSIS or DT_EDITCONTROL or DT_WORDBREAK or DT_CENTER or DT_VCENTER; if FDown then OffsetRect(R, FOffset, FOffset); FTextRect := R; H := DrawText(Canvas.Handle, PChar(Caption), -1, FTextRect, Flags or DT_CALCRECT); if ImageSize = isLarge then begin FTextRect.Top := R.Top; FTextRect.Bottom := FTextRect.Top + H; FTextRect.Right := R.Left + Canvas.TextWidth(Caption); end else begin FTextRect.Top := (Height - Canvas.TextHeight(Caption)) div 2; FTextRect.Bottom := FTextRect.Top + Canvas.TextHeight(Caption); FTextRect.Right := R.Left + Canvas.TextWidth(Caption); end; DrawText(Canvas.Handle, PChar(Caption), -1, R, Flags); end; } end; procedure TxSpeedButton.PaintFrame; var R: TRect; begin R := GetClientRect; if csDesigning in ComponentState then begin Frame3D(Canvas, R, clBtnHighLight, clBtnShadow, 1); Exit; end; if not Enabled then Exit; if FOver or FChecked or FAllwaysShowFrame then begin case FStyle of ssbsFlat: begin if (FState=ssbsDown) or FChecked then Frame3D(Canvas, R, clBtnShadow, clBtnHighLight, 1) else Frame3D(Canvas, R, clBtnHighLight, clBtnShadow, 1); end; ssbsUser: begin if FState=ssbsDown then InflateRect(R, -1, -1); Canvas.Brush.Color:=FHotBorderColor; Canvas.FrameRect(R); end; end; end; end; procedure TxSpeedButton.SetAllwaysShowFrame(const Value: boolean); begin FAllwaysShowFrame := Value; Invalidate; end; procedure TxSpeedButton.SetBorderColor(const Value: TColor); begin FHotBorderColor := Value; Invalidate; end; procedure TxSpeedButton.SetButtonType(const Value: TssButtonType); begin if Value<>FButtonType then begin if (Value=ssbtStandard) and FChecked then FChecked:=False; FButtonType := Value; Invalidate; end; end; procedure TxSpeedButton.SetChecked(const Value: boolean); begin if Value<>FChecked then begin if (FButtonType=ssbtStandard) and Value then begin FChecked:=False; end else begin FChecked := Value; end; Invalidate; end; end; procedure TxSpeedButton.SetColor(const Value: TColor); begin FColor := Value; Invalidate; end; procedure TxSpeedButton.SetGroupIndex(const Value: Integer); begin FGroupIndex := Value; end; procedure TxSpeedButton.SetHotTrackColor(const Value: TColor); begin FHotTrackColor := Value; Invalidate; end; procedure TxSpeedButton.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; Invalidate; end; end; procedure TxSpeedButton.SetImages(const Value: TImageList); begin if FImages <> nil then FImages.UnRegisterChanges(FImagesChangeLink); FImages := Value; if FImages <> nil then FImages.RegisterChanges(FImagesChangeLink); Invalidate; end; procedure TxSpeedButton.SetStyle(const Value: TssButtonStyle); begin FStyle := Value; Invalidate; end; procedure TxSpeedButton.SetViewStyle(const Value: TssButtonViewStyle); begin if Value<>FViewStyle then begin FViewStyle:=Value; Invalidate; end; end; { TxSpeedButtonActionLink } procedure TxSpeedButtonActionLink.AssignClient(AClient: TObject); begin inherited AssignClient(AClient); FClient := AClient as TxSpeedButton; end; function TxSpeedButtonActionLink.IsCheckedLinked: Boolean; begin Result := inherited IsCheckedLinked and (FClient.GroupIndex <> 0) and {FClient.AllowAllUp and }(FClient.Checked = (Action as TCustomAction).Checked); end; function TxSpeedButtonActionLink.IsGroupIndexLinked: Boolean; begin Result := (FClient is TxSpeedButton) and (TxSpeedButton(FClient).GroupIndex = (Action as TCustomAction).GroupIndex); end; procedure TxSpeedButtonActionLink.SetChecked(Value: Boolean); begin if IsCheckedLinked then TxSpeedButton(FClient).Checked := Value; end; procedure TxSpeedButtonActionLink.SetGroupIndex(Value: Integer); begin if IsGroupIndexLinked then TxSpeedButton(FClient).GroupIndex := Value; end; end.
unit uihandle; interface uses ui, uimpl, datastorage; type TWinHandle=class; TWinHandleEvent=procedure(Sender:TWinHandle) of object; TWinHandle=class(TWinHandleImpl) private protected wFont:HFONT; wColor, wBkColor, wHoverColor, wHoverBkColor, wBorderColor, wHoverBorderColor:cardinal; // mouse wMouseDown:boolean; wMouseOverComponent:boolean; wName:string; wMinHeight:integer; wAlign:TAlign; wChildHandleList:TListEx; fOnClick:TWinHandleEvent; procedure SetParent(AParent:TWinHandle); function GetParent:TWinHandle; procedure SetFont(AValue:HFONT); public constructor Create(Owner:TWinHandle);virtual; function ShowModal:integer;virtual; procedure SetBounds(ALeft, ATop, AWidth, AHeight : integer); // procedure SetFocus;virtual; procedure CreatePerform;virtual;abstract; procedure SetFontPerform;virtual; procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);override; procedure MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);override; procedure MouseLeavePerform;override; procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override; procedure MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override; procedure MouseButtonDblDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override; procedure KillFocusPerform(handle:HWND);override; procedure ClosePerform;override; procedure CapturePerform(AWindow:HWND);override; procedure KeyCharPerform(keychar:cardinal);override; procedure SizePerform;override; property Window:HWnd read hWindow; property Parent:TWinHandle read GetParent write SetParent; property Align:TAlign read wAlign write wAlign; property Left:integer read hLeft write hLeft; property Top:integer read hTop write hTop; property Width:integer read hWidth write hWidth; property Height:integer read hHeight write hHeight; property MinHeight:integer read wMinHeight write wMinHeight; property Text:string read wText write wText; property Name:string read wName write wName; property Style:cardinal read wStyle write wStyle; property ExStyle:cardinal read wExStyle write wExStyle; property Enabled:boolean read wEnabled write wEnabled; property ChildHandleList:TListEx read wChildHandleList write wChildHandleList; property Font:HFONT read wFont write SetFont; property Color:cardinal read wColor write wColor; property BkColor:cardinal read wBkColor write wBkColor; property BorderColor:cardinal read wBorderColor write wBorderColor; property HoverColor:cardinal read wHoverColor write wHoverColor; property HoverBkColor:cardinal read wBkColor write wHoverBkColor; property HoverBorderColor:cardinal read wHoverBorderColor write wHoverBorderColor; // event property OnClick:TWinHandleEvent read fOnClick write fOnClick; end; function CreateMainWindow(AMainWinForm:TWinHandle; AText:string):TWinHandle; //var MainWinForm:TWinHandle; //KeyboardLanguage:cardinal; implementation constructor TWinHandle.Create(Owner:TWinHandle); begin inherited Create; SetParent(Owner); wTrackingMouse:=false; wMouseOverComponent:=false; wMouseDown:=false; wCursor:=crArrow; fOnClick:=nil; wExStyle:=0; wStyle:=0; wEnabled:=true; wFont:=fntRegular; wColor:=clBlack; wBkColor:=clWhite; wHoverColor:=clBlack; wHoverBkColor:=clWhite; end; function CreateMainWindow(AMainWinForm:TWinHandle; AText:string):TWinHandle; begin MainWinForm:=AMainWinForm; AMainWinForm.Text:=AText; AMainWinForm.Parent := nil; AMainWinForm.CreatePerform; if AMainWinForm.Window = 0 then begin //MessageBox(0, 'WinCreate failed', nil, mb_Ok); //halt(0); end; result:=AMainWinForm; end; function TWinHandle.ShowModal:integer; begin result:=MR_CLOSE end; function TWinHandle.GetParent:TWinHandle; begin result:=TWinHandle(wParent) end; procedure TWinHandle.SetParent(AParent:TWinHandle); begin wParent:=AParent; if AParent<>nil then begin if AParent.ChildHandleList=nil then AParent.ChildHandleList:=TListEx.Create; AParent.ChildHandleList.Add(self); end; end; procedure TWinHandle.SizePerform; var i:integer; r : trect; comp:TWinHandle; begin if ChildHandleList=nil then exit; // r:=GetClientRect; // none for i:=0 to ChildHandleList.Count-1 do begin comp:=TWinHandle(ChildHandleList[i]); if comp.Align=alNone then begin comp.SizePerform; end; end; // top for i:=0 to ChildHandleList.Count-1 do begin comp:=TWinHandle(ChildHandleList[i]); if comp.Align=alTop then begin comp.SetBounds(r.Left, r.Top, r.Right-r.Left, comp.Height); comp.SetPosPerform; comp.SizePerform; r.Top:=r.Top+comp.height end; end; // bottom for i:=ChildHandleList.Count-1 downto 0 do begin comp:=TWinHandle(ChildHandleList[i]); if comp.Align=alBottom then begin comp.SetBounds(r.Left, r.Bottom-comp.hHeight, r.Right-r.Left, comp.Height); comp.SetPosPerform; comp.SizePerform; r.Bottom:=r.Bottom-comp.height end; end; // left for i:=0 to ChildHandleList.Count-1 do begin comp:=TWinHandle(ChildHandleList[i]); if comp.Align=alLeft then begin comp.SetBounds(r.Left, r.Top, comp.Width, r.Bottom-r.Top); comp.SetPosPerform; comp.SizePerform; r.Left:=r.Left+comp.Width end; end; // right for i:=ChildHandleList.Count-1 downto 0 do begin comp:=TWinHandle(ChildHandleList[i]); if comp.Align=alRight then begin comp.SetBounds(r.Right-comp.Width, r.Top, comp.Width, r.Bottom-r.Top); comp.SetPosPerform; comp.SizePerform; r.Right:=r.Right-comp.Width end; end; // client for i:=ChildHandleList.Count-1 downto 0 do begin comp:=TWinHandle(ChildHandleList[i]); if comp.Align=alClient then begin comp.SetBounds(r.Left, r.Top, r.Right-r.Left, r.Bottom-r.Top); comp.SetPosPerform; comp.SizePerform; r.Left:=r.Right; r.Top:=r.Bottom end; end; end; procedure TWinHandle.MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer); begin end; procedure TWinHandle.MouseMovePerform(AButtonControl:cardinal; x,y:integer); begin RegisterMouseLeave; SetCursor; if not wMouseOverComponent then begin wMouseOverComponent:=true; RedrawPerform; end; end; procedure TWinHandle.MouseLeavePerform; begin wTrackingMouse:=false; wMouseOverComponent:=false; wMouseDown:=false; inherited; end; procedure TWinHandle.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin wMouseDown:=true; SetFocus; if (AButton = mbLeft) then begin RedrawPerform; if Assigned(fOnClick) then fOnClick(self); end end; procedure TWinHandle.MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin wMouseDown:=false; end; procedure TWinHandle.MouseButtonDblDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin end; procedure TWinHandle.KeyCharPerform(keychar:cardinal); begin end; procedure TWinHandle.KillFocusPerform; begin end; procedure TWinHandle.CapturePerform(AWindow:HWND); begin end; procedure TWinHandle.ClosePerform; begin end; procedure TWinHandle.SetBounds(ALeft, ATop, AWidth, AHeight:integer); begin hLeft:=ALeft; hTop:=ATop; hWidth:=AWidth; hHeight:=AHeight; end; procedure TWinHandle.SetFont(AValue:HFONT); begin wFont:=AValue; SetFontPerform; end; procedure TWinHandle.SetFontPerform; begin end; end.
unit cCadIgreja; interface uses System.Classes,Vcl.Controls, Vcl.ExtCtrls,Vcl.Dialogs,FireDAC.Comp.Client,System.SysUtils;//LISTA DE UNITS type TIgreja = class private //VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_cod_igreja:Integer; F_nome_igreja:string; F_cidade:string; F_dta_fundacao:TDateTime; F_nome_presidente:string; F_dta_inclusao:TDateTime; F_sigla_igreja:string; F_site:string; F_email:string; F_email_secretaria:string; F_cep:string; F_cnpj:string; F_logradouro:string; F_bairro:string; F_uf:string; F_fone:string; F_percentual_ajuste:Integer; F_sistema:Integer; F_situacao:Integer; //F_foto:TImage; public constructor Create(aConexao:TFDConnection); //CONSTRUTOR DA CLASSE destructor Destroy;override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir:Boolean; function Atualizar:Boolean; function Apagar:Boolean; function Selecionar(id:integer):boolean; //DE SOBRESCREVER //VARIÁVEIS PUBLICAS QUE PODE SER TRABALHADA FORA DA CLASSE published //VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE //PARA FORNECER INFORMAÇÕESD EM RUMTIME property cod_igreja:integer read F_cod_igreja write F_cod_igreja; property nome_igreja:string read F_nome_igreja write F_nome_igreja; property cidade:string read F_cidade write F_cidade; property dta_fundacao:TDateTime read F_dta_fundacao write F_dta_fundacao; property nome_presidente:string read F_nome_presidente write F_nome_presidente; property dta_inclusao:TDateTime read F_dta_inclusao write F_dta_inclusao; property sigla_igreja:string read F_sigla_igreja write F_sigla_igreja; property site:string read F_site write F_site; property email:string read F_email write F_email; property email_secretaria:string read F_email_secretaria write F_email_secretaria; property cep:string read F_cep write F_cep; property cnpj:string read F_cnpj write F_cnpj; property logradouro:string read F_logradouro write F_logradouro; property bairro:string read F_bairro write F_bairro; property uf:string read F_uf write F_uf; property fone:string read F_fone write F_fone; property percentual_ajuste:integer read F_percentual_ajuste write F_percentual_ajuste; property sistema:integer read F_sistema write F_sistema; property situacao:integer read F_situacao write F_situacao; //property foto:TImage read F_foto write F_foto; end; implementation {$region 'Constructor and Destructor'} constructor TIgreja.Create; begin ConexaoDB:=aConexao; end; destructor TIgreja.Destroy; begin inherited; end; {$endregion} {$region 'CRUD'} function TIgreja.Apagar: Boolean; var Qry:TFDQuery; begin if MessageDlg('Apagar o Registro: '+#13+#13+ 'Código: '+IntToStr(F_cod_igreja)+#13+ 'Descrição: '+F_nome_igreja,mtConfirmation,[mbYes,mbNo],0)=mrNO then begin Result:=false; Abort; end; Try Result:=True; Qry:=TFDQuery.Create(nil); Qry.Connection:= ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM tb_igreja WHERE cod_igreja=:cod_igreja; '); Qry.ParamByName('cod_igreja').AsInteger:=F_cod_igreja; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TIgreja.Atualizar: Boolean; var Qry:TFDQuery; begin try Result:=true; Qry:=TFDQuery.Create(nil); Qry.Connection:= ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE tb_igreja '+ ' SET nome_igreja=:nome_igreja '+ ', cidade=:cidade '+ ', dta_fundacao=:dta_fundacao '+ ', nome_presidente=:nome_presidente '+ ', dta_inclusao=:dta_inclusao '+ ', sigla_igreja=:sigla_igreja '+ ', site=:site '+ ', email=:email '+ ', cnpj=:cnpj '+ ', logradouro=:logradouro '+ ', bairro=:bairro '+ ', uf=:uf '+ ', fone=:fone '+ ',percentual_ajuste=:percentual_ajuste '+ ', sistema=:sistema '+ ', situacao=:situacao, email_secretaria=:email_secretaria, cep=:cep '+ ' WHERE cod_igreja=:cod_igreja'); Qry.ParamByName('nome_igreja').AsString:=F_nome_igreja; Qry.ParamByName('cod_igreja').AsInteger:=F_cod_igreja; Qry.ParamByName('dta_fundacao').AsDateTime:=F_dta_fundacao; Qry.ParamByName('nome_presidente').AsString:=F_nome_presidente; Qry.ParamByName('dta_inclusao').AsDateTime :=F_dta_inclusao; Qry.ParamByName('sigla_igreja').AsString:=F_sigla_igreja; Qry.ParamByName('site').AsString:=F_site; Qry.ParamByName('email').AsString:=F_email; Qry.ParamByName('email_secretaria').AsString:=F_email_secretaria; Qry.ParamByName('cep').AsString:=F_cep; Qry.ParamByName('cnpj').AsString:=F_cnpj; Qry.ParamByName('logradouro').AsString:=F_logradouro; Qry.ParamByName('bairro').AsString:=F_bairro; Qry.ParamByName('uf').AsString:=F_uf; Qry.ParamByName('fone').AsString:=F_fone; Qry.ParamByName('percentual_ajuste').AsInteger:=F_percentual_ajuste; Qry.ParamByName('sistema').AsInteger:=F_sistema; Qry.ParamByName('situacao').AsInteger:=F_situacao; Qry.ParamByName('cidade').AsString:=F_cidade; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TIgreja.Inserir: Boolean; var Qry:TFDQuery; begin try Result:=true; Qry:=TFDQuery.Create(nil); Qry.Connection:= ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tb_igreja '+ '(nome_igreja, cidade, dta_fundacao, nome_presidente, dta_inclusao, sigla_igreja, '+ 'site, email, cnpj, logradouro, bairro, uf, fone, percentual_ajuste, sistema, situacao,email_secretaria,cep) '+ 'VALUES(:nome_igreja, :cidade, :dta_fundacao, :nome_presidente, :dta_inclusao, :sigla_igreja '+ ', :site, :email, :cnpj, :logradouro, :bairro, :uf, :fone, :percentual_ajuste, :sistema, :situacao,:email_secretaria,:cep)'); Qry.ParamByName('nome_igreja').AsString:=F_nome_igreja; Qry.ParamByName('dta_fundacao').AsDateTime:=F_dta_fundacao; Qry.ParamByName('nome_presidente').AsString:=F_nome_presidente; Qry.ParamByName('dta_inclusao').AsDateTime :=F_dta_inclusao; Qry.ParamByName('sigla_igreja').AsString:=F_sigla_igreja; Qry.ParamByName('site').AsString:=F_sigla_igreja; Qry.ParamByName('email').AsString:=F_email; Qry.ParamByName('email_secretaria').AsString:=F_email_secretaria; Qry.ParamByName('cep').AsString:=F_cep; Qry.ParamByName('cnpj').AsString:=F_sigla_igreja; Qry.ParamByName('logradouro').AsString:=F_sigla_igreja; Qry.ParamByName('bairro').AsString:=F_sigla_igreja; Qry.ParamByName('uf').AsString:=F_sigla_igreja; Qry.ParamByName('fone').AsString:=F_sigla_igreja; Qry.ParamByName('percentual_ajuste').AsString:=F_sigla_igreja; Qry.ParamByName('sistema').AsString:=F_sigla_igreja; Qry.ParamByName('situacao').AsString:=F_sigla_igreja; Qry.ParamByName('cidade').AsString:=F_cidade; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TIgreja.Selecionar(id: integer): boolean; var Qry:TFDQuery; begin try Result:=true; Qry:=TFDQuery.Create(nil); Qry.Connection:= ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT cod_igreja, nome_igreja, cidade, dta_fundacao, '+ ' nome_presidente, '+ ' dta_inclusao, sigla_igreja, site, email, cnpj '+ ' , logradouro, bairro, uf, fone, '+ ' percentual_ajuste, sistema, situacao,email_secretaria,cep FROM tb_igreja where cod_igreja = :cod_igreja '); Qry.ParamByName('cod_igreja').AsInteger:=id; try Qry.Open; Self.F_cod_igreja:=Qry.FieldByName('cod_igreja').AsInteger; Self.F_nome_igreja:= Qry.FieldByName('nome_igreja').AsString; Self.F_cidade:= Qry.FieldByName('cidade').AsString; Self.F_dta_fundacao:= Qry.FieldByName('dta_fundacao').AsDateTime; Self.F_nome_presidente:= Qry.FieldByName('nome_presidente').AsString; Self.F_dta_inclusao:= Qry.FieldByName('dta_inclusao').AsDateTime; Self.F_sigla_igreja:= Qry.FieldByName('sigla_igreja').AsString; Self.F_site:= Qry.FieldByName('site').AsString; Self.F_email:= Qry.FieldByName('email').AsString; Self.F_email_secretaria:= Qry.FieldByName('email_secretaria').AsString; Self.F_cep:= Qry.FieldByName('cep').AsString; Self.F_cnpj:= Qry.FieldByName('cnpj').AsString; Self.F_logradouro:= Qry.FieldByName('logradouro').AsString; Self.F_bairro:= Qry.FieldByName('bairro').AsString; Self.F_uf:= Qry.FieldByName('uf').AsString; Self.F_fone:= Qry.FieldByName('fone').AsString; Self.F_percentual_ajuste:= Qry.FieldByName('percentual_ajuste').AsInteger; Self.F_sistema:= Qry.FieldByName('sistema').AsInteger; Self.F_situacao:= Qry.FieldByName('situacao').AsInteger; Except Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$endregion} end.
unit enetpas_server_main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, enet_consts, uENetClass; type { TForm1 } TForm1 = class(TForm) ApplicationProperties1: TApplicationProperties; ListBox1: TListBox; Timer1: TTimer; procedure ApplicationProperties1Idle(Sender: TObject; var Done: Boolean); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormShow(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure OnConnect(const Event:ENetEvent); procedure OnReceive(const Event:ENetEvent; var BroadcastMsg : Boolean; var BroadcastChannel : Byte); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} var myServer : TENetClass; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin myServer := TENetClass.Create(30000,True); myServer.OnReceive:=@OnReceive; myServer.OnConnect:=@OnConnect; myServer.OnDisconnect:=@OnConnect; myServer.OnNone:=@OnConnect; myServer.MessageTimeout:=100; // ideal for application idle? myServer.InitHost; Timer1.Enabled:=True; end; procedure TForm1.ApplicationProperties1Idle(Sender: TObject; var Done: Boolean); begin while myServer.ProcessMsg do Application.ProcessMessages; end; procedure TForm1.FormDestroy(Sender: TObject); begin Timer1.Enabled:=False; myServer.Free; end; procedure TForm1.FormPaint(Sender: TObject); begin end; procedure TForm1.FormShow(Sender: TObject); begin end; procedure TForm1.Timer1Timer(Sender: TObject); begin end; procedure TForm1.OnConnect(const Event: ENetEvent); begin if Event.EventType=ord(ENetEventConnect) then ListBox1.AddItem('Connect',nil) else if Event.EventType=ord(ENetEventDisConnect) then ListBox1.AddItem('Disconnect',nil) else ListBox1.AddItem('None',nil); end; procedure TForm1.OnReceive(const Event: ENetEvent; var BroadcastMsg: Boolean; var BroadcastChannel: Byte); var msg : string; begin msg := PChar(Event.packet^.data); ListBox1.AddItem(msg,nil); end; end.
unit UFrameAnalog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UTreeItem, IniFiles, UFrameKP; type TItemAnalog = class; TFrameAnalog = class(TFrame) Panel: TPanel; edR: TEdit; edP: TEdit; Label7: TLabel; Label6: TLabel; BtnChange: TButton; cbOn: TCheckBox; stStatus: TStaticText; procedure BtnChangeClick(Sender: TObject); procedure cbOnClick(Sender: TObject); private { Private declarations } Analog:TItemAnalog; public { Public declarations } end; TItemAnalog = class(TTreeItem) public KP:TItemKP; NetNumber:Integer; CoeffR,CoeffP:Double; isSensorOn:Boolean; FA:TFrameAnalog; DataList:TStringList; CntP:Integer; SumP,P:Double; constructor Load(KP:TItemKP; Ini,Cfg:TIniFile; const Section:String); function Enter:TFrame;override; function Leave:Boolean;override; function Validate:Boolean;override; procedure SaveCfg(Cfg:TIniFile);override; procedure TimerProc;override; procedure RefreshFrame; procedure GetP(const SrcData; var P:Single); private CoeffK,CoeffB:Double; procedure CalcKB; end; implementation uses UFormMain, Misc, SensorTypes; {$R *.DFM} procedure TFrameAnalog.BtnChangeClick(Sender: TObject); begin Analog.ChangeData(BtnChange,Panel); end; { TItemAnalog } function TItemAnalog.Enter: TFrame; begin FA:=TFrameAnalog.Create(FormMain); FA.Analog:=Self; FA.Name:=''; FA.cbOn.Caption:='№'+IntToStr(NetNumber); FA.cbOn.Checked:=isSensorOn; FA.edR.Text:=Format('%g',[CoeffR]); FA.edP.Text:=Format('%g',[CoeffP]); RefreshFrame; Result:=FA; end; function TItemAnalog.Leave: Boolean; begin FA.Free; FA:=nil; Result:=True; end; constructor TItemAnalog.Load(KP:TItemKP; Ini,Cfg: TIniFile; const Section: String); begin inherited; Self.KP:=KP; Self.Section:=Section; Node:=FormMain.TreeView.Items.AddChildObject(KP.Node,Section,Self); NetNumber:=Ini.ReadInteger(Section,'NetNumber',0); isSensorOn:=Cfg.ReadBool(Section,'On',True); CoeffR:=Cfg.ReadFloat(Section,'R',124); CoeffP:=Cfg.ReadFloat(Section,'P',60); CalcKB; end; procedure TItemAnalog.TimerProc; begin if CntP>0 then begin P:=SumP/CntP; end; if FA<>nil then RefreshFrame; SumP:=0; CntP:=0; end; function TItemAnalog.Validate: Boolean; var CR,CP:Double; begin try CheckMinMax(CR,1,999,FA.edR); CheckMinMax(CP,0.01,128,FA.edP); CoeffR:=CR; CoeffP:=CP; CalcKB; Result:=True; except Result:=False; end; end; procedure TItemAnalog.SaveCfg(Cfg: TIniFile); begin // Ini.WriteInteger(Section,'NetNumber',NetNumber); Cfg.WriteBool(Section,'On',isSensorOn); Cfg.WriteFloat(Section,'R',CoeffR); Cfg.WriteFloat(Section,'P',CoeffP); end; procedure TItemAnalog.RefreshFrame; begin FA.stStatus.Caption:=Format('%3d | %7.3f ',[CntP,P]);; FA.cbOn.Checked:=isSensorOn; end; procedure TItemAnalog.CalcKB; var Ua,Ub:Double; begin Ua:=0.004*CoeffR; Ub:=0.020*CoeffR; CoeffK:=CoeffP/(Ub-Ua); CoeffB:=-CoeffK*Ua; end; procedure TItemAnalog.GetP(const SrcData; var P: Single); const fErrorFlag =$8000; fErrorComm =$4000; fErrorADCRange=$2000; fErrorInvData =$1000; fErrorInvResp =$0800; Prescale=2.5/32767; var AD:TAnalogData; Tmp:Word; begin Tmp:=0; move(SrcData,Tmp,2); if Tmp and fErrorFlag<>0 then begin // признак сбоя if Tmp and (fErrorComm or fErrorInvData or fErrorInvResp)<>0 then SetErrADCComm(AD) else if Tmp and fErrorADCRange<>0 then SetErrADCRange(AD) else SetErrUnknown(AD); if not isSensorOn then SetSensorRepair(AD); end else begin AD.Value:=Tmp*Prescale*CoeffK+CoeffB; Inc(CntP); SumP:=SumP+AD.Value; if AD.Value < -1 then SetErrAnalog(AD); end; P:=AD.Value; end; procedure TFrameAnalog.cbOnClick(Sender: TObject); begin Analog.isSensorOn:=cbOn.Checked; end; end.
unit uTipoVO; interface uses System.SysUtils, uKeyField, uTableName; type [TableName('Tipo')] TTipoVO = class private FConceito: string; FAtivo: Boolean; FCodigo: Integer; FId: Integer; FPrograma: Integer; FNome: string; procedure SetAtivo(const Value: Boolean); procedure SetCodigo(const Value: Integer); procedure SetConceito(const Value: string); procedure SetId(const Value: Integer); procedure SetNome(const Value: string); procedure SetPrograma(const Value: Integer); public [KeyField('Tip_Id')] property Id: Integer read FId write SetId; [FieldName('Tip_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('Tip_Nome')] property Nome: string read FNome write SetNome; [FieldName('Tip_Ativo')] property Ativo: Boolean read FAtivo write SetAtivo; [FieldName('Tip_Programa')] property Programa: Integer read FPrograma write SetPrograma; [FieldName('Tip_Conceito')] property Conceito: string read FConceito write SetConceito; end; implementation { TTipoVO } procedure TTipoVO.SetAtivo(const Value: Boolean); begin FAtivo := Value; end; procedure TTipoVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TTipoVO.SetConceito(const Value: string); begin FConceito := Value; end; procedure TTipoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TTipoVO.SetNome(const Value: string); begin FNome := Value; end; procedure TTipoVO.SetPrograma(const Value: Integer); begin FPrograma := Value; 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. } { } { *************************************************************************** } unit FireDac.ObjectDataSet; interface uses System.Classes, System.Rtti, Data.DB, System.Generics.Collections, System.TypInfo, FireDac.Stan.Intf, FireDac.Stan.Option, FireDac.Stan.Param, FireDac.Stan.Error, FireDac.DatS, FireDac.Phys.Intf, FireDac.DApt.Intf, FireDac.Comp.DataSet, FireDac.Comp.Client, System.SysUtils, System.Contnrs; type TObjectListEvent = procedure(sender: TObject; Action: TListNotification) of object; TObjectListEventing = class(TObjectList) private FOnAddEvent: TObjectListEvent; procedure SetOnAddEvent(const Value: TObjectListEvent); procedure Notify(Ptr: Pointer; Action: TListNotification); override; public property OnNotifyEvent: TObjectListEvent read FOnAddEvent write SetOnAddEvent; end; TObjectDataSet = class(TFDMemTable) private FActiveRow:integer; FNotifyControls: integer; FObjectClass: TClass; FStringMax: integer; FObjectList: TObjectListEventing; FObjectListOwned: Boolean; FObjectClassName: string; procedure InternalInitFieldDefsObjectClass; procedure InternalDelete; override; procedure DoBeforeInsert;override; procedure InternalInsert; override; procedure InternalPost; override; procedure InternalEdit; override; procedure DoAfterEdit; override; procedure DoAfterInsert;override; procedure InternalClose;override; procedure DoAddToObjectListEvent(sender: TObject; Action: TListNotification); function GetRecNo: Integer; override; procedure SetObjectClass(const Value: TClass); procedure SetStringMax(const Value: integer); procedure InternalSetToRecord(Buffer: TRecBuf); overload; override; procedure SetOwnsObjects(const Value: Boolean); function GetOwnsObjects: Boolean; procedure SetObjectClassName(const Value: string); procedure SetObjectList(const Value: TObjectListEventing); public constructor create(AOwner: TComponent); overload; override; constructor create(AOwnder: TComponent; AClass: TClass); overload; destructor destroy; override; procedure FieldToObject(LRow: integer);overload; procedure FieldToObject(Obj:TObject);overload; procedure ObjectToField(LRow: integer);overload; procedure ObjectToField(Obj:TObject);overload; procedure DisableListControls; procedure EnableListControls; procedure Reopen; published procedure LoadFromList( AList:TList );overload;virtual; procedure SaveToList( AList:TList );overload;virtual; property ObjectClass: TClass read FObjectClass write SetObjectClass; property ObjectList: TObjectListEventing read FObjectList write SetObjectList; property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects; property ObjectClassName: string read FObjectClassName write SetObjectClassName; property StringWidth: integer read FStringMax write SetStringMax; end; TGenericObjectDataset<T: Class> = class(TObjectDataset) private function GetItems(idx: Integer): T; procedure SetItems(idx: Integer; const Value: T); public constructor create(AOwner:TComponent);override; procedure LoadFromList( AList:TList<T> );overload; procedure SaveToList( AList:TList<T> );overload; function Count:integer; property Items[idx:Integer]:T read GetItems write SetItems; end; implementation constructor TObjectDataSet.create(AOwner: TComponent); begin inherited; FStringMax := 255; FObjectList := TObjectListEventing.create(true); FObjectListOwned := true; FObjectList.OnNotifyEvent := DoAddToObjectListEvent; end; constructor TObjectDataSet.create(AOwnder: TComponent; AClass: TClass); begin create(AOwnder); ObjectClass := AClass; end; destructor TObjectDataSet.destroy; begin FObjectList.OnNotifyEvent := nil; if FObjectListOwned then FreeAndNil(FObjectList); inherited; end; procedure TObjectDataSet.DoAfterEdit; var LRow: integer; begin inherited; LRow := GetRecNo - 1; if (LRow >= 0) and (LRow < FObjectList.Count) then ObjectToField(LRow); end; procedure TObjectDataSet.DoAfterInsert; begin inherited; end; procedure TObjectDataSet.DoBeforeInsert; begin last; inherited; end; procedure TObjectDataSet.DoAddToObjectListEvent(sender: TObject; Action: TListNotification); var LRow: integer; begin if (FNotifyControls > 0) then exit; case Action of lnAdded: begin if state in dsEditModes then post; DisableListControls; try insert; LRow := GetRecNo - 1; if (LRow >= 0) and (LRow < FObjectList.Count) then FieldToObject(LRow); finally EnableListControls; end; end; lnExtracted: ; lnDeleted: ; end; end; procedure TObjectDataSet.FieldToObject(LRow: integer); var obj:TObject; begin obj := FObjectList.Items[LRow]; FieldToObject(obj); end; function TObjectDataSet.GetOwnsObjects: Boolean; begin result := FObjectList.OwnsObjects; end; function TObjectDataSet.GetRecNo: Integer; begin if state in [dsInsert] then result := FActiveRow +1 else result := inherited GetRecNo; end; procedure TObjectDataSet.InternalClose; begin inherited; if assigned(FObjectList) then FObjectList.Clear; end; procedure TObjectDataSet.InternalDelete; var LRow: integer; begin LRow := GetRecNo - 1; inherited; if (LRow >= 0) and (LRow < FObjectList.Count) then FObjectList.Delete(LRow); end; procedure TObjectDataSet.InternalEdit; begin inherited; end; procedure TObjectDataSet.InternalInitFieldDefsObjectClass; var LContext: TRttiContext; LRttiType: TRttiType; LRttiProp: TRttiProperty; FType: TFieldType; FSize: integer; begin LContext := TRttiContext.create(); try LRttiType := LContext.GetType(FObjectClass); for LRttiProp in LRttiType.GetProperties do begin FType := ftString; FSize := FStringMax; case LRttiProp.PropertyType.TypeKind of tkInteger, tkInt64: begin FType := ftInteger; FSize := 0; end; tkFloat: begin FSize := 0; if LRttiProp.PropertyType.Name.Equals('TDateTime') then FType := ftDateTime else if LRttiProp.PropertyType.Name.Equals('TDate') then FType := ftDate else if LRttiProp.PropertyType.Name.Equals('TTime') then FType := ftTime else if LRttiProp.PropertyType.Name.Equals('Currency') then FType := ftCurrency else FType := ftFloat; end; tkVariant: FType := ftVariant; end; fieldDefs.Add(LRttiProp.Name, FType, FSize); end; finally LContext.Free; end; end; procedure TObjectDataSet.InternalInsert; begin inherited; if FNotifyControls = 0 then begin DisableListControls; try FObjectList.Add(FObjectClass.create); FActiveRow := FObjectList.Count-1; if (FActiveRow >= 0) and (FActiveRow < FObjectList.Count) then FieldToObject(FActiveRow); finally EnableListControls; end; end; end; procedure TObjectDataSet.InternalPost; var LRow: integer; begin inherited; LRow := GetRecNo - 1; if (LRow >= 0) and (LRow < FObjectList.Count) then begin FieldToObject(LRow); end; end; procedure TObjectDataSet.InternalSetToRecord(Buffer: TRecBuf); begin inherited InternalSetToRecord(Buffer); end; procedure TObjectDataSet.LoadFromList(AList: TList); var obj:TObject; nObj:TObject; i:integer; begin if AList.Count=0 then exit; // nao tem nada para ler try try if active then EmptyDataSet; close; FieldDefs.Clear; obj := AList.Items[0]; ObjectClass := obj.ClassType; open; for I := 0 to AList.Count-1 do begin obj := AList.Items[i]; append; ObjectToField(obj); Post; end; finally end; finally Resync([]); end; end; procedure TObjectDataSet.ObjectToField(Obj: TObject); var LNome: string; LContext: TRttiContext; LType: TRttiType; LProp: TRttiProperty; LVar: TValue; fld: TField; begin LContext := TRttiContext.create; try LType := LContext.GetType(obj.ClassType); for LProp in LType.GetProperties do begin fld := Fields.FindField(LProp.Name); if fld <> nil then begin LVar := LProp.GetValue(obj); fld.Value := LVar.AsVariant; end; end; finally LContext.Free; end; end; procedure TObjectDataSet.ObjectToField(LRow: integer); var obj:TObject; begin if (LRow >= 0) and (LRow < FObjectList.Count) then begin obj := FObjectList.Items[LRow]; ObjectToField(obj); end; end; procedure TObjectDataSet.Reopen; begin close; open; end; procedure TObjectDataSet.SaveToList(AList: TList); var i:integer; obj:TObject; book:TBookmark; OldRow:Integer; begin DisableControls; try oldRow := GetRecNo; AList.Clear; first; while eof=false do begin obj := FObjectClass.Create; FieldToObject(obj); AList.Add(obj); next; end; finally SetRecNo(oldRow); EnableControls; end; end; procedure TObjectDataSet.SetObjectClass(const Value: TClass); begin FObjectClass := Value; InternalInitFieldDefsObjectClass; end; procedure TObjectDataSet.SetObjectClassName(const Value: string); begin FObjectClassName := Value; ObjectClass := FindClass(Value); end; procedure TObjectDataSet.SetObjectList(const Value: TObjectListEventing); begin FObjectList.OnNotifyEvent := nil; FreeAndNil(FObjectList); FObjectList := Value; FObjectList.OnNotifyEvent := DoAddToObjectListEvent; FObjectListOwned := false; end; procedure TObjectDataSet.SetOwnsObjects(const Value: Boolean); begin FObjectList.OwnsObjects := Value; end; procedure TObjectDataSet.SetStringMax(const Value: integer); begin FStringMax := Value; end; { TObjectListChangeEvent } procedure TObjectDataSet.DisableListControls; begin inc(FNotifyControls); end; procedure TObjectDataSet.EnableListControls; begin dec(FNotifyControls); if FNotifyControls < 0 then FNotifyControls := 0; end; procedure TObjectDataSet.FieldToObject(Obj: TObject); var LContext: TRttiContext; LTypes: TRttiType; LProp: TRttiProperty; fld: TField; LVal: TValue; begin LContext := TRttiContext.create; try LTypes := LContext.GetType(obj.ClassType); for LProp in LTypes.GetProperties do begin fld := Fields.FindField(LProp.Name); if fld <> nil then begin LVal := TValue.From<variant>(fld.Value); LProp.SetValue(obj, LVal); end; end; finally LContext.Free; end; end; { TObjectListEventing } procedure TObjectListEventing.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; if assigned(FOnAddEvent) then FOnAddEvent(self, Action); end; procedure TObjectListEventing.SetOnAddEvent(const Value: TObjectListEvent); begin FOnAddEvent := Value; end; { TGenericObjectDataset<T> } function TGenericObjectDataset<T>.Count: integer; begin result := FObjectList.Count; end; constructor TGenericObjectDataset<T>.create(AOwner: TComponent); begin inherited; ObjectClass := T; end; function TGenericObjectDataset<T>.GetItems(idx: Integer): T; var obj:TObject; begin obj := FObjectList.Items[idx]; result := T(obj); end; procedure TGenericObjectDataset<T>.LoadFromList(AList: TList<T>); var obj:TObject; nObj:TObject; i:integer; begin if AList.Count=0 then exit; // nao tem nada para ler try try if active then EmptyDataSet; close; FieldDefs.Clear; obj := AList.Items[0]; ObjectClass := obj.ClassType; open; for I := 0 to AList.Count-1 do begin obj := AList.Items[i]; append; ObjectToField(obj); Post; end; finally end; finally Resync([]); end; end; procedure TGenericObjectDataset<T>.SaveToList(AList: TList<T>); var obj:TObject; oldRow:Integer; begin AList.clear; oldRow := GetRecNo; DisableControls; try first; while eof=false do begin obj := FObjectClass.Create; FieldToObject(obj); AList.Add(obj); next; end; finally SetRecNo(oldRow); EnableControls; end; end; procedure TGenericObjectDataset<T>.SetItems(idx: Integer; const Value: T); begin FObjectList.SetItem(idx,Value); end; end.
unit acReportContainer; interface uses SysUtils, Classes, System.Contnrs; type TReportInfo = class id: Integer; name: string; template: string; end; TacReportContainer = class(TComponent) private reports: TObjectList; public constructor Create(owner: TComponent); override; destructor Destroy; override; procedure addReport(id:Integer; name: string; template: string); function findReportById(id: Integer): string; function findReportByName(name: string): string; function findRportIdByName(name: string):Integer; procedure removeAll(); published { Published declarations } end; procedure Register; implementation constructor TacReportContainer.Create(owner: TComponent); begin inherited create(owner); reports := TObjectList.Create; reports.OwnsObjects := True; end; destructor TacReportContainer.Destroy; begin inherited; FreeAndNil(reports); end; procedure TacReportContainer.addReport(id: Integer; name: string; template: string); var report: TReportInfo; begin report := TReportInfo.Create; report.id := id; report.name := name; report.template := template; reports.Add(report); end; function TacReportContainer.findReportById(id: Integer): string; var i: integer; begin Result := ''; for i := 0 to reports.Count-1 do begin if TReportInfo(reports.Items[i]).id = id then Result := TReportInfo(reports.Items[i]).template; end; end; function TacReportContainer.findReportByName(name: string): string; var i: integer; begin Result := ''; for i := 0 to reports.Count-1 do begin if UpperCase(TReportInfo(reports.Items[i]).name) = UpperCase(name) then Result := TReportInfo(reports.Items[i]).template; end; end; function TacReportContainer.findRportIdByName(name: string): Integer; var i: integer; begin Result := -1; for i := 0 to reports.Count-1 do begin if UpperCase(TReportInfo(reports.Items[i]).name) = UpperCase(name) then Result := TReportInfo(reports.Items[i]).id; end; end; procedure TacReportContainer.removeAll; begin reports.Clear; end; procedure Register; begin RegisterComponents('Acras', [TacReportContainer]); end; end.
program COPYTEXT ( EING , OUTPUT ) ; (**********************************************) (* This program copies the characters *) (* and line structure of the textfile *) (* input to the textfile output. *) (**********************************************) var CH : CHAR ; EING : TEXT ; begin (* HAUPTPROGRAMM *) // RESET ( EING ) ; if true then writeln ('+++ Anfang:', ' EOF = ', EOF (EING), ' EOLN = ', EOLN (EING)); while not EOF ( EING ) do begin while not EOLN ( EING ) do begin READ ( EING , CH ) ; WRITE ( OUTPUT , CH ) end (* while *) ; READLN ( EING ) ; WRITELN ( OUTPUT , '***'); end (* while *) end (* HAUPTPROGRAMM *) .
unit UPageList; interface type TPageRange = record a,b:integer; end; TPageRangeArray = array of TPageRange; TPageList = class(TObject) private FList : TPageRangeArray; procedure SetPagesString(const Value: string); procedure AddStringEntry(entry:string); procedure DelEntry(idx:integer); function GetPagesString: string; public procedure Clear; procedure AddPage(p:integer); procedure AddRange(p,q:integer); function IsPageInList(x:integer):Boolean; property PagesString:string read GetPagesString write SetPagesString; end; implementation uses SysUtils; // Hilfsfunktionen für Stringverarbeitung function StrToken(var S: string; Separator: Char): string; var I: Integer; begin I := Pos(Separator, S); if I <> 0 then begin Result := Copy(S, 1, I - 1); Delete(S, 1, I); end else begin Result := S; S := ''; end; end; function CharPos(const S: string; const C: Char): Integer; begin for Result := 1 to Length(S) do if S[Result] = C then Exit; Result := 0; end; function IsInRange(x,a,b:integer):Boolean; register; begin Result := (x>=a) and (x<=b); end; { TPageList } procedure TPageList.AddPage(p: integer); begin if p >= 0 then AddRange(p,p); end; procedure TPageList.AddRange(p, q: integer); var i, len : integer; begin if p > q then exit; for i := Length(FList) - 1 downto 0 do begin if (p >= FList[i].a) and (q <= FList[i].b) then exit; if (p <= FList[i].a) and (q >= FList[i].b) then begin DelEntry(i); end else if IsInRange(q, FList[i].a-1, FList[i].b) then begin q := FList[i].b; DelEntry(i); end else if IsInRange(p, FList[i].a, FList[i].b+1) then begin p := FList[i].a; DelEntry(i); end; end; len := Length(FList); SetLength(FList, len+1); FList[len].a := p; FList[len].b := q; end; procedure TPageList.AddStringEntry(entry: string); var a, b : integer; s : string; begin if CharPos(entry, '-') = 0 then begin AddPage(StrToIntDef(Trim(entry), -1)); end else begin s := Trim(StrToken(entry, '-')); if s='' then a := 0 else a := StrToIntDef(s, -1); if entry = '' then b := 9999999 else begin s := Trim(StrToken(entry, '-')); b := StrToIntDef(s, -1); end; AddRange(a,b); end; end; procedure TPageList.Clear; begin SetLength(Flist,0); end; procedure TPageList.DelEntry(idx: integer); begin if idx < Length(FList)-1 then Move(Flist[idx+1], FList[idx], (Length(FList)-idx)*sizeof(TPageRange)); SetLength(FList, Length(FList)-1); end; function TPageList.GetPagesString: string; var i : integer; begin Result := ''; for i := 0 to Length(FList) - 1 do begin if i <> 0 then Result := Result +';'; result := Result + IntToStr(FList[i].a); if FList[i].a<>FList[i].b then Result := Result + '-'+IntToStr(FList[i].b); end; end; procedure TPageList.SetPagesString(const Value: string); var tmp, entry : string; begin tmp := Value; Clear; repeat entry := StrToken(tmp, ';'); AddStringEntry(entry); until tmp =''; end; function TPageList.IsPageInList(x: integer): Boolean; var i : integer; begin for i := 0 to Length(FList) - 1 do begin if IsInRange(x, FList[i].a, FList[i].b) then begin result := True; exit; end; end; Result := False; end; end.
FUNCTION LoadPCXPicToRAM(AName : String; Var Laenge : LongInt) : Pointer; (* ---------------------------------------------------------------- *) Var F : File; PH1 : Pointer; Begin If Not (AFirst In [0..PCXMAX]) Then Begin VGA_Error := VGA_Error_Error_InvalidArgumentValues; Exit; End; Assign(F, AName); (* Datei ™ffnen: *) {$I-} Reset(F, 1); (* Recordl„nge = 1 Byte. *) {$I+} VGA_Error := IOResult; If VGA_Error <> 0 Then CriticalError(AName); (* Dateil„nge bestimmen: *) {$I-} Laenge := FileSize(F); {$I+} VGA_Error := IOResult; If VGA_Error <> 0 Then CriticalError(AName); (* Gr”áer als 65528 Bytes (= 64 KByte-$08), dann Ende: *) If Laenge > 65528 Then Begin VGA_Error := VGA_Error_FileSizeTooBig; CriticalError(AName); End; (* Speicher fr Datei belegen: *) GetMem(PH1, Laenge); (* Daten einlesen: *) {$I-} BlockRead(F, PH1^, Laenge); {$I+} VGA_Error := IOResult; If VGA_Error <> 0 Then CriticalError(AName); (* Rckgabe: *) LoadPCXPicToRAM := PH1; VGA_Error := VGA_Error_Ok; End; FUNCTION ShowPCXPicFromRAM(APtr : Pointer; ALaenge : LongInt; APage : Byte; AUsePal, ASetPal : Boolean) : Pointer; (* ---------------------------------------------------------------- *) Const BlockReadSize = 526; (* Nicht ver„ndern !!!! *) Type TPCXHeader = Record Hersteller : Byte; Version : Byte; CodierArt : Byte; BitProPixel : Byte; Bildgroesse : Array[1..4] Of Word; HorizAufl : Word; VertiAufl : Word; Farbskala : Array[1..48] Of Byte; Reserviert : Byte; Farbebenen : Byte; BytesProZeile : Word; FarbeOdGrau : Word; Fueller : Array[1..58] Of Byte; End; Var PCXHeader : TPCXHeader; PCXFarbSkala256 : TPalette; CountDataBlocks : Integer; (* Anzahl an Pixeldaten zu "BLOCKREADSIZE"-Bl”cken. *) BlocksRead : Integer; (* Schon gelesene Blocks. *) ByteInLastBlock : Integer; (* Wieviele Byte im letzten Block gebraucht werden. *) ByteReadInBlock : Integer; (* Aktuelle Anzahl gelesener Byte in diesem Block. *) PFile : Pointer; PFileByte : ^Byte; PDatenIn4er : Pointer; (* Hier ist das Bild gespeichert, nach *) (* Ebenen geordnet, also E0-Daten, E1... *) PBlockDaten : Pointer; (* Zeiger auf 1 geladenen Block. *) PEbenen : Array[0..3] Of ^Byte; AktEbene : Byte; IH1 : Integer; PB1 : ^Byte; BH1 : Byte; WH1, WH2, WH3 : Word; SH1 : String[79]; BreakTrue : Boolean; OK : Boolean; Zaehler : Integer; Begin ShowPCXPicFromRAM := Nil; (* Anzahl der Blocks lesen: *) CountDataBlocks := (ALAENGE - SizeOf(PCXFarbSkala256)) Div BlockReadSize; If (ALaenge - SizeOf(PCXFarbSkala256)) Mod BlockReadSize > 0 Then Inc(CountDataBlocks); ByteInLastBlock := (ALaenge - SizeOf(PCXFarbSkala256)) Mod BlockReadSize -1; (* Header lesen: *) PB1 := @PCXHeader; Move(APtr^, PB1^, SizeOf(PCXHeader)); (* Lade Farbskala: *) If AUsePal And (PCXHeader.Version >= 5) Then Begin LongInt(APtr) := LongInt(APtr) + ALaenge - 768; PB1 := @PCXFarbSkala256; Move(APtr^, PB1^, 768); LongInt(APtr) := LongInt(APtr) - ALaenge + 768; If ASetPal Then SetPalette(PCXFarbSkala256); ShowPCXPicFromRAM := @PCXFarbSkala256; End; (* Datens„tze lesen: *) BlocksRead := 0; AktEbene := 0; ByteReadInBlock := 0; GetMem(PDatenIn4er, 320*200); (* Speicher fr 1 Bild reservieren. *) LongInt(PEbenen[0]) := LongInt(PDatenIn4er) + 0 * ((320 * 200) Div 4); LongInt(PEbenen[1]) := LongInt(PDatenIn4er) + 1 * ((320 * 200) Div 4); LongInt(PEbenen[2]) := LongInt(PDatenIn4er) + 2 * ((320 * 200) Div 4); LongInt(PEbenen[3]) := LongInt(PDatenIn4er) + 3 * ((320 * 200) Div 4); GetMem(PBlockDaten, BlockReadSize); BreakTrue := False; OK := False; Zaehler := 1; While (BlocksRead <= CountDataBlocks) Do Begin (* Zeiger zum einlesen: *) Move(APtr^, PBlockDaten^, BlockReadSize); Inc(LongInt(APtr), BlockReadSize); ByteReadInBlock := 0; Inc(BlocksRead); PB1 := PBlockDaten; (* Ein Satz entpacken und gleich in die richtigen Ebenen verteilen: *) If BlocksRead = 1 Then (* Header berspringen. *) Begin Inc(PB1, 128); Inc(ByteReadInBlock, 128); End; While LongInt(PB1) < LongInt(PBlockDaten)+BlockReadSize Do Begin If (Not OK) And (PB1^ >= 192) Then Begin Zaehler := PB1^ - 192; OK := False; End; If (Not OK) And (PB1^ < 192) Then Begin Zaehler := 1; OK := True; End; If (OK) Then Begin For IH1 := 1 To Zaehler Do Begin PEbenen[AktEbene]^ := PB1^; Inc(PEbenen[AktEbene]); Inc(AktEbene); If AktEbene > 3 Then AktEbene := 0; End; Inc(PB1); Inc(ByteReadInBlock); OK := False; End Else Begin OK := True; Inc(PB1); Inc(ByteReadInBlock); End; If (BlocksRead >= CountDataBlocks) And (ByteReadInBlock >= ByteInLastBlock) Then Begin BreakTrue := True; Break; End; End; If BreakTrue Then Break; End; FreeMem(PBlockDaten, BlockReadSize); (* PBLOCKDATEN^ Ebenenweise auf Schirm bringen: *) WH1 := Seg(PDatenIn4er^); WH2 := Ofs(PDatenIn4er^); WH3 := PAdr[APage]; AktEbene := 1; Asm push ds mov ax, ScreenSeg mov es, ax (* ES = ZielSegment. *) mov ax, WH1 mov ds, ax (* DS = QuellSegment. *) mov ax, WH2 mov si, ax (* SI = QuellOffset. *) (* Ebenen ausgeben: *) mov cx, 4 (* Alle Ebenen durch. *) @EineEbene: push cx mov ax, WH3 mov bx, ax (* BX = ZielOffset. *) mov ah, AktEbene mov al, 2 (* AL = Index Map Mask Register. *) mov dx, 3C4h out dx, ax (* Ebene w„hlen. *) mov cx, ScreenSize / 2 (* BYTES -> WORDS. *) (* Alle Daten von 1 Ebene ausgeben: *) (* CX = Anzahl Bytes, *) (* ES = Bildschirm-Segment, *) (* BX = Bildschirm-Offset, *) (* DS = Spritedaten-Segment, *) (* SI = Spritedaten-Offset. *) stc (* BX so verringern, daá es zusammen *) sbb bx, si (* mit SI zugleich als Zielindex *) (* verwendet werden kann. *) dec bx @AllePunkteEinerEbene: lodsw (* 1 Byte holen. *) mov es:[bx+si], ax (* šbertragen. *) loop @AllePunkteEinerEbene (* N„chstes Byte. *) pop cx mov al, AktEbene (* N„chste Ebene. *) shl al, 1 mov AktEbene, al loop @EineEbene pop ds End; FreeMem(PDatenIn4er, 320*200); (* Speicher fr 1 Bild freigeben. *) VGA_Error := VGA_Error_OK; End; Const BlockReadSize = 526; (* Nicht ver„ndern !!!! *) Type TPCXHeader = Record Hersteller : Byte; Version : Byte; CodierArt : Byte; BitProPixel : Byte; Bildgroesse : Array[1..4] Of Word; HorizAufl : Word; VertiAufl : Word; Farbskala : Array[1..48] Of Byte; Reserviert : Byte; Farbebenen : Byte; BytesProZeile : Word; FarbeOdGrau : Word; Fueller : Array[1..58] Of Byte; End; Var PCXHeader : TPCXHeader; PCXFarbSkala256 : TPalette; CountDataBlocks : Integer; (* Anzahl an Pixeldaten zu "BLOCKREADSIZE"-Bl”cken. *) BlocksRead : Integer; (* Schon gelesene Blocks. *) ByteInLastBlock : Integer; (* Wieviele Byte im letzten Block gebraucht werden. *) ByteReadInBlock : Integer; (* Aktuelle Anzahl gelesener Byte in diesem Block. *) PFile : Pointer; PFileByte : ^Byte; PDatenIn4er : Pointer; (* Hier ist das Bild gespeichert, nach *) (* Ebenen geordnet, also E0-Daten, E1... *) PBlockDaten : Pointer; (* Zeiger auf 1 geladenen Block. *) PEbenen : Array[0..3] Of ^Byte; AktEbene : Byte; IH1 : Integer; PB1 : ^Byte; BH1 : Byte; WH1, WH2, WH3 : Word; SH1 : String[79]; BreakTrue : Boolean; OK : Boolean; Zaehler : Integer; Begin ShowPCXPicFromRAM := Nil; (* Anzahl der Blocks lesen: *) CountDataBlocks := (ALAENGE - SizeOf(PCXFarbSkala256)) Div BlockReadSize; If (ALaenge - SizeOf(PCXFarbSkala256)) Mod BlockReadSize > 0 Then Inc(CountDataBlocks); ByteInLastBlock := (ALaenge - SizeOf(PCXFarbSkala256)) Mod BlockReadSize -1; (* Header lesen: *) PB1 := @PCXHeader; Move(APtr^, PB1^, SizeOf(PCXHeader)); (* Lade Farbskala: *) If AUsePal And (PCXHeader.Version >= 5) Then Begin LongInt(APtr) := LongInt(APtr) + ALaenge - 768; PB1 := @PCXFarbSkala256; Move(APtr^, PB1^, 768); LongInt(APtr) := LongInt(APtr) - ALaenge + 768; If ASetPal Then SetPalette(PCXFarbSkala256); ShowPCXPicFromRAM := @PCXFarbSkala256; End; (* Datens„tze lesen: *) BlocksRead := 0; AktEbene := 0; ByteReadInBlock := 0; GetMem(PDatenIn4er, 320*200); (* Speicher fr 1 Bild reservieren. *) LongInt(PEbenen[0]) := LongInt(PDatenIn4er) + 0 * ((320 * 200) Div 4); LongInt(PEbenen[1]) := LongInt(PDatenIn4er) + 1 * ((320 * 200) Div 4); LongInt(PEbenen[2]) := LongInt(PDatenIn4er) + 2 * ((320 * 200) Div 4); LongInt(PEbenen[3]) := LongInt(PDatenIn4er) + 3 * ((320 * 200) Div 4); GetMem(PBlockDaten, BlockReadSize); BreakTrue := False; OK := False; Zaehler := 1; While (BlocksRead <= CountDataBlocks) Do Begin (* Zeiger zum einlesen: *) Move(APtr^, PBlockDaten^, BlockReadSize); Inc(LongInt(APtr), BlockReadSize); ByteReadInBlock := 0; Inc(BlocksRead); PB1 := PBlockDaten; (* Ein Satz entpacken und gleich in die richtigen Ebenen verteilen: *) If BlocksRead = 1 Then (* Header berspringen. *) Begin Inc(PB1, 128); Inc(ByteReadInBlock, 128); End; While LongInt(PB1) < LongInt(PBlockDaten)+BlockReadSize Do Begin If (Not OK) And (PB1^ >= 192) Then Begin Zaehler := PB1^ - 192; OK := False; End; If (Not OK) And (PB1^ < 192) Then Begin Zaehler := 1; OK := True; End; If (OK) Then Begin For IH1 := 1 To Zaehler Do Begin PEbenen[AktEbene]^ := PB1^; Inc(PEbenen[AktEbene]); Inc(AktEbene); If AktEbene > 3 Then AktEbene := 0; End; Inc(PB1); Inc(ByteReadInBlock); OK := False; End Else Begin OK := True; Inc(PB1); Inc(ByteReadInBlock); End; If (BlocksRead >= CountDataBlocks) And (ByteReadInBlock >= ByteInLastBlock) Then Begin BreakTrue := True; Break; End; End; If BreakTrue Then Break; End; FreeMem(PBlockDaten, BlockReadSize); (* PBLOCKDATEN^ Ebenenweise auf Schirm bringen: *) WH1 := Seg(PDatenIn4er^); WH2 := Ofs(PDatenIn4er^); WH3 := PAdr[APage]; AktEbene := 1; Asm push ds mov ax, ScreenSeg mov es, ax (* ES = ZielSegment. *) mov ax, WH1 mov ds, ax (* DS = QuellSegment. *) mov ax, WH2 mov si, ax (* SI = QuellOffset. *) (* Ebenen ausgeben: *) mov cx, 4 (* Alle Ebenen durch. *) @EineEbene: push cx mov ax, WH3 mov bx, ax (* BX = ZielOffset. *) mov ah, AktEbene mov al, 2 (* AL = Index Map Mask Register. *) mov dx, 3C4h out dx, ax (* Ebene w„hlen. *) mov cx, ScreenSize / 2 (* BYTES -> WORDS. *) (* Alle Daten von 1 Ebene ausgeben: *) (* CX = Anzahl Bytes, *) (* ES = Bildschirm-Segment, *) (* BX = Bildschirm-Offset, *) (* DS = Spritedaten-Segment, *) (* SI = Spritedaten-Offset. *) stc (* BX so verringern, daá es zusammen *) sbb bx, si (* mit SI zugleich als Zielindex *) (* verwendet werden kann. *) dec bx @AllePunkteEinerEbene: lodsw (* 1 Byte holen. *) mov es:[bx+si], ax (* šbertragen. *) loop @AllePunkteEinerEbene (* N„chstes Byte. *) pop cx mov al, AktEbene (* N„chste Ebene. *) shl al, 1 mov AktEbene, al loop @EineEbene pop ds End; FreeMem(PDatenIn4er, 320*200); (* Speicher fr 1 Bild freigeben. *) VGA_Error := VGA_Error_OK;
Program Running_Man; Uses Crt,Graph; Const MaxX = 640; MaxY = 480; Right = True; Left = False; Rad = Pi/180; BodyA = -70*Rad; HeadR = 5; BodyL = 30; HipL = 15; ShinL = 15; ArmL = 15; SholderL = 15; Type tHead = Record x,y,Rad : Integer; end; tManPart = Record x,y : Integer; Angle : Real end; tSide = Boolean; tArms = Array [tSide] of tManPart; Var Head : tHead; Body : tManPart; Sholders : tArms; Arms : tArms; Hips : tArms; Shins : tArms; Procedure GraphInit; Var Gd,Gm : Integer; Res : Word; Begin Gd:=VGA; Gm:=VgaHi; InitGraph(Gd,Gm,''); Res:=IoResult; if Res<>0 then WriteLn('Graphics error : ',GraphErrorMsg(Res)) End; Procedure InitMan(aX,aY : Integer); Begin With Body do begin x:=aX; y:=aY; Angle:=BodyA end; With Head do Begin x:=Round(BodyL*Cos(BodyA))+2; y:=Round(BodyL*Sin(BodyA))+2 End; End; Procedure DrawMan; Var lx,ly : Integer; Begin SetColor(White); SetFillStyle(SolidFIll,White); SetLineStyle(SolidLn,0,ThickWidth); With Body do begin lx:=x; ly:=y; Line(x,y,x+Round(BodyL*Cos(BodyA)),y+Round(BodyL*Sin(BodyA))); end; With Head do Circle(lx+x,ly+y,Rad); End; Begin GraphInit; InitMan(320,240); DrawMan; ReadKey; CloseGraph End.
unit m3RootStream; // Модуль: "w:\common\components\rtl\Garant\m3\m3RootStream.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tm3RootStream" MUID: (53FDE7290320) {$Include w:\common\components\rtl\Garant\m3\m3Define.inc} interface uses l3IntfUses , ActiveX , l3Logger , m3BaseHeaderStream ; type Rm3RootStream = class of Tm3RootStream; Tm3RootStreamHeader = packed record {* Заголовок потока в котором живет IStorage. Данные определяются через пользовательскую секцию, чтобы они не дай бог местами не переставились. } //#UC START# *53FEFB4C03AEpubl* rZerroFrontierByte: Byte; {* - начальный ноль. } rFirstFreeFATElement: Int64; {* - первый свободный элемент FAT. } rRootStorageFATElement: Int64; {* - начальная позиция корня IStorage. } rFirstFreeCluster: Int64; {* - первый свободный кластер. } rClusterBodySize: LongInt; {* - размер ТЕЛА кластера. } rAllocatedStreamSize: Int64; {* - размер корневого потока. } //#UC END# *53FEFB4C03AEpubl* end;//Tm3RootStreamHeader _HeaderType_ = Tm3RootStreamHeader; {$Include w:\common\components\rtl\Garant\m3\m3RootStream.imp.pas} Tm3RootStream = class(_m3RootStream_) public procedure ForceLockHeader; {* Гарантированно блокирует заголовок потока. } class function HeaderID: TCLSID; override; class function DefaultHeaderValue: _HeaderType_; override; end;//Tm3RootStream implementation uses l3ImplUses , m3StorageBlock , SysUtils , m2AddDbg , m2AddPrc , m2COMLib , m2MemLib , l3Base , ComObj , m3Const , Windows //#UC START# *53FDE7290320impl_uses* //#UC END# *53FDE7290320impl_uses* ; {$Include w:\common\components\rtl\Garant\m3\m3RootStream.imp.pas} procedure Tm3RootStream.ForceLockHeader; {* Гарантированно блокирует заголовок потока. } //#UC START# *542BEDF501C7_53FDE7290320_var* const cMaxTry = 1000; var l_TryCount : Integer; l_S : AnsiString; //#UC END# *542BEDF501C7_53FDE7290320_var* begin //#UC START# *542BEDF501C7_53FDE7290320_impl* l_TryCount := 0; while (l_TryCount < cMaxTry) do begin Inc(l_TryCount); try LockHeader; except on E: EOleSysError do if (E.ErrorCode = STG_E_LOCKVIOLATION) then begin if (l_TryCount < cMaxTry) then begin l_S := 'Попытка залочить заголовок номер ' + IntToStr(l_TryCount); l3System.Msg2Log(l_S); if (Logger <> nil) then Logger.ToLog(l_S); Sleep(0); continue; end//l_TryCount < cMaxTry else raise; end//E.ErrorCode = STG_E_LOCKVIOLATION else raise; end;//try..except break; end;//while (l_TryCount < cMaxTry) //#UC END# *542BEDF501C7_53FDE7290320_impl* end;//Tm3RootStream.ForceLockHeader class function Tm3RootStream.HeaderID: TCLSID; //#UC START# *53FDFAF900ED_53FDE7290320_var* const cHeaderID : TCLSID = '{37E90B6E-5CBC-4EB3-BF2C-75EDF2924172}'; //#UC END# *53FDFAF900ED_53FDE7290320_var* begin //#UC START# *53FDFAF900ED_53FDE7290320_impl* Result := cHeaderID; //#UC END# *53FDFAF900ED_53FDE7290320_impl* end;//Tm3RootStream.HeaderID class function Tm3RootStream.DefaultHeaderValue: _HeaderType_; //#UC START# *53FF37DC003A_53FDE7290320_var* const CHeaderData000 : Tm3RootStreamHeader = ( rZerroFrontierByte: 0; rFirstFreeFATElement: Int64(-1); rRootStorageFATElement: Int64(-1); rFirstFreeCluster: Int64(-1); rClusterBodySize: m3ClusterSize - SizeOf(Tm3StorageBlockHeader); rAllocatedStreamSize: 0 ); //#UC END# *53FF37DC003A_53FDE7290320_var* begin //#UC START# *53FF37DC003A_53FDE7290320_impl* Result := CHeaderData000; //#UC END# *53FF37DC003A_53FDE7290320_impl* end;//Tm3RootStream.DefaultHeaderValue end.
unit GX_TabOrder; {$I GX_CondDefine.inc} interface uses Classes, Forms, Controls, ExtCtrls, ToolsAPI, ComCtrls, StdCtrls, GX_BaseForm; type TfmTabOrder = class(TfmBaseForm) gbxComponents: TGroupBox; btnOK: TButton; btnClose: TButton; btnHelp: TButton; pnlButtons: TPanel; pnlComponents: TPanel; btnOrderByPosition: TButton; btnResetOrder: TButton; pnlComponentTree: TPanel; tvComps: TTreeView; procedure btnHelpClick(Sender: TObject); procedure tvCompsDragDrop(Sender, Source: TObject; X, Y: Integer); procedure tvCompsDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure tvCompsClick(Sender: TObject); procedure tvCompsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnOrderByPositionClick(Sender: TObject); procedure btnResetOrderClick(Sender: TObject); private FormEditor: IOTAFormEditor; FBiDiMode: TBiDiMode; procedure ChildComponentCallback(Param: Pointer; Component: IOTAComponent; var Result: Boolean); procedure SelectCurrentComponent; procedure FillTreeView(FromComponent: IOTAComponent); procedure ShowOrderButtons(Value: Boolean); procedure SortTreeViewComponentsByXYPosition; procedure SortTreeViewComponentsByOriginalTabOrder; end; implementation {$R *.dfm} uses SysUtils, TypInfo, ActnList, GX_Experts, GX_GxUtils, GX_GenericUtils, GX_OtaUtils; const TabOrderPropertyName = 'TabOrder'; TabStopPropertyName = 'TabStop'; TopPropertyName = 'Top'; LeftPropertyName = 'Left'; type TComponentData = class(TComponent) public X: Integer; Y: Integer; TabOrder: Integer; end; TTabExpert = class(TGX_Expert) private function GetSelectedComponentsFromCurrentForm(FormEditor: IOTAFormEditor; var ParentName, ParentType: WideString): TInterfaceList; procedure ShowTabOrderForm; protected procedure UpdateAction(Action: TCustomAction); override; public function GetActionCaption: string; override; class function GetName: string; override; procedure Execute(Sender: TObject); override; function HasConfigOptions: Boolean; override; function HasDesignerMenuItem: Boolean; override; end; { TfmTabOrder } procedure TfmTabOrder.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 11); end; procedure TfmTabOrder.SelectCurrentComponent; var Component: IOTAComponent; i: Integer; begin if Assigned(FormEditor) and Assigned(tvComps.Selected) then begin i := Pos(':', tvComps.Selected.Text); if i > 0 then Component := FormEditor.FindComponent(Copy(tvComps.Selected.Text, 1, i-1)) else Component := FormEditor.FindComponent(tvComps.Selected.Text); if Assigned(Component) then Component.Select(False) else FormEditor.GetRootComponent.Select(False); end; end; procedure TfmTabOrder.ChildComponentCallback(Param: Pointer; Component: IOTAComponent; var Result: Boolean); var ComponentData: TComponentData; TreeNode: TTreeNode; AName: WideString; begin if (GxOtaPropertyExists(Component, TabStopPropertyName) and GxOtaPropertyExists(Component, TabOrderPropertyName)) or (Component.GetControlCount > 0) then begin // These are freed by the owner form ComponentData := TComponentData.Create(Self); ShowOrderButtons(True); Component.GetPropValueByName(LeftPropertyName, ComponentData.X); Component.GetPropValueByName(TopPropertyName, ComponentData.Y); Component.GetPropValueByName(TabOrderPropertyName, ComponentData.TabOrder); AName := GxOtaGetComponentName(Component); TreeNode := tvComps.Items.AddChildObject(TTreeNode(Param), AName + ': ' + Component.GetComponentType, ComponentData); Component.GetChildren(TreeNode, ChildComponentCallback); end; Result := True; end; function CustomSortProcByPos(Node1, Node2: TTreeNode; Data: Integer): Integer; stdcall; begin Result := 0; if Assigned(Node1) and Assigned(Node2) and Assigned(Node1.Data) and Assigned(Node2.Data) then begin Result := TComponentData(Node1.Data).Y - TComponentData(Node2.Data).Y; if Result = 0 then begin if TBiDiMode(Data) in [bdRightToLeft, bdRightToLeftNoAlign, bdRightToLeftReadingOnly] then Result := TComponentData(Node2.Data).X - TComponentData(Node1.Data).X else Result := TComponentData(Node1.Data).X - TComponentData(Node2.Data).X; end; end; end; function CustomSortProcByTabOrder(Node1, Node2: TTreeNode; Data: Integer): Integer; stdcall; begin Result := 0; if Assigned(Node1) and Assigned(Node2) and Assigned(Node1.Data) and Assigned(Node2.Data) then Result := TComponentData(Node1.Data).TabOrder - TComponentData(Node2.Data).TabOrder; end; procedure TfmTabOrder.SortTreeViewComponentsByXYPosition; begin {$T-} tvComps.CustomSort(@CustomSortProcByPos, Ord(FBiDiMode)); {$T+} end; procedure TfmTabOrder.SortTreeViewComponentsByOriginalTabOrder; begin {$T-} tvComps.CustomSort(@CustomSortProcByTabOrder, 0); {$T+} end; procedure TfmTabOrder.FillTreeView(FromComponent: IOTAComponent); begin if tvComps.Items.GetFirstNode <> nil then FromComponent.GetChildren(tvComps.Items.GetFirstNode, ChildComponentCallback); end; procedure TfmTabOrder.ShowOrderButtons(Value: Boolean); begin btnOrderByPosition.Visible := Value; btnResetOrder.Visible := Value; end; { TTabExpert } procedure TTabExpert.UpdateAction(Action: TCustomAction); begin Action.Enabled := GxOtaCurrentlyEditingForm; end; procedure TTabExpert.Execute(Sender: TObject); begin ShowTabOrderForm; end; function TTabExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Set Tab &Order...'; begin Result := SMenuCaption; end; class function TTabExpert.GetName: string; begin Result := 'SetTabOrder'; end; function TTabExpert.GetSelectedComponentsFromCurrentForm(FormEditor: IOTAFormEditor; var ParentName, ParentType: WideString): TInterfaceList; resourcestring SSameParentRequired = 'All selected controls must have the same parent.'; SNoComponentInterface = 'Unable to obtain component interface for component %d. ' + 'Make sure all selected components are descendents of TWinControl/' + 'TWidgetControl and have valid Parent properties.'; var CurrentComponent: IOTAComponent; {$IFNDEF GX_VER160_up} CurrentComponentParent: TComponent; NativeComponent: TComponent; BaseComponentParent: TComponent; {$ELSE GX_VER160_up} CurrentComponentParent: IOTAComponent; BaseComponentParent: IOTAComponent; {$ENDIF GX_VER160_up} i: Integer; ComponentSelCount: Integer; begin ParentName := ''; Result := TInterfaceList.Create; try BaseComponentParent := nil; ComponentSelCount := FormEditor.GetSelCount; for i := 0 to ComponentSelCount - 1 do begin CurrentComponent := FormEditor.GetSelComponent(i); if not Assigned(CurrentComponent) then raise Exception.CreateFmt(SNoComponentInterface, [i]); // All selected components need to have the same parent {$IFNDEF GX_VER160_up} NativeComponent := GxOtaGetNativeComponent(CurrentComponent); Assert(Assigned(NativeComponent)); CurrentComponentParent := NativeComponent.GetParentComponent; if not Assigned(CurrentComponentParent) then Continue // Ignore components without a parent (non-visual components) else if BaseComponentParent = nil then BaseComponentParent := CurrentComponentParent; if BaseComponentParent <> CurrentComponentParent then raise Exception.Create(SSameParentRequired); {$ELSE GX_VER160_up} CurrentComponentParent := CurrentComponent.GetParent; if not Assigned(CurrentComponentParent) then Continue // Ignore components without a parent (non-visual components) else if BaseComponentParent = nil then BaseComponentParent := CurrentComponentParent; if not GxOtaComponentsAreEqual(BaseComponentParent, CurrentComponentParent) then raise Exception.Create(SSameParentRequired); {$ENDIF GX_VER160_up} // Only use controls with a TabStop property of // type Boolean (which is an enumeration) if CurrentComponent.GetPropTypeByName('TabStop') = tkEnumeration then begin // ... and make dead sure that they have the relevant properties if GxOtaPropertyExists(CurrentComponent, TabStopPropertyName) and GxOtaPropertyExists(CurrentComponent, TabOrderPropertyName) then begin if ParentName = '' then begin {$IFNDEF GX_VER160_up} ParentName := BaseComponentParent.Name; ParentType := BaseComponentParent.ClassName; {$ELSE GX_VER160_up} ParentName := GxOtaGetComponentName(BaseComponentParent); ParentType := BaseComponentParent.GetComponentType; {$ENDIF GX_VER160_up} end; Result.Add(CurrentComponent); end; end; end; except FreeAndNil(Result); raise; end; end; function TTabExpert.HasConfigOptions: Boolean; begin Result := False; end; procedure TTabExpert.ShowTabOrderForm; resourcestring SNoFormForCurrentModule = 'There is no form for the current source module.'; var FormEditor: IOTAFormEditor; ComponentList: TInterfaceList; ParentName, ParentType: WideString; AComponentName, AComponentType: WideString; TabOrderForm: TfmTabOrder; AComponent: IOTAComponent; TreeNode: TTreeNode; IsMultiSelection: Boolean; i: Integer; ComponentData: TComponentData; FirstTabOrder: Integer; procedure UseRootComponent; begin AComponent := FormEditor.GetRootComponent; Assert(Assigned(AComponent)); ParentType := AComponent.GetComponentType; ParentName := GxOtaGetComponentName(AComponent); end; begin ComponentList := nil; AComponent := nil; IsMultiSelection := False; FirstTabOrder := -1; if not GxOtaTryGetCurrentFormEditor(FormEditor) then raise Exception.Create(SNoFormForCurrentModule); if FormEditor.GetSelCount > 1 then begin IsMultiSelection := True; ComponentList := GetSelectedComponentsFromCurrentForm(FormEditor, ParentName, ParentType); if ComponentList.Count = 0 then Exit; end else if (FormEditor.GetSelCount = 1) then begin AComponent := IOTAComponent(FormEditor.GetSelComponent(0)); if AComponent.GetControlCount = 0 then UseRootComponent else begin ParentType := AComponent.GetComponentType; ParentName := GxOtaGetComponentName(AComponent); end; end else UseRootComponent; TabOrderForm := TfmTabOrder.Create(nil); try TabOrderForm.ShowOrderButtons(False); TabOrderForm.FormEditor := FormEditor; SetFormIcon(TabOrderForm); TreeNode := TabOrderForm.tvComps.Items.Add(nil, ParentName + ': ' + ParentType); if IsMultiSelection then begin if Assigned(ComponentList) then try if ComponentList.Count > 0 then begin for i := 0 to ComponentList.Count-1 do begin AComponent := ComponentList.Items[i] as IOTAComponent; Assert(Assigned(AComponent)); AComponentType := AComponent.GetComponentType; AComponentName := GxOtaGetComponentName(AComponent); ComponentData := TComponentData.Create(TabOrderForm); TabOrderForm.ShowOrderButtons(True); AComponent.GetPropValueByName('Left', ComponentData.X); AComponent.GetPropValueByName('Top', ComponentData.Y); AComponent.GetPropValueByName(TabOrderPropertyName, ComponentData.TabOrder); if (FirstTabOrder > ComponentData.TabOrder) or (FirstTabOrder = -1) then FirstTabOrder := ComponentData.TabOrder; AComponentName := GxOtaGetComponentName(AComponent); TabOrderForm.tvComps.Items.AddChildObject(TreeNode, AComponentName + ': ' + AComponentType,ComponentData); end; end; finally FreeAndNil(ComponentList); end; end else begin TabOrderForm.FBiDiMode := GxOtaGetFormBiDiMode(FormEditor); TabOrderForm.FillTreeView(AComponent); TabOrderForm.SortTreeViewComponentsByXYPosition; end; TabOrderForm.tvComps.FullExpand; TabOrderForm.tvComps.Selected := TabOrderForm.tvComps.Items.GetFirstNode; CenterForm(TabOrderForm); if FirstTabOrder < 0 then FirstTabOrder := 0; if TabOrderForm.ShowModal = mrOk then begin TreeNode := TabOrderForm.tvComps.Items.GetFirstNode; TreeNode := TreeNode.GetNext; while TreeNode <> nil do begin AComponent := FormEditor.FindComponent(Copy(TreeNode.Text, 1, Pos(':', TreeNode.Text)-1)); if AComponent <> nil then begin i := TreeNode.Index + FirstTabOrder; AComponent.SetPropByName('TabOrder', i); end; TreeNode := TreeNode.GetNext; end; end; finally FreeAndNil(TabOrderForm); end; end; procedure TfmTabOrder.tvCompsDragDrop(Sender, Source: TObject; X, Y: Integer); var TargetNode, SourceNode: TTreeNode; begin TargetNode := TTreeView(Sender).GetNodeAt(X, Y); if TargetNode <> nil then begin SourceNode := TTreeView(Sender).Selected; SourceNode.MoveTo(TargetNode, naInsert); TTreeView(Sender).Selected := TargetNode; end; end; procedure TfmTabOrder.tvCompsDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var TargetNode: TTreeNode; SourceNode: TTreeNode; begin Assert(Sender is TTreeView); TargetNode := TTreeView(Sender).GetNodeAt(X, Y); SourceNode := TTreeView(Sender).Selected; Assert(Assigned(SourceNode)); if SourceNode = TargetNode then Accept := False else if (Source = Sender) and (TargetNode <> nil) then Accept := SourceNode.Parent = TargetNode.Parent else Accept := False; end; procedure TfmTabOrder.tvCompsClick(Sender: TObject); begin SelectCurrentComponent; end; procedure TfmTabOrder.tvCompsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin SelectCurrentComponent; end; procedure TfmTabOrder.btnOrderByPositionClick(Sender: TObject); begin SortTreeViewComponentsByXYPosition; end; procedure TfmTabOrder.btnResetOrderClick(Sender: TObject); begin SortTreeViewComponentsByOriginalTabOrder; end; function TTabExpert.HasDesignerMenuItem: Boolean; begin Result := True; end; initialization RegisterGX_Expert(TTabExpert); end.
unit k007232; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} sound_engine,timer_engine; const KDAC_A_PCM_MAX=2; type tk007232_call_back=procedure (valor:byte); k007232_chip=class(snd_chip_class) constructor create(clock:dword;rom_adpcm:pbyte;size:dword;amplifi:single;call_back:tk007232_call_back;stereo:boolean=false); destructor free; public procedure update; procedure set_volume(channel,volumeA,volumeB:byte); procedure write(direccion,valor:byte); function read(direccion:byte):byte; procedure set_bank(banka,bankb:byte); private vol:array[0..KDAC_A_PCM_MAX-1,0..1] of byte; // volume for the left and right channel address,start,step,bank:array[0..KDAC_A_PCM_MAX-1] of dword; play:array[0..KDAC_A_PCM_MAX-1] of boolean; wreg:array[0..$f] of byte; //write data pcmlimit:dword; ntimer:byte; fncode:array[0..$1ff] of dword; call_back:tk007232_call_back; rom:pbyte; out1,out2:integer; tsample_num2:byte; stereo:boolean; procedure internal_update; end; procedure internal_update_k007232(index:byte); procedure internal_update_k007232_0; procedure internal_update_k007232_1; var k007232_0,k007232_1:k007232_chip; chips_total:integer=-1; implementation const BASE_SHIFT=12; constructor k007232_chip.create(clock:dword;rom_adpcm:pbyte;size:dword;amplifi:single;call_back:tk007232_call_back;stereo:boolean=false); var f:word; begin chips_total:=chips_total+1; // Set up the chips */ self.pcmlimit:=size; self.call_back:=call_back; self.clock:=clock; for f:=0 to (KDAC_A_PCM_MAX-1) do begin self.address[f]:=0; self.start[f]:=0; self.step[f]:=0; self.play[f]:=false; self.bank[f]:=0; end; self.vol[0,0]:=255; // channel A output to output A */ self.vol[0,1]:=0; self.vol[1,0]:=0; self.vol[1,1]:=255; // channel B output to output B */ self.amp:=amplifi; for f:=0 to $f do self.wreg[f]:=0; self.ntimer:=timers.init(sound_status.cpu_num,sound_status.cpu_clock/(clock/128),nil,internal_update_k007232,true,chips_total); self.tsample_num:=init_channel; self.tsample_num2:=init_channel; self.rom:=rom_adpcm; //KDAC_A_make_fncode; for f:=0 to $1ff do self.fncode[f]:=round((32 shl BASE_SHIFT)/($200-f)); self.stereo:=stereo; end; destructor k007232_chip.free; begin chips_total:=chips_total-1; end; procedure k007232_chip.write(direccion,valor:byte); var r,idx:word; v,reg_port:byte; begin r:=direccion; v:=valor; self.wreg[r]:=v; //store write data case r of $c:if (@self.call_back<>nil) then self.call_back(v); // external port, usually volume control $d:; // loopflag. else begin if (r>=$06) then begin reg_port:=1; r:=r-$06; end else reg_port:=0; case r of 0,1:begin //*** address step **** idx:=((self.wreg[reg_port*6+1] shl 8) and $100) or self.wreg[reg_port*6]; self.step[reg_port]:=self.fncode[idx]; end; 2,3,4:; 5:begin //*** start address **** self.start[reg_port]:=((self.wreg[reg_port*6+4] and 1) shl 16) or (self.wreg[reg_port*6+3] shl 8) or self.wreg[reg_port*6+2] or self.bank[reg_port]; if (self.start[reg_port]<self.pcmlimit) then begin self.play[reg_port]:=true; self.address[reg_port]:=0; end; end; end; end; end; end; function k007232_chip.read(direccion:byte):byte; var r:byte; ch:byte; begin r:=direccion; ch:=0; if ((r=$5) or (r=$b)) then begin ch:=r div 6; r:=ch*6; self.start[ch]:=((self.wreg[r+4] and 1) shl 16) or (self.wreg[r+3] shl 8) or (self.wreg[r+2]) or self.bank[ch]; if (self.start[ch]<self.pcmlimit) then begin self.play[ch]:=true; self.address[ch]:=0; end; end; read:=0; end; procedure k007232_chip.set_volume(channel,volumeA,volumeB:byte); begin self.vol[channel,0]:=volumeA; self.vol[channel,1]:=volumeB; end; procedure k007232_chip.set_bank(banka,bankb:byte); begin self.bank[0]:=banka shl 17; self.bank[1]:=bankb shl 17; end; procedure k007232_chip.internal_update; var f:byte; addr,old_addr:dword; volA,volB:word; begin self.out1:=0; self.out2:=0; for f:=0 to (KDAC_A_PCM_MAX-1) do begin if self.play[f] then begin //*** PCM setup ****/ addr:=self.start[f]+((self.address[f] shr BASE_SHIFT) and $fffff); volA:=self.vol[f,0]*2; volB:=self.vol[f,1]*2; old_addr:=addr; addr:=self.start[f]+((self.address[f] shr BASE_SHIFT) and $fffff); while (old_addr<=addr) do begin if (((self.rom[old_addr] and $80)<>0) or (old_addr>=self.pcmlimit)) then begin // end of sample if (self.wreg[$d] and (1 shl f))<>0 then begin // loop to the beginning self.start[f]:=((self.wreg[f*6+4] and 1) shl 16) or (self.wreg[f*6+3] shl 8) or (self.wreg[f*6+2]) or self.bank[f]; addr:=self.start[f]; self.address[f]:=0; old_addr:=addr; // skip loop end else self.play[f]:=false; // stop sample break; end; old_addr:=old_addr+1; end; if not(self.play[f]) then break; self.address[f]:=self.address[f]+self.step[f]; self.out1:=self.out1+(((self.rom[addr] and $7f)-$40)*volA); self.out2:=self.out2+(((self.rom[addr] and $7f)-$40)*volB); end; end; end; procedure internal_update_k007232(index:byte); begin case index of 0:k007232_0.internal_update; 1:k007232_1.internal_update; end; end; procedure internal_update_k007232_0; begin k007232_0.internal_update; end; procedure internal_update_k007232_1; begin k007232_1.internal_update; end; procedure k007232_chip.update; begin if sound_status.stereo then begin if self.stereo then begin tsample[self.tsample_num,sound_status.posicion_sonido]:=round(self.out1*self.amp); tsample[self.tsample_num,sound_status.posicion_sonido+1]:=round(self.out2*self.amp); end else begin tsample[self.tsample_num,sound_status.posicion_sonido]:=round(self.out1*self.amp); tsample[self.tsample_num,sound_status.posicion_sonido+1]:=round(self.out1*self.amp); tsample[self.tsample_num2,sound_status.posicion_sonido]:=round(self.out2*self.amp); tsample[self.tsample_num2,sound_status.posicion_sonido+1]:=round(self.out2*self.amp); end; end else begin //Channel 1 tsample[self.tsample_num,sound_status.posicion_sonido]:=round(self.out1*self.amp); //Channel 2 tsample[self.tsample_num2,sound_status.posicion_sonido]:=round(self.out2*self.amp); end; end; end.
unit lgTypes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/lgTypes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> F1 Базовые определения предметной области::F1 Application Template::View::lgTypes // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface type TlgQueryType = ( {* Тип запроса на поиск } lg_qtNone // неопределенный тип запроса , lg_qtKeyWord // по ситуации , lg_qtAttribute // по реквизитам (новый) , lg_qtPublishedSource // по источнику опубликования , lg_qtPostingOrder // заказ рассылки , lg_qtLegislationReview // обзор законадательства , lg_qtSendConsultation // запрос на правовую поддержку, при этом поиск не осуществляется, запрос уходит на обработку в компанию Гарант , lg_qtBaseSearch // базовый поиск , lg_qtInpharmSearch // лекарственного препарата );//TlgQueryType implementation end.
unit Main; interface //#################################################################### ■ uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, WinApi.Windows, vulkan_core, vulkan.util, vulkan.util_init, LUX, LUX.D3, LUX.D4x4, LUX.GPU.Vulkan; type TForm1 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { private 宣言 } const sample_title = 'Draw Textured Cube'; function CreateWindow( const ClientW_,ClientH_:Integer ) :HWND; procedure DestroWindow( const Window_:HWND ); function CalcMatrix :TSingleM4; public { public 宣言 } _Window :HWND; _Vulkan :TVulkan; _Instan :TVkInstan; _Surfac :TVkSurfac; _Device :TVkDevice; _Pooler :TVkPooler; _Comman :TVkComman; _Swapch :TVkSwapch; _Depthr :TVkDepthr; _Textur :TVkTextur; _Buffer :TVkUniBuf<TSingleM4>; _Pipeli :TVkPipeli; _ShaderV :TVkShaderVert; _ShaderF :TVkShaderFrag; imageAcquiredSemaphore :VkSemaphore; drawFence :VkFence; end; var Form1: TForm1; implementation //############################################################### ■ {$R *.fmx} uses System.Math, WinApi.Messages, cube_data; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private procedure run( var info:T_sample_info ); begin (* Placeholder for samples that want to show dynamic content *) end; function WndProc( hwnd:HWND; uMsg:UINT; wParam:WPARAM; lParam:LPARAM ) :LRESULT; stdcall; var Info :P_sample_info; begin Info := P_sample_info( GetWindowLongPtr( hWnd, GWLP_USERDATA ) ); case uMsg of WM_CLOSE: PostQuitMessage( 0 ); WM_PAINT: begin run( Info^ ); //Exit( 0 ); end; else end; Result := DefWindowProc( hWnd, uMsg, wParam, lParam ); end; function TForm1.CreateWindow( const ClientW_,ClientH_:Integer ) :HWND; var C :LPCWSTR; M :HINST; W :WNDCLASSEX; R :TRect; begin C := 'Sample'; M := HInstance; // Initialize the window class structure: with W do begin cbSize := SizeOf( WNDCLASSEX ); style := CS_HREDRAW or CS_VREDRAW; lpfnWndProc := @WndProc; cbClsExtra := 0; cbWndExtra := 0; hInstance := M; // hInstance hIcon := LoadIcon( 0, IDI_APPLICATION ); hCursor := LoadCursor( 0, IDC_ARROW ); hbrBackground := HBRUSH( GetStockObject( WHITE_BRUSH ) ); lpszMenuName := nil; lpszClassName := C; hIconSm := LoadIcon( 0, IDI_WINLOGO ); end; // Register window class: if RegisterClassEx( W ) = 0 then begin // It didn't work, so try to give a useful error: Log.d( 'Unexpected error trying to start the application!' ); RunError( 1 ); end; // Create window with the registered class: R := TRect.Create( 0, 0, ClientW_, ClientH_ ); AdjustWindowRect( R, WS_OVERLAPPEDWINDOW, False ); Result := CreateWindowEx( 0, C, // class name C, // app name WS_OVERLAPPEDWINDOW or WS_VISIBLE or WS_SYSMENU, // window style 100, 100, // x/y coords R.Width, // width R.Height, // height 0, // handle to parent 0, // handle to menu M, // hInstance nil ); // no extra parameters if Result = 0 then begin // It didn't work, so try to give a useful error: Log.d( 'Cannot create a window in which to draw!' ); RunError( 1 ); end; SetWindowLongPtr( Result, GWLP_USERDATA, LONG_PTR( @_Vulkan.Info ) ); end; procedure TForm1.DestroWindow( const Window_:HWND ); begin DestroyWindow( Window_ ); end; //------------------------------------------------------------------------------ function TForm1.CalcMatrix :TSingleM4; var fov :Single; Projection :TSingleM4; View :TSingleM4; Model :TSingleM4; Clip :TSingleM4; begin fov := DegToRad( 45 ); Projection := TSingleM4.ProjPersH( fov, 1, 0.1, 100 ); View := TSingleM4.LookAt( TSingle3D.Create( -5, +3, -10 ), // Camera is at (-5,3,-10), in World Space TSingle3D.Create( 0, 0, 0 ), // and looks at the origin TSingle3D.Create( 0, -1, 0 ) ); // Head is up (set to 0,-1,0 to look upside-down) Model := TSingleM4.Identity; // Vulkan clip space has inverted Y and half Z. Clip := TSingleM4.Create( +1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, +0.5, +0.5, 0.0, 0.0, 0.0, +1.0 ); Result := Clip * Projection *View * Model; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& procedure TForm1.FormCreate(Sender: TObject); const depthPresent :Boolean = True; var res :VkResult; clear_values :array [ 0..2-1 ] of VkClearValue; imageAcquiredSemaphoreCreateInfo :VkSemaphoreCreateInfo; rp_begin :VkRenderPassBeginInfo; offsets :array [ 0..1-1 ] of VkDeviceSize; cmd_bufs :array [ 0..1-1 ] of VkCommandBuffer; fenceInfo :VkFenceCreateInfo; pipe_stage_flags :VkPipelineStageFlags; submit_info :array [ 0..1-1 ] of VkSubmitInfo; present :VkPresentInfoKHR; begin _Window := CreateWindow( 500, 500 ); _Vulkan := TVulkan.Create; _Instan := TVkInstan.Create( _Vulkan ); //= _Vulkan.Instans.Add; _Device := _Instan.Devices[0]; _Surfac := TVkSurfac.Create( _Instan, _Window ); //= _Instan.Surfacs.Add( _Window ); _Device.Surfac := _Surfac; _Pooler := TVkPooler.Create( _Device ); _Comman := TVkComman.Create( _Pooler ); //= _Pooler.Commans.Add; _Comman.BeginRecord; _Swapch := TVkSwapch.Create( _Device ); _Depthr := TVkDepthr.Create( _Device ); _Textur := TVkTextur.Create( _Device ); _Textur.LoadFromFile( '../../_DATA/lunarg.ppm' ); _Buffer := TVkUniBuf<TSingleM4>.Create( _Device ); _Buffer.Value := CalcMatrix; init_descriptor_and_pipeline_layouts( _Vulkan, true ); init_renderpass( _Vulkan, depthPresent ); init_framebuffers( _Vulkan, depthPresent ); init_vertex_buffer( _Vulkan, @g_vb_texture_Data[0], SizeOf( T_VertexUV ) * Length( g_vb_texture_Data ), SizeOf( T_VertexUV ), True ); init_descriptor_pool( _Vulkan, True ); init_descriptor_set( _Vulkan, True ); init_pipeline_cache( _Vulkan ); _Pipeli := TVkPipeli.Create( _Device, depthPresent ); _ShaderV := TVkShaderVert.Create( _Pipeli ); _ShaderF := TVkShaderFrag.Create( _Pipeli ); _ShaderV.LoadFromFile( '../../_DATA/draw_textured_cube.vert' ); _ShaderF.LoadFromFile( '../../_DATA/draw_textured_cube.frag' ); (* VULKAN_KEY_START *) clear_values[0].color.float32[0] := 0.2; clear_values[0].color.float32[1] := 0.2; clear_values[0].color.float32[2] := 0.2; clear_values[0].color.float32[3] := 0.2; clear_values[1].depthStencil.depth := 1.0; clear_values[1].depthStencil.stencil := 0; imageAcquiredSemaphoreCreateInfo.sType := VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; imageAcquiredSemaphoreCreateInfo.pNext := nil; imageAcquiredSemaphoreCreateInfo.flags := 0; res := vkCreateSemaphore( _Device.Handle, @imageAcquiredSemaphoreCreateInfo, nil, @imageAcquiredSemaphore ); Assert( res = VK_SUCCESS ); // Get the index of the next available swapchain image: res := vkAcquireNextImageKHR( _Device.Handle, _Swapch.Handle, UINT64.MaxValue, imageAcquiredSemaphore, VK_NULL_HANDLE, @_Swapch.Framers.SelectI ); // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes Assert( res = VK_SUCCESS ); rp_begin.sType := VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rp_begin.pNext := nil; rp_begin.renderPass := _Vulkan.Info.render_pass; rp_begin.framebuffer := _Vulkan.Info.framebuffers[ _Swapch.Framers.SelectI ]; rp_begin.renderArea.offset.x := 0; rp_begin.renderArea.offset.y := 0; rp_begin.renderArea.extent.width := _Surfac.PxSizeX; rp_begin.renderArea.extent.height := _Surfac.PxSizeY; rp_begin.clearValueCount := 2; rp_begin.pClearValues := @clear_values[0]; vkCmdBeginRenderPass( _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle, @rp_begin, VK_SUBPASS_CONTENTS_INLINE ); vkCmdBindPipeline( _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle, VK_PIPELINE_BIND_POINT_GRAPHICS, _Pipeli.Handle ); vkCmdBindDescriptorSets( _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle, VK_PIPELINE_BIND_POINT_GRAPHICS, _Vulkan.Info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS, @_Vulkan.Info.desc_set[0], 0, nil ); offsets[0] := 0; vkCmdBindVertexBuffers( _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle, 0, 1, @_Vulkan.Info.vertex_buffer.buf, @offsets[0] ); init_viewports( _Vulkan ); init_scissors( _Vulkan ); vkCmdDraw( _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle, 12 * 3, 1, 0, 0 ); vkCmdEndRenderPass( _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle ); _Comman.EndRecord; cmd_bufs[0] := _Vulkan.Instans[0].Devices[0].Poolers[0].Commans[0].Handle; fenceInfo.sType := VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext := nil; fenceInfo.flags := 0; vkCreateFence( _Device.Handle, @fenceInfo, nil, @drawFence ); pipe_stage_flags := Ord( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT ); submit_info[0] := Default( VkSubmitInfo ); submit_info[0].pNext := nil; submit_info[0].sType := VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount := 1; submit_info[0].pWaitSemaphores := @imageAcquiredSemaphore; submit_info[0].pWaitDstStageMask := @pipe_stage_flags; submit_info[0].commandBufferCount := 1; submit_info[0].pCommandBuffers := @cmd_bufs[0]; submit_info[0].signalSemaphoreCount := 0; submit_info[0].pSignalSemaphores := nil; (* Queue the command buffer for execution *) res := vkQueueSubmit( _Device.QueuerG, 1, @submit_info[0], drawFence ); Assert( res = VK_SUCCESS ); (* Now present the image in the window *) present.sType := VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present.pNext := nil; present.swapchainCount := 1; present.pSwapchains := _Swapch.HandleP; present.pImageIndices := @_Swapch.Framers.SelectI; present.pWaitSemaphores := nil; present.waitSemaphoreCount := 0; present.pResults := nil; (* Make sure command buffer is finished before presenting *) repeat res := vkWaitForFences( _Device.Handle, 1, @drawFence, VK_TRUE, FENCE_TIMEOUT ); until res <> VK_TIMEOUT; Assert( res = VK_SUCCESS ); res := vkQueuePresentKHR( _Device.QueuerP, @present ); Assert( res = VK_SUCCESS ); wait_seconds( 1 ); (* VULKAN_KEY_END *) if _Vulkan.Info.save_images then write_ppm( _Vulkan, 'draw_textured_cube' ); end; procedure TForm1.FormDestroy(Sender: TObject); begin vkDestroyFence( _Device.Handle, drawFence, nil ); vkDestroySemaphore( _Device.Handle, imageAcquiredSemaphore, nil ); _Pipeli.Free; destroy_pipeline_cache( _Vulkan ); destroy_descriptor_pool( _Vulkan ); destroy_vertex_buffer( _Vulkan ); destroy_framebuffers( _Vulkan ); destroy_renderpass( _Vulkan ); destroy_descriptor_and_pipeline_layouts( _Vulkan ); _Vulkan.Free; DestroWindow( _Window ); end; end. //######################################################################### ■
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMain_Form = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main_Form: TMain_Form; implementation {$R *.dfm} uses jc.LogFile; procedure TMain_Form.Button1Click(Sender: TObject); begin TjcLog.New .SaveLog('to say hello !') end; procedure TMain_Form.Button2Click(Sender: TObject); begin TjcLog.New .ShowLog('Hello world !'); end; procedure TMain_Form.Button3Click(Sender: TObject); begin try StrToInt('jc'); except On E: Exception do TjcLog.New(Sender, E) .CustomMsg('Erro ao converter variavel') .showError; end; end; procedure TMain_Form.Button4Click(Sender: TObject); begin try StrToInt('jc'); except On E: Exception do TjcLog.New(Sender, E) .CustomMsg('Erro ao converter variavel') .SaveError; end; end; procedure TMain_Form.Button5Click(Sender: TObject); begin try StrToInt('jc'); except On E: Exception do TjcLog.New(Sender, E) .CustomMsg('Erro ao converter variavel') .showError .SaveError; end; end; procedure TMain_Form.Button6Click(Sender: TObject); begin TjcLog.New .CustomMsg('Hello world') .ShowLog .SaveLog; end; end.
unit FileUploadingActionsUnit; interface uses SysUtils, Classes, BaseActionUnit, IConnectionUnit; type TFileUploadingActions = class(TBaseAction) public function Preview(FileId: String; out ErrorString: String): TStringList; function UploadFileGeocoding(FileId: String; out ErrorString: String): TStringList; function Upload(Stream: TStream; out ErrorString: String): String; end; implementation uses System.Generics.Collections, GenericParametersUnit, CommonTypesUnit, SettingsUnit, UtilsUnit, FileUploadErrorsResponseUnit, FilePreviewErrorResponseUnit; function TFileUploadingActions.Preview(FileId: String; out ErrorString: String): TStringList; const ErrorTag = '{"status":false,"errors":["'; var Response: TObject; Parameters: TGenericParameters; ClassArray: TClassArray; begin Result := TStringList.Create; Parameters := TGenericParameters.Create; try Parameters.AddParameter('strUploadID', FileId); Parameters.AddParameter('format', 'json'); SetLength(ClassArray, 2); ClassArray[0] := TSimpleString; ClassArray[1] := TFilePreviewErrorResponse; Response := FConnection.Get(TSettings.EndPoints.CsvXlsPreview, Parameters, ClassArray, ErrorString); try if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'File Preview fault'; if (Response is TFilePreviewErrorResponse) then begin if Length(TFilePreviewErrorResponse(Response).Errors) > 0 then ErrorString := TFilePreviewErrorResponse(Response).Errors[0] else ErrorString := 'File Preview fault'; end; if (Response is TSimpleString) and (ErrorString = EmptyStr) then begin if (pos(ErrorTag, TSimpleString(Response).Value) = 0) then Result.Text := TSimpleString(Response).Value else ErrorString := 'Error'; (*todo: невозможно отличить строку {"status":false,"errors":["Upload not found"]} от контента Похоже парсинг этой строки надо производить здесь, а не в Connection *) end; finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; function TFileUploadingActions.Upload(Stream: TStream; out ErrorString: String): String; var Response: TSimpleString; Parameters: TGenericParameters; begin Result := EmptyStr; Parameters := TGenericParameters.Create; try Parameters.AddParameter('format', 'json'); Response := FConnection.Post(TSettings.EndPoints.FileUploading, Parameters, Stream, TSimpleString, ErrorString) as TSimpleString; try if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'File Upload fault'; Result := Response.Value; finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; function TFileUploadingActions.UploadFileGeocoding( FileId: String; out ErrorString: String): TStringList; var Response: TObject; Parameters: TGenericParameters; ClassArray: TClassArray; begin Result := TStringList.Create; Parameters := TGenericParameters.Create; try Parameters.AddParameter('strUploadID', FileId); SetLength(ClassArray, 2); ClassArray[0] := TSimpleString; ClassArray[1] := TFileUploadErrorsResponse; Response := FConnection.Post(TSettings.EndPoints.CsvXlsGeocode, Parameters, ClassArray, ErrorString); try if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'Upload File Geocoding fault'; if (Response is TFileUploadErrorsResponse) then begin if Length(TFileUploadErrorsResponse(Response).Errors) > 0 then ErrorString := TFileUploadErrorsResponse(Response).Errors[0] else ErrorString := 'Upload File Geocoding fault'; end; if (Response is TSimpleString) and (ErrorString = EmptyStr) then Result.Text := TSimpleString(Response).Value; finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; end.
unit nsTextWithCommentsRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/nsTextWithCommentsRes.pas" // Начат: 15.02.2011 15:23 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Core::Base Operations::View::Base Forms::nsTextWithCommentsRes // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, afwInterfaces, l3CProtoObject, l3StringIDEx ; var { Локализуемые строки ShowVersionComments } str_svcCollapsed : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'svcCollapsed'; rValue : 'В свернутом виде'); { 'В свернутом виде' } str_svcExpanded : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'svcExpanded'; rValue : 'В развернутом виде'); { 'В развернутом виде' } const { Карта преобразования локализованных строк ShowVersionComments } ShowVersionCommentsMap : array [Boolean] of Pl3StringIDEx = ( @str_svcCollapsed , @str_svcExpanded );//ShowVersionCommentsMap type ShowVersionCommentsMapHelper = {final} class {* Утилитный класс для преобразования значений ShowVersionCommentsMap } public // public methods class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Boolean; {* Преобразование строкового значения к порядковому } end;//ShowVersionCommentsMapHelper TShowVersionCommentsMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для ShowVersionCommentsMap } protected // realized methods function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TShowVersionCommentsMapImplPrim } end;//TShowVersionCommentsMapImplPrim TShowVersionCommentsMapImpl = {final} class(TShowVersionCommentsMapImplPrim) {* Класс для реализации мапы для ShowVersionCommentsMap } public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TShowVersionCommentsMapImpl } end;//TShowVersionCommentsMapImpl var { Локализуемые строки Local } str_pi_Document_ShowVersionsComment : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'pi_Document_ShowVersionsComment'; rValue : 'Показывать информацию об изменениях в тексте документа'); { 'Показывать информацию об изменениях в тексте документа' } str_pi_Document_ShowVersionsComment_Hint : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'pi_Document_ShowVersionsComment_Hint'; rValue : 'Показывать информацию об изменениях в тексте документа'); { 'Показывать информацию об изменениях в тексте документа' } str_pi_Document_SubPanel_ShowVersionComments : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'pi_Document_SubPanel_ShowVersionComments'; rValue : 'Информация об изменениях'); { 'Информация об изменениях' } {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3MessageID, l3String, SysUtils, l3Base ; // start class ShowVersionCommentsMapHelper class procedure ShowVersionCommentsMapHelper.FillStrings(const aStrings: IafwStrings); var l_Index: Boolean; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(ShowVersionCommentsMap[l_Index].AsCStr); end;//ShowVersionCommentsMapHelper.FillStrings class function ShowVersionCommentsMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Boolean; var l_Index: Boolean; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, ShowVersionCommentsMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "ShowVersionCommentsMap"', [l3Str(aDisplayName)]); end;//ShowVersionCommentsMapHelper.DisplayNameToValue // start class TShowVersionCommentsMapImplPrim class function TShowVersionCommentsMapImplPrim.Make: Il3IntegerValueMap; var l_Inst : TShowVersionCommentsMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TShowVersionCommentsMapImplPrim.pm_GetMapID: Tl3ValueMapID; {-} begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TShowVersionCommentsMapImplPrim.pm_GetMapID procedure TShowVersionCommentsMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {-} begin ShowVersionCommentsMapHelper.FillStrings(aList); end;//TShowVersionCommentsMapImplPrim.GetDisplayNames function TShowVersionCommentsMapImplPrim.MapSize: Integer; {-} begin Result := Ord(High(Boolean)) - Ord(Low(Boolean)); end;//TShowVersionCommentsMapImplPrim.MapSize function TShowVersionCommentsMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} begin Result := Ord(ShowVersionCommentsMapHelper.DisplayNameToValue(aDisplayName)); end;//TShowVersionCommentsMapImplPrim.DisplayNameToValue function TShowVersionCommentsMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; {-} begin Assert(aValue >= Ord(Low(Boolean))); Assert(aValue <= Ord(High(Boolean))); Result := ShowVersionCommentsMap[Boolean(aValue)].AsCStr; end;//TShowVersionCommentsMapImplPrim.ValueToDisplayName // start class TShowVersionCommentsMapImpl var g_TShowVersionCommentsMapImpl : Pointer = nil; procedure TShowVersionCommentsMapImplFree; begin IUnknown(g_TShowVersionCommentsMapImpl) := nil; end; class function TShowVersionCommentsMapImpl.Make: Il3IntegerValueMap; begin if (g_TShowVersionCommentsMapImpl = nil) then begin l3System.AddExitProc(TShowVersionCommentsMapImplFree); Il3IntegerValueMap(g_TShowVersionCommentsMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TShowVersionCommentsMapImpl); end; {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_svcCollapsed str_svcCollapsed.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_svcExpanded str_svcExpanded.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_pi_Document_ShowVersionsComment str_pi_Document_ShowVersionsComment.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_pi_Document_ShowVersionsComment_Hint str_pi_Document_ShowVersionsComment_Hint.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_pi_Document_SubPanel_ShowVersionComments str_pi_Document_SubPanel_ShowVersionComments.Init; {$IfEnd} //not Admin AND not Monitorings end.
unit nsJournalBookmarkNode; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Common$Lib" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Common/nsJournalBookmarkNode.pas" // Начат: 21.10.2009 19:08 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Core::Common::Common$Lib::MainMenu::TnsJournalBookmarkNode // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses DocumentUnit, l3Interfaces, l3Tree_TLB, MainMenuDomainInterfaces, nsWrapperNode, l3IID ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsJournalBookmarkNode = class(TnsWrapperNode, InsJournalBookmarkNode) private // private fields f_Bookmark : IJournalBookmark; f_DocName : Il3CString; protected // realized methods function Get_DocName: Il3CString; function Get_Bookmark: IJournalBookmark; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } public // public methods constructor Create(const aBookmark: IJournalBookmark; aFullDocName: Boolean); reintroduce; class function Make(const aBookmark: IJournalBookmark; aFullDocName: Boolean = False): Il3Node; reintroduce; end;//TnsJournalBookmarkNode {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3String, IOUnit, nsTypes, BaseTypesUnit ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsJournalBookmarkNode constructor TnsJournalBookmarkNode.Create(const aBookmark: IJournalBookmark; aFullDocName: Boolean); //#UC START# *4ADF23C202CF_4ADDF4D901D1_var* procedure lp_MakeText; const c_MaxLenght = 170; c_Suffix = ' ...'; var l_Index : Integer; l_Str : IString; begin // Показывать полное имя: if aFullDocName then begin Get_DocName; // - инициализация поля f_DocName; with f_DocName.AsWStr do if SLen > c_MaxLenght then begin // Обрезаем размер текста до c_MaxLenght, по ближайшему к 170 символу // пробелу: for l_Index := Pred(c_MaxLenght) downto 0 do if l3Compare(S[l_Index], ' ') = 0 then begin l3SetLen(f_DocName, l_Index); Break; end;//if l3Compare(S[l_Index], ' ') = 0 then // Добавим троеточие: f_DocName := l3Cat(f_DocName, c_Suffix); end;//if SLen > c_MaxLenght then // Установим название: pm_SetName(f_DocName.AsWStr); end//if aFullDocName then else // Показывать короткое имя: begin // Name f_Bookmark.GetName(l_Str); try pm_SetName(nsWStr(l_Str)); finally l_Str := nil; end;//try..finally end;//if aFullDocName then end;//lp_MakeText; procedure lp_MakeComment; var l_Str : IString; begin // Comment f_Bookmark.GetFullName(l_Str); try pm_SetComment(nsWStr(l_Str)); finally l_Str := nil; end;//try..finally end;//lp_MakeComment //#UC END# *4ADF23C202CF_4ADDF4D901D1_var* begin //#UC START# *4ADF23C202CF_4ADDF4D901D1_impl* inherited Create; if not Assigned(aBookmark) then Exit; f_Bookmark := aBookmark; lp_MakeText; lp_MakeComment; //#UC END# *4ADF23C202CF_4ADDF4D901D1_impl* end;//TnsJournalBookmarkNode.Create class function TnsJournalBookmarkNode.Make(const aBookmark: IJournalBookmark; aFullDocName: Boolean = False): Il3Node; var l_Inst : TnsJournalBookmarkNode; begin l_Inst := Create(aBookmark, aFullDocName); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TnsJournalBookmarkNode.Get_DocName: Il3CString; //#UC START# *4A8BAAA50229_4ADDF4D901D1get_var* var l_Str : IString; //#UC END# *4A8BAAA50229_4ADDF4D901D1get_var* begin //#UC START# *4A8BAAA50229_4ADDF4D901D1get_impl* Result := nil; // Фиктивный узел if not Assigned(f_Bookmark) then Exit; // Получим имя документа if not Assigned(f_DocName) then begin // Document try f_Bookmark.GetFullName(l_Str); f_DocName := nsCStr(l_Str); except // Документа нет on ECanNotFindData do begin end; end; // DocName end;//not Assigned(f_Document) Result := f_DocName; //#UC END# *4A8BAAA50229_4ADDF4D901D1get_impl* end;//TnsJournalBookmarkNode.Get_DocName function TnsJournalBookmarkNode.Get_Bookmark: IJournalBookmark; //#UC START# *4A8BAACC02D5_4ADDF4D901D1get_var* //#UC END# *4A8BAACC02D5_4ADDF4D901D1get_var* begin //#UC START# *4A8BAACC02D5_4ADDF4D901D1get_impl* Result := f_Bookmark; //#UC END# *4A8BAACC02D5_4ADDF4D901D1get_impl* end;//TnsJournalBookmarkNode.Get_Bookmark procedure TnsJournalBookmarkNode.Cleanup; //#UC START# *479731C50290_4ADDF4D901D1_var* //#UC END# *479731C50290_4ADDF4D901D1_var* begin //#UC START# *479731C50290_4ADDF4D901D1_impl* f_Bookmark := nil; f_DocName := nil; inherited; //#UC END# *479731C50290_4ADDF4D901D1_impl* end;//TnsJournalBookmarkNode.Cleanup function TnsJournalBookmarkNode.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //#UC START# *4A60B23E00C3_4ADDF4D901D1_var* //#UC END# *4A60B23E00C3_4ADDF4D901D1_var* begin //#UC START# *4A60B23E00C3_4ADDF4D901D1_impl* Result := inherited COMQueryInterface(IID, Obj); if Result.Fail then begin if (f_Bookmark = nil) then Result.SetNOINTERFACE else Result := Tl3HResult_C(f_Bookmark.QueryInterface(IID.IID, Obj)); end; //#UC END# *4A60B23E00C3_4ADDF4D901D1_impl* end;//TnsJournalBookmarkNode.COMQueryInterface {$IfEnd} //not Admin AND not Monitorings end.
unit uPEN_AppInit; interface uses System.Classes, uAppInit; type TPEN_AppInit = class(TAppInit, IAppInitInterface) private procedure CreateDBConnection; function CreateAndExecuteLogin: Boolean; function CreateAndExecuteSplashScreen: Boolean; procedure CreateAndShowMainApplicationLayer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var PEN_AppInit: TPEN_AppInit; implementation uses System.SysUtils, Vcl.ExtCtrls, Vcl.Forms, Winapi.Windows, Winapi.ShellAPI, uLogin, uPEN_SplashScreen, uDMConnection, uPEN_Login, Vcl.Dialogs, uPEN_AppMain; { TPEN_AppInit } constructor TPEN_AppInit.Create(AOwner: TComponent); begin (*** Creates and initializes this application ***) inherited; if CreateAndExecuteSplashScreen then begin if CreateAndExecuteLogin then begin if Assigned(PEN_Login) then PEN_Login.Free; CreateAndShowMainApplicationLayer; end; end; end; function TPEN_AppInit.CreateAndExecuteLogin: Boolean; begin (*** If login passes, then returns true else returns false ***) Application.CreateForm(TPEN_Login, PEN_Login); PEN_Login.ShowModal; Result := PEN_Login.LoggedOn; end; function TPEN_AppInit.CreateAndExecuteSplashScreen: Boolean; begin Result := True; try PEN_SplashScreen := TPEN_SplashScreen.Create(nil); try PEN_SplashScreen.Show; Application.ProcessMessages; Sleep(500); CreateDBConnection; finally PEN_SplashScreen.Free; end; Except Result := False; end; end; procedure TPEN_AppInit.CreateAndShowMainApplicationLayer; begin Application.CreateForm(TPEN_AppMain, PEN_AppMain); PEN_AppMain.Show; end; procedure TPEN_AppInit.CreateDBConnection; begin (*** Create simple database connection ***) Application.CreateForm(TDMConnection, DMConnection); end; destructor TPEN_AppInit.Destroy; begin inherited; end; end.
unit VisualClassManager; interface uses IniClasses, Collection, Classes, SysUtils; type TCollection = Collection.TCollection; type TClassManager = class; TVisualClass = class; TSection = class; TClassManager = class public constructor Create; destructor Destroy; override; private fClasses : TCollection; public procedure AddClass(aClass : TIniClass); private function GetCount : integer; function GetClass(index : integer) : TVisualClass; function GetClassById(id : integer) : TVisualClass; public property Count : integer read GetCount; property Classes[index : integer] : TVisualClass read GetClass; property ClassById[id : integer] : TVisualClass read GetClassById; private function CompareItems(Item1, Item2 : TObject) : integer; public constructor Load(Stream : TStream); procedure Store(Stream : TStream); end; TVisualClass = class public constructor Create(aIniClass : TIniClass); constructor Load(Stream : TStream; Strs : TStrings); constructor CreateFromINI(path : string); procedure Store(Stream : TStream); procedure StoreToINI(path : string); destructor Destroy; override; private fId : word; fSections : TCollection; private function GetCount : integer; function GetSection(index : integer) : TSection; public property Id : word read fId write fId; property Count : integer read GetCount; property Sections[index : integer] : TSection read GetSection; public function ReadString(const Section, Name, DefVal : string) : string; function ReadInteger(const Section, Name : string; DefVal : integer) : integer; function ReadBool(const Section, Name : string; DefVal : boolean) : boolean; procedure WriteString(const Section, Name, Value : string); //procedure WriteInteger(const Section, Name, Value : string); //procedure WriteBool(const Section, Name, Value : string); end; TSection = class public constructor Create(aName : string; Properties : TStringList); constructor Load(Stream : TStream; Strs : TStrings); procedure Store(Stream : TStream); destructor Destroy; override; private fNameIndex : word; fName : string; fProperties : TStringList; public property Name : string read fName; property Properties : TStringList read fProperties; end; implementation uses DelphiStreamUtils, IniFiles; // TClassManager constructor TClassManager.Create; begin inherited Create; fClasses := TSortedCollection.Create(0, rkBelonguer, CompareItems); end; constructor TClassManager.Load(Stream : TStream); var List : TStringList; i : integer; cnt : word; aux : string; begin inherited Create; fClasses := TSortedCollection.Create(0, rkBelonguer, CompareItems); List := TStringList.Create; Stream.Read(cnt, sizeof(cnt)); for i := 0 to pred(cnt) do if ReadLine(Stream, aux) then List.Add(aux); Stream.Read(cnt, sizeof(cnt)); for i := 0 to pred(cnt) do fClasses.Insert(TVisualClass.Load(Stream, List)); List.Free; end; procedure TClassManager.Store(Stream : TStream); var List : TStringList; vcIdx : integer; scIdx : integer; ppIdx : integer; VCls : TVisualClass; idx : integer; Sctn : TSection; aux : string; w : word; begin List := TStringList.Create; List.Duplicates := dupIgnore; // Get the string table for vcIdx := 0 to pred(Count) do begin VCls := Classes[vcIdx]; for scIdx := 0 to pred(VCls.Count) do begin Sctn := VCls.Sections[scIdx]; idx := List.IndexOf(Sctn.Name); if idx = -1 then idx := List.Add(Sctn.Name); Sctn.fNameIndex := idx; for ppIdx := 0 to pred(Sctn.Properties.Count) do begin aux := Sctn.Properties[ppIdx]; idx := List.IndexOf(aux); if idx = -1 then idx := List.Add(aux); Sctn.Properties.Objects[ppIdx] := TObject(idx); end; end; end; // Save the string table w := List.Count; Stream.Write(w, sizeof(w)); for ppIdx := 0 to pred(w) do WriteLine(Stream, List[ppIdx]); List.Free; // Save the indexes w := Count; Stream.Write(w, sizeof(w)); for vcIdx := 0 to pred(Count) do begin VCls := Classes[vcIdx]; VCls.Store(Stream); end; end; destructor TClassManager.Destroy; begin fClasses.Free; inherited; end; procedure TClassManager.AddClass(aClass : TIniClass); var NewClass : TVisualClass; begin NewClass := TVisualClass.Create(aClass); if NewClass.Id <> 0 then fClasses.Insert(NewClass) else raise Exception.Create(''); end; function TClassManager.GetCount : integer; begin result := fClasses.Count; end; function TClassManager.GetClass(index : integer) : TVisualClass; begin result := TVisualClass(fClasses[index]); end; function TClassManager.GetClassById(id : integer) : TVisualClass; var i : integer; cnt : integer; begin i := 0; cnt := fClasses.Count; while (i < cnt) and (Classes[i].Id <> id) do inc(i); if i < cnt then result := Classes[i] else result := nil; end; function TClassManager.CompareItems(Item1, Item2 : TObject) : integer; begin result := TVisualClass(Item1).fId - TVisualClass(Item2).fId; end; // TVisualClass constructor TVisualClass.Create(aIniClass : TIniClass); var i : integer; begin inherited Create; fSections := TCollection.Create(0, rkBelonguer); for i := 0 to pred(aIniClass.SectionList.Count) do fSections.Insert(TSection.Create(aIniClass.SectionList[i], TStringList(aIniClass.SectionList.Objects[i]))); fId := aIniClass.ReadInteger(tidGeneral, 'Id', 0); end; constructor TVisualClass.Load(Stream : TStream; Strs : TStrings); var sn : byte; i : integer; begin inherited Create; fSections := TCollection.Create(0, rkBelonguer); // Save the Id Stream.Read(fId, sizeof(fId)); Stream.Read(sn, sizeof(sn)); for i := 0 to pred(sn) do fSections.Insert(TSection.Load(Stream, Strs)); end; constructor TVisualClass.CreateFromINI(path : string); var Ini : TIniFile; Secs : TStringList; i, j : integer; Names : TStringList; Props : TStringList; Sec : TSection; begin inherited Create; fSections := TCollection.Create(0, rkBelonguer); Ini := TIniFile.Create(path); Secs := TStringList.Create; Props := TStringList.Create; Names := TStringList.Create; Ini.ReadSections(Secs); for i := 0 to pred(Secs.Count) do begin if lowercase(Secs[i]) = 'general' then fId := Ini.ReadInteger('general', 'Id', 0); Ini.ReadSection(Secs[i], Names); for j := 0 to pred(Names.Count) do Props.Values[Names[j]] := Ini.ReadString(Secs[i], Names[j], ''); Sec := TSection.Create(Secs[i], Props); fSections.Insert(Sec); Props.Clear; Names.Clear; end; Names.Free; Props.Free; Secs.Free; Ini.Free; end; procedure TVisualClass.Store(Stream : TStream); var sn : byte; i : integer; begin // Save the Id Stream.Write(fId, sizeof(fId)); // Save sections sn := Count; Stream.Write(sn, sizeof(sn)); for i := 0 to pred(Count) do Sections[i].Store(Stream); end; procedure TVisualClass.StoreToINI(path : string); var Ini : TIniFile; i, j : integer; Sec : TSection; aux : string; begin inherited Create; Ini := TIniFile.Create(path); for i := 0 to pred(fSections.Count) do begin Sec := TSection(fSections[i]); for j := 0 to pred(Sec.Properties.Count) do begin aux := Sec.Properties.Names[j]; if j <> pred(Sec.Properties.Count) then Ini.WriteString(Sec.Name, #9 + aux, Sec.Properties.Values[aux]) else Ini.WriteString(Sec.Name, #9 + aux, Sec.Properties.Values[aux] + ^M^J); end; end; if fId <> 0 then Ini.WriteInteger('General', #9 + 'Id', fId); Ini.Free; end; destructor TVisualClass.Destroy; begin fSections.Free; inherited; end; function TVisualClass.GetCount : integer; begin result := fSections.Count; end; function TVisualClass.GetSection(index : integer) : TSection; begin result := TSection(fSections[index]); end; function TVisualClass.ReadString(const Section, Name, DefVal : string) : string; var index : integer; cnt : integer; begin cnt := Count; index := 0; while (index < cnt) and (Sections[index].Name <> Section) do inc(index); if index < cnt then begin result := Sections[index].Properties.Values[Name]; if result = '' then result := DefVal; end else result := DefVal; end; function TVisualClass.ReadInteger(const Section, Name : string; DefVal : integer) : integer; var aux : string; begin aux := ReadString(Section, Name, ''); if aux <> '' then try result := StrToInt(aux); except result := DefVal; end else result := DefVal; end; function TVisualClass.ReadBool(const Section, Name : string; DefVal : boolean) : boolean; var aux : string; begin aux := ReadString(Section, Name, ''); if aux <> '' then result := aux = '1' else result := DefVal; end; procedure TVisualClass.WriteString(const Section, Name, Value : string); var index : integer; cnt : integer; begin cnt := Count; index := 0; while (index < cnt) and (Sections[index].Name <> Section) do inc(index); if index < cnt then Sections[index].Properties.Values[Name] := Value; end; // TSection constructor TSection.Create(aName : string; Properties : TStringList); begin inherited Create; fName := aName; fProperties := TStringList.Create; fProperties.AddStrings(Properties); {$IFNDEF KEEP_GENERAL} if lowercase(fName) = 'general' then begin fProperties.Values[tidName] := ''; fProperties.Values[tidInherits] := ''; fProperties.Values[tidId] := ''; end; {$ENDIF} end; constructor TSection.Load(Stream : TStream; Strs : TStrings); var idx : word; ppc : byte; i : integer; begin inherited Create; Stream.Read(idx, sizeof(idx)); fName := Strs[idx]; Stream.Read(ppc, sizeof(ppc)); fProperties := TStringList.Create; for i := 0 to pred(ppc) do begin Stream.Read(idx, sizeof(idx)); fProperties.Add(Strs[idx]); end; end; procedure TSection.Store(Stream : TStream); var pn : byte; i : integer; w : word; begin // Save the index Stream.Write(fNameIndex, sizeof(fNameIndex)); // Save properties pn := fProperties.Count; Stream.Write(pn, sizeof(pn)); for i := 0 to pred(pn) do begin w := integer(fProperties.Objects[i]); Stream.Write(w, sizeof(w)); end; end; destructor TSection.Destroy; begin fProperties.Free; inherited; end; end.
unit fTSAEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GR32_Image, GR32, GR32_Layers, ComCtrls, cMegaROM, cConfiguration; type TfrmTSA = class(TForm) imgTSA: TImage32; StatusBar: TStatusBar; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure imgTSAMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure imgTSAMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; TileX, TileY : Integer; { Private declarations } public procedure DrawPatternTable(); property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmTSA: TfrmTSA; implementation uses fRockAndRollMain, uGlobal, fTileEditor; {$R *.dfm} procedure TfrmTSA.FormClose(Sender: TObject; var Action: TCloseAction); begin frmRockAndRollMain.CurTSABlock := -1; frmRockAndRollMain.UpdateTitleCaption; frmRockAndROllMain.DrawTileSelector; Action := caFree; end; procedure TfrmTSA.DrawPatternTable(); var TSA : TBitmap32; begin TSA := TBitmap32.Create; try TSA.Width := 128; TSA.Height := 128; _ROMData.DrawTSAPatternTable(TSA,_EditorConfig.LastPaletteTSA); TSA.FrameRectS(TileX,TileY,TileX+16,TileY + 16,clRed32); imgTSA.Bitmap := TSA; finally FreeAndNil(TSA); end; end; procedure TfrmTSA.FormShow(Sender: TObject); begin DrawPatternTable(); frmRockAndRollMain.CurTSABlock := 0; end; procedure TfrmTSA.imgTSAMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var Tile : Integer; TilEd : Tfrm16x16TileEditor; // Erase : TfrmErasePatRange; begin if (Button = mbMiddle) or ((ssShift in Shift) and (Button = mbLeft)) then begin TileX := ((X div 2) div 16) * 16; TileY := ((y div 2) div 16) * 16; Tile := ((TileY div 16) * 8) + (TileX div 16); //showmessage(IntToStr(Y)); frmRockAndRollMain.CurTSABlock := Tile; // showmessage(IntToStr(Tile div 32)); DrawPatternTable(); TilEd := Tfrm16x16TileEditor.Create(self); try TilEd.TileID := frmRockAndRollMain.CurTSABlock + $40; TilEd.ROMData := _ROMData; TilEd.EditorConfig := _EditorConfig; if TilEd.ShowModal = mrOK then begin _ROMData.SavePatternTable(); DrawPatternTable(); frmRockAndRollMain.RedrawScreen; frmRockAndRollMain.UpdateTitleCaption; end; finally FreeAndNil(TilEd); end; end else if button = mbLeft then begin TileX := ((X div 2) div 16) * 16; TileY := ((y div 2) div 16) * 16; Tile := ((TileY div 16) * 8) + (TileX div 16); frmRockAndRollMain.CurTSABlock := Tile; end else if button = mbRight then begin { if ssShift in Shift then begin Erase := TfrmErasePatRange.Create(self); try Erase.Mode := 0; if Erase.ShowModal = mrOk then begin CVROM.SavePatternTable(); DrawPatternTable(); frmStake.RedrawScreen; end; finally FreeAndNil(Erase); end; end else} begin if _EditorConfig.LastPaletteTSA = 3 then _EditorConfig.LastPaletteTSA := 0 else _EditorConfig.LastPaletteTSA := _EditorConfig.LastPaletteTSA + 1; end; end; DrawPatternTable(); end; procedure TfrmTSA.imgTSAMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin StatusBar.Panels[0].Text := 'Selected: ' + IntToHex(frmRockAndRollMain.CurTSABlock,2); StatusBar.Panels[1].Text := IntToHex(((((X div 2) div 16) * 16) div 16) + (((((y div 2) div 16) * 16) div 16) * 8),2); end; end.
unit mnSynHighlighterFirebird; {$mode objfpc}{$H+} {** * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey *} interface uses SysUtils, Classes, Graphics, SynEditTypes, SynEditHighlighter, mnSynUtils, SynHighlighterHashEntries; type TtkTokenKind = (tkComment, tkDatatype, tkObject, tkException, tkFunction, tkIdentifier, tkKey, tkNull, tkNumber, tkSpace, tkString, tkSymbol, tkUnknown, tkVariable); TRangeState = (rsUnknown, rsComment, rsString); TSynFirebirdSyn = class(TSynCustomHighlighter) private Run: LongInt; FProcTable: array[#0..#255] of TProcTableProc; FRange: TRangeState; FLine: PChar; FStringLen: Integer; FTokenPos: Integer; FTokenID: TtkTokenKind; FCommentAttri: TSynHighlighterAttributes; FDataTypeAttri: TSynHighlighterAttributes; FObjectAttri: TSynHighlighterAttributes; FExceptionAttri: TSynHighlighterAttributes; FFunctionAttri: TSynHighlighterAttributes; FIdentifierAttri: TSynHighlighterAttributes; FKeyAttri: TSynHighlighterAttributes; FNumberAttri: TSynHighlighterAttributes; FSpaceAttri: TSynHighlighterAttributes; FStringAttri: TSynHighlighterAttributes; FSymbolAttri: TSynHighlighterAttributes; FVariableAttri: TSynHighlighterAttributes; procedure AndSymbolProc; procedure StringProc; procedure CRProc; procedure EqualProc; procedure GreaterProc; procedure IdentProc; procedure LFProc; procedure LowerProc; procedure MinusProc; procedure NullProc; procedure NumberProc; procedure OrSymbolProc; procedure PlusProc; procedure SlashProc; procedure SpaceProc; procedure SymbolProc; procedure SymbolAssignProc; procedure VariableProc; procedure ObjectProc; procedure UnknownProc; procedure CommentProc; procedure MakeProcTables; protected function GetIdentChars: TSynIdentChars; override; function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override; function GetEol: Boolean; override; function GetRange: Pointer; override; function GetToken: string; override; procedure GetTokenEx(out TokenStart: PChar; out TokenLength: Integer); override; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetTokenID: TtkTokenKind; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; function IsKeyword(const AKeyword: string): boolean; override; procedure Next; override; procedure ResetRange; override; procedure SetLine(const NewValue: string; LineNumber: Integer); override; procedure SetRange(Value: Pointer); override; published property CommentAttri: TSynHighlighterAttributes read FCommentAttri write FCommentAttri; property DataTypeAttri: TSynHighlighterAttributes read FDataTypeAttri write FDataTypeAttri; property ObjectAttri: TSynHighlighterAttributes read FObjectAttri write FObjectAttri; property ExceptionAttri: TSynHighlighterAttributes read FExceptionAttri write FExceptionAttri; property FunctionAttri: TSynHighlighterAttributes read FFunctionAttri write FFunctionAttri; property IdentifierAttri: TSynHighlighterAttributes read FIdentifierAttri write FIdentifierAttri; property KeyAttri: TSynHighlighterAttributes read FKeyAttri write FKeyAttri; property NumberAttri: TSynHighlighterAttributes read FNumberAttri write FNumberAttri; property SpaceAttri: TSynHighlighterAttributes read FSpaceAttri write FSpaceAttri; property StringAttri: TSynHighlighterAttributes read FStringAttri write FStringAttri; property SymbolAttri: TSynHighlighterAttributes read FSymbolAttri write FSymbolAttri; property VariableAttri: TSynHighlighterAttributes read FVariableAttri write FVariableAttri; end; const // functions FirebirdFunctions = 'avg,cast,count,gen_id,max,min,sum,upper'+ 'abs,acos,ascii_char,ascii_val,asin,atan,atan2,'+ 'bin_and,bin_or,bin_shl,bin_shr,bin_xor,'+ 'ceil,cos,cosh,cot,dateadd,datediff,decode,'+ 'exp,floor,gen_uuid,hash,ln,log,log10,lpad,'+ 'maxvalue,minvalue,mod,overlay,pi,power,'+ 'rand,replace,reverse,round,rpad,'+ 'sign,sin,sinh,sqrt,tan,tanh,trunc,'+ 'uuid_to_char,char_to_uuid'; // keywords FirebirdKeywords: string = 'active,add,after,all,alter,and,any,as,asc,ascending,at,auto,autonomous,autoddl,'+ 'based,basename,base_name,before,begin,between,blobedit,block,break,buffer,by,' + 'cache,case,character_length,char_length,check,' + 'check_point_len,check_point_length,coalesce,collate,collation,column,commit,' + 'commited,compiletime,computed,close,conditional,connect,constraint,' + 'containing,continue,create,current,current_date,current_time,' + 'current_connection,current_timestamp,current_transaction,cursor,' + 'database,day,db_key,debug,dec,declare,default,delete,deleting,desc,descending,' + 'describe,descriptor,disconnect,distinct,do,domain,drop,echo,edit,else,end,' + 'entry_point,escape,event,exception,execute,exists,exit,extern,external,extract,' + 'fetch,file,filter,first,for,foreign,found,free_it,from,full,function,' + 'gdscode,generator,global,goto,grant,group,group_commit_wait,group_commit_wait_time,' + 'having,help,hour,'+ 'if,iif,immediate,in,inactive,index,indicator,init,inner,input,input_type,insensitive,' + 'insert,inserting,int,into,is,isolation,isql,'+ 'join,'+ 'key,last,list,'+ 'lc_messages,lc_type,leave,left,length,lev,level,like,' + 'logfile,log_buffer_size,log_buf_size,long,lock,manual,' + 'matching,maximum,maximum_segment,max_segment,merge,message,minimum,minute,module_name,month,' + 'names,national,natural,nchar,new,next,no,noauto,not,null,nullif' + 'num_log_buffs,num_log_buffers,'+ 'octet_length,of,old,on,only,open,option,or,' + 'order,outer,output,output_type,overflow,'+ 'page,pagelength,pages,page_size,' + 'parameter,password,plan,position,post_event,prepare,procedure,' + 'protected,primary,privileges,public,quit,raw_partitions,read,real,' + 'record_version,recreate,references,release,reserv,reserving,retain,return,' + 'returning,returning_values,returns,restart,revoke,right,rollback,row_count,rows,runtime,'+ 'savepoint,schema,second,' + 'segment,select,set,sequence,shadow,shared,shell,show,similar,singular,size,snapshot,some,' + 'sort,skip,sql,sqlcode,sqlerror,sqlwarning,stability,starting,starts,' + 'sensitive,statement,static,statistics,sub_type,suspend,substring,'+ 'table,terminator,then,to,transaction,translate,translation,trigger,trim,type,' + 'uncommitted,union,unique,unicode,update,updating,user,using,utf8,'+ 'value,values,variable,varying,version,view,' + 'wait,weekday,when,whenever,where,while,with,work,write,'+ 'year,yearday'; // types FirebirdTypes = 'bigint,blob,char,character,date,decimal,double,float,int64,integer,' + 'numeric,precision,smallint,time,timestamp,varchar'; ISQLKeywords = 'TERM'; type { TFirebirdSyn } TFirebirdSyn = class(TSynPersistent) private protected procedure MakeIdentifiers; override; procedure MakeHashes; override; function GetDefaultKind: Integer; override; public function IdentKind(MayBe: PChar; out L: Integer): TtkTokenKind; overload; function IdentKind(MayBe: PChar): TtkTokenKind; overload; constructor Create; override; end; function FirebirdSyn: TFirebirdSyn; implementation uses SynEditStrConst; const SYNS_AttrObjects = 'Objects'; var FFirebirdSyn: TFirebirdSyn = nil; function FirebirdSyn: TFirebirdSyn; begin if FFirebirdSyn = nil then FFirebirdSyn := TFirebirdSyn.Create; Result := FFirebirdSyn; end; { TFirebirdSyn } procedure TFirebirdSyn.MakeIdentifiers; begin inherited; Identifiers[':'] := True; Identifiers['"'] := True; end; procedure TFirebirdSyn.MakeHashes; begin inherited; HashTable[':'] := HashTable['Z'] + 1; HashTable['"'] := HashTable['Z'] + 2; end; function TFirebirdSyn.GetDefaultKind: Integer; begin Result := ord(tkIdentifier); end; function TFirebirdSyn.IdentKind(MayBe: PChar; out L: Integer): TtkTokenKind; begin Result := TtkTokenKind(GetIdentKind(MayBe, L)); end; function TFirebirdSyn.IdentKind(MayBe: PChar): TtkTokenKind; var L: Integer; begin Result := TtkTokenKind(GetIdentKind(MayBe, L)); end; constructor TFirebirdSyn.Create; begin inherited; EnumerateKeywords(Ord(tkDatatype), FirebirdTypes, GetIdentChars, @DoAddKeyword); EnumerateKeywords(Ord(tkFunction), FirebirdFunctions, GetIdentChars, @DoAddKeyword); EnumerateKeywords(Ord(tkKey), FirebirdKeywords, GetIdentChars, @DoAddKeyword); EnumerateKeywords(Ord(tkKey), ISQLKeywords, GetIdentChars, @DoAddKeyword); end; procedure TSynFirebirdSyn.MakeProcTables; var I: Char; begin for I := #0 to #255 do case I of #0: FProcTable[I] := @NullProc; #10: FProcTable[I] := @LFProc; #13: FProcTable[I] := @CRProc; '=': FProcTable[I] := @EqualProc; '>': FProcTable[I] := @GreaterProc; '<': FProcTable[I] := @LowerProc; '-': FProcTable[I] := @MinusProc; '|': FProcTable[I] := @OrSymbolProc; '+': FProcTable[I] := @PlusProc; '/': FProcTable[I] := @SlashProc; '&': FProcTable[I] := @AndSymbolProc; #39: FProcTable[I] := @StringProc; '"': FProcTable[I] := @ObjectProc; ':': FProcTable[I] := @VariableProc; 'A'..'Z', 'a'..'z', '_': FProcTable[I] := @IdentProc; '0'..'9': FProcTable[I] := @NumberProc; #1..#9, #11, #12, #14..#32: FProcTable[I] := @SpaceProc; '^', '%', '*', '!': FProcTable[I] := @SymbolAssignProc; '{', '}', '.', ',', ';', '?', '(', ')', '[', ']', '~': FProcTable[I] := @SymbolProc; else FProcTable[I] := @UnknownProc; end; end; constructor TSynFirebirdSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment); FCommentAttri.Foreground := clMaroon; FCommentAttri.Style := [fsItalic]; AddAttribute(FCommentAttri); FDataTypeAttri := TSynHighlighterAttributes.Create(SYNS_AttrDataType); FDataTypeAttri.Style := [fsBold]; FDataTypeAttri.Foreground := $00C56A31; AddAttribute(FDataTypeAttri); FObjectAttri := TSynHighlighterAttributes.Create(SYNS_AttrObjects); FObjectAttri.Style := [fsBold]; FObjectAttri.Foreground := clGreen; AddAttribute(FObjectAttri); FFunctionAttri := TSynHighlighterAttributes.Create(SYNS_AttrFunction); FFunctionAttri.Style := [fsBold]; FFunctionAttri.Foreground := $00C56A31; AddAttribute(FFunctionAttri); FExceptionAttri := TSynHighlighterAttributes.Create(SYNS_AttrException); FExceptionAttri.Style := [fsItalic]; AddAttribute(FExceptionAttri); FIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier); FIdentifierAttri.Foreground := clBlack; AddAttribute(FIdentifierAttri); FKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord); FKeyAttri.Style := [fsBold]; FKeyAttri.Foreground := $00C56A31; AddAttribute(FKeyAttri); FNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber); AddAttribute(FNumberAttri); FSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace); AddAttribute(FSpaceAttri); FStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString); AddAttribute(FStringAttri); FSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol); AddAttribute(FSymbolAttri); FVariableAttri := TSynHighlighterAttributes.Create(SYNS_AttrVariable); FVariableAttri.Style := [fsBold]; FVariableAttri.Foreground := clBlack; AddAttribute(FVariableAttri); SetAttributesOnChange(@DefHighlightChange); FDefaultFilter := SYNS_FilterSQL; FRange := rsUnknown; MakeProcTables; end; destructor TSynFirebirdSyn.Destroy; begin inherited; end; procedure TSynFirebirdSyn.Assign(Source: TPersistent); begin inherited Assign(Source); end; procedure TSynFirebirdSyn.SetLine(const NewValue: string; LineNumber: Integer); begin inherited; FLine := PChar(NewValue); Run := 0; Next; end; procedure TSynFirebirdSyn.AndSymbolProc; begin FTokenID := tkSymbol; Inc(Run); if FLine[Run] in ['=', '&'] then Inc(Run); end; procedure TSynFirebirdSyn.StringProc; begin if FLine[Run] = #0 then NullProc else begin FTokenID := tkString; if (Run > 0) or (FRange <> rsString) or (FLine[Run] <> #39) then begin FRange := rsString; repeat Inc(Run); until FLine[Run] in [#0, #10, #13, #39]; end; if FLine[Run] = #39 then begin Inc(Run); FRange := rsUnknown; end; end; end; procedure TSynFirebirdSyn.CRProc; begin FTokenID := tkSpace; Inc(Run); if FLine[Run] = #10 then Inc(Run); end; procedure TSynFirebirdSyn.EqualProc; begin FTokenID := tkSymbol; Inc(Run); if FLine[Run] in ['=', '>'] then Inc(Run); end; procedure TSynFirebirdSyn.GreaterProc; begin FTokenID := tkSymbol; Inc(Run); if FLine[Run] in ['=', '>'] then Inc(Run); end; procedure TSynFirebirdSyn.IdentProc; begin FTokenID := FirebirdSyn.IdentKind((FLine + Run)); inc(Run, FStringLen); if FTokenID = tkComment then begin while not (FLine[Run] in [#0, #10, #13]) do Inc(Run); end else while FirebirdSyn.Identifiers[FLine[Run]] do inc(Run); end; procedure TSynFirebirdSyn.LFProc; begin FTokenID := tkSpace; inc(Run); end; procedure TSynFirebirdSyn.LowerProc; begin FTokenID := tkSymbol; Inc(Run); case FLine[Run] of '=': Inc(Run); '<': begin Inc(Run); if FLine[Run] = '=' then Inc(Run); end; end; end; procedure TSynFirebirdSyn.MinusProc; begin Inc(Run); if FLine[Run] = '-' then begin FTokenID := tkComment; repeat Inc(Run); until FLine[Run] in [#0, #10, #13]; end else FTokenID := tkSymbol; end; procedure TSynFirebirdSyn.NullProc; begin FTokenID := tkNull; end; procedure TSynFirebirdSyn.NumberProc; begin inc(Run); FTokenID := tkNumber; while FLine[Run] in ['0'..'9', '.', '-'] do begin case FLine[Run] of '.': if FLine[Run + 1] = '.' then break; end; inc(Run); end; end; procedure TSynFirebirdSyn.OrSymbolProc; begin FTokenID := tkSymbol; Inc(Run); if FLine[Run] in ['=', '|'] then Inc(Run); end; procedure TSynFirebirdSyn.PlusProc; begin FTokenID := tkSymbol; Inc(Run); if FLine[Run] in ['=', '+'] then Inc(Run); end; procedure TSynFirebirdSyn.SlashProc; begin Inc(Run); case FLine[Run] of '*': begin FRange := rsComment; FTokenID := tkComment; repeat Inc(Run); if (FLine[Run] = '*') and (FLine[Run + 1] = '/') then begin FRange := rsUnknown; Inc(Run, 2); break; end; until FLine[Run] in [#0, #10, #13]; end; '=': begin Inc(Run); FTokenID := tkSymbol; end; else FTokenID := tkSymbol; end; end; procedure TSynFirebirdSyn.SpaceProc; begin FTokenID := tkSpace; repeat Inc(Run); until (FLine[Run] > #32) or (FLine[Run] in [#0, #10, #13]); end; procedure TSynFirebirdSyn.SymbolProc; begin Inc(Run); FTokenID := tkSymbol; end; procedure TSynFirebirdSyn.SymbolAssignProc; begin FTokenID := tkSymbol; Inc(Run); if FLine[Run] = '=' then Inc(Run); end; procedure TSynFirebirdSyn.VariableProc; var i: integer; begin if (FLine[Run] = ':') then begin FTokenID := tkVariable; i := Run; repeat Inc(i); until not (FirebirdSyn.Identifiers[FLine[i]]); Run := i; end; end; procedure TSynFirebirdSyn.UnknownProc; begin inc(Run); FTokenID := tkUnknown; end; procedure TSynFirebirdSyn.CommentProc; begin case FLine[Run] of #0: NullProc; #10: LFProc; #13: CRProc; else begin FTokenID := tkComment; repeat if (FLine[Run] = '*') and (FLine[Run + 1] = '/') then begin FRange := rsUnknown; Inc(Run, 2); break; end; Inc(Run); until FLine[Run] in [#0, #10, #13]; end; end; end; function TSynFirebirdSyn.IsKeyword(const AKeyword: string): boolean; var tk: TtkTokenKind; begin tk := FirebirdSyn.IdentKind(PChar(AKeyword)); Result := tk in [tkDatatype, tkException, tkFunction, tkKey, tkObject]; end; procedure TSynFirebirdSyn.Next; begin FTokenPos := Run; case FRange of rsComment: CommentProc; rsString: StringProc; else FProcTable[FLine[Run]]; end; end; function TSynFirebirdSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := FCommentAttri; SYN_ATTR_IDENTIFIER: Result := FIdentifierAttri; SYN_ATTR_KEYWORD: Result := FKeyAttri; SYN_ATTR_STRING: Result := FStringAttri; SYN_ATTR_WHITESPACE: Result := FSpaceAttri; SYN_ATTR_SYMBOL: Result := FSymbolAttri; else Result := nil; end; end; function TSynFirebirdSyn.GetEOL: Boolean; begin Result := FTokenID = tkNull; end; function TSynFirebirdSyn.GetRange: Pointer; begin Result := Pointer(PtrUInt(FRange)); end; function TSynFirebirdSyn.GetToken: string; var Len: LongInt; begin Len := Run - FTokenPos; Setstring(Result, (FLine + FTokenPos), Len); end; procedure TSynFirebirdSyn.GetTokenEx(out TokenStart: PChar; out TokenLength: integer); begin TokenLength := Run - FTokenPos; TokenStart := FLine + FTokenPos; end; function TSynFirebirdSyn.GetTokenID: TtkTokenKind; begin Result := FTokenID; end; function TSynFirebirdSyn.GetTokenAttribute: TSynHighlighterAttributes; begin case GetTokenID of tkComment: Result := FCommentAttri; tkDatatype: Result := FDataTypeAttri; tkObject: Result := FObjectAttri; tkException: Result := FExceptionAttri; tkFunction: Result := FFunctionAttri; tkIdentifier: Result := FIdentifierAttri; tkKey: Result := FKeyAttri; tkNumber: Result := FNumberAttri; tkSpace: Result := FSpaceAttri; tkString: Result := FStringAttri; tkSymbol: Result := FSymbolAttri; tkVariable: Result := FVariableAttri; tkUnknown: Result := FIdentifierAttri; else Result := nil; end; end; function TSynFirebirdSyn.GetTokenKind: integer; begin Result := Ord(FTokenID); end; function TSynFirebirdSyn.GetTokenPos: Integer; begin Result := FTokenPos; end; procedure TSynFirebirdSyn.ResetRange; begin FRange := rsUnknown; end; procedure TSynFirebirdSyn.SetRange(Value: Pointer); begin FRange := TRangeState(PtrUInt(Value)); end; function TSynFirebirdSyn.GetIdentChars: TSynIdentChars; begin Result := FirebirdSyn.GetIdentChars end; class function TSynFirebirdSyn.GetLanguageName: string; begin Result := SYNS_LangSQL; end; function TSynFirebirdSyn.GetSampleSource: string; begin Result := 'select EMP_NO, "EMP_NAME" from EMPLOYEE' + LineEnding + 'where EMP_NO=?EMP_NO'; end; procedure TSynFirebirdSyn.ObjectProc; begin FTokenID := tkObject; Inc(Run); while not (FLine[Run] in [#0, #10, #13]) do begin if FLine[Run] = '"' then begin Inc(Run); break; end; Inc(Run); end; end; initialization RegisterPlaceableHighlighter(TSynFirebirdSyn); finalization FreeAndNil(FFirebirdSyn); end.
unit Tile; interface uses Engine, DGLE, DGLE_Types; type TTile = array [0..TILES_COUNT - 1] of ITexture; const TileFName: array [0..TILES_COUNT - 1] of AnsiString = ( 'Dirt.png' ); type TTiles = class private pTile: TTile; public constructor Create; destructor Destroy; override; procedure Render(X, Y, ID: Integer); end; implementation { TTiles } constructor TTiles.Create; var I: Byte; begin for I := 0 to TILES_COUNT - 1 do begin pTile[I] := nil; pResMan.Load(PAnsiChar('Resources\Sprites\Tiles\' + TileFName[I]), IEngineBaseObject(pTile[I]), TEXTURE_LOAD_DEFAULT_2D); end; end; destructor TTiles.Destroy; var I: Byte; begin for I := 0 to TILES_COUNT - 1 do pTile[I] := nil; inherited; end; procedure TTiles.Render(X, Y, ID: Integer); begin pRender2D.DrawTexture(pTile[ID], Point2(X * TILE_SIZE + SCR_LEFT, Y * TILE_SIZE + SCR_TOP), Point2(TILE_SIZE, TILE_SIZE)); end; end.
unit D3DXCore; /////////////////////////////////////////////////////////////////////////// // // Copyright (C) 1999 Microsoft Corporation. All Rights Reserved. // // File: d3dxcore.pas // Content: D3DX core types and functions // /////////////////////////////////////////////////////////////////////////// interface uses Windows, Math, DirectDraw, Direct3D, {Limits} D3DXErr; const IID_ID3DXContext : TGuid = '{9B74ED7A-BBEF-11d2-9F8E-0000F8080835}'; /////////////////////////////////////////////////////////////////////////// // Interfaces: /////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- // ID3DXContext interface: // // This encapsulates all the stuff that the app might // want to do at initialization time and any global control over d3d and // ddraw. //------------------------------------------------------------------------- type ID3DXContext = interface(IUnknown) ['{9B74ED7A-BBEF-11d2-9F8E-0000F8080835}'] // Get the DDraw and Direct3D objects to call DirectDraw or // Direct3D Immediate Mode functions. // If the objects don't exist (because they have not // been created for some reason) NULL is returned. // All the objects returned in the following Get* functions // are addref'ed. It is the application's responsibility to // release them when no longer needed. function GetDD : pointer; stdcall; function GetD3D : pointer; stdcall; function GetD3DDevice : pointer; stdcall; // Get the various buffers that get created at the init time // These are addref'ed as well. It is the application's responsibility // to release them before the app quits or when it needs a resize. function GetPrimary : pointer; stdcall; function GetZBuffer : pointer; stdcall; function GetBackBuffer(which : dword) : pointer; stdcall; // Get the associated window handles function GetWindow : HWND; stdcall; function GetFocusWindow : HWND; stdcall; // // Various Get methods, in case the user had specified default // parameters // function GetDeviceIndex(out DeviceIndex, HwLevel : dword) : HRESULT; stdcall; function GetNumBackBuffers : dword; stdcall; function GetNumBits(out ColorBits, DepthBits, AlphaBits, StencilBits : dword) : HRESULT; stdcall; function GetBufferSize(out Width, Height : dword) : HRESULT; stdcall; // Get the flags that were used to create this context function GetCreationFlags : dword; stdcall; function GetRefreshRate : dword; stdcall; // Restoring surfaces in case stuff is lost function RestoreSurfaces: HRESULT; stdcall; // Resize all the buffers to the new width and height function Resize(width, height : dword) : HRESULT; stdcall; // Update the frame using a flip or a blit, // If the D3DX_UPDATE_NOVSYNC flag is set, blit is used if the // driver cannot flip without waiting for vsync in full-screen mode. function UpdateFrame(flags : dword) : HRESULT; stdcall; // Render a string at the specified coordinates, with the specified // colour. This is only provided as a convenience for // debugging/information during development. // topLeftX and topLeftY represent the location of the top left corner // of the string, on the render target. // The coordinate and color parameters each have a range of 0.0-1.0 function DrawDebugText(topLeftX, topLeftY : single; color : TD3DCOLOR; pString : pchar) : HRESULT; stdcall; // Clears to the current viewport // The following are the valid flags: // D3DCLEAR_TARGET (to clear the render target ) // D3DCLEAR_ZBUFFER (to clear the depth-buffer ) // D3DCLEAR_STENCIL (to clear the stencil-buffer ) function Clear(ClearFlags : dword) : HRESULT; stdcall; function SetClearColor(color : TD3DCOLOR) : HRESULT; stdcall; function SetClearDepth(z : single) : HRESULT; stdcall; function SetClearStencil(stencil : dword) : HRESULT; stdcall; end; /////////////////////////////////////////////////////////////////////////// // Defines and Enumerators used below: /////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- // D3DX_DEFAULT: // --------- // A predefined value that could be used for any parameter in D3DX APIs or // member functions that is an enumerant or a handle. The D3DX // documentation indicates wherever D3DX_DEFAULT may be used, // and how it will be interpreted in each situation. //------------------------------------------------------------------------- const D3DX_DEFAULT = $FFFFFFFF; //------------------------------------------------------------------------- // D3DX_DEFAULT_FLOAT: // ------------------ // Similar to D3DX_DEFAULT, but used for floating point parameters. // The D3DX documentation indicates wherever D3DX_DEFAULT_FLOAT may be used, // and how it will be interpreted in each situation. //------------------------------------------------------------------------- const D3DX_DEFAULT_FLOAT = MaxSingle; //------------------------------------------------------------------------- // Hardware Acceleration Level: // --------------------------- // These constants represent pre-defined hardware acceleration levels, // and may be used as a default anywhere a (DWORD) deviceIndex is required. // Each pre-define indicates a different level of hardware acceleration. // They are an alternative to using explicit deviceIndices retrieved by // D3DXGetDeviceDescription(). // // The only case these pre-defines should be used as device indices is if // a particular level of acceleration is required, and given more than // one capable device on the computer, it does not matter which one // is used. // // The method of selection is as follows: If one of the D3DX devices on // the primary DDraw device supports a requested hardware acceleration // level, it will be used. Otherwise, the first matching device discovered // by D3DX will be used. // // Of course, it is possible for no match to exist for any of the // pre-defines on a particular computer. Passing such a value into the // D3DX apis will simply cause them to fail, reporting that no match // is available. // // D3DX_HWLEVEL_NULL: Null implementation (draws nothing) // D3DX_HWLEVEL_REFERENCE: Reference implementation (slowest) // D3DX_HWLEVEL_2D: 2D acceleration only (RGB rasterizer used) // D3DX_HWLEVEL_RASTER: Rasterization acceleration (likely most useful) // D3DX_HWLEVEL_TL: Transform and lighting acceleration // D3DX_DEFAULT: The highest level of acceleration available // on the primary DDraw device. //------------------------------------------------------------------------- const D3DX_HWLEVEL_NULL = D3DX_DEFAULT - 1; D3DX_HWLEVEL_REFERENCE = D3DX_DEFAULT - 2; D3DX_HWLEVEL_2D = D3DX_DEFAULT - 3; D3DX_HWLEVEL_RASTER = D3DX_DEFAULT - 4; D3DX_HWLEVEL_TL = D3DX_DEFAULT - 5; //------------------------------------------------------------------------- // Surface Class: // ------------- // These are the various types of 2D-surfaces classified according to their // usage. Note that a number of them overlap. e.g. STENCILBUFFERS and // DEPTHBUFFERS overlap (since in DX7 implementation the stencil and depth // bits are part of the same pixel format). // // Mapping to the DX7 DDPIXELFORMAT concepts: // ----------------------------------------- // D3DX_SC_DEPTHBUFFER: All ddpfs which have the DDPF_ZPIXELS or the // DDPF_ZBUFFER flags set. // D3DX_SC_STENCILBUFFER: All ddpfs which have the DDPF_STENCILBUFFER // flag set. // D3DX_SC_BUMPMAP: All ddpfs which have the DDPF_BUMPLUMINANCE // or the DDPF_BUMPDUDV flags set. // D3DX_SC_LUMINANCEMAP: All ddpfs which have the DDPF_BUMPLUMINANCE // or the DDPF_LUMINANCE flags set. // D3DX_SC_COLORTEXTURE: All the surfaces that have color information in // them and can be used for texturing. // D3DX_SC_COLORRENDERTGT: All the surfaces that contain color // information and can be used as render targets. //------------------------------------------------------------------------- const D3DX_SC_DEPTHBUFFER = $01; D3DX_SC_STENCILBUFFER = $02; D3DX_SC_COLORTEXTURE = $04; D3DX_SC_BUMPMAP = $08; D3DX_SC_LUMINANCEMAP = $10; D3DX_SC_COLORRENDERTGT = $20; //------------------------------------------------------------------------- // Surface Formats: // --------------- // These are the various types of surface formats that can be enumerated, // there is no DDPIXELFORMAT structure in D3DX, the enums carry the meaning // (like FOURCCs). // // All the surface classes are represented here. // //------------------------------------------------------------------------- type PD3DX_SURFACEFORMAT = ^TD3DX_SURFACEFORMAT; TD3DX_SURFACEFORMAT = dword; const D3DX_SF_UNKNOWN = 0; D3DX_SF_R8G8B8 = 1; D3DX_SF_A8R8G8B8 = 2; D3DX_SF_X8R8G8B8 = 3; D3DX_SF_R5G6B5 = 4; D3DX_SF_R5G5B5 = 5; D3DX_SF_PALETTE4 = 6; D3DX_SF_PALETTE8 = 7; D3DX_SF_A1R5G5B5 = 8; D3DX_SF_X4R4G4B4 = 9; D3DX_SF_A4R4G4B4 = 10; D3DX_SF_L8 = 11; // 8 bit luminance-only D3DX_SF_A8L8 = 12; // 16 bit alpha-luminance D3DX_SF_U8V8 = 13; // 16 bit bump map format D3DX_SF_U5V5L6 = 14; // 16 bit bump map format with luminance D3DX_SF_U8V8L8 = 15; // 24 bit bump map format with luminance D3DX_SF_UYVY = 16; // UYVY format (PC98 compliance) D3DX_SF_YUY2 = 17; // YUY2 format (PC98 compliance) D3DX_SF_DXT1 = 18; // S3 texture compression technique 1 D3DX_SF_DXT3 = 19; // S3 texture compression technique 3 D3DX_SF_DXT5 = 20; // S3 texture compression technique 5 D3DX_SF_R3G3B2 = 21; // 8 bit RGB texture format D3DX_SF_A8 = 22; // 8 bit alpha-only D3DX_SF_TEXTUREMAX = 23; // Last texture format D3DX_SF_Z16S0 = 256; D3DX_SF_Z32S0 = 257; D3DX_SF_Z15S1 = 258; D3DX_SF_Z24S8 = 259; D3DX_SF_S1Z15 = 260; D3DX_SF_S8Z24 = 261; D3DX_SF_DEPTHMAX = 262; // Last depth format D3DX_SF_FORCEMAX = -1; //------------------------------------------------------------------------- // Filtering types for Texture APIs // // ------------- // These are the various filter types for generation of mip-maps // // D3DX_FILTERTYPE // ----------------------------------------- // D3DX_FT_POINT: Point sampling only - no filtering // D3DX_FT_LINEAR: Bi-linear filtering // //------------------------------------------------------------------------- type TD3DX_FILTERTYPE = longint; const D3DX_FT_POINT = $01; D3DX_FT_LINEAR = $02; D3DX_FT_DEFAULT = D3DX_DEFAULT; /////////////////////////////////////////////////////////////////////////// // Structures used below: /////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- // D3DX_VIDMODEDESC: Display mode description. // ---------------- // width: Screen Width // height: Screen Height // bpp: Bits per pixel // refreshRate: Refresh rate //------------------------------------------------------------------------- type PD3DX_VIDMODEDESC = ^PD3DX_VIDMODEDESC; TD3DX_VIDMODEDESC = record width : dword; height : dword; bpp : dword; refreshRate : dword; end; //------------------------------------------------------------------------- // D3DX_DEVICEDESC: Description of a device that can do 3D // --------------- // deviceIndex: Unique (DWORD) number for the device. // hwLevel: Level of acceleration afforded. This is one of the // predefined Device Indices, and exists in this // structure for informational purposes only. More than // one device on the system may have the same hwLevel. // To refer to a particular device with the D3DX apis, // use the value in the deviceIndex member instead. // ddGuid: The ddraw GUID // d3dDeviceGuid: Direct3D Device GUID // ddDeviceID: DDraw's GetDeviceIdentifier GUID. This GUID is unique to // a particular driver revision on a particular video card. // driverDesc: String describing the driver // monitor: Handle to the video monitor used by this device (multimon // specific). Devices that use different monitors on a // multimon system report different values in this field. // Therefore, to test for a multimon system, an application // should look for more than one different monitor handle in // the list of D3DX devices. // onPrimary: Indicates if this device is on the primary monitor // (multimon specific). //------------------------------------------------------------------------- const D3DX_DRIVERDESC_LENGTH = 256; type PD3DX_DEVICEDESC = ^TD3DX_DEVICEDESC; TD3DX_DEVICEDESC = record deviceIndex : dword; hwLevel : dword; ddGuid : TGuid; d3dDeviceGuid : TGuid; ddDeviceID : TGuid; driverDesc : array [0..pred(D3DX_DRIVERDESC_LENGTH)] of char; monitor : HMONITOR; onPrimary : BOOL; end; /////////////////////////////////////////////////////////////////////////// // APIs: /////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- // D3DXInitialize: The very first call a D3DX app must make. //------------------------------------------------------------------------- function D3DXInitialize : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXInitialize'; //------------------------------------------------------------------------- // D3DXUninitialize: The very last call a D3DX app must make. //------------------------------------------------------------------------- function D3DXUninitialize : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXUninitialize'; //------------------------------------------------------------------------- // D3DXGetDeviceCount: Returns the maximum number of D3DXdevices // ------------------ available. // // D3DXGetDeviceDescription: Lists the 2D and 3D capabilities of the devices. // ------------------------ Also, the various guids needed by ddraw and d3d. // // Params: // [in] DWORD deviceIndex: Which device? Starts at 0. // [in] D3DX_DEVICEDESC* pd3dxDevice: Pointer to the D3DX_DEVICEDESC // structure to be filled in. //------------------------------------------------------------------------- function D3DXGetDeviceCount : dword; cdecl; external 'd3dx.dll' name '_D3DXGetDeviceCount'; function D3DXGetDeviceDescription(deviceIndex : dword; out d3dxDeviceDesc : TD3DX_DEVICEDESC) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXGetDeviceDescription'; //------------------------------------------------------------------------- // D3DXGetMaxNumVideoModes: Returns the maximum number of video-modes . // ----------------------- // // Params: // [in] DWORD deviceIndex: The device being referred to. // [in] DWORD flags: If D3DX_GVM_REFRESHRATE is set, then the refresh // rates are not ignored. // // D3DXGetVideoMode: Describes a particular video mode for this device // ---------------- // // Note: These queries will simply give you a list of modes that the // display adapter tells DirectX that it supports. // There is no guarantee that D3DXCreateContext(Ex) will succeed // with all listed video modes. This is a fundamental limitation // of the current DirectX architecture which D3DX cannot hide in // any clean way. // // Params: // [in] DWORD deviceIndex: The device being referred to. // [in] DWORD flags: If D3DX_GVM_REFRESHRATE is set, then the refresh // rates are returned // [in] DWORD which: Which VideoMode ? Starts at 0. // [out] D3DX_VIDMODEDESC* pModeList: Pointer to the D3DX_VIDMODEDESC // structure that will be filled in. //------------------------------------------------------------------------- function D3DXGetMaxNumVideoModes(deviceIndex, flags : dword) : dword; cdecl; external 'd3dx.dll' name '_D3DXGetMaxNumVideoModes'; function D3DXGetVideoMode(deviceIndex, flags, modeIndex : dword; out ModeList : TD3DX_VIDMODEDESC) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXGetVideoMode'; const D3DX_GVM_REFRESHRATE = $00000001; //------------------------------------------------------------------------- // D3DXGetMaxSurfaceFormats: Returns the maximum number of surface // ------------------------ formats supported by the device at that // video mode. // // D3DXGetSurfaceFormat: Describes one of the supported surface formats. // --------------------- // // Params: // [in] DWORD deviceIndex: The device being referred to. // [in] D3DX_VIDMODEDESC* pDesc: The display mode at which the supported // surface formats are requested. If it is // NULL, the current display mode is // assumed. // [in] DWORD surfClassFlags: Required surface classes. Only surface // formats which support all specified // surface classes will be returned. // (Multiple surface classes may be specified // using bitwise OR.) // [in] DWORD which: Which surface formats to retrieve. Starts at 0. // [out] D3DX_SURFACEFORMAT* pFormat: The surface format //------------------------------------------------------------------------- function D3DXGetMaxSurfaceFormats(deviceIndex : dword; const Desc : TD3DX_VIDMODEDESC; surfClassFlags : dword) : dword; cdecl; external 'd3dx.dll' name '_D3DXGetMaxSurfaceFormats'; function D3DXGetSurfaceFormat(deviceIndex : dword; const Desc : TD3DX_VIDMODEDESC; surfClassFlags, surfaceIndex : dword; out Format : TD3DX_SURFACEFORMAT) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXGetSurfaceFormat'; //------------------------------------------------------------------------- // D3DXGetCurrentVideoMode: Retrieves the current video mode for this device. // ------------------- // // Params: // [in] DWORD deviceIndex: The device being referred to. // [out] D3DX_VIDMODEDESC* pVidMode: The current video mode //------------------------------------------------------------------------- function D3DXGetCurrentVideoMode(deviceIndex : dword; out VidMode : TD3DX_VIDMODEDESC) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXGetCurrentVideoMode'; //------------------------------------------------------------------------- // D3DXGetDeviceCaps: Lists all the capabilities of a device at a display // mode. // ---------------- // // Params: // [in] DWORD deviceIndex: The device being referred to. // [in] D3DX_VIDMODEDESC* pDesc: If this is NULL, we will return the // caps at the current display mode of // the device. // [out] D3DDEVICEDESC7* pD3DDeviceDesc7: D3D Caps ( NULL to ignore // parameter) // [out] DDCAPS7* pDDHalCaps: DDraw HAL Caps (NULL to ignore parameter) // [out] DDCAPS7* pDDHelCaps: DDraw HEL Caps (NULL to ignore paramter) //------------------------------------------------------------------------- function D3DXGetDeviceCaps(deviceIndex : dword; pVidMode : PD3DX_VIDMODEDESC; pD3DCaps : PD3DDEVICEDESC7; pDDHALCaps, pDDHELCaps : PDDCAPS) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXGetDeviceCaps'; //------------------------------------------------------------------------- // D3DXCreateContext: Initializes the chosen device. It is the simplest init // ----------------- function available. Parameters are treated the same // as the matching subset of parameters in // D3DXCreateContextEx, documented below. // Remaining D3DXCreateContextEx parameters that are // not present in D3DXCreateContext are treated as // D3DX_DEFAULT. Note that multimon is not supported // with D3DXCreateContext. // // D3DXCreateContextEx: A more advanced function to initialize the device. // ------------------- Also accepts D3DX_DEFAULT for most of the parameters // and then will do what D3DXCreateContext did. // // Note: Do not expect D3DXCreateContext(Ex) to be fail-safe (as with any // API). Supported device capablilites should be used as a guide // for choosing parameter values. Keep in mind that there will // inevitably be some combinations of parameters that just do not work. // // Params: // [in] DWORD deviceIndex: The device being referred to. // [in] DWORD flags: The valid flags are D3DX_CONTEXT_FULLSCREEN, and // D3DX_CONTEXT_OFFSCREEN. These flags cannot both // be specified. If no flags are specified, the // context defaults to windowed mode. // // [in] HWND hwnd: Device window. See note. // [in] HWND hwndFocus: Window which receives keyboard messages from // the device window. The device window should be // a child of focus window. Useful for multimon // applications. See note. // NOTE: // windowed: // hwnd must be a valid window. hwndFocus must be NULL or // D3DX_DEFAULT. // // fullscreen: // Either hwnd or hwndFocus must be a valid window. (Both cannot // be NULL or D3DX_DEFAULT). If hwnd is NULL or D3DX_DEFAULT, // a default device window will be created as a child of hwndFocus. // // offscreen: // Both hwnd and hwndFocus must be NULL or D3DX_DEFAULT // // [in] DWORD numColorBits: If D3DX_DEFAULT is passed for windowed mode, // the current desktop's color depth is chosen. // For full screen mode, D3DX_DEFAULT causes 16 // bit color to be used. // [in] DWORD numAlphaBits: If D3DX_DEFAULT is passed, 0 is chosen. // [in] DWORD numDepthbits: If D3DX_DEFAULT is passed, // the highest available number of depth bits // is chosen. See note. // [in] DWORD numStencilBits: If D3DX_DEFAULT is passed, the highest // available number of stencil bits is chosen. // See note. // // NOTE: If both numDepthBits and numStencilBits are D3DX_DEFAULT, // D3DX first picks the highest available number of stencil // bits. Then, for the chosen number of stencil bits, // the highest available number of depth bits is chosen. // If only one of numStencilBits or numDepthBits // is D3DX_DEFAULT, the highest number of bits available // for this parameter is chosen out of only the formats // that support the number of bits requested for the // fixed parameter. // // [in] DWORD numBackBuffers: Number of back buffers, or D3DX_DEFAULT. // See note. // // NOTE: // windowed: D3DX_DEFAULT means 1. You must specify one back buffer. // // fullscreen: D3DX_DEFAULT means 1. Any number of back buffers can be // specified. // // offscreen: D3DX_DEFAULT means 0. You cannot specify additional back // buffers. // // [in] DWORD width: Width, in pixels, or D3DX_DEFAULT. See note. // [in] DWORD height: Height, in pixels, or D3DX_DEFAULT. See note. // // NOTE: // windowed: If either width or height is D3DX_DEFAULT, both values // default to the dimensions of the client area of hwnd. // // fullscreen: If either width or height is D3DX_DEFAULT, width // defaults to 640, and height defaults to 480. // // offscreen: An error is returned if either width or height is // D3DX_DEFAULT. // // [in] DWORD refreshRate: D3DX_DEFAULT means we let ddraw choose for // us. Ignored for windowed and offscreen modes. // [out] LPD3DXCONTEXT* ppCtx: This is the Context object that is used for // rendering on that device. // //------------------------------------------------------------------------- function D3DXCreateContext(deviceIndex, flags : dword; wnd : HWND; width, height : dword; out Ctx : ID3DXContext) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXCreateContext'; function D3DXCreateContextEx(deviceIndex, flags : dword; wnd : HWND; hwndFocus : HWND; numColorBits, numAlphaBits, numDepthbits, numStencilBits, numBackBuffers, width, height, refreshRate : integer; out Ctx : ID3DXContext) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXCreateContextEx'; // The D3DXCreateContext(Ex) flags are: const D3DX_CONTEXT_FULLSCREEN = $00000001; D3DX_CONTEXT_OFFSCREEN = $00000002; //------------------------------------------------------------------------- // D3DXGetErrorString: Prints out the error string given an hresult. Prints // ------------------ Win32 as well as DX6 error messages besides the D3DX // messages. // // Params: // [in] HRESULT hr: The error code to be deciphered. // [in] DWORD strLength: Length of the string passed in. // [out] LPSTR pStr: The string output. This string of appropriate // size needs to be passed in. //------------------------------------------------------------------------- procedure D3DXGetErrorString(hr : HRESULT; strLength : dword; pStr : pchar); cdecl; external 'd3dx.dll' name '_D3DXGetErrorString'; //------------------------------------------------------------------------- // D3DXMakeDDPixelFormat: Fills in a DDPIXELFORMAT structure based on the // --------------------- D3DX surface format requested. // // Params: // [in] D3DX_SURFACEFORMAT d3dxFormat: Surface format. // [out] DDPIXELFORMAT* pddpf: Pixel format matching the given // surface format. //------------------------------------------------------------------------- function D3DXMakeDDPixelFormat(d3dxFormat : TD3DX_SURFACEFORMAT; out ddpf : TDDPIXELFORMAT) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXMakeDDPixelFormat'; //------------------------------------------------------------------------- // D3DXMakeSurfaceFormat: Determines the surface format corresponding to // --------------------- a given DDPIXELFORMAT. // // Params: // [in] DDPIXELFORMAT* pddpf: Pixel format. // Return Value: // D3DX_SURFACEFORMAT: Surface format matching the given pixel format. // D3DX_SF_UNKNOWN if the format is not supported //------------------------------------------------------------------------- function D3DXMakeSurfaceFormat(const ddpf : TDDPIXELFORMAT) : TD3DX_SURFACEFORMAT; cdecl; external 'd3dx.dll' name '_D3DXMakeSurfaceFormat'; //------------------------------------------------------------------------- // Flags for Update member function: // // Flag to indicate that blit should be used instead of a flip // for full-screen rendering. const D3DX_UPDATE_NOVSYNC = 1 shl 0; /////////////////////////////////////////////////////////////////////////// // Texturing APIs: /////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- // D3DXCheckTextureRequirements: Return information about texture creation // ---------------------------- (used by CreateTexture, CreateTextureFromFile // and CreateCubeMapTexture) // // Parameters: // // pd3dDevice // The D3D device with which the texture is going to be used. // pFlags // allows specification of D3DX_TEXTURE_NOMIPMAP // D3DX_TEXTURE_NOMIPMAP may be returned in the case where mipmap creation // is not supported. // pWidth // width in pixels or NULL // returns corrected width // pHeight // height in pixels or NULL // returns corrected height // pPixelFormat // surface format // returns best match to input format // // Notes: 1. Unless the flags is set to specifically prevent creating // mipmaps, mipmaps are generated all the way till 1x1 surface. // 2. width, height and pixelformat are altered based on available // hardware. For example: // a. Texture dimensions may be required to be powers of 2 // b. We may require width == height for some devices // c. If PixelFormat is unavailable, a best fit is made //------------------------------------------------------------------------- function D3DXCheckTextureRequirements(const d3dDevice : IDirect3DDevice7; pFlags, pWidth, pHeight : pdword; var PixelFormat : TD3DX_SURFACEFORMAT) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXCheckTextureRequirements'; //------------------------------------------------------------------------- // D3DXCreateTexture: Create an empty texture object // ----------------- // // Parameters: // // pd3dDevice // The D3D device with which the texture is going to be used. // pFlags // allows specification of D3DX_TEXTURE_NOMIPMAP // D3DX_TEXTURE_NOMIPMAP may be returned in the case where mipmap creation // is not supported. Additionally, D3DX_TEXTURE_STAGE<n> can be specified // to indicate which texture stage the texture is for e.g. // D3D_TEXTURE_STAGE1 indicates that the texture is for use with texture // stage one. Stage Zero is the default if no TEXTURE_STAGE flags are // set. // pWidth // width in pixels; 0 or NULL is unacceptable // returns corrected width // pHeight // height in pixels; 0 or NULL is unacceptable // returns corrected height // pPixelFormat // surface format. D3DX_DEFAULT is unacceptable. // returns actual format that was used // pDDPal // DDraw palette that is set (if present) on paletted surfaces. // It is ignored even if it is set, for non-paletted surfaces. // ppDDSurf // The ddraw surface that will be created // pNumMipMaps // the number of mipmaps actually generated // // Notes: See notes for D3DXCheckTextureRequirements. //------------------------------------------------------------------------- function D3DXCreateTexture(const d3dDevice : IDirect3DDevice7; pFlags, pWidth, pHeight : pdword; pPixelFormat : PD3DX_SURFACEFORMAT; const DDPal : IDirectDrawPalette; out DDSurf : IDirectDrawSurface7; pNumMipMaps : pdword) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXCreateTexture'; //------------------------------------------------------------------------- // D3DXCreateCubeMapTexture: Create blank cube-map texture // ------------------------ // // Parameters: // // pd3dDevice // The D3D device with which the texture is going to be used. // pFlags // allows specification of D3DX_TEXTURE_NOMIPMAP // D3DX_TEXTURE_NOMIPMAP may be returned in the case where mipmap creation // is not supported. Additionally, D3DX_TEXTURE_STAGE<n> can be specified // to indicate which texture stage the texture is for e.g. // D3D_TEXTURE_STAGE1 indicates that the texture is for use with texture // stage one. Stage Zero is the default if no TEXTURE_STAGE flags are // set. // cubefaces // allows specification of which faces of the cube-map to generate. // D3DX_DEFAULT, 0, and DDSCAPS2_CUBEMAP_ALLFACES all mean // "create all 6 faces of the cubemap". Any combination of // DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, // DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, // DDSCAPS2_CUBEMAP_POSITIVEZ, or DDSCAPS2_CUBEMAP_NEGATIVEZ, is // valid. // colorEmptyFaces // allows specification of the color to use for the faces that were not // specified in the cubefaces parameter. // pWidth // width in pixels; 0 or NULL is unacceptable // returns corrected width // pHeight // height in pixels; 0 or NULL is unacceptable // returns corrected height // pPixelFormat // surface format. D3DX_DEFAULT is unacceptable. // returns actual format that was used // pDDPal // DDraw palette that is set (if present) on paletted surfaces. // It is ignored even if it is set, for non-paletted surfaces. // ppDDSurf // the ddraw surface that will be created // pNumMipMaps // the number of mipmaps generated for a particular face of the // cubemap. // // Notes: See notes for D3DXCheckTextureRequirements. //------------------------------------------------------------------------- function D3DXCreateCubeMapTexture(const d3dDevice : IDirect3DDevice7; pFlags : pdword; cubefaces : dword; colorEmptyFaces : TD3DCOLOR; pWidth, pHeight : pdword; pPixelFormat : PD3DX_SURFACEFORMAT; const DDPal : IDirectDrawPalette; out DDSurf : IDirectDrawSurface7; pNumMipMaps : pdword) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXCreateCubeMapTexture'; //------------------------------------------------------------------------- // D3DXCreateTextureFromFile: Create a texture object from a file or from the // ------------------------- resource. Only BMP and DIB are supported from the // resource portion of the executable. // // Parameters: // // pd3dDevice // The D3D device with which the texture is going to be used. // pFlags // allows specification of D3DX_TEXTURE_NOMIPMAP // D3DX_TEXTURE_NOMIPMAP may be returned in the case where mipmap creation // is not supported. Additionally, D3DX_TEXTURE_STAGE<n> can be specified // to indicate which texture stage the texture is for e.g. // D3D_TEXTURE_STAGE1 indicates that the texture is for use with texture // stage one. Stage Zero is the default if no TEXTURE_STAGE flags are // set. // pWidth // Width in pixels. If 0 or D3DX_DEFAULT, the width will be taken // from the file // returns corrected width // pHeight // Height in pixels. If 0 or D3DX_DEFAULT, the height will be taken // from the file // returns corrected height // pPixelFormat // If D3DX_SF_UNKNOWN is passed in, pixel format closest to the bitmap // will be chosen // returns actual format that was used // pDDPal // DDraw palette that is set (if present) on paletted surfaces. // It is ignored even if it is set, for non-paletted surfaces. // ppDDSurf // The ddraw surface that will be created. // pNumMipMaps // The number of mipmaps generated. // pSrcName // File name. BMP, DIB, DDS, are supported. // // TGA is supported for the following cases: 16, 24, 32bpp direct color and 8bpp palettized. // Also, 8, 16bpp grayscale is supported. RLE versions of the above // TGA formats are also supported. ColorKey and Premultiplied Alpha // are not currently supported for TGA files. // returns created format // // Notes: See notes for D3DXCheckTextureRequirements. //------------------------------------------------------------------------- function D3DXCreateTextureFromFile(const d3dDevice : IDirect3DDevice7; pFlags, pWidth, pHeight : pdword; pPixelFormat : PD3DX_SURFACEFORMAT; const DDPal : IDirectDrawPalette; out DDSurf : IDirectDrawSurface7; pNumMipMaps : pdword; pSrcName : pchar; filterType : TD3DX_FILTERTYPE) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXCreateTextureFromFile'; //------------------------------------------------------------------------- // D3DXLoadTextureFromFile: Load from a file into a mipmap level. Doing the // ----------------------- necessary color conversion and rescaling. File // format support is identical to // D3DXCreateTextureFromFile's. // // pd3dDevice // The D3D device with which the texture is going to be used. // pTexture // a pointer to a DD7Surface which was created with either // CreateTextureFromFile or CreateTexture. // mipMapLevel // indicates mipmap level // Note: // 1. Error if mipmap level doesn't exist // 2. If D3DX_DEFAULT and equal number of mipmap levels exist // then all the source mip-levels are loaded // 3. If the source has mipmaps and the dest doesn't, use the top one // 4. If the dest has miplevels and source doesn't, we expand // 5. If there are unequal numbers of miplevels, we expand // pSrcName // File name. BMP, DIB, DDS, are supported. // For details on TGA support, refer to the comments for // D3DXCreateTextureFromFile // pSrcRect // the source rectangle or null (whole surface) // pDestRect // the destination rectangle or null (whole surface) // filterType // filter used for mipmap generation //------------------------------------------------------------------------- function D3DXLoadTextureFromFile(const d3dDevice : IDirect3DDevice7; const Texture : IDirectDrawSurface7; mipMapLevel : dword; pSrcName : pchar; pSrcRect, pDestRect : PRect; filterType : TD3DX_FILTERTYPE) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXLoadTextureFromFile'; //------------------------------------------------------------------------- // D3DXLoadTextureFromSurface: Load from a DDraw Surface into a mipmap level. // -------------------------- Doing the necessary color conversion. // // pd3dDevice // The D3D device with which the texture is going to be used. // pTexture // a pointer to a DD7Surface which was created with either // CreateTextureFromFile or CreateTexture. // mipMapLevel // indicates mipmap level // Note: // 1. Error if mipmap level doesn't exist // 2. If D3DX_DEFAULT and equal number of mipmap levels exist // then all the source mip-levels are loaded // 3. If the source has mipmaps and the dest doesn't, use the top one // 4. If the dest has miplevels and source doesn't, we expand // 5. If there are unequal numbers of miplevels, we expand // pSurfaceSrc // the source surface // pSrcRect // the source rectangle or null (whole surface) // pDestRect // the destination rectangle or null (whole surface) // filterType // filter used for mipmap generation //------------------------------------------------------------------------- function D3DXLoadTextureFromSurface(const d3dDevice : IDirect3DDevice7; const Texture : IDirectDrawSurface7; mipMapLevel : dword; const SurfaceSrc : IDirectDrawSurface7; pSrcRect, pDestRect : PRect; filterType : TD3DX_FILTERTYPE) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXLoadTextureFromSurface'; //------------------------------------------------------------------------- // D3DXLoadTextureFromMemory: Load a mip level from memory. Doing the necessary // ------------------------- color conversion. // // pd3dDevice // The D3D device with which the texture is going to be used. // pTexture // a pointer to a DD7Surface which was created with either // CreateTextureFromFile or CreateTexture. // mipMapLevel // indicates mipmap level // Note: // 1. Error if mipmap level doesn't exist // 2. If D3DX_DEFAULT and equal number of mipmap levels exist // then all the source mip-levels are loaded // 3. If the source has mipmaps and the dest doesn't, use the top one // 4. If the dest has miplevels and source doesn't, we expand // 5. If there are unequal numbers of miplevels, we expand // pMemory // pointer to source memory from which the texture will be loaded // pDDPal // DirectDraw Palette, that the app passes in optionally if the memory is // supposed to be paletteized. // srcPixelFormat // PixelFormat of the source. // srcPitch // The pitch of the memory or D3DX_DEFAULT (based on srcPixelFormat) // pDestRect // The destination rectangle or null (whole surface) // filterType // filter used for mipmap generation // // Assumptions: The source (memory) is loaded in full //------------------------------------------------------------------------- function D3DXLoadTextureFromMemory(const d3dDevice : IDirect3DDevice7; const Texture : IDirectDrawSurface7; mipMapLevel : dword; pMemory : pointer; const pDDPal : IDirectDrawPalette; psrcPixelFormat : PD3DX_SURFACEFORMAT; // >> srcPitch : dword; pDestRect : PRect; filterType : TD3DX_FILTERTYPE) : HRESULT; cdecl; external 'd3dx.dll' name '_D3DXLoadTextureFromMemory'; //------------------------------------------------------------------------- // Flags for texture create functions; applies to // D3DXCreateTexture, D3DXCreateCubeMapTexture and D3DXCreateTextureFromFile. // // Flag to indicate that mipmap generation is not desired. const D3DX_TEXTURE_NOMIPMAP = 1 shl 8; // Flags to indicate which texture stage the texture is // intended for use with. Specifying the stage is necessary at // texture creation time for HW devices that expose the // D3DDEVCAPS_SEPARATETEXTUREMEMORIES bit in their D3DDEVICEDESC // structure. const D3DX_TEXTURE_STAGE0 = 0; D3DX_TEXTURE_STAGE1 = 1; D3DX_TEXTURE_STAGE2 = 2; D3DX_TEXTURE_STAGE3 = 3; D3DX_TEXTURE_STAGE4 = 4; D3DX_TEXTURE_STAGE5 = 5; D3DX_TEXTURE_STAGE6 = 6; D3DX_TEXTURE_STAGE7 = 7; // Mask to extract the texture stage value out of the flags to // the texture create functions. const D3DX_TEXTURE_STAGE_MASK = $7; implementation end.
unit UOrderedServerAddressListTS; interface //uses // UNetData; // third circular unit references, saving to git. uses UThread, Classes, UNetConnection, UNodeServerAddress, UNetStatistics; type // This will maintain a list sorted by 2 values: ip/port and netConnection in thread safe mode // Using this object, NodeServerAddress can be more high in length and also more quick to search { TOrderedServerAddressListTS } TOrderedServerAddressListTS = Class private FAllowDeleteOnClean: Boolean; FNetStatistics : PNetStatistics; FCritical : TPCCriticalSection; FListByIp : TList; FListByNetConnection : TList; Procedure SecuredDeleteFromListByIp(index : Integer); Function SecuredFindByIp(const ip : AnsiString; port : Word; var Index: Integer): Boolean; Function SecuredFindByNetConnection(const search : TNetConnection; var Index: Integer): Boolean; protected public Constructor Create( ParaNetStatistics : PNetStatistics); Destructor Destroy; Override; Procedure Clear; Function Count : Integer; Function CleanBlackList(forceCleanAll : Boolean) : Integer; procedure CleanNodeServersList; Function LockList : TList; Procedure UnlockList; function IsBlackListed(const ip: AnsiString): Boolean; function GetNodeServerAddress(const ip : AnsiString; port:Word; CanAdd : Boolean; var nodeServerAddress : TNodeServerAddress) : Boolean; procedure SetNodeServerAddress(const nodeServerAddress : TNodeServerAddress); Procedure UpdateNetConnection(netConnection : TNetConnection); procedure GetNodeServersToConnnect(maxNodes : Integer; useArray : Boolean; var nsa : TNodeServerAddressArray); Function GetValidNodeServers(OnlyWhereIConnected : Boolean; Max : Integer): TNodeServerAddressArray; // Skybuck: moved to here to offer access to UNetConnection function DeleteNetConnection(netConnection : TNetConnection) : Boolean; property AllowDeleteOnClean : Boolean read FAllowDeleteOnClean write FAllowDeleteOnClean; // Skybuck: property added to offer access to UNetData property Critical : TPCCriticalSection read FCritical; End; implementation uses UNetProtocolConst, UTime, SysUtils, ULog, UConst, UPtrInt; { TOrderedServerAddressListTS } function TOrderedServerAddressListTS.CleanBlackList(forceCleanAll : Boolean) : Integer; Var P : PNodeServerAddress; i : Integer; begin CleanNodeServersList; // This procedure cleans old blacklisted IPs Result := 0; FCritical.Acquire; Try for i := FListByIp.Count - 1 downto 0 do begin P := FListByIp[i]; // Is an old blacklisted IP? (More than 1 hour) If (P^.is_blacklisted) AND ((forceCleanAll) OR ((P^.last_connection+(CT_LAST_CONNECTION_MAX_MINUTES)) < (UnivDateTimeToUnix(DateTime2UnivDateTime(now))))) then begin if (AllowDeleteOnClean) then begin SecuredDeleteFromListByIp(i); end else begin P^.is_blacklisted:=False; end; inc(Result); end; end; Finally FCritical.Release; End; // if (Result>0) then FNetData.NotifyBlackListUpdated; // if (Result>0) then FNetDataNotifyEventsThread.FNotifyOnBlackListUpdated := true; end; procedure TOrderedServerAddressListTS.CleanNodeServersList; var i : Integer; nsa : TNodeServerAddress; currunixtimestamp : Cardinal; begin If Not (FAllowDeleteOnClean) then Exit; currunixtimestamp := UnivDateTimeToUnix(DateTime2UnivDateTime(now)); FCritical.Acquire; Try i := FListByIp.Count-1; while (i>=0) do begin nsa := PNodeServerAddress( FListByIp[i] )^; If ( Not (nsa.is_blacklisted) ) // Not blacklisted And ( (nsa.netConnection = Nil) // No connection OR // Connected but a lot of time without data... ( (Assigned(nsa.netConnection)) AND ( (nsa.last_connection + CT_LAST_CONNECTION_MAX_MINUTES) < currunixtimestamp ) ) ) And ( (nsa.total_failed_attemps_to_connect>0) OR ( // I've not connected CT_LAST_CONNECTION_MAX_MINUTES minutes before ( (nsa.last_connection + CT_LAST_CONNECTION_MAX_MINUTES) < currunixtimestamp ) And // Others have connected CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES minutes before ( (nsa.last_connection_by_server + CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES) < currunixtimestamp ) And ( (nsa.last_connection>0) Or (nsa.last_connection_by_server>0) ) ) ) And ( (nsa.last_connection_by_me=0) Or ( (nsa.last_connection_by_me + 86400) < currunixtimestamp ) // Not connected in 24 hours ) then begin TLog.NewLog(ltdebug,ClassName,Format('Delete node server address: %s : %d last_connection:%d last_connection_by_server:%d total_failed_attemps:%d last_attempt_to_connect:%s ', [nsa.ip,nsa.port,nsa.last_connection,nsa.last_connection_by_server,nsa.total_failed_attemps_to_connect,FormatDateTime('dd/mm/yyyy hh:nn:ss',nsa.last_attempt_to_connect)])); SecuredDeleteFromListByIp(i); end; dec(i); end; finally FCritical.Release; end; end; procedure TOrderedServerAddressListTS.Clear; Var P : PNodeServerAddress; i : Integer; begin FCritical.Acquire; Try for i := 0 to FListByIp.Count - 1 do begin P := FListByIp[i]; Dispose(P); end; // inc(FNetData.FNetStatistics.NodeServersDeleted,FListByIp.count); // ** FIX ** FListByIp.Clear; FListByNetConnection.Clear; // FNetData.FNetStatistics.NodeServersListCount := 0; // ** FIX ** finally FCritical.Release; end; end; function TOrderedServerAddressListTS.Count: Integer; begin FCritical.Acquire; try Result := FListByIp.Count; finally FCritical.Release; end; end; constructor TOrderedServerAddressListTS.Create( ParaNetStatistics : PNetStatistics ); begin FNetStatistics := ParaNetStatistics; FCritical := TPCCriticalSection.Create(Classname); FListByIp := TList.Create; FListByNetConnection := TList.Create; FAllowDeleteOnClean := True; end; function TOrderedServerAddressListTS.DeleteNetConnection(netConnection: TNetConnection) : Boolean; Var i : Integer; begin FCritical.Acquire; Try If SecuredFindByNetConnection(netConnection,i) then begin PNodeServerAddress( FListByNetConnection[i] )^.netConnection := Nil; FListByNetConnection.Delete(i); Result := True; end else Result := False; Finally FCritical.Release; end; end; destructor TOrderedServerAddressListTS.Destroy; begin Clear; FreeAndNil(FCritical); FreeAndNil(FListByIp); FreeAndNil(FListByNetConnection); inherited Destroy; end; function TOrderedServerAddressListTS.GetNodeServerAddress(const ip: AnsiString; port: Word; CanAdd: Boolean; var nodeServerAddress: TNodeServerAddress): Boolean; Var i : Integer; P : PNodeServerAddress; begin FCritical.Acquire; Try if SecuredFindByIp(ip,port,i) then begin P := FListByIp.Items[i]; nodeServerAddress := P^; Result := True; end else if CanAdd then begin New(P); P^ := CT_TNodeServerAddress_NUL; P^.ip := ip; P^.port := port; FListByIp.Insert(i,P); nodeServerAddress := P^; Result := True end else begin nodeServerAddress := CT_TNodeServerAddress_NUL; Result := False; end; Finally FCritical.Release; End; end; procedure TOrderedServerAddressListTS.GetNodeServersToConnnect(maxNodes: Integer; useArray : Boolean; var nsa: TNodeServerAddressArray); Procedure sw(l : TList); Var i,j,x,y : Integer; begin if l.Count<=1 then exit; j := Random(l.Count)*3; for i := 0 to j do begin x := Random(l.Count); y := Random(l.Count); if x<>y then l.Exchange(x,y); end; end; Function IsValid(Const ns : TNodeServerAddress) : Boolean; Begin Result := (Not Assigned(ns.netConnection)) AND (Not IsBlackListed(ns.ip)) AND (Not ns.its_myself) And ((ns.last_attempt_to_connect=0) Or ((ns.last_attempt_to_connect+EncodeTime(0,3,0,0)<now))) And ((ns.total_failed_attemps_to_connect<3) Or (ns.last_attempt_to_connect+EncodeTime(0,10,0,0)<now)); End; Var i,j, iStart : Integer; P : PNodeServerAddress; l : TList; ns : TNodeServerAddress; begin SetLength(nsa,0); FCritical.Acquire; Try l := TList.Create; Try if useArray then begin for i := 0 to High(nsa) do begin If GetNodeServerAddress(nsa[i].ip,nsa[i].port,true,ns) then begin if IsValid(ns) then begin new(P); P^ := ns; l.Add(P); end; end; end; end else begin if FListByIp.Count>0 then begin iStart := Random(FListByIp.Count); i := iStart; j := FListByIp.Count; while (l.Count<maxNodes) And (i<j) do begin P := FListByIp[i]; If (Not Assigned(P.netConnection)) AND (Not IsBlackListed(P^.ip)) AND (Not P^.its_myself) And ((P^.last_attempt_to_connect=0) Or ((P^.last_attempt_to_connect+EncodeTime(0,3,0,0)<now))) And ((P^.total_failed_attemps_to_connect<3) Or (P^.last_attempt_to_connect+EncodeTime(0,10,0,0)<now)) then begin l.Add(P); end; // Second round inc(i); if (i>=j) and (iStart>0) then begin j := iStart; iStart := 0; i := 0; end; end; end; end; if (l.Count>0) then begin sw(l); if l.Count<maxNodes then setLength(nsa,l.Count) else setLength(nsa,maxNodes); for i := 0 to high(nsa) do begin nsa[i] := PNodeServerAddress(l[i])^; end; end; Finally if useArray then begin for i := 0 to l.Count - 1 do begin P := l[i]; Dispose(P); end; end; l.Free; End; Finally FCritical.Release; end; end; function TOrderedServerAddressListTS.GetValidNodeServers(OnlyWhereIConnected: Boolean; Max: Integer): TNodeServerAddressArray; var i,j,iStart : Integer; nsa : TNodeServerAddress; currunixtimestamp : Cardinal; begin SetLength(Result,0); currunixtimestamp := UnivDateTimeToUnix(DateTime2UnivDateTime(now)); CleanNodeServersList; // Save other node servers FCritical.Acquire; try If Max>0 then iStart := Random(FListByIp.Count) else iStart := 0; i := iStart; j := FListByIp.Count; while ((length(Result)<Max) Or (Max<=0)) And (i<j) do begin nsa := PNodeServerAddress( FListByIp[i] )^; if ( Not IsBlackListed(nsa.ip) ) And ( // I've connected 1h before ( (nsa.last_connection>0) And ( (Assigned(nsa.netConnection)) Or ( (nsa.last_connection + CT_LAST_CONNECTION_MAX_MINUTES) > currunixtimestamp ) ) ) Or // Others have connected 3h before ( (nsa.last_connection_by_server>0) And ( (nsa.last_connection_by_server + CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES) > currunixtimestamp ) ) Or // Peer cache ( (nsa.last_connection=0) And (nsa.last_connection_by_server=0) ) ) And ( // Never tried to connect or successfully connected (nsa.total_failed_attemps_to_connect=0) ) And ( (Not nsa.its_myself) Or (nsa.port=CT_NetServer_Port) ) And ( (Not OnlyWhereIConnected) Or (nsa.last_connection>0) ) then begin SetLength(Result,length(Result)+1); Result[high(Result)] := nsa; end; // Second round inc(i); if (i>=j) and (iStart>0) then begin j := iStart; iStart := 0; i := 0; end; end; finally FCritical.Release; end; end; function TOrderedServerAddressListTS.IsBlackListed(const ip: AnsiString): Boolean; Var i : Integer; P : PNodeServerAddress; begin Result := false; FCritical.Acquire; Try SecuredFindByIp(ip,0,i); // Position will be the first by IP: while (i<FListByIp.Count) And (Not Result) do begin P := PNodeServerAddress(FListByIp[i]); if Not SameStr(P^.ip,ip) then exit; if P^.is_blacklisted then begin Result := Not P^.its_myself; end; inc(i); end; Finally FCritical.Release; End; end; function TOrderedServerAddressListTS.LockList: TList; begin FCritical.Acquire; Result := FListByIp; end; procedure TOrderedServerAddressListTS.SecuredDeleteFromListByIp(index: Integer); Var P : PNodeServerAddress; i2 : Integer; begin P := FListByIp.Items[index]; if (Assigned(P^.netConnection)) then begin If SecuredFindByNetConnection(P^.netConnection,i2) then begin FListByNetConnection.Delete(i2); end else TLog.NewLog(ltError,ClassName,'DEV ERROR 20180201-1 NetConnection not found!'); end; Dispose(P); FListByIp.Delete(index); // dec(FNetData.FNetStatistics.NodeServersListCount); // ** FIX ** // inc(FNetData.FNetStatistics.NodeServersDeleted); // ** FIX ** end; function TOrderedServerAddressListTS.SecuredFindByIp(const ip: AnsiString; port: Word; var Index: Integer): Boolean; var L, H, I, C: Integer; PN : PNodeServerAddress; begin Result := False; L := 0; H := FListByIp.Count - 1; while L <= H do begin I := (L + H) shr 1; PN := FListByIp.Items[I]; C := CompareStr( PN.ip, ip ); If (C=0) then begin C := PN.port-port; end; if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; function TOrderedServerAddressListTS.SecuredFindByNetConnection(const search: TNetConnection; var Index: Integer): Boolean; var L, H, I: Integer; PN : PNodeServerAddress; C : PtrInt; begin Result := False; L := 0; H := FListByNetConnection.Count - 1; while L <= H do begin I := (L + H) shr 1; PN := FListByNetConnection.Items[I]; C := PtrInt(PN.netConnection) - PtrInt(search); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; procedure TOrderedServerAddressListTS.SetNodeServerAddress( const nodeServerAddress: TNodeServerAddress); Var i : Integer; P : PNodeServerAddress; begin FCritical.Acquire; Try if SecuredFindByIp(nodeServerAddress.ip,nodeServerAddress.port,i) then begin P := FListByIp.Items[i]; if (P^.netConnection<>nodeServerAddress.netConnection) then begin // Updated netConnection if Assigned(P^.netConnection) then begin // Delete old value if Not DeleteNetConnection(P^.netConnection) then TLog.NewLog(lterror,Classname,'DEV ERROR 20180205-1'); end; end; P^ := nodeServerAddress; end else begin New(P); P^ := nodeServerAddress; FListByIp.Insert(i,P); // Inc(FNetData.FNetStatistics.NodeServersListCount); // ** FIX ** TLog.NewLog(ltdebug,Classname,'Adding new server: '+NodeServerAddress.ip+':'+Inttostr(NodeServerAddress.port)); end; if Assigned(nodeServerAddress.netConnection) then begin If Not SecuredFindByNetConnection(nodeServerAddress.netConnection,i) then begin FListByNetConnection.Insert(i,P); end; end; Finally FCritical.Release; end; end; procedure TOrderedServerAddressListTS.UnlockList; begin FCritical.Release; end; procedure TOrderedServerAddressListTS.UpdateNetConnection(netConnection: TNetConnection); Var i : Integer; begin FCritical.Acquire; Try If SecuredFindByNetConnection(netConnection,i) then begin PNodeServerAddress(FListByNetConnection[i])^.last_connection := (UnivDateTimeToUnix(DateTime2UnivDateTime(now))); PNodeServerAddress(FListByNetConnection[i])^.total_failed_attemps_to_connect := 0; end; Finally FCritical.Release; End; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clTcpCommandClient; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Windows, Messages, SysUtils, WinSock,{$IFDEF DEMO} Forms,{$ENDIF} {$ELSE} System.Classes, Winapi.Windows, Winapi.Messages, System.SysUtils, Winapi.WinSock,{$IFDEF DEMO} Vcl.Forms,{$ENDIF} {$ENDIF} clTcpClient, clTcpClientTls, clSspi, clWUtils, clSocketUtils, clUtils; type TclTcpTextEvent = procedure(Sender: TObject; const AText: string) of object; TclTcpListEvent = procedure(Sender: TObject; AList: TStrings) of object; TclTcpCommandClient = class(TclTcpClientTls) private FUserName: string; FPassword: string; FResponse: TStrings; FLastResponseCode: Integer; FOnReceiveResponse: TclTcpListEvent; FOnSendCommand: TclTcpTextEvent; FOnProgress: TclProgressEvent; FAuthorization: string; FCharSet: string; procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); procedure SetCharSet(const Value: string); function ReceiveResponse(AddToLastString: Boolean): Boolean; function IsOkResponse(AResponseCode: Integer; const AOkResponses: array of Integer): Boolean; procedure DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); function GetLinesTrailer(const ALinesTrailer: string): string; procedure WriteLine(AStream: TStream; const ALine: string); protected procedure InternalOpen; override; procedure InternalClose(ANotifyPeer: Boolean); override; procedure DoDestroy; override; procedure OpenSession; virtual; abstract; procedure CloseSession; virtual; abstract; function GetResponseCode(const AResponse: string): Integer; virtual; abstract; function ParseResponse(AStartFrom: Integer; const AOkResponses: array of Integer): Integer; function InternalWaitResponse(AStartFrom: Integer; const AOkResponses: array of Integer): Integer; procedure InternalSendCommandSync(const ACommand: string; const AOkResponses: array of Integer); virtual; procedure SetAuthorization(const Value: string); virtual; function GetWriteCharSet(const AText: string): string; virtual; function GetReadCharSet(AStream: TStream): string; virtual; procedure DoSendCommand(const AText: string); dynamic; procedure DoReceiveResponse(AList: TStrings); dynamic; procedure DoProgress(ABytesProceed, ATotalBytes: Int64); dynamic; public constructor Create(AOwner: TComponent); override; procedure SendCommand(const ACommand: string); procedure SendCommandSync(const ACommand: string; const AOkResponses: array of Integer); overload; procedure SendCommandSync(const ACommand: string; const AOkResponses: array of Integer; const Args: array of const); overload; procedure SendSilentCommand(const ACommand: string; const AOkResponses: array of Integer); overload; procedure SendSilentCommand(const ACommand: string; const AOkResponses: array of Integer; const Args: array of const); overload; procedure SendMultipleLines(ALines: TStrings; const ALinesTrailer: string); procedure WaitMultipleLines(ATotalBytes: Int64); virtual; procedure WaitResponse(const AOkResponses: array of Integer); virtual; property Response: TStrings read FResponse; property LastResponseCode: Integer read FLastResponseCode; published property UserName: string read FUserName write SetUserName; property Password: string read FPassword write SetPassword; property Authorization: string read FAuthorization write SetAuthorization; property CharSet: string read FCharSet write SetCharSet; property OnSendCommand: TclTcpTextEvent read FOnSendCommand write FOnSendCommand; property OnReceiveResponse: TclTcpListEvent read FOnReceiveResponse write FOnReceiveResponse; property OnProgress: TclProgressEvent read FOnProgress write FOnProgress; end; const SOCKET_WAIT_RESPONSE = 0; SOCKET_DOT_RESPONSE = 1; implementation uses clTranslator{$IFDEF LOGGER}, clLogger{$ENDIF}; { TclTcpCommandClient } procedure TclTcpCommandClient.SendCommand(const ACommand: string); var cmd: string; begin CheckConnected(); cmd := ACommand + #13#10; Connection.InitProgress(0, 0); {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'SendCommand: ' + cmd);{$ENDIF} Connection.WriteString(cmd, GetWriteCharSet(cmd)); DoSendCommand(cmd); end; function TclTcpCommandClient.ReceiveResponse(AddToLastString: Boolean): Boolean; var stream: TStream; strUtils: TclStringsUtils; begin stream := nil; strUtils := nil; try stream := TMemoryStream.Create(); Connection.ReadData(stream); stream.Position := 0; strUtils := TclStringsUtils.Create(Response, GetReadCharSet(stream)); Result := strUtils.AddTextStream(stream, AddToLastString) > 0; finally strUtils.Free(); stream.Free(); end; end; function TclTcpCommandClient.IsOkResponse(AResponseCode: Integer; const AOkResponses: array of Integer): Boolean; var i: Integer; begin Result := False; i := Low(AOkResponses); while (i <= High(AOkResponses)) and (AOkResponses[i] <> 0) do begin if (AOkResponses[i] = AResponseCode) then begin Result := True; Break; end; Inc(i); end; end; procedure TclTcpCommandClient.WaitResponse(const AOkResponses: array of Integer); begin Response.Clear(); InternalWaitResponse(0, AOkResponses); DoReceiveResponse(Response); end; procedure TclTcpCommandClient.InternalSendCommandSync(const ACommand: string; const AOkResponses: array of Integer); begin SendCommand(ACommand); WaitResponse(AOkResponses); end; procedure TclTcpCommandClient.SendCommandSync(const ACommand: string; const AOkResponses: array of Integer); begin InProgress := True; try InternalSendCommandSync(ACommand, AOkResponses); finally InProgress := False; end; end; procedure TclTcpCommandClient.SendCommandSync(const ACommand: string; const AOkResponses: array of Integer; const Args: array of const); begin SendCommandSync(Format(ACommand, Args), AOkResponses); end; procedure TclTcpCommandClient.SetAuthorization(const Value: string); begin if (FAuthorization <> Value) then begin FAuthorization := Value; Changed(); end; end; procedure TclTcpCommandClient.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; Changed(); end; end; procedure TclTcpCommandClient.SetPassword(const Value: string); begin if (FPassword <> Value) then begin FPassword := Value; Changed(); end; end; procedure TclTcpCommandClient.SetUserName(const Value: string); begin if (FUserName <> Value) then begin FUserName := Value; Changed(); end; end; constructor TclTcpCommandClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FResponse := TStringList.Create(); FCharSet := ''; end; procedure TclTcpCommandClient.InternalClose(ANotifyPeer: Boolean); begin try if Active and not InProgress then begin CloseSession(); end; finally inherited InternalClose(ANotifyPeer); end; end; procedure TclTcpCommandClient.InternalOpen; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end; {$ENDIF} {$ENDIF} inherited InternalOpen(); OpenSession(); end; function TclTcpCommandClient.GetLinesTrailer(const ALinesTrailer: string): string; begin Result := ALinesTrailer; if (Result <> '') and (Result[Length(Result)] <> #10) then begin Result := Result + #13#10; end; end; function TclTcpCommandClient.GetReadCharSet(AStream: TStream): string; begin Result := FCharSet; end; function TclTcpCommandClient.GetWriteCharSet(const AText: string): string; begin Result := FCharSet; end; procedure TclTcpCommandClient.WriteLine(AStream: TStream; const ALine: string); var buf: TclByteArray; begin buf := TclTranslator.GetBytes(ALine, GetWriteCharSet(ALine)); if (Length(buf) > 0) then begin AStream.Write(buf[0], Length(buf)); end; end; procedure TclTcpCommandClient.SendMultipleLines(ALines: TStrings; const ALinesTrailer: string); var i: Integer; stream: TStream; line, trailer: string; begin if (BatchSize < 1) then begin RaiseSocketError(InvalidBatchSize, InvalidBatchSizeCode); end; trailer := GetLinesTrailer(ALinesTrailer); stream := TMemoryStream.Create(); Connection.OnProgress := DoDataProgress; InProgress := True; try i := 0; line := ''; Connection.InitProgress(0, GetStringsSize(ALines) + Length(trailer)); while (i < ALines.Count) do begin line := ALines[i]; if (Length(ALines[i]) + Length(#13#10) + 1 > BatchSize) then begin if (stream.Size > 0) then begin stream.Position := 0; Connection.WriteData(stream); stream.Size := 0; end; Connection.WriteString(line + #13#10, GetWriteCharSet(line)); end else if ((stream.Size + 3 + Length(line)) <= BatchSize) then begin if (Length(line) > 0) then begin if (trailer = '.'#13#10) and (line[1] = '.') then begin WriteLine(stream, '.'); end; WriteLine(stream, line); end; WriteLine(stream, #13#10); end else begin stream.Position := 0; Connection.WriteData(stream); stream.Position := 0; stream.Size := 0; Continue; end; Inc(i); end; if (stream.Size > 0) then begin stream.Position := 0; Connection.WriteData(stream); end; if (trailer <> '') then begin stream.Position := 0; stream.Size := 0; WriteLine(stream, trailer); stream.Position := 0; Connection.WriteData(stream); end; finally InProgress := False; Connection.OnProgress := nil; stream.Free(); end; end; procedure TclTcpCommandClient.DoReceiveResponse(AList: TStrings); begin if Assigned(OnReceiveResponse) then begin OnReceiveResponse(Self, AList); end; end; procedure TclTcpCommandClient.DoSendCommand(const AText: string); begin if Assigned(OnSendCommand) then begin OnSendCommand(Self, AText); end; end; procedure TclTcpCommandClient.DoProgress(ABytesProceed, ATotalBytes: Int64); begin if Assigned(OnProgress) then begin OnProgress(Self, ABytesProceed, ATotalBytes); end; end; procedure TclTcpCommandClient.DoDestroy; begin FResponse.Free(); inherited DoDestroy(); end; procedure TclTcpCommandClient.WaitMultipleLines(ATotalBytes: Int64); function CheckForDotTerminator: Boolean; begin Result := (Response.Count > 0) and (Response[Response.Count - 1] = '.'); end; procedure RemoveResponseLine; begin if (Response.Count > 0) then begin Response.Delete(0); end; end; procedure RemoveDotTerminatorLine; begin Assert(Response.Count > 0); Response.Delete(Response.Count - 1); end; procedure ReplaceLeadingDotTerminator; var i: Integer; begin for i := 0 to Response.Count - 1 do begin if (system.Pos('..', Response[i]) = 1) then begin Response[i] := system.Copy(Response[i], 2, Length(Response[i])); end; end; end; begin Connection.OnProgress := DoDataProgress; InProgress := True; try if (ATotalBytes > 0) then begin Connection.InitProgress(GetStringsSize(Response), ATotalBytes); end else begin Connection.InitProgress(0, 0); end; RemoveResponseLine(); if not CheckForDotTerminator then begin InternalWaitResponse(0, [SOCKET_DOT_RESPONSE]); end; ReplaceLeadingDotTerminator(); RemoveDotTerminatorLine(); finally InProgress := False; Connection.OnProgress := nil; end; if (ATotalBytes > 0) then begin DoProgress(ATotalBytes, ATotalBytes); end; end; procedure TclTcpCommandClient.DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin if (ABytesProceed <= ATotalBytes) then begin DoProgress(ABytesProceed, ATotalBytes); end; end; function TclTcpCommandClient.ParseResponse(AStartFrom: Integer; const AOkResponses: array of Integer): Integer; var i, tempCode: Integer; begin Result := -1; for i := AStartFrom to Response.Count - 1 do begin tempCode := GetResponseCode(Response[i]); if (tempCode <> SOCKET_WAIT_RESPONSE) then begin FLastResponseCode := tempCode; if IsOkResponse(LastResponseCode, AOkResponses) then begin Result := i; Exit; end; end; end; end; function TclTcpCommandClient.InternalWaitResponse(AStartFrom: Integer; const AOkResponses: array of Integer): Integer; var keepLastString: Boolean; begin Result := -1; keepLastString := False; repeat keepLastString := ReceiveResponse(keepLastString); if keepLastString then begin Continue; end; FLastResponseCode := SOCKET_WAIT_RESPONSE; if (Response.Count = AStartFrom) and (Length(AOkResponses) = 0) then begin Break; end; Result := ParseResponse(AStartFrom, AOkResponses); if Result > -1 then begin Break; end; if not ((Length(AOkResponses) = 1) and (AOkResponses[Low(AOkResponses)] = SOCKET_DOT_RESPONSE)) and (LastResponseCode <> SOCKET_WAIT_RESPONSE) then begin RaiseTcpClientError(Trim(Response.Text), LastResponseCode); end; until False; end; procedure TclTcpCommandClient.SendSilentCommand(const ACommand: string; const AOkResponses: array of Integer; const Args: array of const); begin CheckConnected(); try SendCommandSync(ACommand, AOkResponses, Args); except on EclSocketError do ; on EclSSPIError do ; end; end; procedure TclTcpCommandClient.SendSilentCommand(const ACommand: string; const AOkResponses: array of Integer); begin CheckConnected(); try SendCommandSync(ACommand, AOkResponses); except on EclSocketError do ; on EclSSPIError do ; end; end; end.
{******************************************************************************* Nordson Corporation Amherst, Ohio, USA Copyright 1998 $Workfile: LogManagerUnit.pas$ DESCRIPTION: Logs maintains a list of current events . Deletes and creates logfiles as needed. Allows multiple reads or copy of files on networks Has onUpdateEvent *******************************************************************************} unit LogManagerUnit; interface uses SysUtils, Classes, syncobjs, FileCtrl, IsoIniFileUnit,windows; type // these are event classes or sources of log events // A const array type of EnglishNames is defined below for translation purposes. TEventClass = ( ecMinClass, ecStartup, ecShutdown, ecConveyor, ecComm, ecRobot, ecProduction, ecDispense, ecUser, ecEditing, ecRuntime, ecIDSystem, ecTool, ecFluidSystem, ecCamera, ecFIS, ecSecurity, ecMaxClass); // the following comments are for the language manager to read in // the string names for the Event Class and Level for its translation file. { 'Startup','Shutdown','Conveyor', 'Comm', 'Robot', 'Production', //ivlm 'Dispense', 'User', 'Editing', 'Runtime', 'IDSystem', 'Tool', //ivlm 'FluidSystem' //ivlm } { 'Debug', 'Event', 'Warning', 'Error' //ivlm } // these are event levels of severity TEventLevel = ( elDebug, elEvent, elWarning, elError); TEventClassFilter = set of TEventClass; { forward declarations} TLogManager = class; TLogItem = class; // // TLogItem Class // encapsulates a loggable event, including the time stamp, event level, // event class, and an event string; can produce a string summarizing the event // TLogItem = class(TObject) protected FTimeStamp : TDateTime; FEventString : string; FEventLevel : TEventLevel; FEventCLass : TEventClass; FBriefDateTimeFormatString : string; FBriefSummaryClassEnabled : boolean; function GetEventSummary: String; virtual; function GetBriefSummary: String; virtual; public constructor Create; virtual; function Assign( Source : TLogItem ) : Boolean; virtual; function Duplicate : TLogItem; virtual; property TimeStamp : TDateTime read FTimeStamp write FTimeStamp; property EventString : string read FEventString write FEventString; property EventLevel : TEventLevel read FEventLevel write FEventLevel; property EventClass : TEventClass read FEventClass write FEventClass; property EventSummary : String read GetEventSummary; property BriefSummary : String read GetBriefSummary; property BriefDateTimeFormatString : string read FBriefDateTimeFormatString write FBriefDateTimeFormatString; property BriefSummaryClassEnabled : boolean read FBriefSummaryClassEnabled write FBriefSummaryClassEnabled; end; TLogItemWithThreadID = class( TLogItem ) protected FThreadID : integer; function GetEventSummary: String; override; function GetBriefSummary: String; override; public constructor Create; override; function Assign( Source : TLogItem ) : Boolean; override; function Duplicate : TLogItem; override; property ThreadID : integer read FThreadID write FThreadID; end; // Delphi event declaration TLogStatusEvent = Procedure(Sender : TObject; RecordStr : string; DataObject : TObject; Source : TEventClass) of object; TLogListEvent = Procedure(Sender : TObject; EventItemList : TList) of object; TLogTriggerEvent = Procedure(id: integer) of object; TLogStatusEventReference = record pCode: pointer; pData: pointer; end; // // TThreadBuffer // this buffer is a TList wrapper used TLogManager to communicate // with TLogThread; it contains a CS as well as waking up the thread // on Add() // TThreadBuffer = class( TObject ) private FLogItemList : TList; FStatusList : TStringList; FLogThread : TThread; FCS : TCriticalSection; function GetLogItemCount: Integer; function GetStatusCount: Integer; public constructor Create; destructor Destroy; override; function PushLogItem( NewItem : TLogItem ) : Boolean; function PopLogItem : TLogItem; function PushStatus( NewStatus : String ; EventClass : TEventClass; DataObject : TObject ) : Boolean; function PopStatus( var NewStatus : String; var EventClass : TEventClass; var DataObject : TObject) : Boolean; function PopLogItemsIntoList : TList; property LogItemCount : Integer read GetLogItemCount; property StatusCount : Integer read GetStatusCount; property LogThread : TThread read FLogThread write FLogThread; end; TBufferItem = class( TObject ) private FEventClass: TEventClass; FDataObject: TObject; public constructor Create; destructor Destroy; override; property EventClass : TEventClass read FEventClass write FEventClass; property DataObject : TObject read FDataObject write FDataObject; end; // // TLogThread // this is used to buffer events to VCL objects, such as updating a display // of log items or status // TLogThread = class( TThread ) private FBuffer : TThreadBuffer; FLog : TLogManager; FNewLogEntryEvent: TEvent; FShuttingDown: Boolean; protected procedure Execute; override; procedure SendLogItem; procedure SendStatus; public constructor Create( Log : TLogManager; Buffer : TThreadBuffer ); destructor Destroy; override; property NewLogEntryEvent : TEvent read FNewLogEntryEvent; end; TTriggerRecord = class(TObject) public triggerID: integer; triggerCaption: string; triggerCallback: TLogTriggerEvent; triggerDelayOn: Boolean; triggerDelayMilliseconds: integer; triggerTime: TDateTime; constructor Create(id: integer; callback: TLogTriggerEvent; cap: string); end; TLogItemClass = class of TLogItem; // // TLogManager // This handles all logging operations and is the main interface for clients // of the logging system // TTriggerStringList = class (TObject) private FWildcardStrings : TStringList; FExactStrings: TStringList; //FFoundTriggers: TStringList; public destructor Destroy; override; constructor Create; function Find(const S: string): TStringList; function AddTrigger(const S: string; AObject: TObject): Integer; // property FoundTriggers: TStringList read FFoundTriggers write FFoundTriggers; end; {TTriggerStringListOld = class (TStringList) private FWildcardStrings : TStringList; FExactStrings: TStringList; //FFoundTriggers: TStringList; public destructor Destroy; override; constructor Create; function Find(const S: string): TStringList; function AddTrigger(const S: string; AObject: TObject): Integer; // property FoundTriggers: TStringList read FFoundTriggers write FFoundTriggers; end; } TTriggerStringListOld = class (TStringList) private FPartialStrings : TStringList; public destructor Destroy; override; function Find(const S: string; var Index: Integer): Boolean; override; function AddObject(const S: string; AObject: TObject): Integer; override; end; TLogManager = class(TObject) private { Private declarations } FLogPath : string; // path to the log directory FFileList : TStringList; // used to find the log files // FOnLogUpdate : TLogListEvent; // event generated with each log entry FOnLogUpdate1 : TLogListEvent; // event generated with each log entry FOnLogUpdate2 : TLogListEvent; // event generated with each log entry // FOnStatusUpdate: TLogStatusEvent; FThreadBuffer : TThreadBuffer; FThread : TLogThread; FFileFilter: TEventClassFilter; FDisplayFilter: TEventClassFilter; FDisplayFilterLevel: TEventLevel; FFileFilterLevel: TEventLevel; FUnpaddedLevelMap : TStringList; FUnpaddedClassMap : TStringList; FMaxNumberLogFiles: integer; FDataFileName: string; FFileBufferList : TList; FBufferDepth: integer; FDumpBufferSize: integer; FLogItemClass : TLogItemClass; FTriggerList: TTriggerStringList; FDelayedTriggers: TStringList; FDumpBufferList : TList; FPostErrorCountdown: integer; FPostErrorMessages: integer; FMainVCLThreadID: THandle; FMessageDepth: integer; FTriggerEnable: Boolean; function FlushFileBuffer : boolean; procedure HandleTrigger(trig: TTriggerRecord); procedure DelegateTrigger(trig: TTriggerRecord); function GetStatusSubscriberCount: integer; procedure SetTriggerEnable(const Value: Boolean); // SingletonCS : TCriticalSection; protected { Protected declarations } FLogCriticalSection : TCriticalSection; FStatusCriticalSection : TCriticalSection; FBriefDateTimeFormatString : string; FBriefSummaryClassEnabled : boolean; StatusSubscribers: Array of TLogStatusEvent; constructor SpecialCreate; function InsertLogEntry(LogItemIn : TLogItem) : Boolean; function WriteLogEntryToFile( LogItem : TLogItem ) : Boolean; function WriteLogEntryToDisplayBuffer( LogItem : TLogItem ) : Boolean; function RemoveOldLogFiles : Boolean; function GenerateLogFileName( LogItem : TLogItem ) : string; function IsItemInFilter( FilterLevel : TEventLevel; FilterClasses : TEventClassFilter; LogItem : TLogItem ) : boolean; function OpenFileForWriting(FName: String; var FStream : TFileStream): boolean; function CreateLogDirectoryIfNeeded : Boolean; function LogItemFactory : TLogItem; public { Public declarations } constructor Create; procedure SetStatus(EventClass: TEventClass; const Value: string; DataObject : TObject); procedure PadStrings; class function Instance : TLogManager; destructor Destroy; override; function LogDebug( EventClass : TEventClass; EventString : String ) : Boolean; function LogEvent( EventClass : TEventClass; EventString : String ) : Boolean; function LogWarning( EventClass : TEventClass; EventString : String ) : Boolean; function LogError( EventClass : TEventClass; EventString : String ) : Boolean; function LogMessage( EventLevel: TEventLevel; EventClass : TEventClass; EventString : String ) : Boolean; function LogStrings( EventLevel: TEventLevel; EventClass : TEventClass; EventStrings : TStrings; prefix: string ) : Boolean; function SaveFilterStateToIniFile( IFile : TIsoIniFile ) : Boolean; function FlushLog : Boolean; function LoadFilterStateFromIniFile( IFile : TIsoIniFile ) : Boolean; function AddLogTrigger(triggerID: integer; triggerString: string; callbackFunction: TLogTriggerEvent; caption: string; delayMilliseconds: integer=0): Boolean; procedure TBD(EventString: string); procedure AddStatusSubscriber(subscriber: TLogStatusEvent); procedure RemoveStatusSubscriber(subscriber: TLogStatusEvent); procedure ShutdownNotify; procedure ProcessMessages; procedure SwitchToDebugMode; property ClassMap: TStringList read FUnPaddedClassMap; property LevelMap: TStringList read FUnpaddedLevelMap; property LogThread : TLogThread read FThread; property DataFileName : string read FDataFileName write FDataFileName; property StatusSubscriberCount: integer read GetStatusSubscriberCount; property TriggerEnable: Boolean read FTriggerEnable write SetTriggerEnable; // property OnStatusUpdate : TLogStatusEvent read FOnStatusUpdate // write FOnStatusUpdate; //taj published { Published declarations } property FileFilter : TEventClassFilter read FFileFilter write FFileFilter; property FileFilterLevel : TEventLevel read FFileFilterLevel write FFileFilterLevel; property DisplayFilter : TEventClassFilter read FDisplayFilter write FDisplayFilter; property DisplayFilterLevel : TEventLevel read FDisplayFilterLevel write FDisplayFilterLevel; property MaxNumberLogFiles : integer read FMaxNumberLogFiles write FMaxNumberLogfiles; property LogPath : string read FLogPath write FLogPath; // property OnLogUpdate : TLogListEvent read FOnLogUpdate // write FOnLogUpdate; property OnLogUpdate1 : TLogListEvent read FOnLogUpdate1 write FOnLogUpdate1; property OnLogUpdate2 : TLogListEvent read FOnLogUpdate2 write FOnLogUpdate2; property BriefDateTimeFormatString : string read FBriefDateTimeFormatString write FBriefDateTimeFormatString; property BriefSummaryClassEnabled : boolean read FBriefSummaryClassEnabled write FBriefSummaryClassEnabled; end; // these two functions use RTTI methods to get strings out of the // enumerated types function GetEventClass( EventClass : TEventClass ): String; function GetEventLevel( EventLevel : TEventLevel): String; implementation uses Forms, Dialogs, typinfo, ivDictio; var SingletonInstance : TLogManager; // singleton reference FEventLevelMap : TStringList; // holds the map of enumerated values to their // string representations FEventClassMap : TStringList; // holds the map of enumerated values to their // string representations { FEventLevelMap : TStringList; // holds the map of enumerated values to their // string representations FEventClassMap : TStringList; // holds the map of enumerated values to their // string representations MaxClass : integer; // maximum class value MaxLevel : integer; // maximum level value pti : PTypeInfo; ptd : PTypeData; IndexI, IndexJ, IndexK : integer; SingletonCS : TCriticalSection; EnumString : string; } const newLine = #13#10; // CR and LF MAX_BUFFERED_ITEMS = 500; // DEFAULT_INIFILESECTION = 'Log Settings'; //no trans DEFAULT_MAX_LOG_FILES = 15; DEFAULT_FILE_BUFFER_DEPTH = 50; DEFAULT_BRIEF_FORMAT = 'hh:mm:ss.zzz'; //no trans BUFFER_DEPTH_KEY = 'BufferDepth'; //no trans DUMP_BUFFER_SIZE_KEY = 'Dump Buffer Size'; //no trans DEFAULT_DUMP_BUFFER_SIZE = 500; DUMP_POST_ERROR_MESSAGES_KEY = 'Post Error Messages'; //no trans DEFAULT_DUMP_POST_ERROR_MESSAGES = 100; // Logger destructor procedure TLogManager.DelegateTrigger(trig: TTriggerRecord); begin //note that the delays are minimums; there needs to be another //message logged to check for any delayed messages. //However, with the real machine, there is constant communication, so //there are frequent checks of these delayed log triggers. if trig.triggerDelayOn then begin FDelayedTriggers.AddObject(trig.triggerCaption,trig); if trig.triggerDelayMilliseconds > 0 then begin //convert the milliseconds to days trig.triggerTime := now + (trig.triggerDelayMilliseconds/(1000*3600*24)); end else begin //a negative delay means make it random up to the magnitude of the delay trig.triggerTime := now + (Random(0-trig.triggerDelayMilliseconds)/(1000*3600*24)); end; end else begin HandleTrigger(trig); end; end; destructor TLogManager.destroy; begin // free file buffer // there shouldn't be any entries left by the time we get here (see finalization call to flushlog) // but delete them in any case - it is too late to do anything useful with them while( FFileBufferList.Count > 0 ) do begin TLogItem( FFileBufferList.Items[0] ).Free; FFileBufferList.Delete(0); end; FFileBufferList.Free; while( FDumpBufferList.Count > 0 ) do begin TLogItem( FDumpBufferList.Items[0] ).Free; FDumpBufferList.Delete(0); end; FDumpBufferList.Free; // free up variables associated with limiting the number of log files if assigned(FFileList) then begin FFileList.clear; FFileList.free; end; // free critical sections FLogCriticalSection.Free; FStatusCriticalSection.Free; while( FUnPaddedLevelMap.Count > 0 ) do begin FUnPaddedLevelMap[0] := ''; //no trans FUnPaddedLevelMap.Delete(0); end; FUnPaddedLevelMap.Free; while( FUnPaddedClassMap.Count > 0 ) do begin FUnPaddedClassMap[0] := ''; //no trans FUnPaddedClassMap.Delete(0); end; FUnPaddedClassMap.Free; // terminate thread FThread.Terminate; // thread is responsible for Freeing ThreadBuffer FThread.WaitFor; FThread.Free; { while FTriggerList.Count > 0 do begin FTriggerList.Objects[0].Free; FTriggerList.Delete(0); end; } FTriggerList.Free; while FDelayedTriggers.Count > 0 do begin //these objects are duplicates of the trigger list, //so only delete the list items, do not free //the objects FDelayedTriggers.Delete(0); end; FDelayedTriggers.Free; inherited Destroy; end; // Log an event of level Event function TLogManager.LogEvent(EventClass: TEventClass; EventString: String) : Boolean; var NewLogItem : TLogItem; begin // create new log Item; try NewLogItem := LogItemFactory; except result := FALSE; exit; end; NewLogItem.EventString := EventString; NewLogItem.EventClass := EventClass; NewLogitem.EventLevel := elEvent; // insert item into log result := InsertLogEntry( NewLogItem ); end; // log an event of level Error function TLogManager.LogError(EventClass: TEventClass; EventString: String): Boolean; var NewLogItem : TLogItem; begin // create new log Item; try NewLogItem := LogItemFactory; except result := FALSE; exit; end; NewLogItem.EventString := EventString; NewLogItem.EventClass := EventClass; NewLogitem.EventLevel := elError; // insert item into log result := InsertLogEntry( NewLogItem ); end; // log an event of level Warning function TLogManager.LogWarning(EventClass: TEventClass; EventString: String): Boolean; var NewLogItem : TLogItem; begin // create new log Item; try NewLogItem := LogItemFactory; except result := FALSE; exit; end; NewLogItem.EventString := EventString; NewLogItem.EventClass := EventClass; NewLogitem.EventLevel := elWarning; // insert item into log result := InsertLogEntry( NewLogItem ); end; // insert TLogItem into log function TLogManager.InsertLogEntry(LogItemIn: TLogItem) : Boolean; var i: integer; //matchIndex: integer; triggeredItems,testItem: string; tmpFoundList: TStringList; begin // enter CS FLogCriticalSection.Enter; try result := WriteLogEntryToFile( LogItemIn); if result and TriggerEnable then begin //add this new section here, because sending it to //the display buffer means we are done with it and it //may be freed. tmpfoundList := FTriggerList.Find(LogItemIn.EventString); if assigned(tmpFoundList) then begin //there is at least one trigger, so go through the list while tmpFoundList.Count > 0 do begin DelegateTrigger(TTriggerRecord(tmpFoundList.Objects[0])); tmpFoundList.Delete(0); end; tmpFoundList.Free; end; { if FTriggerList.Find(LogItemIn.EventString,matchIndex) then begin //this is a trigger DelegateTrigger(TTriggerRecord(FTriggerList.Objects[matchIndex])); //check if there are more than one trigger registered for this string //find will have returned the first one in the list triggeredItems := IntToStr(Integer(FTriggerList.Objects[matchIndex]))+' ';//no trans i := matchIndex + 1; //changed for version 481 while ( i < FTriggerList.Count) // while ( i < Pred(FTriggerList.Count)) and ( AnsiCompareText(FTriggerList[matchIndex],FTriggerList[i])=0 ) do begin //we have another trigger for this string //for language independence, we have two strings in the list for the same trigger //one is translated, and one is not. However, the translated string might still be native //in which case we end up here //so check the string of the pointer testItem := IntToStr(Integer(FTriggerList.Objects[i]))+' '; //no trans if AnsiPos(testItem,triggeredItems)<= 0 then begin //this one has not been done yet triggeredItems := triggeredItems + testItem; DelegateTrigger(TTriggerRecord(FTriggerList.Objects[i])); end; inc(i); end; end; } //check any delayed triggers we are monitoring if FDelayedTriggers.Count > 0 then begin //this is a list of the delayed guys for i := FDelayedTriggers.Count - 1 downto 0 do begin //start at the end in case we delete one if (now > TTriggerRecord(FDelayedTriggers.Objects[i]).triggerTime)then begin HandleTrigger(TTriggerRecord(FDelayedTriggers.Objects[i])); FDelayedTriggers.Delete(i); end; end; end; end; if result then begin result := WriteLogEntryToDisplayBuffer( LogItemIn ); end; finally // leave CS FLogCriticalSection.Leave; end; end; // // TLogItem // // copy contents of a TLogItem into self function TLogItem.Assign(Source: TLogItem): Boolean; begin if Assigned( Source ) then begin FTimeStamp := Source.TimeStamp; FEventString := Source.EventString; FEventLevel := Source.EventLevel; FEventCLass := Source.EventClass; result := TRUE; end else begin result := FALSE; end; end; // create a log item constructor TLogItem.create; begin inherited Create; TimeStamp := Now; end; // return the string summarizing the event function TLogItem.Duplicate: TLogItem; begin result := TLogItem.Create; result.Assign( self ); end; function TLogItem.GetBriefSummary: String; begin // DecodeTime(TimeStamp, Hour, Min, Sec, MSec); // result := FormatDateTime('YYYY-MMM-DD hh:mm:ss', TimeStamp) //no trans // + format('.%.3d ',[MSec]); //no trans result := FormatDateTime(BriefDateTimeFormatString,TimeStamp); //no trans // optionally include the class (e.g., startup, robot, shutdown, etc.) if( FBriefSummaryClassEnabled ) then result := result + ' ' + Translate(GetEventClass( EventClass )); //no trans // now include the event message itself result := result + ' ' + EventString; //no trans end; function TLogItem.GetEventSummary: String; var Hour, Min, Sec, Msec : Word; begin DecodeTime(TimeStamp, Hour, Min, Sec, MSec); result := FormatDateTime('YYYY-MMM-DD hh:mm:ss', TimeStamp) //no trans + format('.%.3d ',[MSec]); //no trans result := result + ' ' + Translate(GetEventLevel( EventLevel )); //no trans result := result + ' ' + Translate(GetEventClass( EventClass )); //no trans result := result + ' ' + EventString; //no trans end; // map enumerated event class type to a string function GetEventClass( EventClass : TEventClass ): String; var EvtClass : Integer; begin EvtClass := Ord( EventClass ); if( ( EvtClass < FEventClassMap.Count ) and ( EvtClass >= 0 ) ) then begin result := FEventClassMap[ EvtClass ]; end else begin result := ''; //no trans end; end; // map enumerated event level type to a string function GetEventLevel( EventLevel : TEventLevel): String; var EvtLevel : Integer; begin EvtLevel := Ord(EventLevel); if( ( EvtLevel < FEventLevelMap.Count ) and ( EvtLevel >= 0 ) ) then begin result := FEventLevelMap[ EvtLevel ]; end else begin result := ''; //no trans end; end; procedure TLogManager.AddStatusSubscriber(subscriber: TLogStatusEvent); var i: integer; pCurrent,pTarget: TLogStatusEventReference; tmpFound : Boolean; begin i := 0; //added a check to prevent another bug related to adding duplicate status //subscribers and deleting one later (leaving one around to cause AVs) tmpFound := False; pTarget := TLogStatusEventReference(subscriber); while i < Length(StatusSubscribers) do begin pCurrent := TLogStatusEventReference(StatusSubscribers[i]); if pCurrent.pData = pTarget.pData then begin tmpFound := True; end; inc(i); end; if tmpFound then begin LogError(ecRuntime, 'Duplicate Status Subscriber'); //no trans end else begin SetLength(StatusSubscribers,Length(StatusSubscribers)+1); StatusSubscribers[Length(StatusSubscribers)-1] := subscriber; end; end; constructor TLogManager.Create; begin ShowMessage(Translate('Error: TLogManager Constructor Called!!!!')); //no trans end; class function TLogManager.Instance: TLogManager; begin { if( SingletonInstance = nil ) then begin // enter CS SingletonCS.Enter; // double-checked locking; this second test of SingletonInstance // is important! don't remove if( SingletonInstance = nil ) then begin SingletonInstance := TLogManager.SpecialCreate; end; // leave CS SingletonCS.Leave; end; } result := SingletonInstance; end; constructor TLogManager.SpecialCreate; var i : integer; begin try inherited Create; FMainVCLThreadID := GetCurrentThreadID(); // setup default log item brief date time format string BriefDateTimeFormatString := DEFAULT_BRIEF_FORMAT;// 'YYYY-MMM-DD hh:mm:ss.zzz';//no trans // default to include the class in the brief event summary (used for display) FBriefSummaryClassEnabled := TRUE; // setup startup CS // SingletonCS := TCriticalSection.Create; // initialize log item factory class FLogItemClass := TLogItemWithThreadID; // by default log the thread IDs // this gets us full debugging by default (i.e., when the /d command-line option is used) // create critical sections FLogCriticalSection := TCriticalSection.Create; FStatusCriticalSection := TCriticalSection.Create; // create buffer FThreadBuffer := TThreadBuffer.Create; // create file buffer FFileBufferList := TList.Create; FFileBufferList.Capacity := 1; // by default the buffer is one entry deep-ie, no buffering FDumpBufferList := TList.Create; FDumpBufferList.Capacity := DEFAULT_DUMP_BUFFER_SIZE; //dump this many messages when error occurs // create log thread FThread := TLogThread.Create( self, FThreadBuffer ); for i := 0 to 100 do begin if( Fthread.NewLogEntryEvent.WaitFor(300) = wrSignaled ) then begin break; end else if (i = 100) then begin // error creating log thread ShowMessage(Translate('Error Creating Log Thread!')); //no trans exit; end; Application.ProcessMessages; end; FThread.Resume; FThreadBuffer.LogThread := FThread; FLogPath := ExtractFilePath(application.ExeName) + 'LOG\'; //no trans // by default, log everything to file and display FDisplayFilter := [ecMinClass..ecMaxClass]; FFileFilter := [ecMinClass..ecMaxClass]; // set level to log everything FDisplayFilterLevel := elEvent; FFileFilterLevel := elEvent; // create maps FUnpaddedLevelMap := TStringList.Create; FUnpaddedClassMap := TStringList.Create; // set max number of files FMaxNumberLogFiles := DEFAULT_MAX_LOG_FILES; //create the class name maps FEventClassMap := TStringList.Create; FEventLevelMap := TStringList.Create; //make the list of triggers FTriggerList := TTriggerStringList.Create; //make the list of delayed triggers //it holds any pending delays, so the contents are temporary FDelayedTriggers := TStringList.Create; FDelayedTriggers.Duplicates := dupAccept; FMessageDepth := 0; FTriggerEnable := True; except ShowMessage(Translate('Fatal error starting logging system.')); //no trans raise; end; end; procedure TLogManager.SwitchToDebugMode; begin LogEvent( ecruntime, 'Switching to Debug Log Mode'); //ivlm DisplayFilter := [ecMinClass..ecMaxClass]; FileFilter := [ecMinClass..ecMaxClass]; // set level to log everything DisplayFilterLevel := elDebug; FileFilterLevel := elDebug; end; procedure TLogManager.TBD(EventString: string); begin //this is a function to catch and log TBD items //for now, log a warning LogWarning(ecStartup,'TBD: '+EventString); // no trans end; { TLogThread } constructor TLogThread.Create( Log : TLogManager; Buffer: TThreadBuffer); begin FreeOnTerminate := False; FBuffer := Buffer; FLog := Log; FNewLogEntryEvent := TEvent.Create( nil, FALSE, FALSE, ''); //no trans FShuttingDown := False; inherited Create( True ); FNewLogEntryEvent.SetEvent; end; destructor TLogThread.Destroy; begin FBuffer.Free; FNewLogEntryEvent.Free; inherited Destroy; end; procedure TLogThread.Execute; begin while( NOT ( Terminated ) )do begin // sleep until something appears in buffer FNewLogEntryEvent.Waitfor( 100 ) ; // if we've woken up, then there should be something // in the buffer (although we might have timed-out which is handled) // see if the log item event is connected and there are any events { while( NOT( Terminated ) AND Assigned( FLog.OnLogUpdate ) AND ( FBuffer.LogItemCount > 0 ) )do begin Synchronize( SendLogItem ); end; } while( NOT( Terminated ) AND Assigned( FLog.OnLogUpdate1 ) AND ( FBuffer.LogItemCount > 0 ) )do begin Synchronize( SendLogItem ); end; while( NOT( Terminated ) AND Assigned( FLog.OnLogUpdate2 ) AND ( FBuffer.LogItemCount > 0 ) )do begin Synchronize( SendLogItem ); end; // see if the status string event is connected and there are any status lines while( NOT( Terminated ) // AND Assigned( FLog.OnStatusUpdate ) AND (FLog.StatusSubscriberCount > 0) AND (FBuffer.StatusCount > 0 ) AND (not FShuttingDown) )do begin Synchronize( SendStatus ); end; end; end; procedure TLogThread.SendLogItem; var tmpList1, tmpList2: Tlist; Loop: integer; begin // if Assigned (FLog.OnLogUpdate) then FLog.OnLogUpdate( FLog, FBuffer.PopLogItemsIntoList ); if Assigned (FLog.OnLogUpdate1) then begin tmpList1 := FBuffer.PopLogItemsIntoList; if assigned (FLog.OnLogUpdate2) then begin tmpList2 := TList.Create; for Loop := 0 to tmpList1.Count - 1 do begin tmpList2.Add(tmpList1.Items[Loop]); end; if Assigned(tmpList2) then begin FLog.OnLogUpdate2( FLog, tmpList2 ); end; end; if Assigned(tmpList1) then try FLog.OnLogUpdate1( FLog, tmpList1 ); except end; end; end; procedure TLogThread.SendStatus; var status : string; eventclass : TEventClass; dataobject : TObject; i: integer; begin if( FBuffer.PopStatus( status, eventclass, dataobject) ) then begin if FLog.StatusSubscriberCount > 0 then begin for i := 0 to FLog.StatusSubscriberCount - 1 do begin // tmpPtr := FLog.StatusSubscribers[i]; // tmpProc := TLogStatusEvent(tmpPtr); FLog.StatusSubscribers[i](FLog,Status,dataObject,eventClass); end; //policy with these is to not free. dataObject.Free; end { else if Assigned(FLog.OnStatusUpdate) then begin FLog.OnStatusUpdate( FLog, status, dataobject, eventclass ) end } else begin dataObject.Free; end; end end; { TThreadBuffer } constructor TThreadBuffer.Create; begin // object calling this constructor will handle any exceptions on Create inherited Create; FCS := TCriticalSection.Create; FLogItemList := TList.Create; FLogItemList.Capacity := MAX_BUFFERED_ITEMS; FStatusList := TStringList.Create; FStatusList.Sorted := FALSE; FStatusList.Capacity := MAX_BUFFERED_ITEMS; FLogThread := nil; end; destructor TThreadBuffer.Destroy; begin while( FLogItemList.Count > 0 ) do begin TLogItem( FLogItemList.Items[0] ).Free; FLogItemList.Delete( 0 ) ; end; FLogItemList.Free; //free the buffer items while( FStatusList.Count > 0 ) do begin FStatusList.Objects[0].Free; FStatusList.Delete( 0 ) ; end; FStatusList.Free; FCS.Free; inherited Destroy; end; function TThreadBuffer.GetLogItemCount: Integer; begin result := FLogItemList.Count; end; function TThreadBuffer.GetStatusCount: Integer; begin result := FStatusList.Count; end; function TThreadBuffer.PopLogItem: TLogItem; begin FCS.Enter; if( FLogItemList.Count > 0 ) then begin result := TLogItem( FLogItemList.Items[0] ); FLogItemList.Delete(0); end else begin result := nil; end; FCS.Leave; end; function TThreadBuffer.PopLogItemsIntoList: TList; begin FCS.Enter; result := TList.Create; // create list to hold entries result.Capacity := FLogItemList.Count; // allocate enough space to save time while( FLogItemList.Count > 0 ) do begin result.Add( FLogItemList.Items[0] ); // move log item pointer into list FLogItemList.Delete(0); // remove item from buffer end; FCS.Leave; end; function TThreadBuffer.PopStatus( var NewStatus : String; var EventClass : TEventClass; var DataObject : TObject ) : Boolean; var TempItem : TBufferItem; begin FCS.Enter; if( FStatusList.Count > 0 ) then begin NewStatus := FStatusList.Strings[0]; TempItem := TBufferItem( FStatusList.Objects[0] ); FStatusList.Delete( 0 ); EventClass := TempItem.EventClass; //here, we effectively move the data object DataObject := TempItem.DataObject; //by setting its pointer TempItem.DataObject := nil; //so tempItem.Free does not destroy the Data Object TempItem.Free; result := TRUE; end else begin result := FALSE; end; FCS.Leave; end; function TThreadBuffer.PushLogItem(NewItem: TLogItem): Boolean; begin FCS.Enter; // when running full-tilt, too many log messages may be generated; // something has to give, so delete the oldest insructions from buffer, // they have already been logged to the file, so we are only cheating // the graphical display; there's no // sense is consuming a bunch of memory when these items // will quickly scroll out of the display buffer when displayed; // the list capacity should be greater than that of the display buffer while( FLogItemList.Count > ( FLogItemList.Capacity - 1 ) ) do begin TLogItem( FLogItemList.Items[0] ).Free; FLogItemList.Delete( 0 ); end; FLogItemList.Add( NewItem ); FCS.Leave; if Assigned( FLogThread ) then TLogThread(FLogThread).NewLogEntryEvent.SetEvent; result := TRUE; end; function TThreadBuffer.PushStatus( NewStatus : String ; EventClass : TEventClass; DataObject : TObject ) : Boolean; var index : integer; tempitem : TBufferItem; begin FCS.Enter; // see comments for PushLogItem while( FStatusList.Count > ( FStatusList.Capacity - 1 ) ) do begin FStatusList.Objects[0].Free; FStatusList.Delete( 0 ); end; index := FStatusList.Add( NewStatus ); try TempItem := TBufferItem.Create; except result := FALSE; FCS.Leave; exit; end; TempItem.EventClass := EventClass; TempItem.DataObject := DataObject; FStatusList.Objects[ index ] := TempItem; FCS.Leave; if Assigned( FLogThread ) then TLogThread(FLogThread).NewLogEntryEvent.SetEvent; result := TRUE; end; function TLogManager.LoadFilterStateFromIniFile(IFile: TIsoIniFile): Boolean; var TempString : string; i : integer; tempClass : TEventClass; classString: string; strTmp: string; begin //if there is no section for us, then write one. if not IFile.SectionExists( DEFAULT_INIFILESECTION ) then SaveFilterStateToIniFile(IFile); // get number of files FMaxNumberLogFiles := IFile.ReadInteger( DEFAULT_INIFILESECTION, 'MaxNumberLogFiles', //no trans DEFAULT_MAX_LOG_FILES, 'How many log files to allow on the hard drive. '//no trans +'Oldest is deleted when this number is exceeded.'); //no trans // remove old files if NOT RemoveOldLogFiles then begin ShowMessage(Translate('Error removing old log files')); end; // get file filter state TempString := IFile.ReadString( DEFAULT_INIFILESECTION, 'FileLogLevel', 'Event', //no trans 'Error, Warning, Event, or Debug are possible values. Events of this level or '//no trans +'more severe are logged into the log file.'); //no trans FFileFilterLevel := TEventLevel( GetEnumValue( Typeinfo (TEventLevel), 'el' + TempString) ); //no trans // get the buffering level FFileBufferList.Capacity := IFile.ReadInteger( DEFAULT_INIFILESECTION, BUFFER_DEPTH_KEY, //no trans DEFAULT_FILE_BUFFER_DEPTH, 'How many messages to buffer before dumping into the log file. '+//no trans 'numbers greater than 1 improve performance, but most recent messages may be missing '+//no trans 'in the event of a software crash.'); //no trans FBufferDepth := FFileBufferList.Capacity; //the dump buffer settings might not be there, so add them only if they //are not present. If they are present, we do not want to add them, //or we will overwrite custom settings strTmp := IFile.ReadString( DEFAULT_INIFILESECTION, DUMP_BUFFER_SIZE_KEY, //no trans '', 'SUPPRESS'); //no trans if strTmp = '' then //no trans begin IFile.WriteInteger( DEFAULT_INIFILESECTION, DUMP_BUFFER_SIZE_KEY, //no trans DEFAULT_DUMP_BUFFER_SIZE); end; strTmp := IFile.ReadString( DEFAULT_INIFILESECTION, DUMP_POST_ERROR_MESSAGES_KEY, //no trans '', 'SUPPRESS'); //no trans if strTmp = '' then //no trans begin IFile.WriteInteger( DEFAULT_INIFILESECTION, DUMP_POST_ERROR_MESSAGES_KEY, //no trans DEFAULT_DUMP_POST_ERROR_MESSAGES); end; FDumpBufferSize := IFile.ReadInteger( DEFAULT_INIFILESECTION, DUMP_BUFFER_SIZE_KEY, //no trans DEFAULT_DUMP_BUFFER_SIZE, 'If nonzero, then when an error is logged, the proceeding debug messages are also inserted in the log, even when not in debug mode'); //no trans if FDumpBufferSize > 0 then begin FDumpBufferList.Capacity := FDumpBufferSize; end; FPostErrorMessages := IFile.ReadInteger( DEFAULT_INIFILESECTION, DUMP_POST_ERROR_MESSAGES_KEY, //no trans DEFAULT_DUMP_POST_ERROR_MESSAGES, 'If nonzero, then when an error is logged, this many debug messages follow the error'); //no trans // get file filter classes // skip first and last entries in list for i := 1 to Pred(FUnPaddedClassMap.Count) - 1 do begin tempClass := TEventClass( i ); classString :=GetEnumName(TypeInfo(TEventClass),Ord(i)); classString := 'FileLog' + Copy(classString,3,Length(classString)-2); //no trans if( IFile.ReadBool( DEFAULT_INIFILESECTION, classString {'[An event class]'}, TRUE, //no trans 'If true, then this class of messages will be included in the display.' ) ) then //no trans begin FFileFilter := FFileFilter + [tempClass]; end else FFileFilter := FFileFilter - [tempClass]; end; // get display filter state TempString := IFile.ReadString( DEFAULT_INIFILESECTION, 'DisplayLogLevel', 'Event', //no trans 'Error, Warning, Event, or Debug are possible values. Events of this level or '//no trans +'more severe are logged in the event monitor.'); //no trans FDisplayFilterLevel := TEventLevel( GetEnumValue( Typeinfo (TEventLevel), 'el' + TempString)); //no trans // get display filter classes // skip first and last entries in list for i := 1 to Pred(FUnPaddedClassMap.Count) - 1 do begin tempClass := TEventClass( i ); classString := GetEnumName(TypeInfo(TEventClass),Ord(i)); classString := 'DisplayLog' + Copy(classString,3,Length(classString)-2); //no trans if( IFile.ReadBool( DEFAULT_INIFILESECTION, classString {'[An event class]'}, TRUE, //no trans 'If true, then this class of messages will be included in the display.' ) ) then //no trans begin FDisplayFilter := FDisplayFilter + [tempClass]; end else FDisplayFilter := FDisplayFilter - [tempClass]; end; // get log item class to use if IFile.ReadBool( DEFAULT_INIFILESECTION, 'LogThreadID', FALSE, //no trans 'For debugging. If true, then thread IDs of source threads ' + //no trans 'for events will be appended to log messages.' ) then //no trans begin FLogItemClass := TLogItemWithThreadID; // TLogManager.Instance.LogDebug( ecruntime, 'Logging with Thread ID'); //no trans end else begin FLogItemClass := TLogItem; // TLogManager.Instance.LogDebug( ecruntime, 'Logging without Thread ID'); //no trans end; // get the brief (i.e., display) date time format string FBriefDateTimeFormatString := IFile.ReadString( DEFAULT_INIFILESECTION, 'BriefDateTimeFormatString', //no trans DEFAULT_BRIEF_FORMAT, 'Operator Screen Date and Time Format String for Log Items' ); // no trans // see if the event class should be included in the brief event summary FBriefSummaryClassEnabled := IFile.ReadBool( DEFAULT_INIFILESECTION, 'BriefSummaryClassEnabled', //no trans TRUE, 'Operator Screen Event Class Display (e.g., Startup, Shutdown, Robot, etc.)' ); // no trans result := TRUE; end; function TLogManager.SaveFilterStateToIniFile(IFile: TIsoIniFile): Boolean; var i : integer; LevelString : string; ClassString: string; begin // backup INI file first //??? DataModuleMain.BackupIniFile; // save max number of files IFile.WriteInteger( DEFAULT_INIFILESECTION, 'MaxNumberLogFiles', //no trans FMaxNumberLogFiles); IFile.WriteInteger( DEFAULT_INIFILESECTION, BUFFER_DEPTH_KEY, //no trans DEFAULT_FILE_BUFFER_DEPTH); // write file filter state LevelString := GetEnumName(TypeInfo(TEventLevel),Ord(FFileFilterLevel)) ; LevelString := Copy(LevelString,3,Length(LevelString)-2); IFile.WriteString( DEFAULT_INIFILESECTION, 'FileLogLevel', LevelString); //no trans // write file filter classes // skip first and last entries in list for i := 1 to Pred(FUnPaddedClassMap.Count) - 1 do begin classString := GetEnumName(TypeInfo(TEventClass),Ord(i)); classString := 'FileLog' + Copy(classString,3,Length(classString)-2); //no trans if( TEventClass( i ) in FFileFilter)then begin IFile.WriteBool( DEFAULT_INIFILESECTION, classString, TRUE); end else begin IFile.WriteBool( DEFAULT_INIFILESECTION, classString, FALSE); end; end; // write Displayfilter state LevelString := GetEnumName(TypeInfo(TEventLevel),Ord(FDisplayFilterLevel)); LevelString := Copy(LevelString,3,Length(LevelString)-2); IFile.WriteString( DEFAULT_INIFILESECTION, 'DisplayLogLevel', LevelString); //no trans // write file filter classes // skip first and last entries in list for i := 1 to Pred(FUnPaddedClassMap.Count) - 1 do begin classString := GetEnumName(TypeInfo(TEventClass),Ord(i)); classString := 'DisplayLog' + Copy(classString,3,Length(classString)-2); //no trans if( TEventClass( i ) in FDisplayFilter)then begin IFile.WriteBool( DEFAULT_INIFILESECTION, classString, TRUE); end else begin IFile.WriteBool( DEFAULT_INIFILESECTION, classString, FALSE); end; end; // write log thread id state to file IFile.WriteBool( DEFAULT_INIFILESECTION, 'LogThreadID', FALSE ); //no trans result := TRUE; end; procedure TLogManager.SetStatus(EventClass: TEventClass; const Value: string; DataObject : TObject); begin FStatusCriticalSection.Enter; // generate event if wired if StatusSubscriberCount > 0 then begin FThreadBuffer.PushStatus( Value, EventClass, DataObject ); end { else if assigned( OnStatusUpdate ) then begin FThreadBuffer.PushStatus( Value, EventClass, DataObject ); end } else begin if Assigned( DataObject ) then begin DataObject.Free; end; end; FStatusCriticalSection.Leave; end; procedure TLogManager.SetTriggerEnable(const Value: Boolean); begin FTriggerEnable := Value; if Value then begin LogDebug(ecRuntime, 'Log Triggers Enabled'); //no trans end else begin LogDebug(ecRuntime, 'Log Triggers Disabled'); //no trans end; end; procedure TLogManager.ShutdownNotify; begin //set this flag so that he stops sending status updates //while things are getting destroyed FThread.FShuttingDown := True; end; { TBufferItem } constructor TBufferItem.Create; begin inherited; end; destructor TBufferItem.Destroy; begin if Assigned( FDataObject ) then begin FDataObject.Free; end; inherited Destroy; end; function TLogManager.LogDebug(EventClass: TEventClass; EventString: String): Boolean; var NewLogItem : TLogItem; begin // create new log Item; try NewLogItem := LogItemFactory; except result := FALSE; exit; end; NewLogItem.EventString := EventString; NewLogItem.EventClass := EventClass; NewLogitem.EventLevel := elDebug; // insert item into log result := InsertLogEntry( NewLogItem ); end; function TLogManager.RemoveOldLogFiles: Boolean; var BackupFileList : TStringList; SearchRec : TSearchRec; FOldFileName : string; TodaysFile : string; begin BackupFileList := TStringList.Create; BackupFileList.Sorted := TRUE; TodaysFile := GenerateLogFileName(nil); if( FindFirst( FLogPath + 'ECW*.log', //no trans faAnyFile, SearchRec) = 0 )then begin FOldFileName := FLogPath + SearchRec.Name; if( FOldFileName <> TodaysFile ) then begin BackupFileList.Add( FOldFileName ); end; while( FindNext( SearchRec ) = 0 ) do begin FOldFileName := FLogPath + SearchRec.Name; if( FOldFileName <> TodaysFile ) then begin BackupFileList.Add( FOldFileName ); end; end; end; result := TRUE; while result AND (BackupFileList.Count > pred( FMaxNumberLogFiles ) )do begin if NOT( sysutils.DeleteFile( BackupFileList.Strings[0] ) ) then begin result := FALSE; end; BackupFileList.Delete( 0 ); end; BackupFileList.Free; sysutils.FindClose( SearchRec ); //this frees memory allocated by FindFirst end; procedure TLogManager.RemoveStatusSubscriber(subscriber: TLogStatusEvent); var i,j: integer; pCurrent,pTarget: TLogStatusEventReference; begin i := 0; //the subscriber is a method pointer, which is actually two pointers, //the first to the code and the second to the data. //so, the first is the same for any subscriber of the same class, //and when deleting, we really want to be looking at the data pointer //which should be unique. //so, this record is used with an explicity typecast to get a reference to //the data pointer for the method... pTarget := TLogStatusEventReference(subscriber); while i < Length(StatusSubscribers) do begin pCurrent := TLogStatusEventReference(StatusSubscribers[i]); if pCurrent.pData = pTarget.pData then //if @StatusSubscribers[i] = @subscriber then begin for j := i to Length(StatusSubscribers)-2 do begin //shift items StatusSubscribers[j] := StatusSubscribers[j+1]; end; SetLength(StatusSubscribers,Length(StatusSubscribers)-1); exit; end; inc(i); end; end; function TLogManager.GenerateLogFileName( LogItem : TLogItem ): string; begin if Assigned( LogITem ) then begin result := FLogPath + 'ECW' //no trans + FormatDateTime('YYYYMMDD', LogItem.TimeStamp) //no trans + '.LOG'; //no trans end else begin // use the current date if no logitem is provided result := FLogPath + 'ECW' //no trans + FormatDateTime('YYYYMMDD', Now) //no trans + '.LOG'; //no trans end; end; function TLogManager.GetStatusSubscriberCount: integer; begin result := Length(StatusSubscribers); end; function TLogManager.WriteLogEntryToDisplayBuffer( LogItem: TLogItem): Boolean; var LogItem2: TLogItem; begin // send event to display monitor // check display filters if IsItemInFilter( FDisplayFilterLevel, FDisplayFilter, LogItem ) then begin // put item in thread buffer FThreadBuffer.PushLogItem( LogItem ); end else begin //if it is not going to the screen, //we are done with it LogItem.Free; end; result := TRUE; end; function TLogManager.WriteLogEntryToFile(LogItem: TLogItem): Boolean; var tmpLogItem: TLogItem; begin result := TRUE; //this section was added to be smart about debug logging //the goal is to log the last n of all messages, regardless of //filter settings, when an error occurs, to cut down on enormous log files. //The buffer is emptied when logged, so that a series of close errors do not //generate large dumps of the same data. //There are a couple of side effects: //this will cause the capacity of the FileBufferList //to grow potentially by the size of the dump buffer. //This will mess up customers with a buffer size of 1. //Also, this will caues messages to be inserted in non-chronological order //And there will be duplicates - however, the dump contents should be in order and //without duplicates. if FDumpBufferSize > 0 then begin //save all messages in rotary buffer for dumping. //if we are already in debug, this has no extra value if (FFileFilterLevel > elDebug) then begin //here we check if the new item should trigger a dump if LogItem.EventLevel = elError then begin //do a dump try tmpLogItem := LogItemFactory; except result := FALSE; exit; end; tmpLogItem.EventString := 'Dump Start'; //no trans tmpLogItem.EventClass := ecRuntime; tmpLogItem.EventLevel := elWarning; FFileBufferList.Add( tmpLogItem ); //it will be logged below, so do nothing further //get out our saved messages while FDumpBufferList.Count > 0 do begin //move the saved items to be logged //and empty the dump buffer FFileBufferList.Add( FDumpBufferList[0] ); FDumpBufferList.Delete(0); end; try tmpLogItem := LogItemFactory; except result := FALSE; exit; end; tmpLogItem.EventString := 'Dump End'; //no trans tmpLogItem.EventClass := ecRuntime; tmpLogItem.EventLevel := elWarning; FFileBufferList.Add( tmpLogItem ); FPostErrorCountdown := FPostErrorMessages; end else begin //save it for possible use later while (FDumpBufferList.Count >= FDumpBufferList.Capacity) do begin TLogItem(FDumpBufferList[0]).Free; FDumpBufferList.Delete(0); end; FDumpBufferList.Add(LogItem.Duplicate); end; end; //filtering some messages end; //nonzero dump buffer //original processing from here on // check file filter options if IsItemInFilter( FFileFilterLevel, FFileFilter, LogItem ) then begin // put log entry into buffer FFileBufferList.Add( LogItem.Duplicate ); // see if buffer is full - if the count equals the capacity, flush the buffer if FFileBufferList.Count >= FBufferDepth then begin result := FlushFileBuffer; end; end else begin if FPostErrorCountdown > 0 then begin Dec(FPostErrorCountdown); end; end; end; function TLogManager.IsItemInFilter(FilterLevel: TEventLevel; FilterClasses: TEventClassFilter; LogItem: TLogItem): boolean; begin if( ( LogItem.EventClass in FilterClasses ) AND ( LogItem.EventLevel >= FilterLevel ) )then begin result := TRUE; end else begin result := FALSE; end; end; function TLogManager.OpenFileForWriting(FName: String; var FStream : TFileStream): boolean; begin result := CreateLogDirectoryIfNeeded; if result then begin // either create file if it doesn't exist or open it if not FileExists(DataFileName) then // if New data file then create it begin try // remove old files before creating new ones if NOT RemoveOldLogFiles then begin ShowMessage(Translate('Error removing old log files')); end; FStream := TFileStream.Create(DataFileName, fmCreate OR fmShareDenyWrite); except ShowMessage( Format(Translate('Error Creating Log File: %s'), [DataFileName]) ); result := FALSE; end; end else // just append to existing file begin try FStream := TFileStream.Create(DataFileName,fmOpenReadWrite OR fmShareDenyWrite); FStream.seek(0, soFromEnd); except ShowMessage( Format(Translate('Error In Appending File %s'), [DataFileName]) ); result := FALSE; end; end; end; end; function TLogManager.CreateLogDirectoryIfNeeded: Boolean; begin result := TRUE; // Create Log Directory if it doesn't exist //taj if not DirectoryExists(FLogpath) then // create log directory if not SysUtils.DirectoryExists(FLogpath) then // create log directory begin if not CreateDir(FLogPath) then begin ShowMessage(Format(Translate('Error Creating Directory %s'), [FlogPath]) ); result := FALSE; end; end; end; procedure TLogManager.PadStrings; var MaxClass : integer; // maximum class value MaxLevel : integer; // maximum level value pti : PTypeInfo; ptd : PTypeData; IndexI, IndexJ, IndexK, charLen : integer; EnumString : string; transString: string; //this is to make the code more readable begin //this procedure is intended to be called at startup and whenever //the language changes. // enter CS, because we do not want anyone logging something //while we are doing surgery on these string lists FLogCriticalSection.Enter; try // setup enumerated-to-string maps FEventClassMap.Clear; FUnPaddedClassMap.Clear; pti := TypeInfo( TEventClass ); ptd := GetTypeData( pti ); MaxClass := ptd^.MaxValue; //first we cycle through the strings to translate and add them to the list, //and count the characters to find the longest one INDEXJ := 0; for INDEXI := 0 to MaxClass do begin EnumString := GetEnumName(TypeInfo( TEventClass ), INDEXI ) ; //enumString is English, so standard byte Length should be OK transString := Translate(Copy( EnumString, 3, Length( EnumString ) - 2 )); FUnPaddedClassMap.Add( transString ); //taj charLen := ByteToCharIndex(transString,Length(transString)); charLen := ElementToCharIndex(transString,Length(transString)); if(charLen > INDEXJ ) then INDEXJ := charLen; end; // pad all strings to make them the length of the longest one for INDEXI := 0 to MaxClass do begin FEventClassMap.Add( FUnPaddedClassMap[INDEXI] ); //taj charLen := ByteToCharIndex(FUnPaddedClassMap[INDEXI],Length(FUnPaddedClassMap[INDEXI])); charLen := ElementToCharIndex(FUnPaddedClassMap[INDEXI],Length(FUnPaddedClassMap[INDEXI])); if(charLen < INDEXJ ) then begin for INDEXK := 1 to ( INDEXJ - charLen ) do begin FEventClassMap[INDEXI] := FEventClassMap[INDEXI] + ' '; //no trans end; end; end; FEventLevelMap.Clear; FUnPaddedLevelMap.Clear; pti := TypeInfo( TEventLevel ); ptd := GetTypeData( pti ); MaxLevel := ptd^.MaxValue; INDEXJ := 0; for INDEXI := 0 to MaxLevel do begin EnumString := GetEnumName( TypeInfo( TEventLevel ), INDEXI ) ; transString := Translate( Copy( EnumString, 3, Length( EnumString ) - 2 )); FUnPaddedLevelMap.Add( transString ); //taj charLen := ByteToCharIndex( transString, Length(transString)); charLen := ElementToCharIndex( transString, Length(transString)); if(charLen > INDEXJ ) then INDEXJ := charLen; end; // pad all strings to make them the length of the longest one for INDEXI := 0 to MaxLevel do begin FEventLevelMap.Add( FUnPaddedLevelMap[INDEXI] ); //taj charLen := ByteToCharIndex(FUnPaddedLevelMap[INDEXI],Length(FUnPaddedLevelMap[INDEXI])); charLen := ElementToCharIndex(FUnPaddedLevelMap[INDEXI],Length(FUnPaddedLevelMap[INDEXI])); if(charLen < INDEXJ ) then begin for INDEXK := 1 to ( INDEXJ - charLen ) do begin FEventLevelMap[INDEXI] := FEventLevelMap[INDEXI] + ' '; //no trans end; end; end; SetLength(EnumString, 0); SetLength(transString, 0); finally // leave CS FLogCriticalSection.Leave; end; end; procedure TLogManager.ProcessMessages; begin //The purpose it to prevent the process messages call from executing //within any thread but the main vcl thread. //this is intended to be a clearing house for all application.processmessages //calls //This is a convenient place to park it, because most of the units that call //the function would already have the log managerunit in the uses clause. // if (GetCurrentThreadID() = FMainVCLThreadID) then //begin //inc(FMessageDepth); Application.ProcessMessages; //TLogManager.Instance.LogWarning(ecRuntime,'message level='+IntToStr(FMessageDepth)); //no trans //dec(FMessageDepth) { end else begin LogDebug(ecRuntime,'ProcessMessages called from secondary thread'); //no trans end; } end; function TLogManager.FlushFileBuffer: boolean; var DataRecFile : TFileStream; lastdatetime : TDateTime; currentlogitem : TLogItem; theRecordStr : string; theAnsiRecordStr : AnsiString; begin lastdatetime := 0; // initialize datetime result := TRUE; DataRecFile := nil; while (FFileBufferList.Count > 0) AND result do begin // get next log item from list currentLogItem := TLogItem( FFileBufferList.Items[0] ); // see if we need to generate a new file name and open it // this will help to make sure that log entries get put into the right // file around midnight, even with buffering enabled if Trunc( LastDateTime ) <> Trunc( currentLogItem.TimeStamp ) then begin // close the current file DataRecFile.Free; // synthesize log file name DataFileName := GenerateLogFileName( currentLogItem ); // open file for writing if NOT OpenFileForWriting( DataFileName, DataRecFile ) then begin result := FALSE; end; LastDateTime := currentLogItem.TimeStamp; // save this datetime end; if result then begin // write log entry to stream try // get string to put in log theRecordStr := currentLogItem.EventSummary; // Convert to ascii for file output //taj theAnsiRecordStr := theRecordStr + newLine; theAnsiRecordStr := AnsiString(theRecordStr + newLine); // write the entry out DataRecFile.Write(Pointer(theAnsiRecordStr)^,Length(theAnsiRecordStr)); except ShowMessage(Format(Translate('Error writing log event to file: %s'), [FDataFileName]) ); result := FALSE; end; end; currentLogItem.Free; // free logItem FFileBufferList.Delete(0); // delete the entry from list end; //close the file and free stream DataRecFile.Free; end; function TLogManager.FlushLog: Boolean; begin // enter CS FLogCriticalSection.Enter; try result := self.FlushFileBuffer; finally // leave CS FLogCriticalSection.Leave; end; end; { TLogItemWithThreadID } function TLogItemWithThreadID.Assign(Source: TLogItem): Boolean; begin if Assigned( Source ) then begin result := inherited Assign(Source); if result and (Source is TLogItemWithThreadID) then begin FThreadID := TLogItemWithThreadID(Source).ThreadID; end; end else begin result := FALSE; end; end; constructor TLogItemWithThreadID.Create; begin inherited; FThreadID := GetCurrentThreadId(); end; function TLogItemWithThreadID.Duplicate: TLogItem; begin result := TLogItemWithThreadID.Create; result.Assign( self ); end; function TLogItemWithThreadID.GetBriefSummary: String; begin result := inherited GetBriefSummary + ' ($' + Format('%x',[FThreadID] ) + ')'; //no trans end; function TLogItemWithThreadID.GetEventSummary: String; begin result := inherited GetEventSummary + ' ($' + Format('%x',[FThreadID] ) + ')'; //no trans end; function TLogManager.LogItemFactory: TLogItem; begin result := FLogItemClass.Create; result.BriefDateTimeFormatString := BriefDateTimeFormatString; result.BriefSummaryClassEnabled := BriefSummaryClassEnabled; end; { Documentation|Log Triggers Certain events, such as transmitting an FIS message, can be triggered based on a certain message getting logged. It is a good idea to trigger events with debug messages since these are not typically translated. The log triggers for an FIS system are defined in the Trigger Map.txt file. Here is an example line from the Trigger Map.txt file: Production>MES,Production State = psStarting In this example, when the message "Production State = psStarting" is logged, then the FIS message called "Production" is sent out the port named "MES". It is also possible to use a wildcard on the trigger portion, but these are computationally expensive and should be used sparingly. This is an example: Report ID>Factory,*Upstream ID= The "Report ID" FIS Message is sent out the port named "Factory" whenever a message containing "Upstream ID=" is logged. If the upstream ID variable is getting set to a scanned barcode, then that portion of the log event would vary, so it is necessary to use the wildcard in this case. } function TLogManager.AddLogTrigger(triggerID: integer; triggerString: string; callbackFunction: TLogTriggerEvent; caption: string; delayMilliseconds: integer=0): Boolean; var tmpTrig: TTriggerRecord; begin result := False; tmpTrig := TTriggerRecord.Create(triggerID,callbackFunction,caption); if (FTriggerList.AddTrigger(triggerString,tmpTrig) > -1) then begin result := True; end else begin TLogManager.Instance.LogError(ecStartup,'Failed to add log trigger: '+ Caption); //no trans end; if delayMilliseconds <> 0 then begin //we have a delay tmpTrig.triggerDelayMilliseconds := delayMilliseconds; tmpTrig.triggerDelayOn := True; end; end; { TTriggerRecord } { TTriggerRecord } constructor TTriggerRecord.Create(id: integer; callback: TLogTriggerEvent; cap: string); begin triggerID := id; triggerCallback := callback; triggerCaption := cap; triggerDelayOn := False; triggerDelayMilliseconds := 0; end; function TLogManager.LogMessage(EventLevel: TEventLevel; EventClass: TEventClass; EventString: String): Boolean; var NewLogItem : TLogItem; begin // create new log Item; try NewLogItem := LogItemFactory; except result := FALSE; exit; end; NewLogItem.EventString := EventString; NewLogItem.EventClass := EventClass; NewLogitem.EventLevel := EventLevel; // insert item into log result := InsertLogEntry( NewLogItem ); end; function TLogManager.LogStrings(EventLevel: TEventLevel; EventClass: TEventClass; EventStrings: TStrings; prefix: string): Boolean; var i: Integer; begin for i := 0 to EventStrings.Count - 1 do begin LogMessage(EventLevel,EventClass,prefix + EventStrings[i]); end; result := True; //taj added end; procedure TLogManager.HandleTrigger(trig: TTriggerRecord); var logItemTrigger: TLogItem; begin trig.triggerCallback(trig.triggerID); //document it logItemTrigger := LogItemFactory; logItemTrigger.EventString := trig.triggerCaption; logItemTrigger.EventClass := ecRuntime; logItemTrigger.EventLevel := elDebug; WriteLogEntryToFile( logItemTrigger); logItemTrigger.Free; end; { TTriggerStringList } function TTriggerStringListOld.AddObject(const S: string; AObject: TObject): Integer; var tmpStr: string; begin result := -1; if length(s) > 0 then begin if s[1]='*' then //no trans begin if not Assigned(FPartialStrings) then begin FPartialStrings := TStringList.Create; FPartialStrings.Sorted := True; FPartialStrings.Duplicates := dupAccept; end; //we add this to both so that the indices match up tmpStr := Copy(S,2,length(S)-1); FPartialStrings.AddObject(tmpStr,AObject); result := inherited AddObject(S,AObject); end else begin result := inherited AddObject(S,AObject); end; end; end; destructor TTriggerStringListOld.Destroy; begin if Assigned(FPartialStrings) then begin while FPartialStrings.Count>0 do begin FPartialStrings.Delete(0); end; FPartialStrings.Free; end; inherited; end; function TTriggerStringListOld.Find(const S: string; var Index: Integer): Boolean; var i: integer; begin result := inherited Find(S,Index); if not result then begin //exaxt match above overrides this partial match if Assigned(FPartialStrings) then begin //beware - this executes with every single log message... for i := 0 to (FPartialStrings.Count - 1) do begin if (Pos(FPartialStrings[i],S) > 0) then begin Index := i; result := True; //added for version 483 //issue with partial match triggers not executing //if multiple triggers registered with the same log message break; end; end; end; end; end; function TTriggerStringList.AddTrigger(const S: string; AObject: TObject): Integer; var tmpStr: string; begin result := -1; if length(s) > 0 then begin if s[1]='*' then //no trans begin //we add this to the wildcard list without the asterisk tmpStr := Copy(S,2,length(S)-1); result := FWildcardStrings.AddObject(tmpStr,AObject); end else begin //just add it to the regular list result := FExactStrings.AddObject(S,AObject); end; end; end; constructor TTriggerStringList.Create; begin inherited Create; FExactStrings := TStringList.Create; FExactStrings.Sorted := True; FExactStrings.Duplicates := dupAccept; FWildcardStrings := TStringList.Create; FWildcardStrings.Sorted := True; FWildcardStrings.Duplicates := dupAccept; end; destructor TTriggerStringList.Destroy; begin while FWildcardStrings.Count>0 do begin FWildcardStrings.Objects[0].Free; FWildcardStrings.Delete(0); end; FWildcardStrings.Free; while FExactStrings.Count>0 do begin FExactStrings.Objects[0].Free; FExactStrings.Delete(0); end; FExactStrings.Free; inherited; end; function TTriggerStringList.Find(const S: string): TStringList; var i,dummyInt: integer; firstMatchIndex: integer; testString: string; begin //Version 571 //This was modified to load a list of all unique //trigger objects that matched //The results are stored in the FoundTriggers property result := nil; //first clear the list // while FFoundTriggers.Count > 0 do FFoundTriggers.Delete(0); //look in the exact list first // tmpFound := FExactStrings.Find(S,i); if FExactStrings.Find(S,i) then begin //we have found a match result := TStringList.Create; result.Sorted := True; result.Duplicates := dupAccept; //add the address of the trigger object as a string //with the trigger object result.AddObject(IntToStr(integer(FExactStrings.Objects[i])),FExactStrings.Objects[i]); //now look for additional matches - there could be multiple triggers //for the same log message //store the index fo teh first match firstMatchIndex := i; i := i + 1; while ( i < FExactStrings.Count) and ( AnsiCompareText(FExactStrings[firstMatchIndex],FExactStrings[i])=0 ) do begin //we have another trigger for this string //for language independence, we have two strings in the list for the same trigger //one is translated, and one is not. However, the translated string might still be native //in which case we end up here //so convert the test item's address to a string and see if it is in our //list testString := IntToStr(Integer(FExactStrings.Objects[i])); //no trans if not (result.Find(testString,dummyInt)) then begin //OK, it is not in the list already, so go ahead and add it result.AddObject(testString,FExactStrings.Objects[i]); end; //and move on to the next item i := i + 1; end; end; //look in the wildcard list //this is different, , and expensive //since we need to search for every single wildcard in the log message for i := 0 to (FWildcardStrings.Count - 1) do begin if (Pos(FWildcardStrings[i],S) > 0) then begin //we have found a match if not Assigned(result) then begin result := TStringList.Create; result.Sorted := True; result.Duplicates := dupAccept; end; //like above, only add it if it is unique testString := IntToStr(Integer(FWildcardStrings.Objects[i])); //no trans if not (result.Find(testString,dummyInt)) then begin //OK, it is not in the list already, so go ahead and add it result.AddObject(testString,FWildcardStrings.Objects[i]); end; end; end; end; initialization // setup singelton SingletonInstance := TLogManager.SpecialCreate; finalization // flush any remaining entries to disk; SingletonInstance.FlushLog; // free up maps while( FEventLevelMap.Count > 0 )do FEventLevelMap.Delete(0); FEventLevelMap.Free; while( FEventClassMap.Count > 0 )do FEventClassMap.Delete(0); FEventClassMap.Free; // SingletonCS.Free; // see if not freeing this removes some shutdown errors SingletonInstance.Free; end.
{ Subroutine SST_W_C_OPCODES (FIRST_P) * * Read a chain of opcodes and produce the output source code from them. * FIRST_P points to the first opcode in the chain. FIRST_P may be NIL, * which indicates an empty chain. } module sst_w_c_OPCODES; define sst_w_c_opcodes; %include 'sst_w_c.ins.pas'; var arg1_p, arg2_p, arg3_p, arg4_p: {pointers to args of main program routine} sst_symbol_p_t; procedure sst_w_c_opcodes ( {read opcode chain and write output lines} in first_p: sst_opc_p_t); {points to first opcode in chain, may be NIL} const max_msg_parms = 1; {max parameters we can pass to a message} type apptype_k_t = ( {application type} apptype_cmline_k, {command line application} apptype_wingui_k); {Microsoft Windows GUI application} var opc_p: sst_opc_p_t; {pointer to current opcode descriptor} opc2: sst_opc_t; {scratch local opcode descriptor} dyn_old_p: sst_out_dyn_p_t; {saved copy of SST_OUT.DYN_P} sym_p: sst_symbol_p_t; {scratch pointer to symbol descriptor} sment_type_old: sment_type_k_t; {saved copy of current statement type} name: string_var80_t; {for printing symbol names} apptype: apptype_k_t; {application type ID} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label done_opcode; { ************************************************************************* * * Local subroutine CONST_UNDEF * * Write #UNDEF compiler directives for all the constants declared at the * beginning with #DEFINE directives. } procedure const_undef; var pos: string_hash_pos_t; {position handle into hash table} name_p: univ_ptr; {unused subroutine argument} sym_p: sst_symbol_p_t; {pointer to to current symbol to write out} sym_pp: sst_symbol_pp_t; {pointer to hash table user data area} found: boolean; {TRUE if hash table entry was found} first: boolean; {TRUE for first UNDEF directive written} label next_sym; begin string_hash_pos_first (sst_scope_p^.hash_h, pos, found); {get pos for first sym} first := true; {next UNDEF directive will be the first} while found do begin {once for each hash table entry} string_hash_ent_atpos (pos, name_p, sym_pp); {get pointer to user data area} sym_p := sym_pp^; {get pointer to symbol descriptor} if (sst_symflag_used_k in sym_p^.flags) and {this symbol was used ?} (sym_p^.symtype = sst_symtype_const_k) {this symbol is a constant ?} then begin if {string constant in IBM AIX OS ?} (sst_config.os = sys_os_aix_k) and {IBM AIX operating system ?} (sym_p^.const_exp_p^.dtype_p^.dtype = sst_dtype_array_k) and {ARRAY ?} sym_p^.const_exp_p^.dtype_p^.ar_string {array is a string of characters ?} then goto next_sym; {these weren't written as string consts} if first then begin {is this the first UNDEF here ?} sst_w.blank_line^; {leave blank line before first UNDEF} first := false; {next UNDEF won't be the first anymore} end; sst_w.tab_indent^; sst_w.appendn^ ('#undef ', 7); sst_w.append^ (sym_p^.name_out_p^); sst_w.line_close^; end; next_sym: {jump here to advance to next symbol in list} string_hash_pos_next (pos, found); {advance to next hash table entry} end; {back and do this new hash table entry} end; { ************************************************************************* * * Local subroutine MAKE_ARG_SYM (NAME, DTYPE, SYM_P) * * Create a new call argument symbol in the current scope. NAME will be * the symbol's input name, and DTYPE is the descriptor for its data type. * SYM_P will be returned pointing to the new symbol descriptor. } procedure make_arg_sym ( {make new call argument symbol} in name: string; {symbol's input name} in dtype: sst_dtype_t; {descriptor for new symbol's data type} out sym_p: sst_symbol_p_t); {returned pointer to the new symbol} var vname: string_var80_t; {var string symbol name} begin vname.max := sizeof(vname.str); {init local var string} string_vstring (vname, name, sizeof(name)); {make var string symbol input name} sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate new symbol descriptor} with sym_p^: sym do begin {SYM is abbrev for newly allocated sym desc} sst_mem_alloc_scope ( {allocate space for input name} string_size(vname.len), sym.name_in_p); sym.name_in_p^.max := vname.len; {init input name string for this symbol} string_copy (vname, sym.name_in_p^); {set symbol's input name} sym.name_out_p := nil; {fill in rest of symbol descriptor} sym.next_p := nil; sym.char_h.crange_p := nil; sym.char_h.ofs := 0; sym.scope_p := sst_scope_p; sym.symtype := sst_symtype_var_k; sym.flags := [ sst_symflag_def_k, sst_symflag_used_k, sst_symflag_written_k, sst_symflag_created_k]; sym.var_dtype_p := addr(dtype); sym.var_val_p := nil; sym.var_arg_p := nil; sym.var_proc_p := nil; sym.var_com_p := nil; sym.var_next_p := nil; sst_w.name_sym^ (sym); {set output name for this symbol} end; {done with SYM abbreviation} end; { ************************************************************************* * * Start of main routine. } begin name.max := sizeof(name.str); {init local var string} apptype := apptype_cmline_k; {init to this is normal command line app} if {check for Win32 GUI application} (sst_config.os = sys_os_win32_k) and {target OS is Win32 ?} sst_gui {GUI, not command line application ?} then apptype := apptype_wingui_k; opc_p := first_p; {init current opcode to first opcode in chain} while opc_p <> nil do begin {keep looping until end of opcode chain} with opc_p^: opc do begin {OPC is current opcode descriptor} case opc.opcode of {what kind of opcode descriptor is this ?} { * Start of a module containing executable units. } sst_opc_module_k: begin sst_w.undent_all^; sst_w_c_scope_push ( {set module's scope as current} opc.module_sym_p^.module_scope_p^, scope_type_module_k); sst_w_c_opcodes (opc.module_p); {process opcodes for this module} sst_w_c_scope_pop; {restore previous scope} end; { * Start of a top level program. } sst_opc_prog_k: begin sst_w_c_scope_push ( {set program's scope as current} opc.prog_sym_p^.prog_scope_p^, scope_type_prog_k); { * Top level programs are really subroutines that are passed special standard * arguments dictated by the system. The variable APPTYPE uniquely indentifies * all the different combinations of system interface and implicit * initialization we must perform. } case apptype of {which interface/init situation is this ?} { **************** * * Application type is a Unix-style command line interface program. * * System interface: * * int main ( * int argc, (number of command line arguments) * char * argv) (list of pointers to command line args) * * Implicit initialization: * * string_cmline_set (argc, argv, <program name>) * * First declare the STRING_CMLINE_SET external subroutine. } apptype_cmline_k: begin {app is Unix command line program} sst_w.blank_line^; sst_w.indent^; sst_w.appends^ ('extern void string_cmline_set ('); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('int,', 4); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('char *,', 7); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('char *);', 8); sst_w.line_close^; sst_w.undent^; { * Create the symbol descriptors for the main routine's arguments. } make_arg_sym ( 'argc', {argument name} sst_config.int_machine_p^, {data type} arg1_p); {returned pointer to ARGC} make_arg_sym ( 'argv', {argument name} sst_dtype_uptr_p^, {data type} arg2_p); {returned pointer to ARGV} { * Write header for program and declare routine MAIN. } sym_p := opc.prog_sym_p; {get pointer to program name symbol} sst_w.blank_line^; sst_w.appends^ ('/*****************************'); sst_w.line_close^; sst_w.appendn^ ('**', 2); sst_w.line_close^; sst_w.appendn^ ('** Start of program ', 22); sst_w.name_sym^ (sym_p^); {make sure routine has a name} string_copy (sym_p^.name_out_p^, name); {make local copy of name} string_upcase (name); sst_w.append^ (name); sst_w.appendn^ ('.', 1); sst_w.line_close^; sst_w.appendn^ ('*/', 2); sst_w.line_close^; frame_scope_p^.sment_type := sment_type_decll_k; {declarations are now local} frame_scope_p^.pos_decll := sst_out.dyn_p^; {start local declarations here} sst_out.dyn_p := addr(frame_scope_p^.pos_decll); {use local declarations position} sst_w.line_new^; {leave blank line before declaration} sst_w.indent^; sst_w.indent^; if sst_config.os = sys_os_win32_k then begin {writing for Win32 API ?} sst_w.appends^ ('__declspec(dllexport)'(0)); {export all global routines} sst_w.delimit^; end; sst_w.appendn^ ('int main (', 10); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('int', 3); sst_w.delimit^; sst_w.append_sym_name^ (arg1_p^); sst_w.appendn^ (',', 1); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('char *', 6); sst_w.delimit^; sst_w.append_sym_name^ (arg2_p^); sst_w.appendn^ (') {', 3); sst_w.undent^; sst_w.line_close^; sst_w_c_symbols (false); {declare local symbols for the program} sst_w_c_opcodes (opc.prog_p); {process opcodes for this program} const_undef; {UNDEF the constants defined earlier} sst_w_c_scope_pop; {restore previous scope} sst_w.tab_indent^; sst_w.appendn^ ('}', 1); sst_w.line_close^; sst_w.undent^; end; {end of Unix command line app case} { **************** * * Application type is Microsoft Windows GUI. * * System interface: * * int WinMain ( * int arg_instance_h, (handle to this instance of this app) * int arg_previous_h, (handle to previous instance of this app) * char * arg_cmdline, (NULL-term raw command line string) * int arg_show_state) (requested initial window show state) * * Note that ARG_INSTANCE_H and ARG_PREVIOUS_H are really supposed to be * unsigned integers. We use signed integers here because unsigned * integers aren't a basic data type. * * Implicit initialization: * * sys_sys_init_wingui (arg_instance_h, arg_previous_h, arg_show_state, * <program name>) * * Declare the SYS_SYS_INIT_WINGUI external subroutine. } apptype_wingui_k: begin sst_w.blank_line^; sst_w.indent^; sst_w.appends^ ('extern void sys_sys_init_wingui ('); sst_w.line_new^; sst_w.tab_indent^; sst_w.appends^ ('int,'(0)); sst_w.line_new^; sst_w.tab_indent^; sst_w.appends^ ('int,'(0)); sst_w.line_new^; sst_w.tab_indent^; sst_w.appends^ ('int,'(0)); sst_w.line_new^; sst_w.tab_indent^; sst_w.appends^ ('char *);'(0)); sst_w.line_close^; sst_w.undent^; { * Create the symbol descriptors for the main routine's arguments. } make_arg_sym ( 'arg_instance_h', {argument name} sst_config.int_machine_p^, {data type} arg1_p); {returned pointer to argument symbol} make_arg_sym ( 'arg_previous_h', {argument name} sst_config.int_machine_p^, {data type} arg2_p); {returned pointer to argument symbol} make_arg_sym ( 'arg_cmdline', {argument name} sst_dtype_uptr_p^, {data type} arg3_p); {returned pointer to argument symbol} make_arg_sym ( 'arg_show_state', {argument name} sst_config.int_machine_p^, {data type} arg4_p); {returned pointer to argument symbol} { * Write header for program and declare routine WinMain. } sym_p := opc.prog_sym_p; {get pointer to program name symbol} sst_w.blank_line^; sst_w.appends^ ('/*****************************'); sst_w.line_close^; sst_w.appendn^ ('**', 2); sst_w.line_close^; sst_w.appendn^ ('** Start of program ', 22); sst_w.name_sym^ (sym_p^); {make sure program has an output name} string_copy (sym_p^.name_out_p^, name); {make local copy of program name} string_upcase (name); sst_w.append^ (name); sst_w.appendn^ ('.', 1); sst_w.line_close^; sst_w.appendn^ ('*/', 2); sst_w.line_close^; frame_scope_p^.sment_type := sment_type_decll_k; {declarations are now local} frame_scope_p^.pos_decll := sst_out.dyn_p^; {start local declarations here} sst_out.dyn_p := addr(frame_scope_p^.pos_decll); {use local declarations position} sst_w.line_new^; {leave blank line before declaration} sst_w.indent^; sst_w.indent^; sst_w.appends^ ('__declspec(dllexport)'(0)); {export all global routines} sst_w.delimit^; sst_w.appends^ ('int WinMain ('(0)); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('int', 3); sst_w.delimit^; sst_w.append_sym_name^ (arg1_p^); sst_w.appendn^ (',', 1); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('int', 3); sst_w.delimit^; sst_w.append_sym_name^ (arg2_p^); sst_w.appendn^ (',', 1); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('char *', 6); sst_w.delimit^; sst_w.append_sym_name^ (arg3_p^); sst_w.appendn^ (',', 1); sst_w.line_new^; sst_w.tab_indent^; sst_w.appendn^ ('int', 3); sst_w.delimit^; sst_w.append_sym_name^ (arg4_p^); sst_w.appendn^ (') {', 3); sst_w.undent^; sst_w.line_close^; sst_w_c_symbols (false); {declare local symbols for the program} sst_w_c_opcodes (opc.prog_p); {process opcodes for this program} const_undef; {UNDEF the constants defined earlier} sst_w_c_scope_pop; {restore previous scope} sst_w.tab_indent^; sst_w.appendn^ ('}', 1); sst_w.line_close^; sst_w.undent^; end; {end of Windows GUI application type} { **************** } end; {end of application type cases} end; {end of opcode is for top level program} { * Opcode is a routine. } sst_opc_rout_k: begin if not (sst_symflag_used_k in opc.rout_sym_p^.flags) {this routine never used ?} then goto done_opcode; {don't write an unused routine} opc.rout_sym_p^.flags := opc.rout_sym_p^.flags + {will define routine here now} [sst_symflag_defnow_k]; sym_p := opc.rout_sym_p; {get pointer to routine symbol descriptor} sst_w.blank_line^; sst_w.appends^ ('/*****************************'); sst_w.line_close^; sst_w.appendn^ ('**', 2); sst_w.line_close^; sst_w.appendn^ ('** Start of ', 14); if sst_symflag_global_k in sym_p^.flags then sst_w.appendn^ ('global', 6) else sst_w.appendn^ ('local', 5); sst_w.appendn^ (' routine ', 9); sst_w.name_sym^ (sym_p^); {make sure routine has a name} string_copy (sym_p^.name_out_p^, name); {make local copy of name} string_upcase (name); sst_w.append^ (name); sst_w.appendn^ ('.', 1); sst_w.line_close^; sst_w.appendn^ ('*/', 2); sst_w.line_close^; dyn_old_p := sst_out.dyn_p; {save pointer to output state block} sment_type_old := frame_scope_p^.sment_type; {save statement type before routine} frame_scope_p^.sment_type := sment_type_decll_k; {declarations are now local} frame_scope_p^.pos_decll := sst_out.dyn_p^; {start local declarations here} sst_out.dyn_p := addr(frame_scope_p^.pos_decll); {use local declarations position} sst_w_c_symbol (opc.rout_sym_p^); {write routine header} sst_w_c_scope_push ( {set routine's scope as current} opc.rout_sym_p^.proc_scope_p^, scope_type_rout_k); sst_w_c_opcodes (opc.rout_p); {process opcodes for this routine} const_undef; {UNDEF the constants defined earlier} sst_w_c_scope_pop; {restore previous scope} dyn_old_p^ := sst_out.dyn_p^; {update old state block with current state} sst_out.dyn_p := dyn_old_p; {restore old state block as current} frame_scope_p^.sment_type := sment_type_old; {restore old statement type} sst_w.tab_indent^; sst_w.appendn^ ('}', 1); sst_w.line_close^; sst_w.undent^; end; { * Chain of opcodes representing executable code. } sst_opc_exec_k: begin path_to_here := true; {init to path exists to this opcode} frame_scope_p^.pos_exec := sst_out.dyn_p^; {init exec out state to curr out state} frame_scope_p^.sment_type := sment_type_exec_k; {now writing executable code} sst_out.dyn_p := addr(frame_scope_p^.pos_exec); {use exec out state} sst_w.tab_indent^; sst_w.appendn^ ('/*', 2); sst_w.line_close^; sst_w.tab_indent^; sst_w.appendn^ ('** Executable code for ', 25); case frame_scope_p^.scope_type of {what kind of structure owns this scope ?} scope_type_prog_k: sst_w.appendn^ ('program', 7); scope_type_rout_k: sst_w.appendn^ ('routine', 7); otherwise sys_msg_parm_int (msg_parm[1], ord(frame_scope_p^.scope_type)); sys_message_bomb ('sst_c_write', 'owner_exec_bad', msg_parm, 1); end; sst_w.appendn^ (' ', 1); string_copy (sst_scope_p^.symbol_p^.name_out_p^, name); string_upcase (name); sst_w.append^ (name); sst_w.appendn^ ('.', 1); sst_w.line_close^; sst_w.tab_indent^; sst_w.appendn^ ('*/', 2); sst_w.line_close^; { * Write implicit initialization at the beginning of the start of the * program. The program routine's call argument symbol pointers are * ARG1_P to ARG4_P. These may not all be used, depending on the system * interface to the top level program routine. APPTYPE id the unique * ID for this combination of system interface and implicit intialization. } if frame_scope_p^.scope_type = scope_type_prog_k then begin {top level program ?} case apptype of {what kind of application type is this} { * Main routine is MAIN, with implicit initialization call to STRING_CMLINE_SET. } apptype_cmline_k: begin sst_w.tab_indent^; sst_w.indent^; sst_w.appendn^ ('string_cmline_set (', 19); sst_w.allow_break^; sst_w.append_sym_name^ (arg1_p^); sst_w.appendn^ (',', 1); sst_w.delimit^; sst_w.append_sym_name^ (arg2_p^); sst_w.appendn^ (',', 1); sst_w.delimit^; sst_w.appendn^ ('"', 1); sst_w.append^ (sst_scope_p^.symbol_p^.name_out_p^); sst_w.appendn^ ('");', 3); sst_w.line_close^; sst_w.undent^; end; { * Main routine is WinMain, with implicit intialization call to * SYS_SYS_INIT_WINGUI. } apptype_wingui_k: begin sst_w.tab_indent^; sst_w.indent^; sst_w.appends^ ('sys_sys_init_wingui ('(0)); sst_w.allow_break^; sst_w.append_sym_name^ (arg1_p^); sst_w.appendn^ (',', 1); sst_w.delimit^; sst_w.append_sym_name^ (arg2_p^); sst_w.appendn^ (',', 1); sst_w.delimit^; sst_w.append_sym_name^ (arg4_p^); sst_w.appendn^ (',', 1); sst_w.delimit^; sst_w.appendn^ ('"', 1); sst_w.append^ (sst_scope_p^.symbol_p^.name_out_p^); sst_w.appendn^ ('");', 3); sst_w.line_close^; sst_w.undent^; end; end; {end of app type cases} end; {end of top level program start case} sst_w_c_exec (opc.exec_p); {process list of executable opcodes} { * We may need an explicit RETURN statement at the end of executable code. * SST defines routines to implicitly return if the end of executable code * is reached. In C, however, functions and top level programs need to return * a value, which is done with a RETURN statement. Therefore, if this is * a function or top level program, write out the code as if a RETURN * opcode were at the end of the chain. This is only done if there is an * executable path to the end of the executable opcodes. } if {need explicit RETURN ?} path_to_here and {end of routine is implicit RETURN ?} ( (frame_scope_p^.scope_type = scope_type_prog_k) or {routine is top program ?} (frame_scope_p^.funcval_sym_p <> nil) {function return value exists ?} ) then begin opc2.next_p := nil; {fill in dummy RETURN opcode} opc2.opcode := sst_opc_return_k; opc2.str_h := opc.str_h; sst_w_c_exec (addr(opc2)); {write explicit return from function} end; frame_scope_p^.sment_type := sment_type_decll_k; {no longer in executable code} end; { * Unrecognized or unexpected opcode. } otherwise sys_msg_parm_int (msg_parm[1], ord(opc.opcode)); sys_message_bomb ('sst', 'opcode_unexpected', msg_parm, 1); end; {end of opcode type cases} end; {done with OPC abbreviation} done_opcode: {jump here if definately done curr opcode} opc_p := opc_p^.next_p; {advance to next opcode descriptor in chain} end; {back and process new opcode} end;
unit GeocodingAddressUnit; interface uses REST.Json.Types, System.Generics.Collections, JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit; type TGeocodingAddress = class(TGenericParameters) private [JSONName('zipcode')] [Nullable] FZipCode: NullableString; [JSONName('street_name')] [Nullable] FStreetName: NullableString; public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; override; /// <summary> /// Zip Code /// </summary> property ZipCode: NullableString read FZipCode write FZipCode; /// <summary> /// Street Name /// </summary> property StreetName: NullableString read FStreetName write FStreetName; end; TGeocodingAddressArray = TArray<TGeocodingAddress>; TGeocodingAddressList = TObjectList<TGeocodingAddress>; implementation constructor TGeocodingAddress.Create; begin Inherited; FZipCode := NullableString.Null; FStreetName := NullableString.Null; end; end.
unit LA.MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, System.Messaging, System.Permissions, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.App, Androidapi.JNI.Location, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Layouts, FMX.TabControl, FMX.ActnList, FMX.Objects, DW.MultiReceiver.Android; type TMessageReceivedEvent = procedure(Sender: TObject; const Msg: string) of object; /// <summary> /// Acts as a receiver of local broadcasts sent by the service /// </summary> TLocalReceiver = class(TMultiReceiver) private FOnMessageReceived: TMessageReceivedEvent; FOnStatus: TNotifyEvent; procedure DoMessageReceived(const AMsg: string); procedure DoStatus; protected procedure Receive(context: JContext; intent: JIntent); override; procedure ConfigureActions; override; public property OnMessageReceived: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; property OnStatus: TNotifyEvent read FOnStatus write FOnStatus; end; TfrmMain = class(TForm) TitleLabel: TLabel; MessagesMemo: TMemo; BottomLayout: TLayout; TabControl: TTabControl; MessagesTab: TTabItem; LogTab: TTabItem; LogMemo: TMemo; RefreshLogButton: TButton; ActionList: TActionList; PauseUpdatesAction: TAction; RefreshLogAction: TAction; BackgroundRectangle: TRectangle; PauseUpdatesButton: TButton; procedure TabControlChange(Sender: TObject); procedure RefreshLogActionExecute(Sender: TObject); procedure PauseUpdatesActionExecute(Sender: TObject); private FReceiver: TLocalReceiver; procedure ApplicationEventMessageHandler(const Sender: TObject; const M: TMessage); procedure EnablePauseUpdates; function IsPaused: Boolean; function IsServiceRunning: Boolean; procedure RefreshLog; procedure LocationPermissionsResultHandler(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); procedure ServiceMessageHandler(Sender: TObject; const AMsg: string); procedure ServiceStatusHandler(Sender: TObject); procedure SendCommand(const ACommand: Integer); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmMain: TfrmMain; implementation {$R *.fmx} uses System.IOUtils, System.Android.Service, Androidapi.Helpers, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, FMX.Platform, DW.OSLog, DW.OSDevice, DW.Androidapi.JNI.LocalBroadcastManager, DW.Android.Helpers, DW.Consts.Android, LS.Consts, LS.Config; type TPermissionResults = TArray<TPermissionStatus>; TPermissionResultsHelper = record helper for TPermissionResults public function AreAllGranted: Boolean; end; { TPermissionResultsHelper } function TPermissionResultsHelper.AreAllGranted: Boolean; var LStatus: TPermissionStatus; begin for LStatus in Self do begin if LStatus <> TPermissionStatus.Granted then Exit(False); // <====== end; Result := True; end; { TLocalReceiver } procedure TLocalReceiver.ConfigureActions; begin // Adds the appropriate actions to the intent filter.. IntentFilter.addAction(StringToJString(cServiceStatusAction)); IntentFilter.addAction(StringToJString(cServiceMessageAction)); end; procedure TLocalReceiver.DoMessageReceived(const AMsg: string); begin if Assigned(FOnMessageReceived) then FOnMessageReceived(Self, AMsg); end; procedure TLocalReceiver.DoStatus; begin if Assigned(FOnStatus) then FOnStatus(Self); end; procedure TLocalReceiver.Receive(context: JContext; intent: JIntent); begin TOSLog.d('TLocalReceiver.Receive'); if intent.getAction.equals(StringToJString(cServiceStatusAction)) then DoStatus else if intent.getAction.equals(StringToJString(cServiceMessageAction)) then DoMessageReceived(JStringToString(intent.getStringExtra(StringToJString(cServiceBroadcastParamMessage)))); end; { TfrmMain } constructor TfrmMain.Create(AOwner: TComponent); begin inherited; TabControl.ActiveTab := MessagesTab; FReceiver := TLocalReceiver.Create(True); FReceiver.OnMessageReceived := ServiceMessageHandler; FReceiver.OnStatus := ServiceStatusHandler; if not IsServiceRunning then TLocalServiceConnection.StartService('LocationService'); TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ApplicationEventMessageHandler); end; destructor TfrmMain.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ApplicationEventMessageHandler); FReceiver.Free; inherited; end; function TfrmMain.IsPaused: Boolean; var LConfig: TLocationConfig; begin Result := True; LConfig := TLocationConfig.GetConfig; if LConfig <> nil then try Result := LConfig.IsPaused; finally LConfig.Free; end; end; function TfrmMain.IsServiceRunning: Boolean; begin Result := TAndroidHelperEx.IsServiceRunning('com.embarcadero.services.LocationService'); end; procedure TfrmMain.EnablePauseUpdates; begin PauseUpdatesAction.Enabled := True; if IsPaused then PauseUpdatesAction.Text := 'Resume Updates' else PauseUpdatesAction.Text := 'Pause Updates'; end; procedure TfrmMain.SendCommand(const ACommand: Integer); var LIntent: JIntent; begin LIntent := TJIntent.JavaClass.init(StringToJString(cServiceCommandAction)); LIntent.putExtra(StringToJString(cServiceBroadcastParamCommand), ACommand); TJLocalBroadcastManager.JavaClass.getInstance(TAndroidHelper.Context).sendBroadcast(LIntent); end; procedure TfrmMain.PauseUpdatesActionExecute(Sender: TObject); begin if IsPaused then TPermissionsService.DefaultService.RequestPermissions([cPermissionAccessCoarseLocation, cPermissionAccessFineLocation], LocationPermissionsResultHandler) else SendCommand(cServiceCommandPause); end; procedure TfrmMain.LocationPermissionsResultHandler(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); begin if AGrantResults.AreAllGranted then SendCommand(cServiceCommandResume); end; procedure TfrmMain.RefreshLog; begin // The service writes certain messages to the log - this routine loads the log with those messages LogMemo.Lines.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'Location.log')); end; procedure TfrmMain.RefreshLogActionExecute(Sender: TObject); begin RefreshLog; end; procedure TfrmMain.ApplicationEventMessageHandler(const Sender: TObject; const M: TMessage); begin case TApplicationEventMessage(M).Value.Event of TApplicationEvent.BecameActive: begin // Assume the service is not running until the app "hears" from it PauseUpdatesAction.Enabled := False; SendCommand(cServiceCommandAppBecameActive); end; TApplicationEvent.EnteredBackground: begin SendCommand(cServiceCommandAppEnteredBackground); end; end; end; procedure TfrmMain.ServiceMessageHandler(Sender: TObject; const AMsg: string); begin MessagesMemo.Lines.Add(AMsg); end; procedure TfrmMain.ServiceStatusHandler(Sender: TObject); begin // If a status message is received from the service it *is* obviously running (IsServiceRunning may return false if it is still starting) EnablePauseUpdates; end; procedure TfrmMain.TabControlChange(Sender: TObject); begin if TabControl.ActiveTab = LogTab then RefreshLog; end; end.
{--------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/NPL/NPL-1_1Final.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: mwPasLexTypes, released November 14, 1999. The Initial Developer of the Original Code is Martin Waldenburg unit CastaliaPasLexTypes; ----------------------------------------------------------------------------} unit SimpleParser.Lexer.Types; interface uses SysUtils, TypInfo; {$INCLUDE SimpleParser.inc} var CompTable: array[#0..#255] of byte; type TMessageEventType = (meError, meNotSupported); TMessageEvent = procedure(Sender: TObject; const Typ: TMessageEventType; const Msg: string; X, Y: Integer) of object; TCommentState = (csAnsi, csBor, csNo); TTokenPoint = packed record X: Integer; Y: Integer; end; TptTokenKind = ( ptAbort, ptAbsolute, ptAbstract, ptAdd, ptAddressOp, ptAmpersand, ptAnd, ptAnsiComment, ptAnsiString, ptArray, ptAs, ptAsciiChar, ptAsm, ptAssembler, ptAssign, ptAt, ptAutomated, ptBegin, ptBoolean, ptBorComment, ptBraceClose, ptBraceOpen, ptBreak, ptByte, ptByteBool, ptCardinal, ptCase, ptCdecl, ptChar, ptClass, ptClassForward, ptClassFunction, ptClassProcedure, ptColon, ptComma, ptComp, ptCompDirect, ptConst, ptConstructor, ptContains, ptContinue, ptCRLF, ptCRLFCo, ptCurrency, ptDefault, ptDefineDirect, ptDeprecated, ptDestructor, ptDispid, ptDispinterface, ptDiv, ptDo, ptDotDot, ptDouble, ptDoubleAddressOp, ptDownto, ptDWORD, ptDynamic, ptElse, ptElseDirect, ptEnd, ptEndIfDirect, ptEqual, ptError, ptExcept, ptExit, ptExport, ptExports, ptExtended, ptExternal, ptFar, ptFile, ptFinal, ptExperimental, ptDelayed, ptFinalization, ptFinally, ptFloat, ptFor, ptForward, ptFunction, ptGoto, ptGreater, ptGreaterEqual, ptHalt, ptHelper, ptIdentifier, ptIf, ptIfDirect, ptIfEndDirect, ptElseIfDirect, ptIfDefDirect, ptIfNDefDirect, ptIfOptDirect, ptImplementation, ptImplements, ptIn, ptIncludeDirect, ptIndex, ptInherited, ptInitialization, ptInline, ptInt64, ptInteger, ptIntegerConst, ptInterface, ptIs, ptLabel, ptLibrary, ptLocal, ptLongBool, ptLongint, ptLongword, ptLower, ptLowerEqual, ptMessage, ptMinus, ptMod, ptName, ptNear, ptNil, ptNodefault, ptNone, ptNot, ptNotEqual, ptNull, ptObject, ptOf, ptOleVariant, ptOn, ptOperator, ptOr, ptOut, ptOverload, ptOverride, ptPackage, ptPacked, ptPascal, ptPChar, ptPlatform, ptPlus, ptPoint, ptPointerSymbol, ptPrivate, ptProcedure, ptProgram, ptProperty, ptProtected, ptPublic, ptPublished, ptRaise, ptRead, ptReadonly, ptReal, ptReal48, ptRecord, ptReference, ptRegister, ptReintroduce, ptRemove, ptRepeat, ptRequires, ptResident, ptResourceDirect, ptResourcestring, ptRoundClose, ptRoundOpen, ptRunError, ptSafeCall, ptSealed, ptSemiColon, ptSet, ptShl, ptShortint, ptShortString, ptShr, ptSingle, ptSlash, ptSlashesComment, ptSmallint, ptSpace, ptSquareClose, ptSquareOpen, ptStar, ptStatic, ptStdcall, ptStored, ptStrict, ptString, ptStringConst, ptStringDQConst, ptStringresource, ptSymbol, ptThen, ptThreadvar, ptTo, ptTry, ptType, ptUndefDirect, ptUnit, ptUnknown, ptUnsafe, ptUntil, ptUses, ptVar, ptVarargs, ptVariant, ptVirtual, ptWhile, ptWideChar, ptWideString, ptWith, ptWord, ptWordBool, ptWrite, ptWriteonly, ptXor); TmwPasLexStatus = record CommentState: TCommentState; ExID: TptTokenKind; LineNumber: Integer; LinePos: Integer; Origin: PChar; RunPos: Integer; TokenPos: Integer; TokenID: TptTokenKind; end; EIncludeError = class(Exception); IIncludeHandler = interface ['{C5F20740-41D2-43E9-8321-7FE5E3AA83B6}'] function GetIncludeFileContent(const FileName: string): string; end; function TokenName(Value: TptTokenKind): string; function ptTokenName(Value: TptTokenKind): string; function IsTokenIDJunk(const aTokenID: TptTokenKind): Boolean; implementation function TokenName(Value: TptTokenKind): string; begin Result := Copy(ptTokenName(Value), 3, MaxInt); end; function ptTokenName(Value: TptTokenKind): string; begin result := GetEnumName(TypeInfo(TptTokenKind), Integer(Value)); end; function IsTokenIDJunk(const aTokenID: TptTokenKind): Boolean; begin Result := aTokenID in [ ptAnsiComment, ptBorComment, ptCRLF, ptCRLFCo, ptSlashesComment, ptSpace, ptIfDirect, ptElseDirect, ptIfEndDirect, ptElseIfDirect, ptIfDefDirect, ptIfNDefDirect, ptEndIfDirect, ptIfOptDirect, ptDefineDirect, ptUndefDirect]; end; end.
{!DOCTOPIC}{ StringTools } const CharsLower = 'abcdefghijklmnopqrstuvwxyz'; CharsUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; CharsLetters = CharsLower + CharsUpper; CharsDigits = '0123456789'; CharsHexDigits = '0123456789abcdefABCDEF'; CharsOctDigits = '01234567'; CharsSigns = '!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~'; CharsAll = CharsLetters + CharsDigits + CharsSigns; {!DOCREF} { @method: function se.StrStrip(const Text:String; Chars:String=' '): String; @desc: Return a copy of the string with leading and trailing characters removed. If chars is omitted, whitespace characters are removed. If chars is given, the characters in the string will be stripped from the both ends of Text. } function SimbaExt.StrStrip(const Text:String; Chars:String=' '): String; begin Result := exp_StrStrip(Text, Chars); end; {!DOCREF} { @method: function se.StrStripL(const Text:String; Chars:String=' '): String; @desc: Return a copy of the string with leading removed. If chars is omitted, whitespace characters are removed. If chars is given, the characters in the string will be stripped from the beginning of Text. } function SimbaExt.StrStripL(const Text:String; Chars:String=' '): String; begin Result := exp_StrStripL(Text, Chars); end; {!DOCREF} { @method: function se.StrStripR(const Text:String; Chars:String=' '): String; @desc: Return a copy of the string with trailing removed. If chars is omitted, whitespace characters are removed. If chars is given, the characters in the string will be stripped from the end of Text. } function SimbaExt.StrStripR(const Text:String; Chars:String=' '): String; begin Result := exp_StrStripR(Text, Chars); end; {!DOCREF} { @method: function se.StrPosEx(const SubStr, Text:String): TIntegerArray; @desc: Same as 'String.PosMulti(..)', returns all the positions where the substring was found. } function SimbaExt.StrPosEx(const SubStr, Text:String): TIntegerArray; begin Result := exp_StrPosEx(SubStr, Text); end; {!DOCREF} { @method: function se.StrPosL(const SubStr, Text: String): Int32; @desc: Same as 'String.Pos(..)', returns the first position where the substring was found, returns 0 if not. } function SimbaExt.StrPosL(const SubStr, Text: String): Int32; begin Result := exp_StrPosL(SubStr, Text); end; {!DOCREF} { @method: function se.StrPosL(const SubStr, Text: String): Int32; @desc: Same as 'String.rPos(..)', returns the first position from right where the substring was found, returns 0 if not. } function SimbaExt.StrPosR(const SubStr, Text: String): Int32; begin Result := exp_StrPosR(SubStr, Text); end; {!DOCREF} { @method: function se.StrReplace(const Text, SubStr, RepStr: String; Flags:TReplaceFlags): String; @desc: This function returns a string or an array with all occurrences of c'SubStr' in c'Text' replaced with the given replace value 'RepStr'. This version is a lot faster then Simbas c'Replace', at least when we are working with more then just a sentance or three. } function SimbaExt.StrReplace(const Text, SubStr, RepStr: String; Flags:TReplaceFlags): String; begin Result := exp_StrReplace(Text, SubStr, RepStr, Flags); end; {!DOCREF} { @method: function se.StrExplode(const Text, Sep: String): TStringArray; @desc: Returns an array of strings, each of which is a substring of c'Text' formed by splitting it on boundaries formed by the string separator c'sep'. Should be a bit faster then simbas c'Explode(...)'. } function SimbaExt.StrExplode(const Text, Sep: String): TStringArray; begin Result := exp_StrExplode(Text, Sep); end;
unit FileCache; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, FastBitmap; type TFileCacheItem = record start: longint; length: longint; number: integer; end; { TFileCache } TFileCache = class private cache_stream: TFileStream; FCount: integer; FCacheList: array of TFileCacheItem; public constructor Create(AFileName: string); destructor Destroy; override; property Count: integer read FCount; function GetData(Number: integer; var Bitmap: TFastBitmap): boolean; procedure Add(Number: integer; Bitmap: TFastBitmap); procedure Clear; end; implementation { TFileCache } constructor TFileCache.Create(AFileName: string); begin FCount := 0; cache_stream := TFileStream.Create(AFileName, fmCreate); end; destructor TFileCache.Destroy; begin Clear; cache_stream.Free; inherited Destroy; end; function TFileCache.GetData(Number: integer; var Bitmap: TFastBitmap): boolean; var i: integer; begin Result := False; for i := 0 to FCount - 1 do if FCacheList[i].number = Number then begin cache_stream.Position := FCacheList[i].start; cache_stream.Read(Bitmap.PixelsData^, FCacheList[i].length); Result := True; exit; end; end; procedure TFileCache.Add(Number: integer; Bitmap: TFastBitmap); begin if Bitmap = nil then exit; Inc(FCount); SetLength(FCacheList, FCount); FCacheList[FCount - 1].number := Number; //move to the end of the stream cache_stream.Position := cache_stream.Size; FCacheList[FCount - 1].start := cache_stream.Position; cache_stream.Write(Bitmap.PixelsData^, Bitmap.Size.x * Bitmap.Size.y * 4); FCacheList[FCount - 1].length := cache_stream.Position - FCacheList[FCount - 1].start; end; procedure TFileCache.Clear; begin FCount := 0; SetLength(FCacheList, FCount); end; end.
unit ATxShellExtension; interface function ApplyShellExtension(AEnable: boolean): boolean; function IsShellExtensionEnabled: boolean; implementation uses Windows, ATxSProc, ATxParamStr, ATxRegistry; const RegKey0 = '*\shell\Universal Viewer'; RegKey1 = RegKey0 + '\command'; RegKeyF0 = 'Directory\shell\Universal Viewer'; RegKeyF1 = RegKeyF0 + '\command'; //Files function ShellValue: WideString; begin Result:= SFormatW('"%s" "%1"', [SParamExe]); end; //Folders function ShellValueF: WideString; begin Result:= SFormatW('"%s" "@@%1"', [SParamExe]); end; function ApplyShellExtension(AEnable: boolean): boolean; begin if AEnable then begin Result:= SetRegKeyStr(HKEY_CLASSES_ROOT, RegKey1, '', ShellValue) and SetRegKeyStr(HKEY_CLASSES_ROOT, RegKeyF1, '', ShellValueF); end else begin Result:= (RegDeleteKey(HKEY_CLASSES_ROOT, RegKey1) = ERROR_SUCCESS) and (RegDeleteKey(HKEY_CLASSES_ROOT, RegKey0) = ERROR_SUCCESS) and (RegDeleteKey(HKEY_CLASSES_ROOT, RegKeyF1) = ERROR_SUCCESS) and (RegDeleteKey(HKEY_CLASSES_ROOT, RegKeyF0) = ERROR_SUCCESS); end; end; function IsShellExtensionEnabled: boolean; begin Result:= (SCompareIW(GetRegKeyStr(HKEY_CLASSES_ROOT, RegKey1, '', ''), ShellValue) = 0) and (SCompareIW(GetRegKeyStr(HKEY_CLASSES_ROOT, RegKeyF1, '', ''), ShellValueF) = 0); end; end.
unit UStartup; interface uses Windows, Messages; const // Name of main window class cWindowClassName = 'Accusys.Tickler.3'; // Any 32 bit number here to perform check on copied data cCopyDataWaterMark = $DE1F1DAB; // User window message handled by main form ensures that // app not minimized or hidden and is in foreground UM_ENSURERESTORED = WM_USER + 1; function FindDuplicateMainWdw: HWND; function SwitchToPrevInst(Wdw: HWND): Boolean; procedure ActivateWindow(Handle: THandle; RestoreIfMinimized: Boolean = True); implementation uses SysUtils; function SendParamsToPrevInst(Wdw: HWND): Boolean; var CopyData: TCopyDataStruct; I: Integer; CharCount: Integer; Data: PChar; PData: PChar; begin CharCount := 0; for I := 1 to ParamCount do Inc(CharCount, Length(ParamStr(I)) + 1); Inc(CharCount); Data := StrAlloc(CharCount); try PData := Data; for I := 1 to ParamCount do begin StrPCopy(PData, ParamStr(I)); Inc(PData, Length(ParamStr(I)) + 1); end; PData^ := #0; CopyData.lpData := Data; CopyData.cbData := CharCount * SizeOf(Char); CopyData.dwData := cCopyDataWaterMark; Result := SendMessage( Wdw, WM_COPYDATA, 0, LPARAM(@CopyData) ) = 1; finally StrDispose(Data); end; end; function FindDuplicateMainWdw: HWND; begin Result := FindWindow(cWindowClassName, nil); end; function SwitchToPrevInst(Wdw: HWND): Boolean; begin Assert(Wdw <> 0); if ParamCount > 0 then Result := SendParamsToPrevInst(Wdw) else Result := True; if Result then SendMessage(Wdw, UM_ENSURERESTORED, 0, 0); end; procedure ActivateWindow(Handle: THandle; RestoreIfMinimized: Boolean = True); var CurThreadID, ThreadID: THandle; begin if RestoreIfMinimized and IsIconic(Handle) then ShowWindow(Handle, SW_RESTORE); CurThreadID:= GetCurrentThreadID; ThreadID:= GetWindowThreadProcessId(GetForegroundWindow, nil); if CurThreadID = ThreadID then SetForegroundWindow(Handle) else begin if AttachThreadInput(GetCurrentThreadID, ThreadID, True) then begin //ActivateWindowOld(Handle, RestoreIfMinimized); SetForegroundWindow(Handle); BringWindowToTop(Handle); AttachThreadInput(GetCurrentThreadID, ThreadID, False); end; end; end; end.
{ Exercicio 24: Escreva um algoritmo que receba o nome e a idade de uma pessoa. Exibir o nome da pessoa e as seguintes expressões, conforme o caso: Idade Expressão Abaixo de 16 anos Parabéns! Mas você é muito jovem. Entre 16 e 17 anos Parabéns! Você já pode votar. Entre 18 e 21 anos Parabéns! Você já pode votar e tirar carteira de motorista. Acima de 21 anos Parabéns! Você está ficando experiente. } { Solução em Portugol Algoritmo Exercicio 24; Var idade: inteiro; nome: caracter; Inicio exiba("Programa que avalia a sua idade."); exiba("Digite o seu nome: "); leia(nome); exiba("Digite a sua idade: "); leia(idade); se(idade < 16) então exiba("Parabéns ",nome,"! Mas você é muito jovem."); fimse; se((idade = 16) ou (idade = 17)) então exiba("Parabéns ",nome,"! Você já pode votar."); fimse; se((idade >= 18) e (idade <= 21)) então exiba("Parabéns ",nome,"! Você já pode votar e tirar carteira de motorista."); fimse; se(idade > 21) então exiba("Parabéns ",nome,"! Você está ficando experiente."); fimse; Fim. } // Solução em Pascal Program Exercicio24; uses crt; var idade: integer; nome: string; begin clrscr; writeln('Programa que avalia a sua idade.'); writeln('Digite o seu nome: '); readln(nome); writeln('Digite a sua idade: '); readln(idade); if(idade < 16) then writeln('Parabéns ',nome,'! Mas você é muito jovem.'); if((idade = 16) or (idade = 17)) then writeln('Parabéns ',nome,'! Você já pode votar.'); if((idade >= 18) and (idade <= 21)) then writeln('Parabéns ',nome,'! Você já pode votar e tirar carteira de motorista.'); if(idade > 21) then writeln('Parabéns ',nome,'! Você está ficando experiente.'); repeat until keypressed; end.
unit RemoveRouteDestinationUnit; interface uses SysUtils, BaseExampleUnit; type TRemoveRouteDestination = class(TBaseExample) public procedure Execute(RouteId: String; DestinationId: integer); end; implementation procedure TRemoveRouteDestination.Execute(RouteId: String; DestinationId: integer); var ErrorString: String; Deleted: boolean; begin Deleted := Route4MeManager.Route.Remove(RouteId, DestinationId, ErrorString); WriteLn(''); if (Deleted) then begin WriteLn('RemoveRouteDestination executed successfully'); WriteLn(Format('Destination ID: %d', [DestinationId])); end else WriteLn(Format('RemoveRouteDestination error: "%s"', [ErrorString])); end; end.
unit SetWallpaperStatementParsingTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FpcUnit, TestRegistry, ParserBaseTestCase, WpcScriptCommons, WpcStatements, WpcScriptParser, WpcExceptions, WpcWallpaperStyles; const SET_WALLPAPER = SET_KEYWORD + ' ' + WALLPAPER_KEYWORD + ' '; WALLPAPER_IMAGE_FILE = 'File.ext'; type { TSetWallpaperStatementParsingTest } TSetWallpaperStatementParsingTest = class(TParserBaseTestCase) protected WallpaperStatement : TWpcWallpaperStatement; published procedure ShouldParseBaseWallpaperStatement(); procedure ShouldParseWallpaperStatementWithStyleProperty(); procedure ShouldParseWallpaperStatementWithProbabilityProperty(); procedure ShouldParseWallpaperStatementWithDelayProperty(); procedure ShouldParseWallpaperStatementWithAllProperties(); procedure SholudRaiseScriptParseExceptionWhenNoWallpaperImageSpecified(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); end; implementation { TSetWallpaperStatementParsingTest } // SET WALLPAPER File.ext procedure TSetWallpaperStatementParsingTest.ShouldParseBaseWallpaperStatement(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_STATEMENT_ID = MainBranchStatements[0].GetId()); WallpaperStatement := TWpcWallpaperStatement(MainBranchStatements[0]); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetImage().GetPath().EndsWith(WALLPAPER_IMAGE_FILE)); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, CENTER = WallpaperStatement.GetStyle()); // CENTER should be default value AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, 0, WallpaperStatement.GetDelay()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, WallpaperStatement.GetProbability()); end; // SET WALLPAER File.ext STYLE STRETCH procedure TSetWallpaperStatementParsingTest.ShouldParseWallpaperStatementWithStyleProperty(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + STYLE_PROPERTY); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_STATEMENT_ID = MainBranchStatements[0].GetId()); WallpaperStatement := TWpcWallpaperStatement(MainBranchStatements[0]); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetImage().GetPath().EndsWith(WALLPAPER_IMAGE_FILE)); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetStyle() = TEST_DEFAULT_STYLE_VALUE); end; // SET WALLPAER File.ext WITH PROBABILITY 50 procedure TSetWallpaperStatementParsingTest.ShouldParseWallpaperStatementWithProbabilityProperty(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_STATEMENT_ID = MainBranchStatements[0].GetId()); WallpaperStatement := TWpcWallpaperStatement(MainBranchStatements[0]); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetImage().GetPath().EndsWith(WALLPAPER_IMAGE_FILE)); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, WallpaperStatement.GetProbability()); end; // SET WALLPAER File.ext FOR 5m procedure TSetWallpaperStatementParsingTest.ShouldParseWallpaperStatementWithDelayProperty(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + DELAY_FOR_PROPERTY); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_STATEMENT_ID = MainBranchStatements[0].GetId()); WallpaperStatement := TWpcWallpaperStatement(MainBranchStatements[0]); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetImage().GetPath().EndsWith(WALLPAPER_IMAGE_FILE)); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WallpaperStatement.GetDelay()); end; // SET WALLPAER File.ext STYLE STRETCH FOR 5m WITH PROBABILITY 50 procedure TSetWallpaperStatementParsingTest.ShouldParseWallpaperStatementWithAllProperties(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + STYLE_PROPERTY + DELAY_FOR_PROPERTY + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_STATEMENT_ID = MainBranchStatements[0].GetId()); WallpaperStatement := TWpcWallpaperStatement(MainBranchStatements[0]); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetImage().GetPath().EndsWith(WALLPAPER_IMAGE_FILE)); AssertTrue(WRONG_STATEMENT_PROPRTY_VALUE, WallpaperStatement.GetStyle() = TEST_DEFAULT_STYLE_VALUE); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_DELAY_VALUE, WallpaperStatement.GetDelay()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, WallpaperStatement.GetProbability()); end; // SET WALLPAPER procedure TSetWallpaperStatementParsingTest.SholudRaiseScriptParseExceptionWhenNoWallpaperImageSpecified(); begin ScriptLines.Add(SET_WALLPAPER); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 2); end; // SET WALLPAER File.ext CENTER procedure TSetWallpaperStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + ' CENTER '); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 3); end; // SET WALLPAER File.ext SMOOTHLY STYLE CENTER procedure TSetWallpaperStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + ' SMOOTHLY ' + STYLE_PROPERTY); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 3); end; // SET WALLPAER File.ext STYLE CENTER FOR 5m ONCE procedure TSetWallpaperStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); begin ScriptLines.Add(SET_WALLPAPER + WALLPAPER_IMAGE_FILE + STYLE_PROPERTY + DELAY_FOR_PROPERTY + ' ONCE '); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 7); end; initialization RegisterTest(PARSER_TEST_SUITE_NAME, TSetWallpaperStatementParsingTest); end.
unit ClassDCNetwaveCam; interface uses ClassDeviceConnect , System.Generics.Collections , IdComponent; type TDCNetwaveCam = class (TDeviceConnect, IDeviceConnect) procedure OnWorkBegin(Sender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure OnWorkEnd(Sender: TObject; AWorkMode: TWorkMode); procedure OnWork(Sender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure OnDisconnected(Sender: TObject); procedure OnStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); const DCNC_AUTH_PIVOT_ALIAS = '[[§]]'; DCNC_AUTH_PIVOT = ':'; private AUsername: string; APassword: string; AInProgress: boolean; protected property InProgress: boolean read AInProgress write AInProgress default false; function GetAuth: string; override; procedure SetAuth(Value: string); override; public constructor Create; override; function Connect(out ErrMsg: string): TDictionary<string, TObject>; override; end; implementation uses System.Types , System.StrUtils , System.SysUtils , IdHTTP , System.Classes , FMX.Forms , FMX.Graphics; { TDCNetwaveCam } function TDCNetwaveCam.Connect(out ErrMsg: string): TDictionary<string, TObject>; var HTTPClient: TIdHTTP; URL, OutPut: string; Stream: TStringStream; StrExtraVal: TStrExtraVal; ImgExtraVal: TImgExtraVal; BitMap: TBitmap; begin Result := nil; try URL := StringReplace(Host, 'http://', '', [rfReplaceAll, rfIgnoreCase]); URL := 'http://' + URL + ':' + IntToStr(Port) + '/snapshot.cgi'; HTTPClient := TIdHTTP.Create(nil); try HTTPClient.ReadTimeout := 120000; HTTPClient.AllowCookies := false; HTTPClient.Request.ContentLength := -1; HTTPClient.Request.ContentRangeEnd := 0; HTTPClient.Request.ContentRangeStart := 0; HTTPClient.Request.ContentType := 'text/html'; HTTPClient.Request.Accept := 'text/html, */*'; HTTPClient.Request.BasicAuthentication := true; HTTPClient.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'; HTTPClient.Request.Username := AUsername; HTTPClient.Request.Password := APassword; HTTPClient.Request.Host := Host + ':' + IntToStr(Port); HTTPClient.OnWorkBegin := OnWorkBegin; HTTPClient.OnWork := OnWork; HTTPClient.OnWorkEnd := OnWorkEnd; HTTPClient.OnDisconnected := OnDisconnected; HTTPClient.OnStatus := OnStatus; Stream := TStringStream.Create; try InProgress := true; HTTPClient.Get(URL, Stream); while InProgress do Application.ProcessMessages; if HTTPClient.ResponseCode = 200 then begin OutPut := Stream.DataString; if Trim(OutPut) <> '' then begin Result := TDictionary<string, TObject>.Create(); StrExtraVal := TStrExtraVal.Create; StrExtraVal.Value := OutPut; Result.Add('RawData', StrExtraVal); BitMap := TBitmap.Create; BitMap.LoadFromStream(Stream); ImgExtraVal := TImgExtraVal.Create; ImgExtraVal.Value := BitMap; Result.Add('Capture', ImgExtraVal); end; end else ErrMsg := 'Response code = ' + IntToStr(HTTPClient.ResponseCode); finally Stream.Free; end; finally HTTPClient.Free; end; except on E: Exception do begin Result := nil; ErrMsg := E.Message; end; end; end; constructor TDCNetwaveCam.Create; begin inherited; AUsername := ''; APassword := ''; end; function TDCNetwaveCam.GetAuth: string; begin Result := AUsername + DCNC_AUTH_PIVOT + APassword; end; procedure TDCNetwaveCam.OnDisconnected(Sender: TObject); begin InProgress := false; end; procedure TDCNetwaveCam.OnStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin case AStatus of // hsResolving, hsConnecting, hsConnected, hsDisconnecting : InProgress := true; hsDisconnected, ftpAborted : InProgress := false; end; end; procedure TDCNetwaveCam.OnWork(Sender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin InProgress := true; end; procedure TDCNetwaveCam.OnWorkBegin(Sender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin InProgress := true; end; procedure TDCNetwaveCam.OnWorkEnd(Sender: TObject; AWorkMode: TWorkMode); begin InProgress := false; end; procedure TDCNetwaveCam.SetAuth(Value: string); var AuthParts: TStringDynArray; begin inherited; if Trim(Value) <> '' then begin AuthParts := SplitString(Value, DCNC_AUTH_PIVOT); if Assigned(AuthParts) and (High(AuthParts) = 1) then begin AUsername := StringReplace(AuthParts[0], DCNC_AUTH_PIVOT_ALIAS, DCNC_AUTH_PIVOT, [rfReplaceAll]); APassword := StringReplace(AuthParts[1], DCNC_AUTH_PIVOT_ALIAS, DCNC_AUTH_PIVOT, [rfReplaceAll]); end else raise Exception.Create('Wrong auth format.'); end; end; end.
unit Model.ExpressasExtratos; interface uses Common.ENum, FireDAC.Comp.Client,System.SysUtils, DAO.Conexao, System.DateUtils, System.Classes; type TExpressasExtratos = class private FTotalEmpresa: Double; FEntregas: Integer; FQuinzena: Integer; FCliente: Integer; FVolumesExtra: Double; FMes: Integer; FPerformance: Double; FVolumes: Integer; FID: Integer; FVerba: Double; FEntregador: Integer; FAno: Integer; FDataInicio: TDate; FCreditos: Double; FProducao: Double; FExtravios: Double; FBase: Integer; FDataCredito: TDate; FTotalExpressas: Double; FAtrasos: Integer; FDebitos: Double; FDataFinal: TDate; FExtrato: String; FConexao : TConexao; FAcao: TAcao; FUniqueKey: String; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; function GenerateNumeroExtrato(): String; public property ID: Integer read FID write FID; property DataInicio: TDate read FDataInicio write FDataInicio; property DataFinal: TDate read FDataFinal write FDataFinal; property Ano: Integer read FAno write FAno; property Mes: Integer read FMes write FMes; property Quinzena: Integer read FQuinzena write FQuinzena; property Base: Integer read FBase write FBase; property Entregador: Integer read FEntregador write FEntregador; property Extrato: String read FExtrato write FExtrato; property Verba: Double read FVerba write FVerba; property Volumes: Integer read FVolumes write FVolumes; property VolumesExtra: Double read FVolumesExtra write FVolumesExtra; property Entregas: Integer read FEntregas write FEntregas; property Atrasos: Integer read FAtrasos write FAtrasos; property Performance: Double read FPerformance write FPerformance; property Producao: Double read FProducao write FProducao; property Creditos: Double read FCreditos write FCreditos; property Debitos: Double read FDebitos write FDebitos; property Extravios: Double read FExtravios write FExtravios; property TotalExpressas: Double read FTotalExpressas write FTotalExpressas; property TotalEmpresa: Double read FTotalEmpresa write FTotalEmpresa; property Cliente: Integer read FCliente write FCliente; property DataCredito: TDate read FDataCredito write FDataCredito; property UniqueKey: String read FUniqueKey write FUniqueKey; constructor Create(); function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function DatasPagamentos(iBase: integer): TStringList; end; const TABLENAME = 'expressas_extrato'; SQLUPDATE = 'update ' + TABLENAME + ' set dat_inicio = :dat_inicio, dat_final = :dat_final, num_ano = :num_ano, ' + 'num_mes = :num_mes, num_quinzena = :num_quinzena, cod_base = :cod_base, cod_entregador = :cod_entregador, ' + 'num_extrato= :num_extrato, val_verba = :val_verba, qtd_volumes = :qtd_volumes, ' + 'qtd_volumes_extra = :qtd_volumes_extra, val_volumes_extra = :val_volumes_extra, qtd_entregas = :qtd_entregas, ' + 'qtd_atraso = :qtd_atraso, val_performance = :val_performance, val_producao :val_producao, ' + 'val_creditos = :val_creditos, val_debitos = :val_debitos, val_extravios = :val_extravios, ' + 'val_total_expressa = :val_total_expressa, val_total_empresa = :val_total_empresa, cod_cliente = :cod_cliente, ' + 'dat_credito = :dat_credito, des_unique_key = :des_unique_key ' + 'where id_extrato = :id_extrato'; SQLINSERT = 'insert into '+ TABLENAME +'(id_extrato, dat_inicio, dat_final, num_ano, num_mes, num_quinzena, cod_base, ' + 'cod_entregador, num_extrato, val_verba,qtd_volumes,qtd_volumes_extra,val_volumes_extra, qtd_entregas, qtd_atraso, ' + 'val_performance, val_producao, val_creditos, val_debitos, val_extravios, val_total_expressa, val_total_empresa, ' + 'cod_cliente, dat_credito, des_unique_key) ' + 'values (:id_extrato, :dat_inicio, :dat_final, :num_ano, :num_mes, :num_quinzena, :cod_base, ' + ':cod_entregador, :num_extrato, :val_verba, :qtd_volumes, :qtd_volumes_extra, :val_volumes_extra, :qtd_entregas, ' + ':qtd_atraso, :val_performance, :val_producao, :val_creditos, :val_debitos, :val_extravios, :val_total_expressa, ' + ':val_total_empresa, :cod_cliente, :dat_credito, :des_unique_key)'; SQLQUERY = 'select id_extrato, dat_inicio, dat_final, num_ano, num_mes, num_quinzena, cod_base, cod_entregador, ' + 'num_extrato, val_verba, qtd_volumes, qtd_volumes_extra, val_volumes_extra, qtd_entregas, qtd_atraso, ' + 'val_performance, val_producao, val_creditos, val_debitos, val_extravios, val_total_expressa, val_total_empresa, ' + 'cod_cliente, dat_credito, des_unique_key ' + 'from ' + TABLENAME; implementation { TExpressasExtratos } function TExpressasExtratos.Alterar: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE,[Self.DataInicio, Self.DataFinal, Self.Ano, Self.Mes, Self.Quinzena, Self.Base, Self.Entregador, Self.Extrato, Self.Verba, Self.Volumes, Self.VolumesExtra, Self.Entregas, Self.Atrasos, Self.Performance, Self.Producao, Self.Creditos, Self.Debitos, Self.Extravios, Self.TotalExpressas, Self.TotalEmpresa, Self.Cliente, Self.DataCredito, Self.UniqueKey, Self.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TExpressasExtratos.Create; begin fConexao := TConexao.Create; end; function TExpressasExtratos.DatasPagamentos(iBase: integer): TStringList; var sSQL : String; FDQuery : TFDQuery; sLista: TStringList; begin try sLista := TStringList.Create; FDQuery := FConexao.ReturnQuery; sSQL := 'select distinct(dat_credito) from ' + TABLENAME + ' where cod_base = :base order by dat_credito desc'; FDQuery.SQL.Add(sSQL); FDQuery.ParamByName('base').AsInteger := iBase; FDQuery.Open(); if not FDQuery.IsEmpty then FDQuery.First; while not FDQuery.Eof do begin sLista.Add(FormatDateTime('dd/mm/yyyy', FDQuery.Fields[0].Value)); FDQuery.Next; end; Result := sLista; finally FDQuery.Free; end; end; function TExpressasExtratos.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_extrato = :id_extrato', [Self.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TExpressasExtratos.GenerateNumeroExtrato: String; var iDias : Integer; sExtrato: String; begin Result := '0'; iDias := DaysBetween(Self.DataFinal, StrToDate('1899-12-31')); sExtrato := IntToStr(iDias) + IntToStr(Self.Base) + IntToStr(Self.Entregador); Result := sExtrato; end; function TExpressasExtratos.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Inserir(); Common.ENum.tacAlterar: Result := Alterar(); Common.ENum.tacExcluir: Result := Excluir(); end; end; function TExpressasExtratos.Inserir: Boolean; var FDQuery: TFDQuery; begin try Result := False; Self.Extrato := GenerateNumeroExtrato; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLINSERT,[Self.ID,Self.DataInicio,Self.DataFinal,Self.Ano,Self.Mes, Self.Quinzena, Self.Base, Self.Entregador, Self.Extrato, Self.Verba, Self.Volumes, Self.VolumesExtra, Self.Entregas, Self.Atrasos, Self.Performance, Self.Producao, Self.Creditos, Self.Debitos, Self.Extravios, Self.TotalExpressas, Self.TotalEmpresa, Self.Cliente, Self.DataCredito, Self.UniqueKey]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TExpressasExtratos.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add(SQLQUERY); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_extrato = :id_extrato'); FDQuery.ParamByName('id_extrato').AsInteger := aParam[1]; end; if aParam[0] = 'DATAS' then begin FDQuery.SQL.Add('where dat_inicio >= :dat_inicio and dat_final <= :dat_final'); FDQuery.ParamByName('dat_inicio').AsDate := aParam[1]; FDQuery.ParamByName('dat_final').AsDate := aParam[2]; end; if aParam[0] = 'QUINZENA' then begin FDQuery.SQL.Add('where num_ano = :num_ano and num_mes = :num_mes and num_quinzena = :num_quinzena'); FDQuery.ParamByName('num_ano').AsInteger := aParam[1]; FDQuery.ParamByName('num_mes').AsInteger := aParam[2]; FDQuery.ParamByName('num_quinzena').AsInteger := aParam[3]; end; if aParam[0] = 'EXTRATO' then begin FDQuery.SQL.Add('where num_extrato = :num_extrato'); FDQuery.ParamByName('num_extrato').AsString := aParam[1]; end; if aParam[0] = 'CREDITO' then begin FDQuery.SQL.Add('where dat_credito = :dat_credito'); FDQuery.ParamByName('dat_credito').AsDate := aParam[1]; end; if aParam[0] = 'BASECREDITO' then begin FDQuery.SQL.Add('where cod_base = :cod_base and dat_credito = :dat_credito'); FDQuery.ParamByName('cod_base').AsInteger := aParam[1]; FDQuery.ParamByName('dat_credito').AsDate := aParam[2]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open; Result := FDQuery; end; end.
{$include lem_directives.inc} unit GameLevelCodeScreen; interface uses Windows, Classes, Controls, Graphics, MMSystem, Forms, GR32, GR32_Image, GR32_Layers, UMisc, LemStrings, LemDosStructures, LemDosStyle, GameControl, GameBaseScreen; type TGameLevelCodeScreen = class(TGameBaseScreen) private LevelCode : string[10]; CursorPosition : Integer; ValidLevelCode: Boolean; YPositions: array[0..3] of Integer; XPos: Integer; BlinkSpeedMS: Cardinal; PrevBlinkTime: Cardinal; Blinking: Boolean; Typing: Boolean; Validated: Boolean; LastMessage: string; LastCheatMessage: string; procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Form_KeyPress(Sender: TObject; var Key: Char); procedure Form_Close(Sender: TObject; var Action: TCloseAction ); procedure Application_Idle(Sender: TObject; var Done: Boolean); function CheckLevelCode: Boolean; function CheckCheatCode: Boolean; procedure DrawChar(aCursorPos: Integer; aBlink: Boolean = False); procedure DrawMessage(const S: string); procedure UpdateCheatMessage; protected public constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure BuildScreen; override; end; implementation uses SysUtils, LemLevelSystem; { TGameLevelCodeScreen } procedure TGameLevelCodeScreen.Application_Idle(Sender: TObject; var Done: Boolean); var CurrTime: Cardinal; // C: Char; begin if ScreenIsClosing then Exit; if Typing then Exit; Done := False; Sleep(1); // relax CPU CurrTime := TimeGetTime; if CurrTime >= PrevBlinkTime + BlinkSpeedMS then begin PrevBlinkTime := CurrTime; Blinking := not Blinking; DrawChar(CursorPosition, Blinking); (* if Blinking then C := '_' else C := LevelCode[CursorPosition]; DrawPurpleText(ScreenImg.Bitmap, C, 200 + CursorPosition * 16 - 16, 120 + 32, BackBuffer); *) end; end; procedure TGameLevelCodeScreen.BuildScreen; var Mainpal: TArrayOfColor32; // S: string; begin ScreenImg.BeginUpdate; try MainPal := GetDosMainMenuPaletteColors32; InitializeImageSizeAndPosition(640, 380); ExtractBackGround; ExtractPurpleFont; TileBackgroundBitmap(0, 0); BackBuffer.Assign(ScreenImg.Bitmap); // save background DrawPurpleText(ScreenImg.Bitmap, SEnterCode, XPos, 120); DrawPurpleText(ScreenImg.Bitmap, LevelCode, XPos, YPositions[1]); UpdateCheatMessage; Application.OnIdle := Application_Idle; finally ScreenImg.EndUpdate; end; end; function TGameLevelCodeScreen.CheckCheatCode: Boolean; var S, CC, tstr: string; x: byte; begin S := stringreplace(LowerCase(LevelCode), '.', '', [rfReplaceAll]); {$ifndef flexi}Result := CompareText(S, SCheatCode) = 0;{$endif} {$ifdef flexi} for x := 0 to 9 do begin if (tstr <> '') or (GameParams.SysDat.CheatCode[x] <> ' ') then begin tstr := tstr + GameParams.SysDat.CheatCode[x]; if GameParams.SysDat.CheatCode[x] <> ' ' then CC := tstr; end; end; if (CC <> '') then Result := CompareText(S, LowerCase(CC)) = 0; {$endif} end; function TGameLevelCodeScreen.CheckLevelCode: Boolean; var // i: Integer; s: string; // P, L: Integer; List: TStringList; Sys: TBaseDosLevelSystem; Txt: string; begin Validated := True; // Result := False; s := stringreplace(LowerCase(LevelCode), '.', '', [rfReplaceAll]); // if not GameParams.CheatMode then // Exit; Sys := GameParams.Style.LevelSystem as TBaseDosLevelSystem; List := TStringList.Create; try Result := Sys.FindLevelCode(LevelCode, GameParams.Info); if not Result then if GameParams.CheatCodesEnabled then Result := Sys.FindCheatCode(LevelCode, GameParams.Info); if Result then begin Txt := Format(SCodeForLevel_sd, [GameParams.Info.dSectionName, GameParams.Info.dLevel + 1]); //DrawPurpleTextCentered(ScreenImg.Bitmap, Txt, YPositions[2], BackBuffer); DrawMessage(Txt); Exit; end else //DrawPurpleTextCentered(ScreenImg.Bitmap, SIncorrectCode, {XPos, }YPositions[2], BackBuffer); DrawMessage(SIncorrectCode); finally List.Free; end; end; constructor TGameLevelCodeScreen.Create(aOwner: TComponent); begin inherited; LevelCode := '..........'; CursorPosition := 1; ScreenImg.Enabled := False; OnKeyDown := Form_KeyDown; OnKeyPress := Form_KeyPress; OnClose := Form_Close; BlinkSpeedMS := 240; XPos := (640 - (10 * 16)) div 2; YPositions[0] := 120; YPositions[1] := 152; YPositions[2] := 184; YPositions[3] := 216; end; destructor TGameLevelCodeScreen.Destroy; begin Application.OnIdle := nil; inherited; end; procedure TGameLevelCodeScreen.DrawChar(aCursorPos: Integer; aBlink: Boolean); var C: Char; begin if aBlink then C := '_' else C := LevelCode[CursorPosition]; DrawPurpleText(ScreenImg.Bitmap, C, XPos + CursorPosition * 16 - 16, YPositions[1], BackBuffer); end; procedure TGameLevelCodeScreen.DrawMessage(const S: string); begin if LastMessage <> '' then // DrawPurpleText(ScreenImg.Bitmap, ); DrawPurpleTextCentered(ScreenImg.Bitmap, LastMessage, YPositions[2], BackBuffer, True); LastMessage := S; if S = '' then Exit; DrawPurpleTextCentered(ScreenImg.Bitmap, S, YPositions[2]); end; procedure TGameLevelCodeScreen.UpdateCheatMessage; begin Assert(GameParams <> nil); if LastCheatMessage <> '' then DrawPurpleTextCentered(ScreenImg.Bitmap, LastCheatMessage, 350- 20, BackBuffer, True); LastCheatMessage := ''; if not (moCheatCodes in Gameparams.MiscOptions) then Exit; LastCheatMessage := 'Cheatcodes Enabled'; DrawPurpleTextCentered(ScreenImg.Bitmap, LastCheatMessage, 350 - 20); end; procedure TGameLevelCodeScreen.Form_Close(Sender: TObject; var Action: TCloseAction); begin Application.OnIdle := nil; if ValidLevelCode then GameParams.WhichLevel := wlLevelCode; end; procedure TGameLevelCodeScreen.Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ScreenIsClosing then Exit; if Shift = [] then begin case Key of VK_ESCAPE: CloseScreen(gstMenu); VK_RETURN: begin if CheckCheatCode then begin // toggle cheat GameParams.CheatCodesEnabled := not GameParams.CheatCodesEnabled;//True; UpdateCheatMessage; // DrawMessage('cheatmode enabled'); Exit; end; if not ValidLevelCode then begin ValidLevelCode := CheckLevelCode; if ValidLevelCode then begin CloseDelay := 1000; DrawChar(CursorPosition, False); CloseScreen(gstMenu); end; // closedelay:=1000; // CloseScreen(gstMenu); end else CloseScreen(gstMenu); // if ValidLevelCode then // GameParams.WhichLevel := wlLevelCode; end; end; end; end; procedure TGameLevelCodeScreen.Form_KeyPress(Sender: TObject; var Key: Char); var OldC, C: Char; OldPos: Integer; //GoBack: Boolean; begin if ScreenIsClosing then Exit; Typing := True; try C := UpCase(Key); if C in ['A'..'Z', '0'..'9'] then begin DrawMessage(''); OldC := LevelCode[CursorPosition]; OldPos := CursorPosition; LevelCode[CursorPosition] := C; if CursorPosition < 10 then begin // maybe blinking: repair // if OldC <> C then DrawChar(CursorPosition, False); // next pos Inc(CursorPosition); end; if (OldPos <> CursorPosition) or (OldC <> C) then begin DrawChar(CursorPosition); end; ValidLevelCode := False; end else if C = Chr(8) then begin DrawMessage(''); // GoBack := True; if CursorPosition > 1 then begin LevelCode[CursorPosition] := '.'; // maybe blinking: repair DrawChar(CursorPosition, False); if CursorPosition > 1 then Dec(CursorPosition); ValidLevelCode := False; end; end; finally Typing := False; end; end; end.
unit pgFunctionFactory; // Модуль: "w:\common\components\rtl\Garant\PG\pgFunctionFactory.pas" // Стереотип: "SimpleClass" // Элемент модели: "TpgFunctionFactory" MUID: (56613507012C) {$Include w:\common\components\rtl\Garant\PG\pgDefine.inc} interface {$If Defined(UsePostgres)} uses l3IntfUses , l3ProtoObject , pgInterfaces , pgConnection , daInterfaces , daTypes , pgParamDecsriptionList ; type TTypeMapRec = record rName: AnsiString; rType: TdaDataType; end;//TTypeMapRec TpgFunctionFactory = class(Tl3ProtoObject, IpgConnectionListener) private f_Connection: TpgConnection; f_TypesQueryName: AnsiString; f_FunctionsQueryName: AnsiString; f_DataConverter: IdaDataConverter; private procedure FillParamDescriptions(aList: TpgParamDecsriptionList; const aFunctionName: AnsiString; const aSchemeName: AnsiString; out theIsRetCursor: Boolean); function ConvertType(const anOID: AnsiString): AnsiString; procedure InitTypesQuery; procedure DoneTypesQuery; procedure InitFuctionsQuery; procedure DoneFuctionsQuery; function ExtractDataType(const aDataType: AnsiString): TdaDataType; function ExtractParamType(const aParamType: AnsiString): TdaParamType; protected procedure AfterConnect; procedure BeforeDisconnect; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aConnection: TpgConnection; const aDataConverter: IdaDataConverter); reintroduce; function MakeFunction(const aFunctionName: AnsiString; const aSchemeName: AnsiString = ''): IdaFunction; end;//TpgFunctionFactory {$IfEnd} // Defined(UsePostgres) implementation {$If Defined(UsePostgres)} uses l3ImplUses , LibPQ , SysUtils , daScheme , Classes , pgUtils , pgFunctionParamDescription , pgFunction //#UC START# *56613507012Cimpl_uses* //#UC END# *56613507012Cimpl_uses* ; const cFunctionParamsCount = 2; cTypesParamsCount = 1; cTypeNameParamIndex = 0; cProcNameParamIndex = 0; cSchemaNameParamIndex = 1; constructor TpgFunctionFactory.Create(aConnection: TpgConnection; const aDataConverter: IdaDataConverter); //#UC START# *56653588036D_56613507012C_var* //#UC END# *56653588036D_56613507012C_var* begin //#UC START# *56653588036D_56613507012C_impl* inherited Create; aConnection.SetRefTo(f_Connection); f_DataConverter := aDataConverter; f_Connection.RegisterListener(Self); //#UC END# *56653588036D_56613507012C_impl* end;//TpgFunctionFactory.Create procedure TpgFunctionFactory.FillParamDescriptions(aList: TpgParamDecsriptionList; const aFunctionName: AnsiString; const aSchemeName: AnsiString; out theIsRetCursor: Boolean); //#UC START# *56653EE801A9_56613507012C_var* var l_Result: PPGresult; l_ArgsStr: String; l_ArgsList: TStringList; l_ModesStr: String; l_ModesList: TSTringList; l_IDX: Integer; l_NamesStr: String; l_NamesList: TSTringList; l_AllInput: Boolean; l_RetType: String; l_ParamsValue: array of AnsiString; l_ParamsValuePtr: TPQparamValues; const cVariadicIDX = 0; cReturnSet = 1; cRetTypeIDX = 2; cAgrsIDX = 3; cAllAgrsIDX = 4; cModesIDX = 5; cParamsIDX = 6; function lp_RepairStr(const aStr: String): String; begin if Length(aStr) > 1 then begin Result := StringReplace(aStr, ' ', ',', [rfReplaceAll, rfIgnoreCase]); if Result[1] = '{' then Result := Copy(Result, 2, Length(Result) - 2); end else Result := aStr; end; function lp_MakeList(const aStr: String): TStringList; begin Result := TStringList.Create; Result.Delimiter := ','; Result.QuoteChar := '"'; Result.DelimitedText := aStr; end; //#UC END# *56653EE801A9_56613507012C_var* begin //#UC START# *56653EE801A9_56613507012C_impl* aList.Clear; SetLength(l_ParamsValue, cFunctionParamsCount); SetLength(l_ParamsValuePtr, cFunctionParamsCount); l_ParamsValue[cProcNameParamIndex] := aFunctionName; l_ParamsValue[cSchemaNameParamIndex] := aSchemeName; for l_IDX := 0 to cFunctionParamsCount - 1 do l_ParamsValuePtr[l_IDX] := PAnsiChar(l_ParamsValue[l_IDX]); l_Result := PQexecPrepared(f_Connection.Handle, PAnsiChar(f_FunctionsQueryName), cFunctionParamsCount, l_ParamsValuePtr, nil, 0, 0); try if not (PQresultStatus(l_Result) in [PGRES_EMPTY_QUERY, PGRES_COMMAND_OK, PGRES_TUPLES_OK]) then raise EpgError.Create(PQresultErrorMessage(l_Result)); Assert(PQntuples(l_Result) = 1); Assert(PQgetvalue(l_Result, 0, cVariadicIDX) = '0', 'Variadic not supported'); theIsRetCursor := PQgetvalue(l_Result, 0, cReturnSet) = 't'; l_ArgsStr := PQgetvalue(l_Result, 0, cAllAgrsIDX); if l_ArgsStr = '' then l_ArgsStr := PQgetvalue(l_Result, 0, cAgrsIDX); l_ArgsStr := lp_RepairStr(l_ArgsStr); l_ArgsList := lp_MakeList(l_ArgsStr); try for l_IDX := 0 to l_ArgsList.Count - 1 do l_ArgsList[l_IDX] := ConvertType(l_ArgsList[l_IDX]); l_ModesStr := lp_RepairStr(PQgetvalue(l_Result, 0, cModesIDX)); l_ModesList := lp_MakeList(l_ModesStr); try while l_ModesList.Count < l_ArgsList.Count do l_ModesList.Add('i'); l_NamesStr := lp_RepairStr(PQgetvalue(l_Result, 0, cParamsIDX)); l_NamesList := lp_MakeList(l_NamesStr); try while l_NamesList.Count < l_ArgsList.Count do l_NamesList.Add(''); for l_IDX := 0 to l_NamesList.Count - 1 do if l_NamesList[l_IDX] = '' then l_NamesList[l_IDX] := Format('$%d', [l_IDX + 1]); l_AllInput := True; for l_IDX := 0 to l_ModesList.Count - 1 do if l_ModesList[l_IDX] <> 'i' then l_AllInput := False; if l_AllInput then begin l_RetType := ConvertType(PQgetvalue(l_Result, 0, cRetTypeIDX)); if not ANSISameText(l_RetType, 'void') then begin l_NamesList.Add(Format('%s.Result', [aFunctionName])); l_ModesList.Add('o'); l_ArgsList.Add(l_RetType); end; end; Assert(l_NamesList.Count = l_ModesList.Count); Assert(l_NamesList.Count = l_ArgsList.Count); for l_IDX := 0 to l_NamesList.Count - 1 do aList.Add(TpgFunctionParamDescription.Make(l_NamesList[l_IDX], ExtractDataType(l_ArgsList[l_IDX]), 0, ExtractParamType(l_ModesList[l_IDX]))); finally FreeAndNil(l_NamesList); end; finally FreeAndNil(l_ModesList); end; finally FreeAndNil(l_ArgsList); end; finally PQclear(l_Result); end; //#UC END# *56653EE801A9_56613507012C_impl* end;//TpgFunctionFactory.FillParamDescriptions function TpgFunctionFactory.ConvertType(const anOID: AnsiString): AnsiString; //#UC START# *566FFAAF03CB_56613507012C_var* var l_ParamsValue: array of AnsiString; l_ParamsValuePtr: TPQparamValues; l_Result: PPGresult; l_IDX: Integer; //#UC END# *566FFAAF03CB_56613507012C_var* begin //#UC START# *566FFAAF03CB_56613507012C_impl* SetLength(l_ParamsValue, cTypesParamsCount); SetLength(l_ParamsValuePtr, cTypesParamsCount); l_ParamsValue[cTypeNameParamIndex] := anOID; for l_IDX := 0 to cTypesParamsCount - 1 do l_ParamsValuePtr[l_IDX] := PAnsiChar(l_ParamsValue[l_IDX]); l_Result := PQexecPrepared(f_Connection.Handle, PAnsiChar(f_TypesQueryName), cTypesParamsCount, l_ParamsValuePtr, nil, 0, 0); try if not (PQresultStatus(l_Result) in [PGRES_EMPTY_QUERY, PGRES_COMMAND_OK, PGRES_TUPLES_OK]) then raise EpgError.Create(PQresultErrorMessage(l_Result)); Assert(PQntuples(l_Result) = 1); Result := PQgetvalue(l_Result, 0, 0); finally PQClear(l_Result); end; //#UC END# *566FFAAF03CB_56613507012C_impl* end;//TpgFunctionFactory.ConvertType procedure TpgFunctionFactory.InitTypesQuery; //#UC START# *566FFEC403B2_56613507012C_var* var l_Result: PPGResult; //#UC END# *566FFEC403B2_56613507012C_var* begin //#UC START# *566FFEC403B2_56613507012C_impl* f_TypesQueryName := Format('TypQry%p', [Pointer(Self)]); l_Result := PQprepare(f_Connection.Handle, PAnsiChar(f_TypesQueryName), 'select typname from pg_type where oid = $1', cTypesParamsCount, nil); try pgCheckStatus(l_Result); finally PQclear(l_Result); end; //#UC END# *566FFEC403B2_56613507012C_impl* end;//TpgFunctionFactory.InitTypesQuery procedure TpgFunctionFactory.DoneTypesQuery; //#UC START# *566FFECF0160_56613507012C_var* var l_Result: PPGResult; //#UC END# *566FFECF0160_56613507012C_var* begin //#UC START# *566FFECF0160_56613507012C_impl* l_Result := PQExec(f_Connection.Handle, PAnsiChar(Format('DEALLOCATE "%s"', [f_TypesQueryName]))); try pgCheckStatus(l_Result); f_TypesQueryName := ''; finally PQClear(l_Result); end; //#UC END# *566FFECF0160_56613507012C_impl* end;//TpgFunctionFactory.DoneTypesQuery procedure TpgFunctionFactory.InitFuctionsQuery; //#UC START# *567010DA02DE_56613507012C_var* var l_Result: PPGResult; //#UC END# *567010DA02DE_56613507012C_var* begin //#UC START# *567010DA02DE_56613507012C_impl* f_FunctionsQueryName := Format('FunQry%p', [Pointer(Self)]); l_Result := PQprepare(f_Connection.Handle, PAnsiChar(f_FunctionsQueryName), 'select p.provariadic, p.proretset, p.prorettype, p.proargtypes, p.proallargtypes, p.proargmodes, p.proargnames '#13#10+ 'from pg_proc p JOIN pg_namespace ns ON (p.pronamespace = ns.oid) '#13#10+ 'where UPPER(p.proname) = UPPER($1) and UPPER(ns.nspname) = UPPER($2)', cFunctionParamsCount, nil); try pgCheckStatus(l_Result); finally PQclear(l_Result); end; //#UC END# *567010DA02DE_56613507012C_impl* end;//TpgFunctionFactory.InitFuctionsQuery procedure TpgFunctionFactory.DoneFuctionsQuery; //#UC START# *567010EB0006_56613507012C_var* var l_Result: PPGResult; //#UC END# *567010EB0006_56613507012C_var* begin //#UC START# *567010EB0006_56613507012C_impl* l_Result := PQExec(f_Connection.Handle, PAnsiChar(Format('DEALLOCATE "%s"', [f_FunctionsQueryName]))); try pgCheckStatus(l_Result); f_FunctionsQueryName := ''; finally PQClear(l_Result); end; //#UC END# *567010EB0006_56613507012C_impl* end;//TpgFunctionFactory.DoneFuctionsQuery function TpgFunctionFactory.ExtractDataType(const aDataType: AnsiString): TdaDataType; //#UC START# *56728B5D00CA_56613507012C_var* const cTypeCount = 8; cMap: array [1..cTypeCount] of TTypeMapRec = ( (rName: 'VARCHAR'; rType: da_dtChar), (rName: 'SMALLINT'; rType: da_dtByte), // (rName: ''; rType: da_dtDate), // (rName: ''; rType: da_dtTime), (rName: 'INT4'; rType: da_dtDWord), (rName: 'INT2'; rType: da_dtWord), (rName: 'INTEGER'; rType: da_dtInteger), (rName: 'BOOL'; rType: da_dtBoolean), (rName: 'INT8'; rType: da_dtQWord), (rName: 'BIGINT'; rType: da_dtQWord) ); (* ++ da_dtChar , da_dtByte , da_dtDate , da_dtTime ++ , da_dtDWord ++ , da_dtWord , da_dtInteger ++ , da_dtBoolean ++ , da_dtQWord *) var l_IDX: Integer; //#UC END# *56728B5D00CA_56613507012C_var* begin //#UC START# *56728B5D00CA_56613507012C_impl* for l_IDX := Low(cMap) to High(cMap) do if AnsiSameText(aDataType, cMap[l_IDX].rName) then begin Result := cMap[l_IDX].rType; Exit; end; Assert(False, Format('Prepare stored proc - unknown data type: %s', [aDataType])); //#UC END# *56728B5D00CA_56613507012C_impl* end;//TpgFunctionFactory.ExtractDataType function TpgFunctionFactory.ExtractParamType(const aParamType: AnsiString): TdaParamType; //#UC START# *56728B7E02D7_56613507012C_var* //#UC END# *56728B7E02D7_56613507012C_var* begin //#UC START# *56728B7E02D7_56613507012C_impl* Assert(Length(aParamType) = 1); case UpCase(aParamType[1]) of 'I': Result := da_ptInput; 'O': Result := da_ptOutput; 'B': Result := da_ptInOut; else Assert(False); end; //#UC END# *56728B7E02D7_56613507012C_impl* end;//TpgFunctionFactory.ExtractParamType function TpgFunctionFactory.MakeFunction(const aFunctionName: AnsiString; const aSchemeName: AnsiString = ''): IdaFunction; //#UC START# *56616E9800EA_56613507012C_var* var l_ParamsDescription: TpgParamDecsriptionList; l_IsRetCursor: Boolean; l_SchemeName: String; //#UC END# *56616E9800EA_56613507012C_var* begin //#UC START# *56616E9800EA_56613507012C_impl* l_ParamsDescription := TpgParamDecsriptionList.Make; try l_SchemeName := TdaScheme.Instance.CheckScheme(aSchemeName); FillParamDescriptions(l_ParamsDescription, aFunctionName, l_SchemeName, l_IsRetCursor); Result := TpgFunction.Make(f_Connection, f_DataConverter, l_SchemeName, aFunctionName, l_ParamsDescription, l_IsRetCursor); finally FreeAndNil(l_ParamsDescription); end; //#UC END# *56616E9800EA_56613507012C_impl* end;//TpgFunctionFactory.MakeFunction procedure TpgFunctionFactory.AfterConnect; //#UC START# *5769243F0191_56613507012C_var* //#UC END# *5769243F0191_56613507012C_var* begin //#UC START# *5769243F0191_56613507012C_impl* InitTypesQuery; InitFuctionsQuery; //#UC END# *5769243F0191_56613507012C_impl* end;//TpgFunctionFactory.AfterConnect procedure TpgFunctionFactory.BeforeDisconnect; //#UC START# *5769244F01F5_56613507012C_var* //#UC END# *5769244F01F5_56613507012C_var* begin //#UC START# *5769244F01F5_56613507012C_impl* DoneTypesQuery; DoneFuctionsQuery; //#UC END# *5769244F01F5_56613507012C_impl* end;//TpgFunctionFactory.BeforeDisconnect procedure TpgFunctionFactory.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_56613507012C_var* //#UC END# *479731C50290_56613507012C_var* begin //#UC START# *479731C50290_56613507012C_impl* f_DataConverter := nil; f_Connection.UnRegisterListener(Self); FreeAndNil(f_Connection); inherited; //#UC END# *479731C50290_56613507012C_impl* end;//TpgFunctionFactory.Cleanup {$IfEnd} // Defined(UsePostgres) end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Object: TMimeDecode is a component whose job is to decode MIME encoded EMail messages (file attach). You can use it for example to decode messages received with a POP3 or NNTP component. MIME is described in RFC-1521. Headers are described if RFC-822. Creation: March 08, 1998 Version: 7.22 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1998-2010 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. QUICK REFERENCE: -------------- TMimeDecode take a file or a stream as input and produce several event when the message is parsed. each event can be used to display or to save to a file the message parts. Two methods can be called to decode either a file or a stream: procedure DecodeFile(FileName : String); procedure DecodeStream(aStream : TStream); During the decode process, the component trigger several events. You have to use those events to save data to a file or to display somehow on the user interface. Events are organized by groups of three for message header, part header and part data: Message header events: OnHeaderBegin OnHeaderLine OnHeaderEnd Part header events: OnPartHeaderBegin OnPartHeaderLine OnPartHeaderEnd Part data events: OnPartDataBegin OnPartDataLine OnPartDataEnd The 'Begin' event is triggered once just before the first item will occur. The 'Line' event is triggered for each item of the given type. The 'End' event is triggered once after the last item. For a multi-part message, we have this sequence: a) The message header OnHeaderBegin, then many OnHeaderLine, one for each line in the header. Lines can be continuated in the message. The event here is triggered with continuated lines concatenated (so it can be quite large !). After the last header line has been processed, the OnHeaderEnd is triggered once. b) The non-significant message part which can be empty. This is part 0. We get OnPartBegin once, then OnPartLine for each line and finally OnPartEnd once. c) The first significant part header with his three events, just like the message header: OnPartHeaderBegin, OnPartHeaderLine and OnPartHeaderEnd. d) The first significant part data with his three events: OnPartBegin once, OnPartLine for each line and OnPartEnd once at the end of the part. It's possible to have an empty part. This gives the OnPartBegin and OnPartEnd events and NO OnPartLine event. e) We can have many other parts. The sequence is always the same. We restart at point (b) here above for each part (header, then data). Note that there is often en empty part at the end of a message. TMimeDecode decode encoded parts using 'base64' and 'quoted-printable' methods. For those parts, the OnPartLine event will gives DECODED data. Other methods are passed not decoded. You can use the property ContentTransferEncoding to know which encoding method is used and add your own decoding mechanism. For each OnHeaderLine, OnPartHeaderLine and OnPartLine, you can find the actual data at the address pointed by the property CurrentData (a PAnsiChar). The reason for a PAnsiChar is that the data can be quite large. The data pointed is a null terminated AnsiString. You can get the length using StrLen, or convert to a AnsiString with StrPas. It is more efficient to process the data using a pointer. Using AnsiStrings tends to copy the data several times. The OnPartLine event passes a PAnsiChar and a length to the handler. This actully point to the internal buffer and overwrite the original data (base64 and quote-printable method produce decoded data smaller tha encoded one). >From the message header, the component extract the following values: >From The message author. Not necessary the real author... Looks like "Francois Piette" <francois.piette@overbyte.be> Dest The message destination (To field, but To is a reserved word) Looks like "Francois Piette" <francois.piette@overbyte.be> Subject The message subject. Free text. Date The message date. Look like: Mon, 16 Feb 1998 12:45:11 -0800 ContentType 'multipart/mixed' or empty. For details about those header fields and others, read RFC-822 For each part, we have the following properties updated (the header is parsed on the fly): PartNumber Starting from 0 for the non-significant part PartLine Starting 1 for the first line of each part or header PartContentType Such as 'text/plain' or 'application/x-zip-compressed' PartCharset This is a complement for the PartContentType. ApplicationType When PartContentType is 'application/something', we get the 'something' extracted PartName This is the value for 'name=something' in the Content-Type header line. PartEncoding Encoding method (Content-Transfer-Encoding). Can be used to decode unsupported methods (supported methods are 'base64' and 'quoted-printable'. '7bit' and '8bit' does'nt generally require processing. PartDisposition Can be 'inline' or 'attachement' and is generally followed by a 'filename=something' PartFileName The specified filename in Content-Disposition header line. Be aware that the file name is not necessary suitable for windows ! Use it with caution... For details about those header fields and others, read RFC-1521. To write part data to files, you can either implement your own writing in the OnPartLine event handler, or use the DestStream property. If assigned, this property will be used to write the data. If not assigned, it will be ignore. To select a file name for each part, you can use the PartFileName property or the 'PartName' property or a comnination of both. But be aware that those value can be either missing or even invalid as a filename because the message was generated with another opertaing system which has different filename conventions. Updates: Apr 13, 1998 V1.01 Corrected a bug in ProcessLineBase64 which decoded one byte too much. Thanks to Rune Fredriksen <runefr@mail.link.no>. Apr 15, 1998 V1.02 Corrected bug in ProcessHeaderLine which retreived only the first word for each item. Added the ReturnPath property. Apr 24, 1998 V1.03 Removed the modification made in version 1.01 ! Apr 26, 1998 V1.04 Corrected a bug in ReallocMem with Delphi 1 Aug 27, 1998 V1.05 Corrected a bug in decoding which incorrectly merge the first message line with the header when the line begon by a space. Thanks to Mitch Cant <mitchcant@hotmail.com> for finding the bug and correction. Sep 13, 1998 V1.06 Correctly handled unterminated messages. Correctly handled parts without header. Dec 26, 1998 V1.07 Added features coded by Eric Fortier <efortier@videotron.ca> (Embedded mime parts, UUDecode). Dec 30, 1998 V1.08 Check for header end when a header line begin with a space or tab character. (Normally a header end with a blank line, we also accept invalid header line). Feb 01, 1999 V1.09 Corrected a bug ProcessLineUUDecode where 'end' was not checked. Thanks to Eric Fortier. Feb 16, 1999 V1.10 Added UUEncoded embedded parts. Thanks to Eric Fortier. Corrected a line termination problem in ProcessLineBase64. Jul 21, 1999 V1.11 Added support for encoded message without multipart. Added Encoding property with the encoding value. Thanks to Marcelo S Massuda <massuda@4web.com.br> for pinting this lack of feature. Aug 20, 1999 V1.12 Added compile time options. Revised for BCB4. Nov 25, 1999 V1.13 Changed continuation line character for quoted printable encoding. By Ken Petersen <KPT@edbgruppen.dk>. Created GetTokenEx function to take care of comments in header lines. This affect ProcessPartHeaderLine and ProcessHeaderLine. Thanks to Boris Daljevic <biber@eunet.yu> for his code. Added CharSet property related to main part charset (see also existing PartCharset property). Thanks to Boris Daljevic <biber@eunet.yu> for his code. Jun 20, 2000 V1.14 Poessler Thomas <Thomas.Poessler@uta.at> corrected a bug in ProcessLineQuotedPrintable. Jul 02, 2000 V1.15 Added OnMessageEnd event Jul 15, 2000 V1.16 Added code from Wolfgang Baron <Wolfgang.Baron@gwtel.de> to support content-description header line. Changed GetToken and GetTokenEx so that a space before a delimiter will not break token parsing. Outlook generate such invalid formatting thanks for Arno van Rossum <a.van.rossum@mmp-obec.nl> for finding this bug. Revised code to handle inline UUEncoded messages. Jul 21, 2000 V1.17 Use GetValue instead of GetToken to solve problem with boundaries of embbeded parts. With help of Jan Bartak <bart@seznam.cz>. As suggested by Sebastien Gariepy <beeper@globetrotter.net>, I added PartContentID. Oct 29, 2000 V1.18 Checked for missing content-type before calling UUProcessLine. Without the check, a part with a line beginning with 'begin 666' will be wrongly decoded. Feb 17, 2001 V1.19 Top of the messages with a field multipart was incorrectly processed.Property FCharset was not initialized in procedure MessageBegin. Thanks to Bayanov <bayanov@alt.ru> Jul 26, 2001 V1.20 Cleared FEncoding in MessageBegin. Thanks to Joel lauvinerie <joel.lauvinerie@wanadoo.fr> who found this bug. Poessler Thomas <Thomas.Poessler@uta.at> added new properties: HeaderName, FileName, HeaderLines, Disposition, EndOfMime, IsMultipart. Jul 29, 2001 V1.21 Moved ProcessLineBase64 to public section. Made CurrentData property read/write. This permit to use Base64 decoding from outside of the component. Corrected a glitche with Delphi 1 May 04, 2002 V1.23 Added "Len" argument to OnInlineDecodeLine event. Corrected UUDec so that nul is handled as space. Thanks to arnaud.mesnews@free.fr who provided a test case. Made UUOutDec a little bit faster. May 10, 2002 V1.24 Accept 'begin 644' as well as 'begin 666' for UUEncoding start. arnaud.mesnews@free.fr found that OE does that. Nov 01, 2002 V1.25 Changed PChar arguments to Pointer to work around Delphi 7 bug with PAnsiChar<->PChar. This will require small changes in your application code: change PChar args to Pointer and add a PChar cast when using the arg. Changed Base64 decoding so that is doesn't crash even if input data is malformed (corrupted message). Changed UUEncoded detection procedure. Thanks to Arnaud <arnaud.mesnews@free.fr> for providing his code. Apr 22, 2003 V1.26 Corrected ProcessLineQuotedPrintable which overflowed input data when an empty line was given. Thanks to Dmitry Andreev for finding a test case. V1.27 Christophe Thiaux <tophet@free.fr> added PartFormat and format properties. Jul 20, 2003 V1.28 <arnaud.mesnews@free.fr> added yEnc decoding and fixed uudecode when "begin" has to be lower case. Aug 06, 2003 V1.29 Dmitry Andreev <advadvadv@mailgate.ru> and Arnaud <arnaud.mesnews@free.fr> corrected a bug with continuation lines in ProcessLineQuotedPrintable. Aug 10, 2003 V1.30 Reformatted the source line to make Arnaud and Dmitry changes looking like my own code. Translated all comments to english. Englicized identificators. Jan 03, 2004 V1.31 Replaced private section by protected. Moved procedure ProcessLineQuotedPrintable to public section. May 31, 2004 V1.32 John Bridgwater <jbridgwater@goodyear.com> fixed GetTokenEx to allow a space around delimiter. Jul 24, 2004 V1.33 arnaud.mesnews@free.fr added TriggerInlineDecodeBegin, TriggerInlineDecodeLine and TriggerInlineDecodeEnd and called them where needed. He also added InlineDecodeLine and LengthHeader properties Nov 3, 2006 V6.00 New version 6.00 started Nov 13, 2007 V6.01 Fixed TMimeDecode.ProcessPartLine to avoid adding a CRLF at the end of attached text file. Nov 14, 2007 V6.02 Added Cc decoding Mar 10, 2008 V6.03 Francois Piette made some changes to prepare code for Unicode. Aug 02, 2008 V6.04 A. Garrels made some changes to prepare code for Unicode. Oct 03, 2008 V6.10 A. Garrels moved IsCharInSysCharSet, IsSpaceChar and IsCrLfChar to OverbyteIcsUtils.pas (and removed Char suffix). Oct 11, 2008 V7.11 Angus added TMimeDecodeEx component which extends TMimeDecode by decoding a MIME file or stream into a PartInfos array with TotParts and HeaderLines StringList without the application needing to use any events Also added functions to decode email MIME header lines with RFC2047 encoded words DecodeHeaderLine returns 8-bit raw text and MimeCharSet DecodeHeaderLineWide returns Unicode text See OverbyteIcsMimeDemo1 for TMimeDecodeEx and DecodeHeaderLine examples Oct 12, 2008 V7.12 Angus fixed DecodeHeaderLine for Q starting with = word Oct 15, 2008 V7.13 Arno added TMimeDecodeW and replaced GetHeaderValue() which was buggy by UnfoldHdrValue. (See comments below). Also changed Angus' TMimeDecodeEx. Removed many implicit string casts. Oct 16, 2008 V7.14 Arno - Formated my previous changes in ICS style. Minor change and correction of the comment in DecodeMimeValue(). Oct 18, 2008 V7.15 Angus added DecodeMimeInlineValueEx, removed DecodeHeaderLine/Ex internal changes and fixes to TMimeDecodeEx Oct 23, 2008 V7.16 Arno - PrepareNextPart did not clear FPartCharset. Property ApplicationType was not implemented. Fixed a bug in DecodeMimeInlineValue and DecodeMimeInlineValueEx, Improved UnfoldHdrValue. In InternalDecodeStream replace both Tab and Space after CRLF by #1 . Made two implicit string casts explicit casts. Added properties PartCodePage and IsTextpart to TMimeDecode. Oct 24, 2008 V7.17 Arno - TMimeDecode: Added property CodePage. Initialization of FIsTextPart changed to TRUE. Added property DefaultCodePage, its value is assigned to both properties CodePage and PartCodePage whenever no code page can be retrieved from a header or if a valid code page cannot be looked up from a Charset value. I'm pretty sure that DefaultCodePage should be set to CP_US_ASCII (20127), however the component initializes this value with the default system code page. TMimeDecodeW: Initializes part properties of part #0 with values from message header if IsMultipart equals FALSE. TMimeDecodeEX: MimeDecodePartEnd adjusted to use FCodePage and FPartCodePage. Oct 9, 2009 V7.18 Bjørnar added PContentId and PSubject to PartInfos array Nov 17, 2009 V7.19 Arno added UTF-16 and UTF-32 support in TMimeDecodeW and TMimeDecodeEx. Made property PartCodePage writable. TMimeDecodeEx.PSubject is MIME inline decoded now (I wonder why PSubject was added to the parts at all). Nov 19, 2009 V7.20 Angus added PIsTextpart to PartInfos and removed PSubject which is the same for all parts Feb 20, 2011 V7.21 Angus, prevent range error for malformed blank lines Mar 11, 2011 V7.22 Angus, prevent range error for blank header in UnfoldHdrValue * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsMimeDec; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long AnsiStrings } {$J+} { Allow typed constant to be modified } {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFDEF COMPILER12_UP} {$WARN IMPLICIT_STRING_CAST ON} {$WARN IMPLICIT_STRING_CAST_LOSS ON} {$WARN EXPLICIT_STRING_CAST OFF} {$WARN EXPLICIT_STRING_CAST_LOSS OFF} {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} interface uses {$IFDEF USEWINDOWS} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} SysUtils, Classes, {$IFDEF COMPILER12_UP} AnsiStrings, { for PosEx } {$ELSE} StrUtils, { for PosEx } {$ENDIF} OverByteIcsLibrary, OverbyteIcsUtils, OverbyteIcsMimeUtils, OverbyteIcsCharsetUtils; const MimeDecodeVersion = 722; CopyRight : String = ' TMimeDecode (c) 1998-2011 Francois Piette V7.22'; type TMimeDecodePartLine = procedure (Sender : TObject; Data : Pointer; DataLen : Integer) of object; TInlineDecodeBegin = procedure (Sender: TObject; Filename: AnsiString) of object; TInlineDecodeLine = procedure (Sender: TObject; Line: Pointer; Len : Integer) of object; TInlineDecodeEnd = procedure (Sender: TObject; Filename: AnsiString) of object; TMimeDecode = class(TComponent) protected FFrom : AnsiString; FDest : AnsiString; FCc : AnsiString; FSubject : AnsiString; FDate : AnsiString; FReturnPath : AnsiString; FEncoding : AnsiString; FCharSet : AnsiString; FCodePage : LongWord; FContentType : AnsiString; FMimeVersion : AnsiString; FHeaderName : AnsiString; FDisposition : AnsiString; FFileName : AnsiString; FFormat : AnsiString; FHeaderLines : TStrings; FIsMultipart : Boolean; FIsTextpart : Boolean; FEndOfMime : Boolean; FPartContentType : AnsiString; FPartEncoding : AnsiString; FPartNumber : Integer; FPartHeaderBeginSignaled : Boolean; FPartName : AnsiString; FPartDisposition : AnsiString; FPartContentID : AnsiString; FPartFileName : AnsiString; FPartFormat : AnsiString; FPartCharset : AnsiString; FPartCodePage : LongWord; FApplicationType : AnsiString; FPartOpened : Boolean; FHeaderFlag : Boolean; FLineNum : Integer; FBuffer : PAnsiChar; FBufferSize : Integer; FCurrentData : PAnsiChar; FBoundary : AnsiString; FUUProcessFlag : Boolean; FProcessFlagYBegin : Boolean; { AS: YEnc handling } FSizeFileY : Integer; { AS: YEnc handling } FSizeBlocY : Integer; { AS: YEnc handling } FSizeLeftY : Integer; { AS: YEnc handling } FNext : procedure of object; FDestStream : TStream; cUUFilename : AnsiString; { ##ERIC } FEmbeddedBoundary : TStringList; { ##ERIC } cIsEmbedded : Boolean; { ##ERIC } FOnHeaderBegin : TNotifyEvent; FOnHeaderLine : TNotifyEvent; FOnHeaderEnd : TNotifyEvent; FOnPartHeaderBegin : TNotifyEvent; FOnPartHeaderLine : TNotifyEvent; FOnPartHeaderEnd : TNotifyEvent; FOnPartBegin : TNotifyEvent; FOnPartLine : TMimeDecodePartLine; FOnPartEnd : TNotifyEvent; FOnMessageEnd : TNotifyEvent; FOnInlineDecodeBegin : TInlineDecodeBegin; FOnInlineDecodeLine : TInlineDecodeLine; FOnInlineDecodeEnd : TInlineDecodeEnd; { Used to force InLine decoding even if there was no OnInlineDecodeLine event. See UUProcessLine } FInlineDecodeLine : Boolean; FLengthHeader : Integer; FPartFirstLine : Boolean; FDefaultCodePage : LongWord; procedure SetDefaultCodePage(const Value: LongWord); procedure TriggerHeaderBegin; virtual; procedure TriggerHeaderLine; virtual; procedure TriggerHeaderEnd; virtual; procedure TriggerPartHeaderBegin; virtual; procedure TriggerPartHeaderLine; virtual; procedure TriggerPartHeaderEnd; virtual; procedure TriggerPartBegin; virtual; procedure TriggerPartLine(Data : Pointer; DataLen : Integer); virtual; procedure TriggerPartEnd; virtual; procedure TriggerMessageEnd; virtual; procedure TriggerInlineDecodeBegin(const Filename: AnsiString); virtual; procedure TriggerInlineDecodeLine(Line: Pointer; Len : Integer); virtual; procedure TriggerInlineDecodeEnd(const Filename: AnsiString); virtual; procedure ProcessLineUUDecode; function UUProcessLine(FCurrentData: PAnsiChar): boolean; procedure ProcessHeaderLine; procedure ProcessPartHeaderLine; procedure ProcessPartLine; procedure ProcessWaitBoundary; procedure ProcessMessageLine; procedure PreparePart; procedure PrepareNextPart; procedure ProcessDecodedLine(Line : Pointer; Len : Integer); procedure InternalDecodeStream(aStream : TStream); procedure MessageBegin; procedure MessageEnd; procedure ParseYBegin(const Ch : AnsiString); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure DecodeFile(const FileName : String); procedure DecodeStream(aStream : TStream); procedure ProcessLineBase64; procedure ProcessLineQuotedPrintable; property From : AnsiString read FFrom; property Dest : AnsiString read FDest; property Cc : AnsiString read FCc; property Subject : AnsiString read FSubject; property Date : AnsiString read FDate; property ReturnPath : AnsiString read FReturnPath; property ContentType : AnsiString read FContentType; property Encoding : AnsiString read FEncoding; property Charset : AnsiString read FCharset; property CodePage : LongWord read FCodePage; property MimeVersion : AnsiString read FMimeVersion; property HeaderName : AnsiString read FHeaderName; property Disposition : AnsiString read FDisposition; property FileName : AnsiString read FFileName; property Format : AnsiString read FFormat; property HeaderLines : TStrings read FHeaderLines; property IsMultipart : Boolean read FIsMultipart; property IsTextpart : Boolean read FIsTextpart; property EndOfMime : Boolean read FEndOfMime; property PartContentType : AnsiString read FPartContentType; property PartEncoding : AnsiString read FPartEncoding; property PartName : AnsiString read FPartName; property PartDisposition : AnsiString read FPartDisposition; property PartContentID : AnsiString read FPartContentID; property PartFileName : AnsiString read FPartFileName; property PartFormat : AnsiString read FPartFormat; property PartCharset : AnsiString read FPartCharset; property PartCodePage : LongWord read FPartCodePage write FPartCodePage; property ApplicationType : AnsiString read FApplicationType; property PartNumber : Integer read FPartNumber; property CurrentData : PAnsiChar read FCurrentData write FCurrentData; property DestStream : TStream read FDestStream write FDestStream; property InlineDecodeLine : boolean read FInlineDecodeLine write FInlineDecodeLine default FALSE; property LengthHeader : Integer read FLengthHeader; property DefaultCodePage : LongWord read FDefaultCodePage write SetDefaultCodePage; published property OnHeaderBegin : TNotifyEvent read FOnHeaderBegin write FOnHeaderBegin; property OnHeaderLine : TNotifyEvent read FOnHeaderLine write FOnHeaderLine; property OnHeaderEnd : TNotifyEvent read FOnHeaderEnd write FOnHeaderEnd; property OnPartHeaderBegin : TNotifyEvent read FOnPartHeaderBegin write FOnPartHeaderBegin; property OnPartHeaderLine : TNotifyEvent read FOnPartHeaderLine write FOnPartHeaderLine; property OnPartHeaderEnd : TNotifyEvent read FOnPartHeaderEnd write FOnPartHeaderEnd; property OnPartBegin : TNotifyEvent read FOnPartBegin write FOnPartBegin; property OnPartLine : TMimeDecodePartLine read FOnPartLine write FOnPartLine; property OnPartEnd : TNotifyEvent read FOnPartEnd write FOnPartEnd; property OnMessageEnd : TNotifyEvent read FOnMessageEnd write FOnMessageEnd; property OnInlineDecodeBegin : TInlineDecodeBegin read FOnInlineDecodeBegin write FOnInlineDecodeBegin; property OnInlineDecodeLine : TInlineDecodeLine read FOnInlineDecodeLine write FOnInlineDecodeLine; property OnInlineDecodeEnd : TInlineDecodeEnd read FOnInlineDecodeEnd write FOnInlineDecodeEnd; end; TMimeDecodeW = class(TMimeDecode) private function GetCcW: UnicodeString; function GetDestW: UnicodeString; function GetFileNameW: UnicodeString; function GetFromW: UnicodeString; function GetPartFileNameW: UnicodeString; function GetPartNameW: UnicodeString; function GetSubjectW: UnicodeString; protected procedure TriggerPartBegin; override; public property FromW : UnicodeString read GetFromW; property DestW : UnicodeString read GetDestW; property CcW : UnicodeString read GetCcW; property SubjectW : UnicodeString read GetSubjectW; property FileNameW : UnicodeString read GetFileNameW; property PartNameW : UnicodeString read GetPartNameW; property PartFileNameW : UnicodeString read GetPartFileNameW; end; { V7.11 MIME Part Information record } TPartInfo = record PContentType: AnsiString ; PCharset: AnsiString ; PApplType: AnsiString ; PName: UnicodeString ; PEncoding: AnsiString ; PDisposition: AnsiString ; PContentId: AnsiString ; {V7.18 Bjørnar} PFileName: UnicodeString ; // PSubject: UnicodeString ; {V7.18 Bjørnar, gone V7.20} PartStream: TMemoryStream ; PSize: integer ; PCodePage: LongWord ; PIsTextpart: Boolean ; { V7.20 Angus } end ; { V7.11 Decode file or stream into MIME Part Information records } TMimeDecodeEx = class(TComponent) private { Private declarations } procedure MimeDecodeHeaderLine(Sender: TObject); procedure MimeDecodePartBegin(Sender: TObject); procedure MimeDecodePartEnd(Sender: TObject); protected { Protected declarations } FDecodeW: TMimeDecodeW; FMaxParts: integer ; // maximum MIME parts decoded FTotParts: integer ; // number of parts in current body FDecParts: integer ; // number of parts decoded (no more than fMaxParts) FTotHeaders: integer ; // number of decoded header lines in WideHeaders FHeaderCharset: AnsiString ; // first character set found decoding headers FSkipBlankParts: boolean ; // ignore parts without ContentType or zero size function GetPartInfo (Index: Integer): TPartInfo ; public { Public declarations } FHeaderLines: TStrings; // raw header lines, may be inline encoded WideHeaders: array of UnicodeString; // Unicode version of each header line, read this to get header lines PartInfos: array of TPartInfo ; // body part info records, one per part, read this to get content constructor Create (Aowner: TComponent) ; override ; destructor Destroy ; override ; procedure Initialise ; procedure Reset ; procedure Finalise ; procedure DecodeFileEx (const FileName : String); procedure DecodeStreamEx (aStream : TStream); published { Published declarations } property DecodeW: TMimeDecodeW read FDecodeW ; property HeaderLines: TStrings read FHeaderLines; property MaxParts: integer read FMaxParts write FMaxParts ; property TotParts: integer read FTotParts ; property DecParts: integer read FDecParts ; property TotHeaders: integer read FTotHeaders ; property HeaderCharset: AnsiString read FHeaderCharset ; property SkipBlankParts: boolean read FSkipBlankParts write FSkipBlankParts ; end; function GetToken(Src : PAnsiChar; var Dst : AnsiString; var Delim : AnsiChar) : PAnsiChar; { This function did not unfold header values correctly, it also removed valid } { spaces. Since its name was also missleading it's been replaced by function } { UnfoldHdrValue(). AG } // function GetHeaderValue(X : PAnsiChar) : AnsiString; function UnfoldHdrValue(const Value: PAnsiChar) : AnsiString; overload; function UnfoldHdrValue(const Value: AnsiString) : AnsiString; {$IFDEF USE_INLINE} inline; {$ENDIF} overload; function DecodeMimeInlineValue(const Value: AnsiString): UnicodeString; function DecodeMimeInlineValueEx(const Value : AnsiString; var CharSet: AnsiString): UnicodeString; function IsCrLf1Char(Ch : AnsiChar) : Boolean; function IsCrLf1OrSpaceChar(Ch : AnsiChar) : Boolean; implementation type TLookup = array [0..127] of Byte; const Base64In: TLookup = ( 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 64, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255 ); {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function HexConv(Ch : AnsiChar) : Integer; begin if IsCharInSysCharSet(Ch, ['0'..'9']) then Result := Ord(Ch) - Ord('0') else Result := (Ord(Ch) and 15) + 9; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TMimeDecode.Create(AOwner : TComponent); begin inherited Create(AOwner); FHeaderLines := TStringList.Create; FIsMultipart := FALSE; FEndOfMime := FALSE; FInlineDecodeLine := false; FDefaultCodePage := IcsSystemCodePage; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TMimeDecode.Destroy; begin if Assigned(FHeaderLines) then begin FHeaderLines.Destroy; FHeaderLines := nil; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerHeaderBegin; begin if Assigned(FOnHeaderBegin) then FOnHeaderBegin(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerHeaderLine; begin if Assigned(FOnHeaderLine) then FOnHeaderLine(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerHeaderEnd; begin if Assigned(FOnHeaderEnd) then FOnHeaderEnd(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerPartHeaderBegin; begin if Assigned(FOnPartHeaderBegin) then FOnPartHeaderBegin(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerPartHeaderLine; begin if Assigned(FOnPartHeaderLine) then FOnPartHeaderLine(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerPartHeaderEnd; begin if Assigned(FOnPartHeaderEnd) then FOnPartHeaderEnd(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerPartBegin; begin if Assigned(FOnPartBegin) then FOnPartBegin(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerPartLine(Data : Pointer; DataLen : Integer); begin if Assigned(FOnPartLine) then FOnPartLine(Self, Data, DataLen); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerPartEnd; begin if Assigned(FOnPartEnd) then FOnPartEnd(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerMessageEnd; begin if Assigned(FOnMessageEnd) then FOnMessageEnd(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerInlineDecodeBegin(const Filename: AnsiString); begin if Assigned(FOnInlineDecodeBegin) then FOnInlineDecodeBegin(self, Filename); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerInlineDecodeLine(Line: Pointer; Len : Integer); begin if Assigned(FOnInlineDecodeLine) then FOnInlineDecodeLine(self, Line, Len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.TriggerInlineDecodeEnd(const Filename: AnsiString); begin if Assigned(FOnInlineDecodeEnd) then FOnInlineDecodeEnd(self, Filename); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessDecodedLine(Line : Pointer; Len : Integer); begin if Len > 0 then begin if (FPartContentType = '') { Not sure it is always OK ! } { As such we can't have a MIME part which } { is uu-encoded. } and uuprocessline(line) then Exit; end; TriggerPartLine(Line, Len); { Write decoded characters to the destination stream } if Assigned(FDestStream) and (Len > 0) then FDestStream.WriteBuffer(Line^, Len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This works if charset="iso-8859-1" ! } procedure TMimeDecode.ProcessLineQuotedPrintable; var SourceIndex : Integer; DecodedIndex : Integer; Ch : AnsiChar; Code : Integer; DecodedBuf : AnsiString; const EmptyLine : array [0..2] of AnsiChar = (#13, #10, #0); begin if FCurrentData = nil then Exit; { Allocate a buffer for decode line. At most the length of encoded data } { plus 2 bytes for CRLF } SetLength(DecodedBuf, StrLen(FCurrentData) + 2); SourceIndex := 0; { It's a PAnsiChar so index start at 0 } DecodedIndex := 1; { It's a AnsiString, so index start at 1 } while TRUE do begin Ch := FCurrentData[SourceIndex]; if Ch = #0 then begin { End of line, add CRLF and let's go } DecodedBuf[DecodedIndex] := #13; Inc(DecodedIndex); DecodedBuf[DecodedIndex] := #10; SetLength(DecodedBuf, DecodedIndex); ProcessDecodedLine(Pointer(DecodedBuf), DecodedIndex); // V7.21 Angus break; end; if Ch = '=' then begin { Encoded character. Next two chars should be hex code } Inc(SourceIndex); Ch := FCurrentData[SourceIndex]; if Ch = #0 then begin {*** Changed 20030806 ***} { process without #13#10 adding } SetLength(DecodedBuf, DecodedIndex-1); ProcessDecodedLine(Pointer(DecodedBuf), DecodedIndex-1); // V7.21 Angus, prevent range error for malformed blank lines break; {*** ***} end; Code := HexConv(Ch); Inc(SourceIndex); Ch := FCurrentData[SourceIndex]; if Ch = #0 then begin { Should not occur: code truncated, ignore } continue; end; Code := (Code shl 4) + HexConv(Ch); DecodedBuf[DecodedIndex] := AnsiChar(Code); end else DecodedBuf[DecodedIndex] := FCurrentData[SourceIndex]; Inc(SourceIndex); Inc(DecodedIndex); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessLineBase64; var SourceIndex : Integer; DataIn0 : Byte; DataIn1 : Byte; DataIn2 : Byte; DataIn3 : Byte; DecodedIndex : Integer; Len : Integer; begin SourceIndex := 0; DecodedIndex := 0; Len := StrLen(FCurrentData); { Remove spaces at the end of line } while (Len > 0) and IsSpace(FCurrentData[Len - 1]) do Dec(Len); { Skip white spaces at the start of line } while (SourceIndex < Len) and IsSpace(FCurrentData[SourceIndex]) do Inc(SourceIndex); { Decode until end of line. Replace coded chars by decoded ones } { Protect agains malformed messages. Normally we have a length which } { is multiple of four. But this may be corrupted ! } while SourceIndex < Len do begin { "And $7F" will clear 8th bit and avoid range error. If found in } { a message, it is probably a corrupted message ! } DataIn0 := Base64In[Byte(FCurrentData[SourceIndex]) and $7F]; Inc(SourceIndex); if SourceIndex >= Len then begin DataIn1 := $40; DataIn2 := $40; DataIn3 := $40; end else begin DataIn1 := Base64In[Byte(FCurrentData[SourceIndex]) and $7F]; Inc(SourceIndex); if SourceIndex >= Len then begin DataIn2 := $40; DataIn3 := $40; end else begin DataIn2 := Base64In[Byte(FCurrentData[SourceIndex]) and $7F]; Inc(SourceIndex); if SourceIndex >= Len then DataIn3 := $40 else begin DataIn3 := Base64In[Byte(FCurrentData[SourceIndex]) and $7F]; Inc(SourceIndex); end; end; end; FCurrentData[DecodedIndex] := AnsiChar((DataIn0 and $3F) shl 2 + (DataIn1 and $30) shr 4); if DataIn2 <> $40 then begin FCurrentData[DecodedIndex + 1] := AnsiChar((DataIn1 and $0F) shl 4 + (DataIn2 and $3C) shr 2); if DataIn3 <> $40 then begin FCurrentData[DecodedIndex + 2] := AnsiChar((DataIn2 and $03) shl 6 + (DataIn3 and $3F)); Inc(DecodedIndex, 3); end else Inc(DecodedIndex, 2); end else Inc(DecodedIndex, 1); end; { Nul terminate decoded line } FCurrentData[DecodedIndex] := #0; { 16/02/99 } ProcessDecodedLine(FCurrentData, DecodedIndex); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function UUDec(Sym : AnsiChar): Byte; begin if Sym = #0 then Result := 0 else Result := (Ord(Sym) - Ord(' ')) and $3F; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure UUOutDec(buf: PAnsiChar; n: Integer; var out1 : AnsiString); begin case n of 0: ; 1: out1 := out1 + AnsiChar((UUDec(buf[0]) SHL 2) + (UUDec(buf[1]) SHR 4)); 2: out1 := out1 + AnsiChar((UUDec(buf[0]) SHL 2) + (UUDec(buf[1]) SHR 4)) + AnsiChar((UUDec(buf[1]) SHL 4) + (UUDec(buf[2]) SHR 2)); else out1 := out1 + AnsiChar((UUDec(buf[0]) SHL 2) + (UUDec(buf[1]) SHR 4)) + AnsiChar((UUDec(buf[1]) SHL 4) + (UUDec(buf[2]) SHR 2)) + AnsiChar((UUDec(buf[2]) SHL 6) + (UUDec(buf[3]))); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF NEVER} procedure UUOutDec(buf: PAnsiChar; n: Integer; var out1 : AnsiString); var c1, c2, c3: AnsiChar; begin c1 := Chr((word(UUDec(buf[0])) SHL 2) or (word(UUDec(buf[1])) SHR 4)); c2 := Chr((word(UUDec(buf[1])) SHL 4) or (word(UUDec(buf[2])) SHR 2)); c3 := Chr((word(UUDec(buf[2])) SHL 6) or (word(UUDec(buf[3])))); if n >= 1 then out1 := out1 + c1; if n >= 2 then out1 := out1 + c2; if n >= 3 then out1 := out1 + c3; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { AG: } { This function did not unfold header values correctly, it also removed valid } { spaces. Since its name was also missleading it's been replaced by function } { UnfoldHdrValue(). } (* { AS: Get a value from a header line. Support multiline header. } { When a second line is present, make sure only ONE space is taken. } { InternalDecodeStream has replaced CR, LF and TAB by #1 character. } function GetHeaderValue(X : PAnsiChar) : AnsiString; var I, J : Integer; Len : Integer; EncStart, EncEnd: Integer; begin Result := SysUtils.StrPas(X); Len := Length(Result); I := Len; while I >= 1 do begin if IsCrLf1Char(Result[I]) then begin { Make sure we preserve a single space } J := I; while (I >= 1) and IsCrLf1OrSpaceChar(Result[I - 1]) do Dec(I); while (J < Len) and IsCrLf1OrSpaceChar(Result[J + 1]) do Inc(J); Delete(Result, I, J - I); Result[I] := ' '; end; Dec(I); end; end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { AG: } { InternalDecodeStream has replaced CR, LF and TAB by #1 dummy character. } { If CRLF+[Space or Tab] or #1#1#1 is found, preserve a space only if we are } { not inside a MIME inline block and the continuation line does not begin } { with a MIME inline encoded block or another continuation line. This is how } { Thunderbird handles MIME inline decoding, OE behaves a little bit } { different but IMO a little bit buggy. } { } { Examples: } { '=?ISO-8859-1?Q?a?='#1#1#1'=?ISO-8859-1?Q?b?=' } { Result: =?ISO-8859-1?Q?a?==?ISO-8859-1?Q?b?= } { } { '=?ISO-8859-1?Q?a?='#13#10#9' =?ISO-8859-1?Q?b?=' } { Result: =?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?= } { } { '=?ISO-8859-1?Q?a?='#1#1#1'<foo@bar.com>' } { Result: =?ISO-8859-1?Q?a?= <foo@bar.com> } { } { #10#10'=?ISO-8859-1?Q?a?= c'#1#1#1'=?ISO-8859-1?Q?b?=' } { Result: =?ISO-8859-1?Q?a?= c =?ISO-8859-1?Q?b?= } { } { 'a'#1#1#1'b' } { Result: a b } { } { ToDo: Skip continuation lines inside address blocks <>. } function UnfoldHdrValue(const Value: PAnsiChar) : AnsiString; var NextInlineEndOffset, PrevInlineEndOffset : Integer; L, I, J, R: Integer; ShouldPreserveSpace : Boolean; { Checks roughly whether a valid MIME inline block begins at current } { offset. If true returns offset of the last "=", otherwise zero. } function GetNextInlineEnd : Integer; var X, Part : Integer; begin Result := 0; if (I + 9 > L) or (not ((Value[I] = '=') and (Value[I + 1] = '?'))) then Exit; X := I + 2; Part := 1; while X <= L do begin if (Part = 1) and (Value[X] = '?') and (X + 2 <= L) and (Value[X + 2] = '?') then begin Inc(Part); Inc(X, 2); end else if (Value[X] = '?') and (X + 1 <= L) and (Value[X + 1] = '=') then begin Result := X + 1; Exit; end; Inc(X); end; end; begin L := StrLen(Value); // V7.22 prevent range error SetLength(Result, L); Dec (L); I := 0; J := I; R := 0; NextInlineEndOffset := 0; PrevInlineEndOffset := 0; ShouldPreserveSpace := FALSE; while I <= L do begin if NextInlineEndOffset = 0 then begin { if continuation line follows } if (Value[I] in [#13, #1]) and (I + 2 <= L) and (Value[I + 1] in [#10, #1]) and (Value[I + 2] in [#9, #1, ' ']) then begin if I > J then begin Move(Value[J], Result[R + 1], I - J); Inc(R, I - J); end; Inc(I, 3); J := I; if PrevInlineEndOffset > 0 then Inc(PrevInlineEndOffset, 3); if not ShouldPreserveSpace then ShouldPreserveSpace := TRUE; NextInlineEndOffset := GetNextInlineEnd; end else if (Value[I] in [#1, #10, #13]) then begin if I > J then begin Move(Value[J], Result[R + 1], I - J); Inc(R, I - J); end; Inc(I); J := I; if PrevInlineEndOffset > 0 then Inc(PrevInlineEndOffset); NextInlineEndOffset := GetNextInlineEnd; end else begin if ShouldPreserveSpace then begin ShouldPreserveSpace := FALSE; Inc(R); Result[R] := ' '; end; NextInlineEndOffset := GetNextInlineEnd; Inc(I); end; end else begin // NextInlineEndOffset > 0 if ShouldPreserveSpace then begin ShouldPreserveSpace := FALSE; { Skip if this block follows a previous block immediately } if PrevInlineEndOffset <> I - 1 then begin Inc(R); Result[R] := ' '; end; end; while I <= NextInlineEndOffset do begin if (Value[I] in [#1, #10, #13]) then begin if I > J then begin Move(Value[J], Result[R + 1], I - J); Inc(R, I - J); end; Inc(I); J := I; end else Inc(I); end; if I > J then begin Move(Value[J], Result[R + 1], I - J); Inc(R, I - J); end; J := I; PrevInlineEndOffset := NextInlineEndOffset; NextInlineEndOffset := GetNextInlineEnd; end; end; if L >= J then begin Move(Value[J], Result[R + 1], L - J + 1); Inc(R, L - J + 1); end; if R <> L + 1 then SetLength(Result, R); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function UnfoldHdrValue(const Value: AnsiString) : AnsiString; begin Result := UnfoldHdrValue(PAnsiChar(Value)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessLineUUDecode; { ##ERIC } var count, Size : Integer; s : AnsiString; out1 : AnsiString; bp : PAnsiChar; pos1 : Integer; begin if FCurrentData^ = #0 then exit; s := StrPas(FCurrentData); if _LowerCase(copy(s, 1, 6)) = 'begin ' then begin out1:=_lowercase(s); if (Pos(AnsiString('--'), out1) > 0) and (Pos(AnsiString('cut here'), out1) > 0) then Exit; pos1 := Pos(AnsiString(' '), s); s := Copy(s, pos1 + 1, 255); pos1 := Pos(AnsiString(' '), s); s := Copy(s, pos1 + 1, 255); cUUFilename := s; exit; end else if _LowerCase(Copy(s, 1, 3)) = 'end' then begin out1 := _LowerCase(s); if (Pos(AnsiString('--'), out1) > 0) and (Pos(AnsiString('cut here'), out1) > 0) then Exit; cUUFilename := ''; exit; end; { if no filename defined yet, exit } if cUUFilename = '' then exit; { decode the line } count := UUDec(s[1]); Size := Count; if count > 0 then begin bp := @s[2]; repeat UUOutDec(bp, count, out1); count := count - 3; bp := bp + 4; until count <= 0; end; { we're done. copy and leave } Move(Out1[1], FCurrentData[0], Size); ProcessDecodedLine(FCurrentData, Size); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function UUSectionBegin( const Line : AnsiString; var FileName : AnsiString) : Boolean; var I : Integer; begin { A UUEncoded section begins by a line having the syntax: } { "begin nnn filename" with xxx being a number (unix file permission) } { We accept xxx with at least 2 digits. Filename is optional. } Result := FALSE; FileName := ''; { AS: "begin" _must_ be in lower case ! } if Copy(Line, 1, 6) = 'begin ' then begin I := 7; while I <= Length(Line) do begin if Line[I] = ' ' then begin Result := (I > 8); if Result then FileName := Copy(Line, I + 1, Length(Line)); break end; if not IsCharInSysCharSet(Line[I], ['0'..'9']) then break; Inc(I) end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { AS: YEnc support routine } procedure TMimeDecode.ParseYBegin(const Ch : AnsiString); var I, J : Integer; begin { AS: Line format is "=ybegin line=128 size=XXXX name=YYYY"; } FSizeFileY := 0; FSizeBlocY := 0; I := 9; while I < Length(Ch) do begin if Copy(Ch, I, 5) = 'line=' then begin I := I + 5; while IsCharInSysCharSet(Ch[I], ['0'..'9']) do begin FSizeBlocY := 10 * FSizeBlocY + (Ord(Ch[I]) - Ord('0')); Inc(I); end; end else if Copy(Ch, I, 5) = 'size=' then begin I := I + 5; while IsCharInSysCharSet(Ch[I], ['0'..'9']) do begin FSizeFileY := 10 * FSizeFileY + (Ord(Ch[I]) - Ord('0')); Inc(I); end; end else if Copy(Ch, I, 5) = 'name=' then begin I := I + 5; J := I; repeat while (J <= Length(Ch)) and (Ch[J] <> ' ') do Inc(J); if (J >= Length(Ch)) or (Ch[J + 1] = '=') then break else Inc(J); until FALSE; cUUFilename := Copy(Ch, I, J - I); I := J; end; Inc(I); end; FSizeLeftY := FSizeFileY; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecode.UUProcessLine(FCurrentData: PAnsiChar): Boolean; var S : AnsiString; out1 : AnsiString; count : Integer; bp : PAnsiChar; chName : AnsiString; I, C : Integer; begin Result := TRUE; S := StrPas(FCurrentData); { AS } if _Trim(S) = '' then begin Result := FALSE; Exit; end; if (not FUUProcessFlag) and UUSectionBegin(S, chName) then begin { AS } if chName <> '' then { AS } cUUFilename := chName; { AS } out1 := _LowerCase(S); if (Pos(AnsiString('--'), out1) > 0) and (Pos(AnsiString('cut here'), out1) > 0) then Exit; FUUProcessFlag := TRUE; FProcessFlagYBegin := false; TriggerInlineDecodeBegin(cUUFilename); Exit; end; { AS: Handle YEnc } if (not FUUProcessFlag) and (Copy(S, 1, 8) = '=ybegin ') then begin { Line format : "=ybegin line=128 size=XXXX name=YYYY"; } ParseYBegin(S); FUUProcessFlag := TRUE; FProcessFlagYBegin := TRUE; TriggerInlineDecodeBegin(cUUFilename); Exit; end; if not FUUProcessFlag then begin Result := FALSE; Exit; end; if _CompareText(Copy(S, 1, 3), AnsiString('end')) = 0 then begin out1 := _LowerCase(S); if (Pos(AnsiString('--'), out1) > 0) and (Pos(AnsiString('cut here'), out1) > 0) then Exit; FUUProcessFlag := FALSE; { I also use the filename here in case the client prefer to save } { data to a stream and save to a file when the decoding is complete } TriggerInlineDecodeEnd(cUUFileName); cUUFilename := ''; Exit; end; { AS: Handle YEnc } if _CompareText(Copy(S, 1, 6), AnsiString('=yend ')) = 0 then begin FUUProcessFlag := FALSE; FProcessFlagYBegin := false; { I also use the filename here in case the client prefer to save } { data to a stream and save to a file when the decoding is complete } TriggerInlineDecodeEnd(cUUFilename); cUUFilename := ''; Exit; end; if _CompareText(Copy(S, 1, 7), AnsiString('=ypart ')) = 0 then begin { The message is in several parts. Something to do ? } Exit; end; if FInlineDecodeLine or Assigned(FOnInlineDecodeLine) then begin { decode the line } { AS: Handle YEnc } if not FProcessFlagYBegin then begin Count := UUDec(S[1]); out1 := ''; { AS: 25/11/2002 } {AS : new method to ignore wrongly coded lines } I := Length(S) - 1; if (Count > 0) and (Length(S) > 1) then begin bp := @S[2]; repeat UUOutDec(bp, Count, out1); if Count >= 3 then begin Count := Count - 3; I := I - 4; end else begin if I >= 4 then I := I - 4 else if I > 0 then I := 0; Count := 0; end; bp := bp + 4; until Count <= 0; if I <> 0 then out1 := ''; end; { Old code if (Count > 0) and (Length(S) > 1) then begin bp := @S[2]; repeat UUOutDec(bp, Count, out1); Count := Count - 3; bp := bp + 4; until Count <= 0; end; } end else begin { AS: Handle YEnc } out1 := ''; I := 0; bp := FCurrentData; while (I < FSizeBlocY) and (bp[I] <> #0) do begin if bp[I] = '=' then begin C := Byte(bp[I + 1]) - 64 - 42; Inc(I); end else C := byte(bp[I]) - 42; if C < 0 then C := C + 256; out1 := out1 + AnsiChar(C); Inc(I); end; end; TriggerInlineDecodeLine(PAnsiChar(Out1), Length(Out1)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function stpblk(PValue : PAnsiChar) : PAnsiChar; begin Result := PValue; { AS: Add #1 which is used to handle header lines } while IsCrLf1OrSpaceChar(Result^) do Inc(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetValue(Src : PAnsiChar; var Dst : AnsiString; var Delim : AnsiChar) : PAnsiChar; begin Result := StpBlk(Src); Dst := ''; Delim := Result^; if Delim = '"' then begin Inc(Result); while TRUE do begin Delim := Result^; if Delim = #0 then break; if Delim = '"' then begin Inc(Result); Delim := Result^; break; end; Dst := Dst + Delim; Inc(Result); end; end else begin while TRUE do begin Delim := Result^; if IsCharInSysCharSet(Delim, [':', ' ', ';', '=', #9, #0]) then break; Dst := Dst + _LowerCase(Result^); Inc(Result); end; end; if IsSpace(Delim) then begin Result := stpblk(Result); if IsCharInSysCharSet(Result^, [':', ';', '=', #9]) then Inc(Result); end else if Delim <> #0 then Inc(Result); Result := stpblk(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetToken(Src : PAnsiChar; var Dst : AnsiString; var Delim : AnsiChar) : PAnsiChar; begin Result := StpBlk(Src); Dst := ''; while TRUE do begin Delim := Result^; if IsCharInSysCharSet(Delim, [':', ' ', ';', '=', #9, #0]) then break; Dst := Dst + _LowerCase(Result^); Inc(Result); end; if IsSpace(Delim) then begin Result := stpblk(Result); if IsCharInSysCharSet(Result^, [':', ';', '=', #9]) then begin {AS: Take delimiter after space } Delim := Result^; Inc(Result); end; end else if Delim <> #0 then Inc(Result); Result := stpblk(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Same as GetToken, but take be aware of comments } function GetTokenEx(Src : PAnsiChar; var Dst : AnsiString; var Delim : AnsiChar) : PAnsiChar; var Comment: Integer; begin Result := StpBlk(Src); Dst := ''; Comment := 0; while TRUE do begin Delim := Result^; if Delim = #0 then break; if Delim = '(' then begin Inc(comment); { Comments can be nested } Inc(Result); Continue; end else if Delim = ')' then begin Dec(Comment); Inc(Result); Continue; end else if (Comment = 0) and IsCharInSysCharSet(Delim, [':', ' ', ';', '=', #9]) then break; Dst := Dst + _LowerCase(Result^); Inc(Result); end; if IsSpace(Delim) then begin Result := stpblk(Result); if IsCharInSysCharSet(Result^, [':', ';', '=', #9]) then begin Delim := Result^; Inc(Result); end; end else if Delim <> #0 then Inc(Result); Result := StpBlk(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetQuoted(Src : PAnsiChar; var Dst : AnsiString) : PAnsiChar; var Quote : AnsiChar; begin Result := StpBlk(Src); Dst := ''; Quote := Result^; if Quote <> #34 then begin { ##ERIC } Dst := StrPas(Src); { ##ERIC } Exit; { ##ERIC } end; { ##ERIC } Inc(Result); while (Result^ <> #0) and (Result^ <> Quote) do begin Dst := Dst + Result^; Inc(Result); end; Result := stpblk(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.PreparePart; begin FPartOpened := FALSE; TriggerPartEnd; PrepareNextPart; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessWaitBoundary; { ##ERIC } var T : Integer; S : AnsiString; begin S := _LowerCase(StrPas(FCurrentData)); if S = FBoundary then begin PreparePart; Exit; end else begin { are we in the embedded boundaries ? } for T := 0 to FEmbeddedBoundary.Count - 1 do begin if AnsiString(FEmbeddedBoundary[T]) = S then begin cIsEmbedded := true; PreparePart; Exit; end; end; { if not in primary boundary or embedded boundaries, then process it.} ProcessDecodedLine(FCurrentData, StrLen(FCurrentData)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.SetDefaultCodePage(const Value: LongWord); begin if not IsValidCodePage(Value) then raise Exception.Create('Code page "' + _IntToStr(Value) + '"' + 'is not a valid ANSI code page or currently not installed'); FDefaultCodePage := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessMessageLine; begin Inc(FLineNum); if FLineNum = 1 then begin FPartFirstLine := TRUE; TriggerPartBegin; end; if FEncoding = 'base64' then ProcessLineBase64 else if FEncoding = 'quoted-printable' then ProcessLineQuotedPrintable else if FEncoding = 'x-uuencode' then ProcessLineUUDecode { ##ERIC } else begin {tap} ProcessDecodedLine(FCurrentData, StrLen(FCurrentData)); ProcessDecodedLine(PAnsiChar(#13#10), 2); {tap: add \r\n to other encodings} end; {tap} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.PrepareNextPart; begin FApplicationType := ''; FIsTextpart := TRUE; FPartCharset := ''; FPartCodePage := FDefaultCodePage; FPartEncoding := ''; FPartContentType := ''; FPartDisposition := ''; FPartContentID := ''; FPartName := ''; FPartFileName := ''; FPartFormat := ''; FHeaderFlag := TRUE; { We begin by a header } FLineNum := 0; FUUProcessFlag := FALSE; FProcessFlagYBegin := FALSE; { AS: Handle YEnc } FPartHeaderBeginSignaled := FALSE; FNext := ProcessPartHeaderLine; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessPartLine; { ##ERIC } var Len : Integer; t : Integer; s : AnsiString; { ##ERIC } begin { Check if end of part (boundary line found) } if (FCurrentData <> nil) and (FCurrentData^ <> #0) then begin s := _LowerCase(StrPas(FCurrentData)); if (s = FBoundary) then begin PreparePart; exit; end else if (s = (FBoundary + '--')) then begin FEndOfMime := TRUE; PreparePart; exit; end else begin for t := 0 to FEmbeddedBoundary.Count - 1 do begin if (s = AnsiString(FEmbeddedBoundary[t])) or (s = (AnsiString(FEmbeddedBoundary[t]) + '--')) then begin { we now have to wait for the next part } PreparePart; exit; end end; end; end; if not FPartOpened then begin FPartOpened := TRUE; FPartFirstLine := TRUE; TriggerPartBegin; end; if FPartEncoding = 'base64' then ProcessLineBase64 else if FPartEncoding = 'quoted-printable' then ProcessLineQuotedPrintable else if FPartEncoding = 'x-uuencode' then { ##ERIC } ProcessLineUUDecode { ##ERIC } else begin if FCurrentData = nil then Len := 0 else Len := StrLen(FCurrentData); if FPartFirstLine then { FP Nov 13, 2007 } FPartFirstLine := FALSE else ProcessDecodedLine(PAnsiChar(#13#10), 2); ProcessDecodedLine(FCurrentData, Len); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessPartHeaderLine; var p : PAnsiChar; Delim : AnsiChar; Token : AnsiString; KeyWord : AnsiString; Value : AnsiString; { Value1 : AnsiString; } begin if (FCurrentData = nil) or (FCurrentData^ = #0) then begin { End of part header } if not FPartHeaderBeginSignaled then begin Inc(FPartNumber); TriggerPartHeaderBegin; end; TriggerPartHeaderEnd; FHeaderFlag := FALSE; { Remember we are no more in a header } FLineNum := 0; FUUProcessFlag := FALSE; FProcessFlagYBegin := FALSE; FNext := ProcessPartLine; Exit; end; Inc(FLineNum); if FLineNum = 1 then begin Inc(FPartNumber); FPartHeaderBeginSignaled := TRUE; TriggerPartHeaderBegin; { FEmbeddedBoundary.clear; } end; { A header line can't begin with a space nor tab char. If we got that } { then we consider the header as begin finished and process line } if FHeaderFlag and IsSpace(FCurrentData[0]) then begin TriggerPartHeaderEnd; FHeaderFlag := FALSE; FLineNum := 0; FUUProcessFlag := FALSE; FProcessFlagYBegin := FALSE; FNext := ProcessPartLine; ProcessPartLine; Exit; end; p := GetToken(FCurrentData, KeyWord, Delim); if KeyWord = 'content-type' then begin p := GetTokenEx(p, FPartContentType, Delim); if Pos(AnsiString('application/'), FPartContentType) = 1 then FApplicationType := Copy(FPartContentType, 13, MaxInt) else FIsTextpart := Pos(AnsiString('text'), FPartContentType) = 1; while Delim = ';' do begin p := GetToken(p, Token, Delim); if Delim = '=' then begin p := GetValue(p, Value, Delim); if Token = 'name' then FPartName := UnfoldHdrValue(Value) else if Token = 'charset' then begin FPartCharset := Value; if not MimeCharsetToCodePageEx(CsuString(FPartCharset), FPartCodePage) then FPartCodePage := FDefaultCodePage; end else if Token = 'format' then FPartFormat := Value else if Token = 'boundary' then begin { we have an embedded boundary } FEmbeddedBoundary.Add('--' + _LowerCase(String(Value))); { Value := Value + #0; }{ NUL terminate AnsiString for Delphi 1 } { GetQuoted(@Value[1], Value1);} { ##ERIC } { FEmbeddedBoundary.Add('--' + LowerCase(Value1));} { ##ERIC } end; { ##ERIC } end; end; end else if KeyWord = 'content-transfer-encoding' then begin GetTokenEx(p, FPartEncoding, Delim); end else if KeyWord = 'content-id' then begin FPartContentID := StrPas(p); if (Length(FPartContentID) >= 2) and (FPartContentID[1] = '<') and (FPartContentID[Length(FPartContentID)] = '>') then FPartContentID := Copy(FPartContentID, 2, Length(FPartContentID) - 2); end else if KeyWord = 'content-disposition' then begin p := GetTokenEx(p, FPartDisposition, Delim); while Delim = ';' do begin p := GetToken(p, Token, Delim); if Delim = '=' then begin p := GetQuoted(p, Value); if Token = 'filename' then FPartFileName := UnfoldHdrValue(Value); end; end; end else if (KeyWord = 'content-description') and (FPartFileName = '') then begin Delim:= ';'; while Delim = ';' do begin p := GetToken(p, Token, Delim); if Delim = '=' then begin p := GetQuoted(p, Value); if Token = 'filename' then FPartFileName := UnfoldHdrValue(Value); end; end; end; TriggerPartHeaderLine; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.ProcessHeaderLine; var p : PAnsiChar; pVal : PAnsiChar; Delim : AnsiChar; Token : AnsiString; Value : AnsiString; begin if (FCurrentData = nil) or (FCurrentData^ = #0) then begin FHeaderFlag := FALSE; { We are no more in a header } TriggerHeaderEnd; FLineNum := 0; FUUProcessFlag := FALSE; FProcessFlagYBegin := FALSE; if FBoundary = '' then FNext := ProcessMessageLine else begin FPartFirstLine := TRUE; TriggerPartBegin; FNext := ProcessWaitBoundary; end; Exit; end; Inc(FLineNum); if FLineNum = 1 then TriggerHeaderBegin; p := GetToken(FCurrentData, Token, Delim); pVal := StpBlk(p); if Delim = ':' then begin p := GetTokenEx(p, Value, Delim); if Token = 'from' then FFrom := UnfoldHdrValue(pVal) else if Token = 'to' then FDest := UnfoldHdrValue(pVal) else if Token = 'cc' then FCc := UnfoldHdrValue(pVal) else if Token = 'subject' then FSubject := UnfoldHdrValue(pVal) else if Token = 'return-path' then begin FReturnPath := UnfoldHdrValue(pVal); if (Length(FReturnPath) >= 2) and (FReturnPath[1] = '<') and (FReturnPath[Length(FReturnPath)] = '>') then FReturnPath := Copy(FReturnPath, 2, Length(FReturnPath) - 2); end else if Token = 'date' then FDate := UnfoldHdrValue(pVal) else if Token = 'mime-version' then FMimeVersion := UnfoldHdrValue(pVal) else if Token = 'content-type' then begin FContentType := Value; while Delim = ';' do begin p := GetToken(p, Token, Delim); if Delim = '=' then begin p := GetValue(p, Value, Delim); if Token = 'name' then FHeaderName := Value else if Token = 'charset' then begin FCharset := Value; if not MimeCharsetToCodePage(CsuString(FCharset), FCodePage) then FCodePage := FDefaultCodePage; end else if Token = 'format' then FFormat := Value else if Token = 'boundary' then begin FBoundary := '--' + _LowerCase(Value); FIsMultipart := TRUE; end; { ##ERIC } end; end; end else if Token = 'content-transfer-encoding' then FEncoding := Value else if Token = 'content-disposition' then begin FDisposition := Value; while Delim = ';' do begin p := GetToken(p, Token, Delim); if Delim = '=' then begin p := GetValue(p, Value, Delim); { p := GetQuoted(p, Value);} if Token = 'filename' then FFileName := UnfoldHdrValue(Value); end end end end; FLengthHeader := FLengthHeader + Integer(StrLen(FCurrentData)) + 2; FHeaderLines.Add(String(UnfoldHdrValue(FCurrentData))); TriggerHeaderLine; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.MessageEnd; begin if (FBoundary = '') or FPartOpened then TriggerPartEnd; TriggerMessageEnd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.MessageBegin; begin FIsTextPart := TRUE; FApplicationType := ''; FBoundary := ''; FCharset := ''; FCodePage := FDefaultCodePage; FContentType := ''; FCurrentData := nil; FDate := ''; FDest := ''; FDisposition := ''; FEncoding := ''; FEndOfMime := FALSE; FFileName := ''; FFormat := ''; FFrom := ''; FCc := ''; FHeaderFlag := TRUE; FHeaderName := ''; FIsMultiPart := FALSE; FLineNum := 0; FMimeVersion := ''; FNext := ProcessHeaderLine; FPartContentType := ''; FPartCharset := ''; FPartContentID := ''; FPartDisposition := ''; FPartEncoding := ''; FPartFileName := ''; FPartFormat := ''; FPartHeaderBeginSignaled := FALSE; FPartName := ''; FPartNumber := 0; FPartOpened := FALSE; FReturnPath := ''; FSubject := ''; FUUProcessFlag := FALSE; FProcessFlagYBegin := FALSE; FHeaderLines.Clear; FEmbeddedBoundary.Clear; FLengthHeader := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.DecodeFile(const FileName : String); var aStream : TStream; begin aStream := TFileStream.Create(FileName, fmOpenRead); try DecodeStream(aStream); finally aStream.Destroy; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecode.DecodeStream(aStream : TStream); begin FBufferSize := 2048; { Start with a reasonable FBuffer } GetMem(FBuffer, FBufferSize); try cUUFilename := ''; { ##ERIC } FEmbeddedBoundary := TStringList.Create; { ##ERIC } try InternalDecodeStream(aStream); finally FEmbeddedBoundary.Free; { ##ERIC } end; finally FreeMem(FBuffer, FBufferSize); FBuffer := nil; FBufferSize := 0; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This routine use an intelligent buffer management, trying to move data } { the less possible times. The buffer is enlarged as necessary to contains } { the largest line we encounter. } procedure TMimeDecode.InternalDecodeStream(aStream : TStream); var RdCnt : LongInt; nUsed : Integer; nStart : Integer; nLast : Integer; nSearch : Integer; I, J : Integer; begin nUsed := 0; nStart := 0; MessageBegin; while TRUE do begin nSearch := nStart + nUsed; RdCnt := aStream.Read(FBuffer[nSearch], FBufferSize - nUsed - nStart - 2); { for next char and #0 } if RdCnt <= 0 then begin break; end; nUsed := nUsed + RdCnt; nLast := nStart + nUsed; { Nul terminate the FBuffer } FBuffer[nLast] := #0; { Search for terminating line feed } while TRUE do begin I := nSearch; while (I < nLast) and (FBuffer[I] <> #10) do Inc(I); if I >= nLast then begin { We did'nt find any LF in the FBuffer, need to read more ! } if nStart > (3 * (FBufferSize div 4)) then begin { Reuse start of FBuffer because 3/4 buffer is unused } Move(FBuffer[nStart], FBuffer[0], nUsed + 1); nStart := 0; end else begin { Makes FBuffer larger } ReallocMem(FBuffer, FBufferSize + 32); FBufferSize := FBufferSize + 32; end; break; end; { We found a line feed, process FBuffer up to this point } { Remove any preceding CR } if (I > nStart) and (FBuffer[I - 1] = #13) then J := I - 1 else J := I; { We found a LF, if we are processing a header, we must } { have the next character to see if the line is continuated } if FHeaderFlag then begin if I >= (nLast - 1) then begin { We don't have the next character in our FBuffer, } { we need to read more data } { Read a single byte at the end of the FBuffer } { We have room because we preserved it previously } RdCnt := aStream.Read(FBuffer[I + 1], 1); if RdCnt > 0 then begin { We have read the next char } Inc(nLast); Inc(nUsed); FBuffer[I + 2] := #0; end; end; if I < nLast then begin if (not IsCrLf(FBuffer[nStart])) and { 27/08/98 } IsSpace(FBuffer[I + 1]) then begin { We have a continuation line, replace CRLF + } { [TAB or Space] by #1 which will be handled } { in UnfoldHdrValue. Comment adjusted AG V7.16 } FBuffer[I] := #1; FBuffer[J] := #1; //if FBuffer[I + 1] = #9 then { AG V7.16 } FBuffer[I + 1] := #1; nSearch := I; { and search new line end } continue; end; end; end; FBuffer[J] := #0; FCurrentData := FBuffer + nStart; FNext; FBuffer[J] := #10; {tap: ERROR ? #13} nStart := I + 1; nUsed := nLast - nStart; nSearch := nStart; end; end; { Process the last line } if nUsed > 0 then begin FCurrentData := FBuffer + nStart; FNext; end; MessageEnd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { V7.11 Extended MIME decoding that save all parts into arrays } constructor TMimeDecodeEx.Create(Aowner:TComponent); begin inherited Create(AOwner); FDecodeW := TMimeDecodeW.Create (Self); FHeaderLines := TStringList.Create; FMaxParts := 10 ; FSkipBlankParts := false ; FDecodeW.OnHeaderLine := MimeDecodeHeaderLine ; FDecodeW.OnPartBegin := MimeDecodePartBegin ; FDecodeW.OnPartEnd := MimeDecodePartEnd ; PartInfos := Nil ; WideHeaders := Nil ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TMimeDecodeEx.Destroy; begin Reset; FreeAndNil (FHeaderLines); FreeAndNil (FDecodeW); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { reset all variables and arrays } procedure TMimeDecodeEx.Reset ; var I: integer ; begin FTotParts := 0 ; FDecParts := 0 ; FTotHeaders := 0 ; FHeaderCharset := '' ; FHeaderLines.Clear ; if Length (PartInfos) > 0 then begin for I := 0 to Pred (Length (PartInfos)) do FreeAndNil (PartInfos[I].PartStream) ; end ; SetLength (PartInfos, 0) ; SetLength (WideHeaders, 0) ; FDecodeW.DestStream := Nil ; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Initialise arrays and streams ready to decode MIME } procedure TMimeDecodeEx.Initialise ; var I: integer ; begin Reset ; SetLength (PartInfos, 4) ; // initial size only for I := 0 to Length (PartInfos) - 1 do PartInfos [I].PartStream := TMemoryStream.Create ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecodeEx.MimeDecodeHeaderLine(Sender: TObject); begin FHeaderLines.Add (string(FDecodeW.CurrentData)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { found a new MIME part, extend array if necessary, set PartStream ready for content } procedure TMimeDecodeEx.MimeDecodePartBegin(Sender: TObject); var I, oldparts: integer ; begin oldparts := Length (PartInfos) ; if FDecParts >= oldparts then begin if FDecParts >= FMaxParts then // ignore more parts begin FDecodeW.DestStream := Nil ; exit ; end ; SetLength (PartInfos, FDecParts * 2) ; for I := oldparts to Length (PartInfos) - 1 do PartInfos [I].PartStream := TMemoryStream.Create ; end; PartInfos [FDecParts].PartStream.Clear ; FDecodeW.DestStream := PartInfos [FDecParts].PartStream ; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { fisished reading MIME part, reset PartStream to start and keep stuff about part } procedure TMimeDecodeEx.MimeDecodePartEnd(Sender: TObject); begin if (FDecParts >= FMaxParts) or (FDecParts >= Length (PartInfos)) then // ignore extra parts begin inc (FTotParts) ; exit ; end ; with PartInfos [FDecParts] do begin PartStream.Seek (soFromBeginning, 0) ; PSize := PartStream.Size ; if FDecodeW.PartNumber = 0 then // main body begin if FSkipBlankParts and (Pos (AnsiString('multipart'), _LowerCase (FDecodeW.ContentType)) = 1) then exit ; PContentType := FDecodeW.ContentType ; PCharset := FDecodeW.Charset ; PCodePage := FDecodeW.CodePage; PApplType := FDecodeW.ApplicationType ; PName := DecodeMimeInlineValue (FDecodeW.HeaderName) ; PEncoding := FDecodeW.Encoding ; PDisposition := FDecodeW.Disposition ; PFileName := DecodeMimeInlineValue (FDecodeW.FileName) ; PContentId := FDecodeW.FPartContentID ; {V7.18 Bjørnar} PIsTextpart := FDecodeW.FIsTextpart ; {V7.20 Angus } end else begin // real part PContentType := FDecodeW.PartContentType ; PCharset := FDecodeW.PartCharset ; PCodePage := FDecodeW.PartCodePage; PApplType := FDecodeW.ApplicationType ; PName := DecodeMimeInlineValue (FDecodeW.PartName) ; PEncoding := FDecodeW.PartEncoding ; PDisposition := FDecodeW.PartDisposition ; PFileName := DecodeMimeInlineValue (FDecodeW.PartFileName) ; PContentId := FDecodeW.FPartContentID ; {V7.18 Bjørnar} PIsTextpart := FDecodeW.FIsTextpart ; {V7.20 Angus } end ; if FSkipBlankParts then begin if PContentType = '' then exit ; if PSize = 0 then exit ; end; inc (FDecParts) ; inc (FTotParts) end ; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { decode headers to Unicode } procedure TMimeDecodeEx.Finalise ; var I: integer ; CharSet: AnsiString; begin FTotHeaders := FHeaderLines.Count ; SetLength (WideHeaders, FTotHeaders) ; for I := 0 to FTotHeaders - 1 do begin WideHeaders [I] := DecodeMimeInlineValueEx (UnfoldHdrValue (AnsiString(FHeaderLines [I])), CharSet) ; if FHeaderCharset = '' then FHeaderCharset := CharSet ; end ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { V7.11 Decode MIME file into PartInfos and PartStreams arrays with TotParts } procedure TMimeDecodeEx.DecodeFileEx (const FileName: String); begin Initialise ; FDecodeW.DecodeFile (FileName) ; Finalise ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { V7.11 Decode MIME stream into PartInfos and PartStreams arrays with TotParts } procedure TMimeDecodeEx.DecodeStreamEx (aStream: TStream); begin Initialise ; FDecodeW.DecodeStream (aStream) ; Finalise ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeEx.GetPartInfo (Index: Integer): TPartInfo ; begin if Index >= Length (PartInfos) then exit; result := PartInfos [Index] ; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IsCrLf1Char(Ch : AnsiChar) : Boolean; begin Result := (Ch = #10) or (Ch = #13) or (Ch = #1); // #1 is used to handle line break end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IsCrLf1OrSpaceChar(Ch : AnsiChar) : Boolean; begin Result := (Ch = #10) or (Ch = #13) or (Ch = #1) or // #1 is used to handle line break (Ch = ' ') or (Ch = #9); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TMimeDecodeW } function DecodeQuotedPrintable(const S: AnsiString) : AnsiString; var I, J, L : Integer; begin I := 1; J := 0; L := Length(S); SetLength(Result, L); while I <= L do begin while (I <= L) and (S[I] <> '=') do begin Inc(J); if S[I] = '_' then Result[J] := ' ' else Result[J] := S[I]; Inc(I); end; if I >= L then Break; Inc(I); Inc(J); Result[J] := AnsiChar(htoi2(PAnsiChar(@S[I]))); Inc(I, 2); end; SetLength(Result, J); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Parameter "Value" MUST NOT contain a folded header line. Pass the result } { of UnfoldHdrValue() if the string still contains CRLF+[TAB or Space] or } { dummy control characters (#1). } function DecodeMimeInlineValue(const Value : AnsiString): UnicodeString; var BeginEnc, BeginType, L, I, J: Integer; EncType : AnsiChar; CharSet, S: AnsiString; CP : LongWord; begin L := Length(Value); EncType := #0; BeginEnc := 0; BeginType := 0; I := 1; J := I; Result := ''; CharSet := ''; CP := IcsSystemCodePage; while I <= L do begin if (BeginEnc = 0) then begin if (Value[I] = '=') and (I + 1 <= L) and (Value[I + 1] = '?') then begin BeginEnc := I; if I > J then begin S := Copy(Value, J, I - J); //Result := Result + AnsiToUnicode(S, CP); Result := Result + IcsBufferToUnicode(Pointer(S)^, Length(S), CP); J := I + 1; end; Inc(I); end; end else if BeginType = 0 then begin if (Value[I] = '?') and (I + 2 <= L) and (Value[I + 2] = '?') then begin BeginType := I; CharSet := Copy(Value, BeginEnc + 2, BeginType - (BeginEnc + 2)); //CP := MimeCharsetToCodePageDef(CsuString(CharSet)); CP := MimeCharsetToCodePageExDef(CsuString(CharSet)); EncType := Value[I + 1]; CharLowerA(@EncType); Inc(I, 2); end; end else begin if (Value[I] = '?') and (I + 1 <= L) and (Value[I + 1] = '=') then begin case EncType of 'q' : begin S := Copy(Value, BeginType + 3, I - (BeginType + 3)); S := DecodeQuotedPrintable(S); end; 'b' : begin S := Copy(Value, BeginType + 3, I - (BeginType + 3)); S := Base64Decode(S); end; else S := Copy(Value, BeginEnc, I - BeginEnc); end; //Result := Result + AnsiToUnicode(S, CP); Result := Result + IcsBufferToUnicode(Pointer(S)^, Length(S), CP); EncType := #0; BeginEnc := 0; BeginType := 0; CP := IcsSystemCodePage; Inc(I); J := I + 1; end; end; Inc(I); end; if (L >= J) then begin { AG 7.16 } S := Copy(Value, J, MaxInt); //Result := Result + AnsiToUnicode(S, CP); Result := Result + IcsBufferToUnicode(Pointer(S)^, Length(S), CP); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Parameter "Value" MUST NOT contain a folded header line. Pass the result } { of UnfoldHdrValue() if the string still contains CRLF+[TAB or Space] or } { dummy control characters (#1). } function DecodeMimeInlineValueEx(const Value : AnsiString; var CharSet: AnsiString): UnicodeString; var BeginEnc, BeginType, L, I, J: Integer; EncType : AnsiChar; S: AnsiString; CP : LongWord; begin L := Length(Value); EncType := #0; BeginEnc := 0; BeginType := 0; I := 1; J := I; Result := ''; CharSet := ''; CP := IcsSystemCodePage; while I <= L do begin if (BeginEnc = 0) then begin if (Value[I] = '=') and (I + 1 <= L) and (Value[I + 1] = '?') then begin BeginEnc := I; if I > J then begin S := Copy(Value, J, I - J); //Result := Result + AnsiToUnicode(S, CP); Result := Result + IcsBufferToUnicode(Pointer(S)^, Length(S), CP); J := I + 1; end; Inc(I); end; end else if BeginType = 0 then begin if (Value[I] = '?') and (I + 2 <= L) and (Value[I + 2] = '?') then begin BeginType := I; CharSet := Copy(Value, BeginEnc + 2, BeginType - (BeginEnc + 2)); //CP := MimeCharsetToCodePageDef(CsuString(CharSet)); CP := MimeCharsetToCodePageExDef(CsuString(CharSet)); EncType := Value[I + 1]; CharLowerA(@EncType); Inc(I, 2); end; end else begin if (Value[I] = '?') and (I + 1 <= L) and (Value[I + 1] = '=') then begin case EncType of 'q' : begin S := Copy(Value, BeginType + 3, I - (BeginType + 3)); S := DecodeQuotedPrintable(S); end; 'b' : begin S := Copy(Value, BeginType + 3, I - (BeginType + 3)); S := Base64Decode(S); end; else S := Copy(Value, BeginEnc, I - BeginEnc); end; //Result := Result + AnsiToUnicode(S, CP); Result := Result + IcsBufferToUnicode(Pointer(S)^, Length(S), CP); EncType := #0; BeginEnc := 0; BeginType := 0; CP := IcsSystemCodePage; Inc(I); J := I + 1; end; end; Inc(I); end; if (L >= J) then begin { AG 7.16 } S := Copy(Value, J, MaxInt); //Result := Result + AnsiToUnicode(S, CP); Result := Result + IcsBufferToUnicode(Pointer(S)^, Length(S), CP); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetCcW: UnicodeString; begin Result := DecodeMimeInlineValue(FCc); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetDestW: UnicodeString; begin Result := DecodeMimeInlineValue(FDest); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetFileNameW: UnicodeString; begin Result := DecodeMimeInlineValue(FFileName); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetFromW: UnicodeString; begin Result := DecodeMimeInlineValue(FFrom); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetPartFileNameW: UnicodeString; begin Result := DecodeMimeInlineValue(FPartFileName); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetPartNameW: UnicodeString; begin Result := DecodeMimeInlineValue(FPartName); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMimeDecodeW.GetSubjectW: UnicodeString; begin Result := DecodeMimeInlineValue(FSubject); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMimeDecodeW.TriggerPartBegin; begin if FPartNumber = 0 then begin if not FIsMultipart then begin { Init part #0 with message header values } FPartCharset := FCharset; FPartCodePage := FCodePage; FPartContentType := FContentType; FPartEncoding := FEncoding; FPartFormat := FFormat; FPartDisposition := FDisposition; FPartName := FHeaderName; FPartFileName := FFileName; FIsTextPart := (Length(FContentType) = 0) or (Pos(AnsiString('text'), FContentType) = 1); end; end; inherited; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
{ ********************************************************************* Gnostice eDocEngine Copyright (c) Gnostice Information Technologies Private Limited http://www.gnostice.com ********************************************************************* } {$I ..\gtSharedDefines.inc} unit gtClasses3; interface uses Classes, SysUtils {$IFDEF gtActiveX} , Controls, Graphics, Buttons {$ENDIF}; Type TgtException = class(Exception) public ErrorCode: Integer; end; CharSet = set of AnsiChar; EInvalidID = class(TgtException); EInvalidStream = class(TgtException); EReadError = class(TgtException); EWriteError = class(TgtException); TWString = record WString: WideString; end; TWideStrings = class private FWideStringList: TList; function Get(Index: Integer): WideString; procedure Put(Index: Integer; const S: WideString); public constructor Create; destructor Destroy; override; function Count: Integer; procedure Clear; function Add(const S: WideString): Integer; function Delete(Index: Integer): WideString; function IndexOf(const S: WideString): Integer; function IndexOfIgnoreCase(const S: WideString): Integer; procedure Insert(Index: Integer; const S: WideString); procedure SetTextStr(const Value: WideString); procedure LoadFromFile(const FileName: WideString); procedure LoadFromStream(Stream: TStream); property Strings[Index: Integer]: WideString read Get write Put; default; end; { TgtExtMemStream } TgtExtMemStream = Class(TMemoryStream) private FPadSize: Int64; public property PadSize: Int64 read FPadSize write FPadSize; constructor Create; procedure PadTo4Bytes; function SkipBytes(ANumBytes: Integer): Integer; function ReadByte: Byte; function ReadLong: Integer; function ReadULong: Cardinal; function ReadShort: SmallInt; function ReadUShort: Word; function ReadString(ALength: Integer): AnsiString; procedure ReadByteArray(AByteArray: array of Byte; AOffset, ALength: Integer); procedure WriteByte(AByte: Byte); procedure WriteLong(ALong: Integer); procedure WriteULong(AULong: Cardinal); procedure WriteShort(AShort: SmallInt); procedure WriteUShort(AUShort: Word); procedure WriteString(AString: AnsiString); procedure WriteByteArray(AByteArray: array of Byte); procedure WriteUShortArray(AUShortArray: array of Word); procedure WriteULongArray(AULongArray: array of Cardinal); end; {$IFDEF gtDelphiXE2Up} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} { TgtBaseComponent } {$IFDEF gtActiveX} TgtBaseComponent = class(TCustomControl) {$ELSE} TgtBaseComponent = class(TComponent) {$ENDIF} private FAbout: String; FVersion: String; {$IFDEF gtActiveX} FIconBmp: TBitmap; function GetControlCanvas: TCanvas; {$ENDIF} procedure SetAbout(const Value: String); procedure SetVersion(const Value: String); protected {$IFDEF gtActiveX} property ControlCanvas: TCanvas read GetControlCanvas; property IconBmp: TBitmap read FIconBmp write FIconBmp; {$ENDIF} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {$IFDEF gtActiveX} procedure Paint; override; {$ENDIF} published property About: String read FAbout write SetAbout; property Version: String read FVersion write SetVersion; end; { TgtReadOnlyFilter } TgtReadOnlyFilter = class(TStream) private FSize: Longint; FStream: TStream; public constructor Create(aStream: TStream); function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; property Stream: TStream read FStream; end; { TgtWriteOnlyFilter } TgtWriteOnlyFilter = class(TStream) private FStream: TStream; public constructor Create(aStream: TStream); function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function CopyFrom(Source: TStream; Count: Int64): Int64; property Stream: TStream read FStream; end; { TgtRandomAccessFilter } TgtRandomAccessFilter = class(TgtReadOnlyFilter) private FPeekLastChar: Boolean; public function PeekChar: Char; function PeekString(Count: Longint): String; function ReadChar: Char; function ReadString(Count: Longint): String; function ReadOffset(var Buffer; FromOffset, ToOffset: Longint): Longint; function Skip(Count: Longint): Longint; procedure PushBackChar; procedure IncPos(Count: Integer); property PeekLastChar: Boolean read FPeekLastChar; end; { TgtObjectList } TgtObjectList = class; PObjectItem = ^TgtObjectItem; TgtObjectItem = record FInteger: Integer; FObject: TObject; end; PObjectItemList = ^TgtObjectItemList; {$IFDEF WIN32} TgtObjectItemList = array [0 .. 134217727] of TgtObjectItem; {$ENDIF} {$IFDEF WIN64} TgtObjectItemList = array [0 .. 134217726] of TgtObjectItem; {$ENDIF} TgtObjectList = class(TPersistent) private FList: PObjectItemList; FCount: Integer; FCapacity: Integer; procedure Grow; function GetCapacity: Integer; function GetCount: Integer; function GetObject(Index: Integer): TObject; procedure SetCapacity(NewCapacity: Integer); function GetItem(Index: Integer): TgtObjectItem; public destructor Destroy; override; function Add(ANo: Integer; AObject: TObject): Integer; overload; procedure Add(AObjectList: TgtObjectList); overload; procedure Clear; procedure Delete(Index: Integer); function IndexOf(const ObjectNo: Integer): Integer; procedure InsertItem(Index: Integer; ANo: Integer; AObject: TObject); property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property Objects[Index: Integer]: TObject read GetObject; default; property Items[Index: Integer]: TgtObjectItem read GetItem; end; // Exception type for improper image format and Unsupported Background Display type EImageExceptions = class(Exception); ExInvalidImageFormat = class(EImageExceptions); ExUnsupportedBackgroundDisplayType = class(EImageExceptions); resourcestring SInvalidID = 'Invalid unique ID (%d)'; SNullStreamError = 'Invalid Stream! Cannot create with null stream'; SWriteError = 'A read-only filter cannot write'; SReadError = 'A write-only filter cannot read'; SInvalidOffset = 'Invalid offset specified'; SSkipCount = 'Skip count exceeds Stream Size'; SListIndexOutOfBounds = 'List index out of bounds (%d)'; ErrInvalidImageFormat = 'Invalid Image Format'; ErrUnsupportedBackgroundDisplayType = 'Unsupported Background Display Type '; // const AX_SIZE = 28; // {$IFDEF gtDelphi5} // soBeginning = 0; // soCurrent = 1; // soEnd = 2; // {$ENDIF} implementation function InOpSet(W: WideChar; const Sets: CharSet): Boolean; begin if W <= #$FF then Result := AnsiChar(W) in Sets else Result := False; end; { TgtBaseComponent } constructor TgtBaseComponent.Create(AOwner: TComponent); begin inherited Create(AOwner); {$IFDEF gtActiveX} FIconBmp := TBitmap.Create; FIconBmp.Transparent := True; FIconBmp.TransparentMode := tmAuto; SetBounds(Left, Top, AX_SIZE, AX_SIZE); Constraints.MinHeight := AX_SIZE; Constraints.MinWidth := AX_SIZE; Constraints.MaxHeight := AX_SIZE; Constraints.MaxWidth := AX_SIZE; {$ENDIF} end; destructor TgtBaseComponent.Destroy; begin {$IFDEF gtActiveX} FreeAndNil(FIconBmp); {$ENDIF} inherited; end; {$IFDEF gtActiveX} procedure TgtBaseComponent.Paint; begin inherited; DrawButtonFace(Canvas, Rect(0, 0, AX_SIZE, AX_SIZE), 1, bsNew, False, False, True); end; function TgtBaseComponent.GetControlCanvas: TCanvas; begin Result := Canvas; end; {$ENDIF} procedure TgtBaseComponent.SetAbout(const Value: String); begin end; procedure TgtBaseComponent.SetVersion(const Value: String); begin end; { TgtExtMemStream } constructor TgtExtMemStream.Create; begin inherited Create; Position := 0; PadSize := 0; end; procedure TgtExtMemStream.PadTo4Bytes; var I: Integer; Zero: Integer; begin Zero := 0; Position := Size; I := (4 - (Size mod 4)); if I <> 4 then Write(Zero, I); if I = 4 then PadSize := 0 else PadSize := I; end; function TgtExtMemStream.ReadByte: Byte; begin Read(Result, 1); end; procedure TgtExtMemStream.ReadByteArray(AByteArray: array of Byte; AOffset, ALength: Integer); var N, Cnt: Integer; begin N := 0; repeat Position := Position + (AOffset + N); Cnt := Read(AByteArray, ALength - N); if (Cnt < 0) then Exit; N := N + Cnt; until (N >= ALength); end; function TgtExtMemStream.ReadLong: Integer; var I: array [0 .. 3] of Byte; begin Read(I, 4); Result := Integer(I[0] shl 24) + (I[1] shl 16) + (I[2] shl 8) + I[3]; end; function TgtExtMemStream.ReadShort: SmallInt; var I: array [0 .. 1] of Byte; begin Read(I, 2); Result := SmallInt((I[0] shl 8) + I[1]); end; function TgtExtMemStream.ReadString(ALength: Integer): AnsiString; begin SetLength(Result, ALength); Read(Result[1], ALength); end; function TgtExtMemStream.ReadULong: Cardinal; var I: array [0 .. 3] of Byte; begin Read(I, 4); Result := Cardinal((I[0] shl 24) + (I[1] shl 16) + (I[2] shl 8) + I[3]); end; function TgtExtMemStream.ReadUShort: Word; var I: array [0 .. 1] of Byte; begin Read(I, 2); Result := Word((I[0] shl 8) + I[1]); end; function TgtExtMemStream.SkipBytes(ANumBytes: Integer): Integer; var NewPos: Integer; begin NewPos := Position + ANumBytes; if (NewPos > Size) then NewPos := Size else if (NewPos < 0) then NewPos := 0; Position := NewPos; Result := NewPos - Position; end; procedure TgtExtMemStream.WriteByte(AByte: Byte); begin Write(AByte, 1); end; procedure TgtExtMemStream.WriteByteArray(AByteArray: array of Byte); begin Write(AByteArray, SizeOf(AByteArray)); end; procedure TgtExtMemStream.WriteLong(ALong: Integer); var B: array [0 .. 3] of Byte; begin B[0] := Byte(ALong shr 24); B[1] := Byte((ALong shl 8) shr 24); B[2] := Byte((ALong shl 16) shr 24); B[3] := Byte((ALong shl 24) shr 24); WriteByteArray(B); end; procedure TgtExtMemStream.WriteShort(AShort: SmallInt); var B: array [0 .. 1] of Byte; begin B[0] := Byte(AShort shr 8); B[1] := Byte((AShort shl 8) shr 8); WriteByteArray(B); end; procedure TgtExtMemStream.WriteString(AString: AnsiString); var I: Integer; begin for I := 1 to Length(AString) do WriteByte(Ord(AString[I])); end; procedure TgtExtMemStream.WriteULong(AULong: Cardinal); var B: array [0 .. 3] of Byte; begin B[0] := Byte(AULong shr 24); B[1] := Byte((AULong shl 8) shr 24); B[2] := Byte((AULong shl 16) shr 24); B[3] := Byte((AULong shl 24) shr 24); WriteByteArray(B); end; procedure TgtExtMemStream.WriteULongArray(AULongArray: array of Cardinal); var LI: Integer; begin for LI := Low(AULongArray) to High(AULongArray) do WriteULong(AULongArray[LI]); end; procedure TgtExtMemStream.WriteUShortArray(AUShortArray: array of Word); var LI: Integer; begin for LI := Low(AUShortArray) to High(AUShortArray) do WriteUShort(AUShortArray[LI]); end; procedure TgtExtMemStream.WriteUShort(AUShort: Word); var B: array [0 .. 1] of Byte; begin B[0] := Byte(AUShort shr 8); B[1] := Byte((AUShort shl 8) shr 8); WriteByteArray(B); end; { TgtReadOnlyFilterStream } constructor TgtReadOnlyFilter.Create(aStream: TStream); begin inherited Create; if not Assigned(aStream) then raise EInvalidStream.Create(SNullStreamError) else begin FStream := aStream; FSize := FStream.Size; end; end; function TgtReadOnlyFilter.Read(var Buffer; Count: Integer): Longint; begin Result := FStream.Read(Buffer, Count); end; function TgtReadOnlyFilter.Seek(Offset: Integer; Origin: Word): Longint; begin if Offset = -1 then Result := Offset else Result := FStream.Seek(Offset, Origin); end; function TgtReadOnlyFilter.Write(const Buffer; Count: Integer): Longint; begin raise EReadError.Create(SReadError); Result := 0; end; { TgtRandomAccessFilter } procedure TgtRandomAccessFilter.IncPos(Count: Integer); begin FStream.Position := FStream.Position + Count; end; function TgtRandomAccessFilter.PeekChar: Char; begin FStream.Read(Result, 1); FPeekLastChar := (FStream.Position = FStream.Size); FStream.Position := FStream.Position - 1; end; function TgtRandomAccessFilter.PeekString(Count: Integer): String; begin SetLength(Result, Count); Count := FStream.Read(Result[1], Count); // FPeekLastChar := (FStream.Position = FStream.Size); FStream.Position := FStream.Position - Count; end; procedure TgtRandomAccessFilter.PushBackChar; begin FStream.Position := FStream.Position - 1; end; function TgtRandomAccessFilter.ReadChar: Char; begin FStream.Read(Result, 1); end; function TgtRandomAccessFilter.ReadOffset(var Buffer; FromOffset, ToOffset: Integer): Longint; function IsValidOffset(FromOffset, ToOffset: Longint): Boolean; begin Result := (FromOffset >= 0) and (ToOffset >= 0) and (ToOffset <= FSize); end; var CurrentPos: Longint; begin if not IsValidOffset(FromOffset, ToOffset) then begin raise Exception.Create(SInvalidOffset); Result := 0; Exit; end; Result := ToOffset - FromOffset; if Result > 0 then begin CurrentPos := FStream.Position; FStream.Position := FromOffset; Result := FStream.Read(Buffer, Result); FStream.Position := CurrentPos; end else Result := 0; end; function TgtRandomAccessFilter.ReadString(Count: Integer): String; begin SetLength(Result, Count); Read(Result[1], Count); end; function TgtRandomAccessFilter.Skip(Count: Integer): Longint; begin if (FStream.Position + Count) > FSize then raise Exception.Create(SSkipCount) else begin FStream.Position := (FStream.Position + Count); Result := Count; end; end; { TgtWriteOnlyFilter } function TgtWriteOnlyFilter.CopyFrom(Source: TStream; Count: Int64): Int64; begin Result := FStream.CopyFrom(Source, Count); end; constructor TgtWriteOnlyFilter.Create(aStream: TStream); begin inherited Create; if not Assigned(aStream) then raise EInvalidStream.Create(SNullStreamError) else FStream := aStream; end; function TgtWriteOnlyFilter.Read(var Buffer; Count: Integer): Longint; begin raise EReadError.Create(SReadError); Result := 0; end; function TgtWriteOnlyFilter.Seek(Offset: Integer; Origin: Word): Longint; begin Result := FStream.Seek(Offset, Origin); end; function TgtWriteOnlyFilter.Write(const Buffer; Count: Integer): Longint; begin Result := FStream.Write(Buffer, Count); end; { TgtObjectList } destructor TgtObjectList.Destroy; begin inherited Destroy; Clear; end; procedure TgtObjectList.Clear; begin if FCount <> 0 then begin FCount := 0; SetCapacity(0); end; end; function TgtObjectList.Add(ANo: Integer; AObject: TObject): Integer; begin Result := FCount; InsertItem(FCount, ANo, AObject); end; procedure TgtObjectList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Exception.CreateFmt(SListIndexOutOfBounds, [Index]); FList^[Index].FObject.Free; Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TStringItem)); end; function TgtObjectList.GetObject(Index: Integer): TObject; begin if (Index < 0) or (Index >= FCount) then Exception.CreateFmt(SListIndexOutOfBounds, [Index]); Result := FList^[Index].FObject; end; function TgtObjectList.GetCapacity: Integer; begin Result := FCapacity; end; function TgtObjectList.GetCount: Integer; begin Result := FCount; end; procedure TgtObjectList.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; function TgtObjectList.IndexOf(const ObjectNo: Integer): Integer; begin for Result := 0 to GetCount - 1 do if (FList^[Result].FInteger = ObjectNo) then Exit; Result := -1; end; procedure TgtObjectList.InsertItem(Index: Integer; ANo: Integer; AObject: TObject); begin if ANo < 0 then raise EInvalidID.CreateFmt(SInvalidID, [ANo]); if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TgtObjectItem)); with FList^[Index] do begin FObject := AObject; FInteger := ANo; end; Inc(FCount); end; procedure TgtObjectList.SetCapacity(NewCapacity: Integer); begin ReallocMem(FList, NewCapacity * SizeOf(TgtObjectItem)); FCapacity := NewCapacity; end; procedure TgtObjectList.Add(AObjectList: TgtObjectList); var LI: Integer; LIndex: Integer; begin SetCapacity(FCount + AObjectList.Count); for LI := 0 to AObjectList.Count - 1 do begin LIndex := IndexOf(AObjectList.Items[LI].FInteger); if LIndex = -1 then begin FList^[FCount] := AObjectList.Items[LI]; Inc(FCount); end else AObjectList.Items[LI].FObject.Free; end; end; function TgtObjectList.GetItem(Index: Integer): TgtObjectItem; begin Result := FList^[Index]; end; { TWideStrings implementation } constructor TWideStrings.Create; begin FWideStringList := TList.Create; end; destructor TWideStrings.Destroy; var Index: Integer; PWStr: ^TWString; begin { TODO - BB Investigate : Could call Clear here } for Index := 0 to FWideStringList.Count - 1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then Dispose(PWStr); end; FWideStringList.Free; inherited Destroy; end; function TWideStrings.Delete(Index: Integer): WideString; begin if ((Index >= 0) and (Index < FWideStringList.Count)) then begin FWideStringList.Delete(Index); end; end; function TWideStrings.Get(Index: Integer): WideString; var PWStr: ^TWString; begin Result := ''; if ((Index >= 0) and (Index < FWideStringList.Count)) then begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then Result := PWStr^.WString; end; end; procedure TWideStrings.Put(Index: Integer; const S: WideString); var PWStr: ^TWString; begin if ((Index < 0) or (Index > FWideStringList.Count)) then Exit; // raise Exception.Create(SWideStringOutofBounds); if Index < FWideStringList.Count then begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then PWStr.WString := S; end else Add(S); end; function TWideStrings.Add(const S: WideString): Integer; var PWStr: ^TWString; begin New(PWStr); PWStr^.WString := S; Result := FWideStringList.Add(PWStr); end; function TWideStrings.IndexOfIgnoreCase(const S: WideString): Integer; var Index: Integer; PWStr: ^TWString; begin Result := -1; for Index := 0 to FWideStringList.Count - 1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then begin if SameText(S, PWStr^.WString) then begin Result := Index; break; end; end; end; end; function TWideStrings.IndexOf(const S: WideString): Integer; var Index: Integer; PWStr: ^TWString; begin Result := -1; for Index := 0 to FWideStringList.Count - 1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then begin if S = PWStr^.WString then begin Result := Index; break; end; end; end; end; function TWideStrings.Count: Integer; begin Result := FWideStringList.Count; end; procedure TWideStrings.Clear; var Index: Integer; PWStr: ^TWString; begin for Index := 0 to FWideStringList.Count - 1 do begin PWStr := FWideStringList.Items[Index]; if PWStr <> nil then Dispose(PWStr); end; FWideStringList.Clear; end; procedure TWideStrings.Insert(Index: Integer; const S: WideString); var PWStr: ^TWString; LIdx: Integer; begin if ((Index < 0) or (Index > FWideStringList.Count)) then Exit; // raise Exception.Create(SWideStringOutofBounds); if Index < FWideStringList.Count then begin Add(S); for LIdx := Count - 1 downto (Index + 1) do begin PWStr := FWideStringList.Items[LIdx]; if PWStr <> nil then PWStr.WString := Strings[LIdx - 1]; end; PWStr := FWideStringList.Items[Index]; if PWStr <> nil then PWStr.WString := S; end else Add(S); end; procedure TWideStrings.LoadFromFile(const FileName: WideString); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TWideStrings.LoadFromStream(Stream: TStream); var Size: Integer; S: WideString; begin Size := Stream.Size - Stream.Position; SetString(S, nil, Size div SizeOf(WideChar)); Stream.Read(Pointer(S)^, Size); SetTextStr(S); end; procedure TWideStrings.SetTextStr(const Value: WideString); var P, Start: PwideChar; S: WideString; begin Clear; P := Pointer(Value); if P <> nil then while P^ <> #0 do begin Start := P; while not InOpSet(P^, [AnsiChar(#0), AnsiChar(#10), AnsiChar(#13)]) do Inc(P); SetString(S, Start, P - Start); Add(S); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; end; end.
unit ScrollBackTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Daily/ScrollBackTest.pas" // Начат: 25.05.2010 18:29 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TScrollBackTest // // Тест скроллирования документа в обратную сторону // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses PrimScrollTest, PrimTextLoad_Form ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TScrollBackTest = {abstract} class(TPrimScrollTest) {* Тест скроллирования документа в обратную сторону } protected // realized methods procedure DoVisit(aForm: TPrimTextLoadForm); override; {* Обработать текст } protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TScrollBackTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TScrollBackTest procedure TScrollBackTest.DoVisit(aForm: TPrimTextLoadForm); //#UC START# *4BE419AF0217_4BFBDEA300F4_var* //#UC END# *4BE419AF0217_4BFBDEA300F4_var* begin //#UC START# *4BE419AF0217_4BFBDEA300F4_impl* ScrollBack(aForm, ''); //#UC END# *4BE419AF0217_4BFBDEA300F4_impl* end;//TScrollBackTest.DoVisit function TScrollBackTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TScrollBackTest.GetFolder function TScrollBackTest.GetModelElementGUID: AnsiString; {-} begin Result := '4BFBDEA300F4'; end;//TScrollBackTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit AutoMapper.MappingExpression; interface uses System.Rtti ; type TMapExpression<TSource, TDestination> = reference to procedure (const source: TSource; out dest: TDestination); TExpressionType = (None, ObjectToObject, ObjectToRecord, RecordToObject, RecordToRecord); TMapExpCollections = class public class procedure MapExpObjectToObject<TSource, TDestination>(const source: TSource; out dest: TDestination); static; class procedure MapExpObjectToRecord<TSource, TDestination>(const source: TSource; out dest: TDestination); static; class procedure MapExpRecordToObject<TSource, TDestination>(const source: TSource; out dest: TDestination); static; class procedure MapExpRecordToRecord<TSource, TDestination>(const source: TSource; out dest: TDestination); static; class function GetExpressionType<TSource, TDestination>: TExpressionType; static; end; implementation uses System.TypInfo , System.SysUtils ; { TMapExpCollections } class function TMapExpCollections.GetExpressionType<TSource, TDestination>: TExpressionType; var Ctx: TRttiContext; SourceType, DestType: TRttiType; begin Ctx := TRttiContext.Create; SourceType := Ctx.GetType(TypeInfo(TSource)); DestType := Ctx.GetType(TypeInfo(TDestination)); if SourceType.IsInstance and DestType.IsInstance then Exit(TExpressionType.ObjectToObject); if SourceType.IsInstance and DestType.IsRecord then Exit(TExpressionType.ObjectToRecord); if SourceType.IsRecord and DestType.IsInstance then Exit(TExpressionType.RecordToObject); if SourceType.IsRecord and DestType.IsRecord then Exit(TExpressionType.RecordToRecord); result := TExpressionType.None; end; class procedure TMapExpCollections.MapExpObjectToObject<TSource, TDestination>( const source: TSource; out dest: TDestination); var LSource : TObject absolute source; LDest : TObject absolute dest; Ctx: TRttiContext; DestRttiType, SourceRttiType, PropType: TRttiType; DestRttiField, SourceRttiField: TRttiField; DestRttiProp, SourceRttiProp: TRttiProperty; BufValue, SourceValue, DestValue: TValue; isFound: boolean; begin Ctx := TRttiContext.Create; SourceRttiType := Ctx.GetType(TypeInfo(TSource)); DestRttiType := Ctx.GetType(TypeInfo(TDestination)); for DestRttiField in DestRttiType.GetFields do begin // DestField <- SourceField isFound := false; for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_', '')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(LSource); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(LDest, BufValue); isFound := true; break; end; end end; if isFound then continue; // DestFiled <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.IsReadable) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(LSource); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(LDest, BufValue); break; end; end; end; end; for DestRttiProp in DestRttiType.GetProperties do begin isFound := false; // DestProp <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (SourceRttiProp.IsReadable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(LSource); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(LDest, BufValue); isFound := true; break; end; end end; if isFound then Continue; // DestProp <- SourceField for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(LSource); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(LDest, BufValue); break; end; end; end; end; Ctx.Free; end; class procedure TMapExpCollections.MapExpObjectToRecord<TSource, TDestination>( const source: TSource; out dest: TDestination); var LSource: TObject absolute source; Ctx: TRttiContext; DestRttiType, SourceRttiType, PropType: TRttiType; DestRttiField, SourceRttiField: TRttiField; DestRttiProp, SourceRttiProp: TRttiProperty; BufValue, SourceValue, DestValue: TValue; isFound: boolean; begin Ctx := TRttiContext.Create; SourceRttiType := Ctx.GetType(TypeInfo(TSource)); DestRttiType := Ctx.GetType(TypeInfo(TDestination)); for DestRttiField in DestRttiType.GetFields do begin // DestField <- SourceField isFound := false; for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_', '')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(LSource); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(@dest, BufValue); isFound := true; break; end; end end; if isFound then continue; // DestFiled <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.IsReadable) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(LSource); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(@dest, BufValue); break; end; end; end; end; for DestRttiProp in DestRttiType.GetProperties do begin isFound := false; // DestProp <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (SourceRttiProp.IsReadable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(LSource); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(@dest, BufValue); isFound := true; break; end; end end; if isFound then Continue; // DestProp <- SourceField for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(LSource); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(@dest, BufValue); break; end; end; end; end; Ctx.Free; end; class procedure TMapExpCollections.MapExpRecordToObject<TSource, TDestination>( const source: TSource; out dest: TDestination); var LDest: TObject absolute dest; Ctx: TRttiContext; DestRttiType, SourceRttiType, PropType: TRttiType; DestRttiField, SourceRttiField: TRttiField; DestRttiProp, SourceRttiProp: TRttiProperty; BufValue, SourceValue, DestValue: TValue; isFound: boolean; begin Ctx := TRttiContext.Create; SourceRttiType := Ctx.GetType(TypeInfo(TSource)); DestRttiType := Ctx.GetType(TypeInfo(TDestination)); for DestRttiField in DestRttiType.GetFields do begin // DestField <- SourceField isFound := false; for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_', '')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(@source); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(LDest, BufValue); isFound := true; break; end; end end; if isFound then continue; // DestFiled <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.IsReadable) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(@source); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(LDest, BufValue); break; end; end; end; end; for DestRttiProp in DestRttiType.GetProperties do begin isFound := false; // DestProp <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (SourceRttiProp.IsReadable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(@source); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(LDest, BufValue); isFound := true; break; end; end end; if isFound then Continue; // DestProp <- SourceField for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(@source); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(LDest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(LDest, BufValue); break; end; end; end; end; Ctx.Free; end; class procedure TMapExpCollections.MapExpRecordToRecord<TSource, TDestination>( const source: TSource; out dest: TDestination); var Ctx: TRttiContext; DestRttiType, SourceRttiType, PropType: TRttiType; DestRttiField, SourceRttiField: TRttiField; DestRttiProp, SourceRttiProp: TRttiProperty; BufValue, SourceValue, DestValue: TValue; isFound: boolean; begin Ctx := TRttiContext.Create; SourceRttiType := Ctx.GetType(TypeInfo(TSource)); DestRttiType := Ctx.GetType(TypeInfo(TDestination)); for DestRttiField in DestRttiType.GetFields do begin // DestField <- SourceField isFound := false; for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_', '')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(@source); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(@dest, BufValue); isFound := true; break; end; end end; if isFound then continue; // DestFiled <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiField.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.IsReadable) and (DestRttiField.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(@source); DestValue := DestRttiType.GetField(DestRttiField.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetField(DestRttiField.Name).SetValue(@dest, BufValue); break; end; end; end; end; for DestRttiProp in DestRttiType.GetProperties do begin isFound := false; // DestProp <- SourceProp for SourceRttiProp in SourceRttiType.GetProperties do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiProp.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (SourceRttiProp.IsReadable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiProp.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetProperty(SourceRttiProp.Name).GetValue(@source); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(@dest, BufValue); isFound := true; break; end; end end; if isFound then Continue; // DestProp <- SourceField for SourceRttiField in SourceRttiType.GetFields do begin if (DestRttiProp.Visibility in [mvPublic, mvPublished]) and (SourceRttiField.Visibility in [mvPublic, mvPublished]) and (DestRttiProp.IsWritable) and (DestRttiProp.Name.ToLower.Replace('_','') = SourceRttiField.Name.ToLower.Replace('_','')) then begin SourceValue := SourceRttiType.GetField(SourceRttiField.Name).GetValue(@source); DestValue := DestRttiType.GetProperty(DestRttiProp.Name).GetValue(@dest); if SourceValue.TryCast(DestValue.TypeInfo, BufValue) then begin DestRttiType.GetProperty(DestRttiProp.Name).SetValue(@dest, BufValue); break; end; end; end; end; Ctx.Free; end; end.
unit StockWeightDataAccess; interface uses define_dealItem, BaseDataSet, QuickList_int, define_price, define_datasrc, define_stock_quotes; type TStockWeightData = record DealItem : PRT_DealItem; IsDataChangedStatus: Byte; WeightData : TALIntegerList; DataSource : TDealDataSource; end; TStockWeightDataAccess = class(TBaseDataSetAccess) protected fStockWeightData: TStockWeightData; procedure SetStockItem(AStockItem: PRT_DealItem); function GetRecordItem(AIndex: integer): Pointer; override; function GetRecordCount: Integer; override; public constructor Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource); destructor Destroy; override; function FindRecord(ADate: Integer): PRT_Weight; function CheckOutRecord(ADate: Word): PRT_Weight; function DoGetRecords: integer; procedure Sort; override; procedure Clear; override; property StockItem: PRT_DealItem read fStockWeightData.DealItem write SetStockItem; property DataSource: TDealDataSource read fStockWeightData.DataSource write fStockWeightData.DataSource; end; implementation uses QuickSortList, SysUtils; { TStockWeightDataAccess } constructor TStockWeightDataAccess.Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource); begin //inherited; FillChar(fStockWeightData, SizeOf(fStockWeightData), 0); fStockWeightData.DealItem := AStockItem; fStockWeightData.WeightData := TALIntegerList.Create; fStockWeightData.WeightData.Clear; fStockWeightData.WeightData.Duplicates := QuickSortList.lstDupIgnore; fStockWeightData.DataSource := ADataSrc; end; destructor TStockWeightDataAccess.Destroy; begin Clear; FreeAndNil(fStockWeightData.WeightData); inherited; end; procedure TStockWeightDataAccess.Clear; var i: integer; tmpWeight: PRT_Weight; begin if nil <> fStockWeightData.WeightData then begin for i := fStockWeightData.WeightData.Count - 1 downto 0 do begin tmpWeight := PRT_Weight(fStockWeightData.WeightData.Objects[i]); FreeMem(tmpWeight); end; fStockWeightData.WeightData.Clear; end; end; procedure TStockWeightDataAccess.SetStockItem(AStockItem: PRT_DealItem); begin if nil <> AStockItem then begin if fStockWeightData.DealItem <> AStockItem then begin end; end; fStockWeightData.DealItem := AStockItem; if nil <> fStockWeightData.DealItem then begin end; end; function TStockWeightDataAccess.GetRecordCount: Integer; begin Result := fStockWeightData.WeightData.Count; end; function TStockWeightDataAccess.GetRecordItem(AIndex: integer): Pointer; begin Result := fStockWeightData.WeightData.Objects[AIndex]; end; procedure TStockWeightDataAccess.Sort; begin fStockWeightData.WeightData.Sort; end; function TStockWeightDataAccess.CheckOutRecord(ADate: Word): PRT_Weight; begin Result := nil; if ADate < 1 then exit; Result := FindRecord(ADate); if nil = Result then begin Result := System.New(PRT_Weight); FillChar(Result^, SizeOf(TRT_Weight), 0); Result.StartDate := ADate; fStockWeightData.WeightData.AddObject(ADate, TObject(Result)); end; end; function TStockWeightDataAccess.FindRecord(ADate: Integer): PRT_Weight; var tmpPos: integer; begin Result := nil; tmpPos := fStockWeightData.WeightData.IndexOf(ADate); if 0 <= tmpPos then Result := PRT_Weight(fStockWeightData.WeightData.Objects[tmpPos]); end; function TStockWeightDataAccess.DoGetRecords: integer; begin Result := Self.RecordCount; end; end.
unit glr_particles2d; {$i defines.inc} interface uses glr_render, glr_render2d, glr_utils, glr_math; type { TglrParticle2D } TglrParticle2D = class (TglrSprite) T: Single; LifeTime: Single; Velocity: TglrVec2f; procedure Reset(); end; TglrParticles2D = TglrObjectList<TglrParticle2D>; TglrUpdateCallback = procedure(const dt: Double) of object; { TglrCustomParticleEmitter2D } TglrCustomParticleEmitter2D = class protected fBatch: TglrSpriteBatch; fMaterial: TglrMaterial; fTextureRegion: PglrTextureRegion; fActiveParticles: Integer; public Visible, Enabled: Boolean; Duration, Time: Single; Particles: TglrParticles2D; OnUpdate: TglrUpdateCallback; constructor Create(aBatch: TglrSpriteBatch; aMaterial: TglrMaterial; aTextureRegion: PglrTextureRegion = nil); virtual; destructor Destroy(); override; function GetNewParticle(): TglrParticle2D; procedure Update(const dt: Double); procedure RenderSelf(); property ActiveParticlesCount: Integer read fActiveParticles; end; //Range of byte is 0..100 (means percent of emitter animation duration) TglrSingleDic = TglrDictionary<Byte, Single>; TglrIntDic = TglrDictionary<Byte, Integer>; TglrVec2fDic = TglrDictionary<Byte, TglrVec2f>; TglrVec4fDic = TglrDictionary<Byte, TglrVec4f>; { TglrParticleEmitter2D } TglrParticleEmitter2D = class protected fBatch: TglrSpriteBatch; fMaterial: TglrMaterial; fTextureRegion: PglrTextureRegion; fParticles: TglrParticles2D; function GetFreeParticleIndex(): Integer; public //Dynamics OriginBoxMinMax: TglrVec4fDic; VelocityMinMax: TglrVec4fDic; VelocityDispersionAngle: TglrSingleDic; VelocityAngularMinMax: TglrVec2fDic; Color: TglrVec4fDic; ParticlesPerSecond: TglrIntDic; LifetimeMinMax: TglrVec2fDic; ParticleSizeMinMax: TglrVec4fDic; //Params Duration, Time: Single; constructor Create(aBatch: TglrSpriteBatch; aMaterial: TglrMaterial; aTextureRegion: PglrTextureRegion = nil); virtual; overload; constructor Create(aBatch: TglrSpriteBatch; aMaterial: TglrMaterial; const aStream: TglrStream; aTextureRegion: PglrTextureRegion = nil; aFreeStreamOnFinish: Boolean = True); virtual; overload; destructor Destroy(); override; function SaveToStream(): TglrStream; procedure Update(const dt: Double); end; implementation { TglrParticle2D } procedure TglrParticle2D.Reset; begin T := 0; Velocity.Reset(); LifeTime := 0.0; fRot := 0; Visible := True; end; { TglrCustomParticleEmitter2D } constructor TglrCustomParticleEmitter2D.Create(aBatch: TglrSpriteBatch; aMaterial: TglrMaterial; aTextureRegion: PglrTextureRegion); var s: TglrParticle2D; i: Integer; begin inherited Create(); fBatch := aBatch; fMaterial := aMaterial; fTextureRegion := aTextureRegion; Particles := TglrParticles2D.Create(128); for i := 0 to Particles.Count - 1 do begin s := TglrParticle2D.Create(); if fTextureRegion <> nil then s.SetTextureRegion(fTextureRegion) else begin s.Width := fMaterial.Textures[0].Texture.Width; s.Height := fMaterial.Textures[0].Texture.Height; end; s.Reset(); s.Visible := False; Particles.Add(s); end; Duration := 1.0; Time := 0; Enabled := True; Visible := True; end; destructor TglrCustomParticleEmitter2D.Destroy; begin Particles.Free(True); inherited Destroy; end; function TglrCustomParticleEmitter2D.GetNewParticle: TglrParticle2D; var i: Integer; p: TglrParticle2D; begin fActiveParticles += 1; for i := 0 to Particles.Count - 1 do if not Particles[i].Visible then begin Particles[i].Reset(); if (fTextureRegion <> nil) then Particles[i].SetTextureRegion(fTextureRegion); Particles[i].SetVerticesColor(Vec4f(1, 1, 1, 1)); Exit(Particles[i]); end; p := TglrParticle2D.Create(); p.Reset(); if fTextureRegion <> nil then p.SetTextureRegion(fTextureRegion); Particles.Add(p); Exit(p); end; procedure TglrCustomParticleEmitter2D.Update(const dt: Double); var i: Integer; begin if not Visible then Exit(); Time += dt; for i := 0 to Particles.Count - 1 do if Particles[i].Visible then with Particles[i] do begin T := T + dt; if T >= LifeTime then begin Visible := False; fActiveParticles -= 1; end else Position += Vec3f(Velocity * dt, 0); end; if Assigned(OnUpdate) then OnUpdate(dt); end; procedure TglrCustomParticleEmitter2D.RenderSelf; var i: Integer; begin fMaterial.Bind(); fBatch.Start(); for i := 0 to Particles.Count - 1 do fBatch.Draw(Particles[i]); fBatch.Finish(); end; { TglrParticleEmitter2D } function TglrParticleEmitter2D.GetFreeParticleIndex: Integer; var i: Integer; p: TglrParticle2D; begin for i := 0 to fParticles.Count - 1 do if not fParticles[i].Visible then Exit(i); p := TglrParticle2D.Create(); if fTextureRegion <> nil then p.SetTextureRegion(fTextureRegion); p.Velocity.Reset(); p.T := 0.0; p.Visible := False; p.LifeTime := 0; Exit(fParticles.Add(p)); end; constructor TglrParticleEmitter2D.Create(aBatch: TglrSpriteBatch; aMaterial: TglrMaterial; aTextureRegion: PglrTextureRegion); var s: TglrParticle2D; i: Integer; begin inherited Create(); fBatch := aBatch; fMaterial := aMaterial; fTextureRegion := aTextureRegion; fParticles := TglrParticles2D.Create(128); for i := 0 to 127 do begin s := TglrParticle2D.Create(); if fTextureRegion <> nil then s.SetTextureRegion(fTextureRegion); s.Velocity.Reset(); s.T := 0.0; s.Visible := False; s.LifeTime := 0; fParticles.Add(s); end; Duration := 1.0; Time := 0; OriginBoxMinMax := TglrVec4fDic.Create (100); VelocityMinMax := TglrVec4fDic.Create (100); VelocityDispersionAngle := TglrSingleDic.Create(100); VelocityAngularMinMax := TglrVec2fDic.Create(100); Color := TglrVec4fDic.Create (100); ParticlesPerSecond := TglrIntDic.Create (100); LifetimeMinMax := TglrVec2fDic.Create (100); ParticleSizeMinMax := TglrVec4fDic.Create (100); end; constructor TglrParticleEmitter2D.Create(aBatch: TglrSpriteBatch; aMaterial: TglrMaterial; const aStream: TglrStream; aTextureRegion: PglrTextureRegion; aFreeStreamOnFinish: Boolean); begin Create(aBatch, aMaterial, aTextureRegion); end; destructor TglrParticleEmitter2D.Destroy; begin fParticles.Free(True); OriginBoxMinMax.Free(); VelocityMinMax.Free(); VelocityDispersionAngle.Free(); VelocityAngularMinMax.Free(); Color.Free(); ParticlesPerSecond.Free(); LifetimeMinMax.Free(); ParticleSizeMinMax.Free(); inherited Destroy; end; function TglrParticleEmitter2D.SaveToStream: TglrStream; begin Log.Write(lCritical, 'ParticleEmitter2D: SaveToStream is not implemented'); end; procedure TglrParticleEmitter2D.Update(const dt: Double); var i: Integer; begin Time += dt; for i := 0 to fParticles.Count - 1 do if fParticles[i].Visible then with fParticles[i] do begin Position += Vec3f(Velocity * dt, 0); T := T + dt; if T >= LifeTime then Visible := False else begin //todo: Update other stuff end; end; //todo: add new particles end; end.
////// // Intro // Endian specific access types // (c) 2011..2017 by Jasper L. Neumann // www.sirrida.de / programming.sirrida.de // E-Mail: info@sirrida.de // Granted to the public domain // First version: 2013-02-14 // Last change: 2013-02-14 // Compile with // Delphi: dcc32 /cc calcperm.pas // Free Pascal: fpc -Mtp calcperm.pas // Here are as an example two classes featuring protected access to fields // of exchange records with an explicit endianess. // These exchange records are principally needed whenever you want to // communicate with other programs or with devices. {$i general.pas } (*$a1 *) // Force byte packed structures. // Pragma push/pop is unfortunately not generally supported, // so we have this global. function bswap_32(q:t_32u):t_32u; begin q := ((q and $00ff00ff) shl 8) or ((q shr 8) and $00ff00ff); bswap_32 := (q shl 16) or (q shr 16); end; type tr_intel_32u = object // Little endian, Intel byte order, least significant byte first private mem: t_32u; public function value:t_32u; procedure assign(q:t_32u); end; function tr_intel_32u.value:t_32u; begin (*$ifdef ENDIAN_BIG *) value := bswap_32(mem); (*$else *) value := mem; (*$endif *) end; procedure tr_intel_32u.assign(q:t_32u); begin (*$ifdef ENDIAN_BIG *) mem := bswap_32(q); (*$else *) mem := q; (*$endif *) end; type tr_motorola_32u = object // Big endian, Motorola byte order, most significant byte first private mem: t_32u; public function value:t_32u; procedure assign(q:t_32u); end; function tr_motorola_32u.value:t_32u; begin (*$ifdef ENDIAN_BIG *) value := mem; (*$else *) value := bswap_32(mem); (*$endif *) end; procedure tr_motorola_32u.assign(q:t_32u); begin (*$ifdef ENDIAN_BIG *) mem := q; (*$else *) mem := bswap_32(q); (*$endif *) end; type tr_exchange = packed record // An example of an exchange record x: tr_intel_32u; y: tr_motorola_32u; end; ////// // Main program var v: tr_exchange; r: t_32u; loop: t_longint; begin if NOT init_general then begin HALT(1); end; writeln('Testing endian access records (in Pascal)...'); if sizeof(tr_exchange)<>8 then begin writeln('tr_exchange defective'); HALT(1); end; if bswap_32($12345678)<>$78563412 then begin writeln('bswap_32 defective'); HALT(1); end; if bswap_32($87654321)<>$21436587 then begin writeln('bswap_32 defective'); HALT(1); end; r:=0; for loop:=1 to 10000 do begin r:=r*256+t_32u(random_int(256)); v.x.assign(r); if v.x.value<>r then begin writeln('tr_intel_32u defective'); HALT(1); end; v.y.assign(r); if v.y.value<>r then begin writeln('tr_motorola_32u defective'); HALT(1); end; end; writeln('OK'); end. // eof.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_ALStub * Implements a OpenAL stub for when the library is not installed on the user computer. *********************************************************************************************************************** } Unit TERRA_ALstub; {$I terra.inc} Interface Procedure LoadALstubs; Implementation Uses TERRA_AL{$IFDEF WINDOWS},Windows{$ENDIF}; Var BufferCount:Integer=0; SourcesCount:Integer=0; Procedure alGenBuffers(n:Cardinal; buffers: PCardinal); CDecl; Begin While (N>0) Do Begin Inc(BufferCount); Buffers^ := BufferCount; Inc(Buffers); Dec(N); End; End; Procedure alDeleteBuffers(n:Cardinal; buffers: PCardinal); CDecl; Begin End; Procedure alBufferData(buffer:Cardinal; format:Integer; data: Pointer; size, freq:Cardinal); CDecl; Begin End; Procedure alGenSources(n:Cardinal; sources: PCardinal); CDecl; Begin While (N>0) Do Begin Inc(SourcesCount); Sources^ := SourcesCount; Inc(Sources); Dec(N); End; End; Procedure alDeleteSources(n:Cardinal; sources: PCardinal); CDecl; Begin End; Procedure alSourcei(source: Cardinal; param:Integer; value: Integer); CDecl; Begin End; Procedure alSourcef(source: Cardinal; param:Integer; value: Single); CDecl; Begin End; Procedure alSourcefv(source: Cardinal; param:Integer; values: PSingle); CDecl; Begin End; Procedure alGetSourcei(source:Cardinal; param:Integer; value: PInteger); CDecl; Begin Value^ := 0; End; Procedure alListenerfv(param:Integer; values: PSingle); CDecl; Begin End; Procedure alSourceQueueBuffers(source:Cardinal; n:Cardinal; buffers: PCardinal); CDecl; Begin End; Procedure alSourceUnqueueBuffers(source:Cardinal; n:Cardinal; buffers: PCardinal); CDecl; Begin End; Procedure alSourcePlay(source:Cardinal); CDecl; Begin End; Procedure alSourcePause(source:Cardinal); CDecl; Begin End; Procedure alSourceStop(source:Cardinal); CDecl; Begin End; Function alcGetString(device: PALCdevice; param: Integer): PAnsiChar; CDecl; Begin Result := Nil; End; Function alcOpenDevice(deviceName: PAnsiChar): PALCdevice; CDecl; Begin Result := Nil; End; Procedure alcCloseDevice(device: PALCdevice); CDecl; Begin End; Function alcGetContextsDevice(context: PALCcontext): PALCdevice; CDecl; Begin Result := Nil; End; Function alcCreateContext(device: PALCdevice; attrlist: PInteger): PALCcontext; CDecl; Begin Result := Nil; End; Function alcMakeContextCurrent(context: PALCcontext): Integer; CDecl; Begin Result := 0; End; Function alcGetCurrentContext: PALCcontext; CDecl; Begin Result := Nil; End; Procedure alcDestroyContext(context: PALCcontext); CDecl; Begin End; Function alGetError:Integer; CDecl; Begin Result := AL_NO_ERROR; End; Procedure alGenEffects(n:Integer; effects:PCardinal); CDecl; Begin End; Procedure alDeleteEffects(N:Integer; effects:PCardinal); CDecl; Begin End; Function alIsEffect(effect:Cardinal):Boolean; CDecl; Begin Result := True; End; Procedure alEffecti(effect:Cardinal; param:Cardinal; iValue:Integer); CDecl; Begin End; Procedure alEffectiv(effect:Cardinal; param:Cardinal; piValues:Integer); CDecl; Begin End; Procedure alEffectf(effect:Cardinal; param:Cardinal; flValue:Single); CDecl; Begin End; Procedure alEffectfv(effect:Cardinal; param:Cardinal; pflValues:PSingle); CDecl; Begin End; Procedure alGetEffecti(effect:Cardinal; param:Cardinal; piValue:PInteger); CDecl; Begin End; Procedure alGetEffectiv(effect:Cardinal; param:Cardinal; piValues:PInteger); CDecl; Begin End; Procedure alGetEffectf(effect:Cardinal; param:Cardinal; pflValue:PSingle); CDecl; Begin End; Procedure alGetEffectfv(effect:Cardinal; param:Cardinal; pflValues:PSingle); CDecl; Begin End; Procedure alGenAuxiliaryEffectSlots(n:Integer; effectslots:PCardinal); CDecl; Begin End; Procedure alDeleteAuxiliaryEffectSlots(N:Integer; effectslots:PCardinal); CDecl; Begin End; Procedure alIsAuxiliaryEffectSlot(effectslot:Cardinal); CDecl; Begin End; Procedure alAuxiliaryEffectSloti(effectslot:Cardinal; param:Cardinal; iValue:Integer); CDecl; Begin End; Procedure alAuxiliaryEffectSlotiv(effectslot:Cardinal; param:Cardinal; piValues:PInteger); CDecl; Begin End; Procedure alAuxiliaryEffectSlotf(effectslot:Cardinal; param:Cardinal; flValue:Single); CDecl; Begin End; Procedure alAuxiliaryEffectSlotfv(effectslot:Cardinal; param:Cardinal; pflValues:PSingle); CDecl; Begin End; Procedure alGetAuxiliaryEffectSloti(effectslot:Cardinal; param:Cardinal; piValue:PInteger); CDecl; Begin End; Procedure alGetAuxiliaryEffectSlotiv(effectslot:Cardinal; param:Cardinal; piValues:PInteger); CDecl; Begin End; Procedure alGetAuxiliaryEffectSlotf(effectslot:Cardinal; param:Cardinal; pflValue:PSingle); CDecl; Begin End; Procedure alGetAuxiliaryEffectSlotfv(effectslot:Cardinal; param:Cardinal; pflValues:PSingle); CDecl; Begin End; Procedure alSource3i(source: Cardinal; param:Integer; v1, v2, v3: Integer); CDecl; Begin End; Procedure LoadALstubs; Begin TERRA_AL.alGenBuffers := alGenBuffers; TERRA_AL.alDeleteBuffers := alDeleteBuffers; TERRA_AL.alBufferData := alBufferData; TERRA_AL.alGenSources := alGenSources; TERRA_AL.alDeleteSources := alDeleteSources; TERRA_AL.alSourcei := alSourcei; TERRA_AL.alSourcef := alSourcef; TERRA_AL.alSourcefv := alSourcefv; TERRA_AL.alGetSourcei := alGetSourcei; TERRA_AL.alListenerfv := alListenerfv; TERRA_AL.alSourceQueueBuffers := alSourceQueueBuffers; TERRA_AL.alSourceUnqueueBuffers := alSourceUnqueueBuffers; TERRA_AL.alSourcePlay := alSourcePlay; TERRA_AL.alSourcePause := alSourcePause; TERRA_AL.alSourceStop := alSourceStop; TERRA_AL.alcGetString := alcGetString; TERRA_AL.alcOpenDevice := alcOpenDevice; TERRA_AL.alcCloseDevice := alcCloseDevice; TERRA_AL.alcGetContextsDevice := alcGetContextsDevice; TERRA_AL.alcCreateContext := alcCreateContext; TERRA_AL.alcMakeContextCurrent := alcMakeContextCurrent; TERRA_AL.alcGetCurrentContext := alcGetCurrentContext; TERRA_AL.alcDestroyContext := alcDestroyContext; TERRA_AL.alGetError := alGetError; TERRA_AL.alGenEffects := alGenEffects; TERRA_AL.alDeleteEffects := alDeleteEffects; TERRA_AL.alIsEffect := alIsEffect; TERRA_AL.alEffecti := alEffecti; TERRA_AL.alEffectiv := alEffectiv; TERRA_AL.alEffectf := alEffectf; TERRA_AL.alEffectfv := alEffectfv; TERRA_AL.alGetEffecti := alGetEffecti; TERRA_AL.alGetEffectiv := alGetEffectiv; TERRA_AL.alGetEffectf := alGetEffectf; TERRA_AL.alGetEffectfv := alGetEffectfv; TERRA_AL.alGenAuxiliaryEffectSlots := alGenAuxiliaryEffectSlots; TERRA_AL.alDeleteAuxiliaryEffectSlots := alDeleteAuxiliaryEffectSlots; TERRA_AL.alIsAuxiliaryEffectSlot := alIsAuxiliaryEffectSlot; TERRA_AL.alAuxiliaryEffectSloti := alAuxiliaryEffectSloti; TERRA_AL.alAuxiliaryEffectSlotiv := alAuxiliaryEffectSlotiv; TERRA_AL.alAuxiliaryEffectSlotf := alAuxiliaryEffectSlotf; TERRA_AL.alAuxiliaryEffectSlotfv := alAuxiliaryEffectSlotfv; TERRA_AL.alGetAuxiliaryEffectSloti := alGetAuxiliaryEffectSloti; TERRA_AL.alGetAuxiliaryEffectSlotiv := alGetAuxiliaryEffectSlotiv; TERRA_AL.alGetAuxiliaryEffectSlotf := alGetAuxiliaryEffectSlotf; TERRA_AL.alGetAuxiliaryEffectSlotfv := alGetAuxiliaryEffectSlotfv; TERRA_AL.alSource3i := alSource3i; End; End.
unit SearchRoutesForSpecifiedTextUnit; interface uses SysUtils, BaseExampleUnit, DataObjectUnit; type TSearchRoutesForSpecifiedText = class(TBaseExample) public function Execute(Text: String): TDataObjectRouteList; end; implementation function TSearchRoutesForSpecifiedText.Execute(Text: String): TDataObjectRouteList; var ErrorString: String; Route: TDataObjectRoute; begin Result := Route4MeManager.Route.GetList(Text, ErrorString); WriteLn(''); if (Result <> nil) and (Result.Count > 0) then begin WriteLn(Format('SearchRoutesForSpecifiedText executed successfully, %d routes returned', [Result.Count])); WriteLn(''); for Route in Result do WriteLn(Format('RouteId: %s', [Route.RouteId])); end else WriteLn(Format('SearchRoutesForSpecifiedText error "%s"', [ErrorString])); end; end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcTimers.pas } { File version: 5.20 } { Description: Timer functions } { } { Copyright: Copyright (c) 1999-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 1999/11/10 0.01 Initial version. } { 2005/08/19 4.02 Compilable with FreePascal 2.0.1 } { 2005/08/26 4.03 Improvements to timer functions. } { 2005/08/27 4.04 Revised for Fundamentals 4. } { 2007/06/08 4.05 Compilable with FreePascal 2.04 Win32 i386 } { 2009/10/09 4.06 Compilable with Delphi 2009 Win32/.NET. } { 2010/06/27 4.07 Compilable with FreePascal 2.4.0 OSX x86-64 } { 2011/05/04 4.08 Split from cDateTime unit. } { 2015/01/16 4.09 Added GetTickAccuracy. } { 2015/01/17 5.10 Revised for Fundamentals 5. } { 2018/07/17 5.11 Word32 changes. } { 2019/04/02 5.12 Compilable with Delphi 10.2 Linux64. } { 2019/06/08 5.13 Use CLOCK_MONOTONIC on Delphi Posix. } { 2019/06/08 5.14 Add GetTick64. } { 2019/10/06 5.15 MicroTick functions. } { 2020/01/28 5.16 MilliTick and MicroDateTime functions. } { 2020/01/31 5.17 Use DateTime implementations on iOS. } { 2020/03/10 5.18 Use MachAbsoluteTime on OSX. } { 2020/03/22 5.19 Use maximum resolution on OSX and Delphi Posix. } { Add high resolution tick functions. } { 2020/05/20 5.20 Use MachAbsoluteTime on iOS. } { Remove legacy tick timer, use MilliTick timer for same } { functionality. } { Remote legacy HPTimer, use HighResolutionTick for same } { functionality. } { Add GetMicroDateTimeNowUT and GetMicroDateTimeNowUTC. } { } { Supported compilers: } { } { Delphi 2010-10.4 Win32/Win64 5.20 2020/06/02 } { Delphi 10.2-10.4 Linux64 5.20 2020/06/02 } { FreePascal 3.0.4 Win64 5.20 2020/06/02 } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$IFDEF DEBUG} {$IFDEF TEST} {$DEFINE TIMERS_TEST} {$ENDIF} {$ENDIF} unit flcTimers; interface uses { System } SysUtils, { Fundamentals } flcStdTypes; { } { Error } { } type ETimerError = class(Exception); { } { High resolution tick } { GetHighResolutionFrequency returns the resolution of the high resolution } { timer in units per second. } { } function GetHighResolutionTick: Word64; function GetHighResolutionFrequency: Word64; function HighResolutionTickDelta(const T1, T2: Word64): Int64; function HighResolutionTickDeltaU(const T1, T2: Word64): Word64; { } { MicroTick } { Timer in microsecond units, based on high resolution timer if available. } { } const MicroTickFrequency = 1000000; function GetMicroTick: Word64; function MicroTickDelta(const T1, T2: Word64): Int64; function MicroTickDeltaU(const T1, T2: Word64): Word64; { } { MilliTick } { Timer in millisecond units, based on high resolution timer if available. } { } const MilliTickFrequency = 1000; function GetMilliTick: Word64; function MilliTickDelta(const T1, T2: Word64): Int64; function MilliTickDeltaU(const T1, T2: Word64): Word64; { } { MicroDateTime } { Represents a TDateTime in microsecond units. } { } function DateTimeToMicroDateTime(const DT: TDateTime): Word64; function MicroDateTimeToDateTime(const DT: Word64): TDateTime; { } { GetMicroDateTimeNow } { Returns current system date/time as a MicroDateTime. } { } function GetMicroDateTimeNow: Word64; { } { GetMicroDateTimeNowUT } { Returns current UT date/time as a MicroDateTime. } { } function GetNowUT: TDateTime; function GetMicroDateTimeNowUT: Word64; { } { GetMicroDateTimeNowUTC } { Returns current UT date/time as a MicroDateTime using a cached start } { time to speed up calculation and ensure monotonic values. } { The UTC version may drift from the uncached UT version. } { If ReInit is True, the cache start time is resynchronised with UT time } { from the system clock. } { } function GetNowUTC(const ReInit: Boolean = False): TDateTime; function GetMicroDateTimeNowUTC(const ReInit: Boolean = False): Word64; { } { Tests } { } {$IFDEF TIMERS_TEST} procedure Test; {$ENDIF} implementation {$IFDEF WindowsPlatform} uses { System } Windows, DateUtils; {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF POSIX} uses { System } BaseUnix, Unix, System.DateUtils; {$ENDIF} {$ENDIF} {$IFDEF DELPHI} {$IFDEF POSIX} uses { System } Posix.Time, {$IFDEF MACOS} Macapi.CoreServices, {$ENDIF} {$IFDEF IOS} Macapi.Mach, {$ENDIF} System.DateUtils; {$ENDIF} {$ENDIF} // Turn off overflow checking. // Most functions rely on overflow checking off to correctly handle counters that wrap around. {$IFOPT Q+}{$DEFINE QOn}{$ELSE}{$UNDEF QOn}{$ENDIF}{$Q-} { } { High resolution counters } { } { Windows } {$IFDEF WindowsPlatform} {$DEFINE Defined_GetHighResolutionCounter} const SHighResCounterError = 'High resolution counter error'; var HighResolutionCounterInit : Boolean = False; HighResolutionFrequency : Word64 = 0; HighResolutionMillisecondFactor : Word64 = 0; HighResolutionMicrosecondFactor : Word64 = 0; function CPUClockFrequency: Word64; var Freq : Windows.TLargeInteger; begin Freq := 0; if not QueryPerformanceFrequency(Freq) then raise ETimerError.Create(SHighResCounterError); if Freq = 0 then raise ETimerError.Create(SHighResCounterError); Result := Word64(Freq); end; procedure InitHighResolutionCounter; var Freq : Word64; begin Freq := CPUClockFrequency; HighResolutionFrequency := Freq; HighResolutionMillisecondFactor := Freq div 1000; HighResolutionMicrosecondFactor := Freq div 1000000; if HighResolutionMicrosecondFactor = 0 then raise ETimerError.Create(SHighResCounterError); HighResolutionCounterInit := True; end; function GetHighResolutionCounter: Word64; var Ctr : Windows.TLargeInteger; begin if not HighResolutionCounterInit then InitHighResolutionCounter; Ctr := 0; if not QueryPerformanceCounter(Ctr) then raise ETimerError.Create(SHighResCounterError); Result := Word64(Ctr); end; {$ENDIF} { Delphi Posix; excluding IOS and OSX } {$IFDEF DELPHI} {$IFDEF POSIX} {$IFNDEF IOS} {$IFNDEF MACOS} {$DEFINE Defined_GetHighResolutionCounter} const HighResolutionFrequency = Word64(1000000000); HighResolutionMillisecondFactor = 1000000; HighResolutionMicrosecondFactor = 1000; function GetHighResolutionCounter: Word64; var TimeVal : timespec; Ticks64 : Word64; begin clock_gettime(CLOCK_MONOTONIC, @TimeVal); Ticks64 := Word64(Word64(TimeVal.tv_sec) * Word64(1000000000)); Ticks64 := Word64(Ticks64 + Word64(TimeVal.tv_nsec)); Result := Ticks64; end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} { Delphi OSX/iOS } // Apple recommends to use the equivalent clock_gettime_nsec_np(CLOCK_UPTIME_RAW) in nanoseconds. {$IFDEF DELPHI} {$IFDEF MACOS} const {$IFDEF UNDERSCOREIMPORTNAME} _PU = '_'; {$ELSE} _PU = ''; {$ENDIF} const LibcLib = '/usr/lib/libc.dylib'; function MachAbsoluteTime: UInt64; cdecl external LibcLib name _PU + 'mach_absolute_time'; {$DEFINE Defined_GetHighResolutionCounter} const HighResolutionFrequency = Word64(1000000000); HighResolutionMillisecondFactor = 1000000; HighResolutionMicrosecondFactor = 1000; function GetHighResolutionCounter: Word64; var Ticks64 : Word64; begin Ticks64 := Word64(AbsoluteToNanoseconds(MachAbsoluteTime)); Result := Ticks64; end; {$ENDIF} {$ENDIF} { FreePascal Posix } {$IFDEF FREEPASCAL} {$IFDEF POSIX} {$DEFINE Defined_GetHighResolutionCounter} const HighResolutionFrequency = 1000000; HighResolutionMillisecondFactor = 1000; HighResolutionMicrosecondFactor = 1; function GetHighResolutionCounter: Word64; var TV : TTimeVal; TZ : PTimeZone; Ticks64 : Word64; begin TZ := nil; fpGetTimeOfDay(@TV, TZ); Ticks64 := Word64(Word64(TV.tv_sec) * 1000000); Ticks64 := Word64(Ticks64 + Word64(TV.tv_usec)); Result := Ticks64; end; {$ENDIF} {$ENDIF} { Default implementation using system time } {$IFNDEF Defined_GetHighResolutionCounter} {$DEFINE Defined_GetHighResolutionCounter} const HighResolutionFrequency = 1000000; HighResolutionMillisecondFactor = 1000; HighResolutionMicrosecondFactor = 1; function GetHighResolutionCounter: Word64; const MicroSecPerDay = Word64(24) * 60 * 60 * 1000 * 1000; var N : Double; T : Word64; begin N := Now; N := N * MicroSecPerDay; T := Word64(Trunc(N)); Result := T; end; {$ENDIF} { } { High resolution tick } { } function GetHighResolutionTick: Word64; begin Result := GetHighResolutionCounter; end; function GetHighResolutionFrequency: Word64; begin {$IFDEF WindowsPlatform} if not HighResolutionCounterInit then InitHighResolutionCounter; {$ENDIF} Result := HighResolutionFrequency; end; // Overflow checking needs to be off here to correctly handle tick values that // wrap around the maximum value. function HighResolutionTickDelta(const T1, T2: Word64): Int64; begin Result := Int64(Word64(T2 - T1)); end; function HighResolutionTickDeltaU(const T1, T2: Word64): Word64; begin Result := Word64(T2 - T1); end; { } { MicroTick } { } function GetMicroTick: Word64; var T : Word64; begin T := GetHighResolutionCounter; T := T div HighResolutionMicrosecondFactor; Result := T; end; // Overflow checking needs to be off here to correctly handle tick values that // wrap around the maximum value. function MicroTickDelta(const T1, T2: Word64): Int64; begin {$IFDEF WindowsPlatform} if not HighResolutionCounterInit then InitHighResolutionCounter; {$ENDIF} Result := Int64(Word64( Word64(T2 * HighResolutionMicrosecondFactor) - Word64(T1 * HighResolutionMicrosecondFactor))) div Int64(HighResolutionMicrosecondFactor); end; function MicroTickDeltaU(const T1, T2: Word64): Word64; begin {$IFDEF WindowsPlatform} if not HighResolutionCounterInit then InitHighResolutionCounter; {$ENDIF} Result := Word64( Word64(T2 * HighResolutionMicrosecondFactor) - Word64(T1 * HighResolutionMicrosecondFactor)) div HighResolutionMicrosecondFactor; end; { } { MilliTick } { } function GetMilliTick: Word64; var T : Word64; begin T := GetHighResolutionCounter; T := T div Word64(HighResolutionMillisecondFactor); Result := T; end; // Overflow checking needs to be off here to correctly handle tick values that // wrap around the maximum value. function MilliTickDelta(const T1, T2: Word64): Int64; begin {$IFDEF WindowsPlatform} if not HighResolutionCounterInit then InitHighResolutionCounter; {$ENDIF} Result := Int64(Word64( Word64(T2 * HighResolutionMillisecondFactor) - Word64(T1 * HighResolutionMillisecondFactor))) div Int64(HighResolutionMillisecondFactor); end; function MilliTickDeltaU(const T1, T2: Word64): Word64; begin {$IFDEF WindowsPlatform} if not HighResolutionCounterInit then InitHighResolutionCounter; {$ENDIF} Result := Word64( Word64(T2 * HighResolutionMillisecondFactor) - Word64(T1 * HighResolutionMillisecondFactor)) div HighResolutionMillisecondFactor; end; { } { MicroDateTime } { } const // Microseconds per day // = 24 * 60 * 60 * 1000 * 1000 // = 86400000000 // = $141DD76000 MicroDateTimeFactor = Word64(86400000000); function DateTimeToMicroDateTime(const DT: TDateTime): Word64; var Fl : Double; Da : Word64; FT : Double; Ti : Word64; begin Fl := DT; if (Fl < -1.0e-12) or (Fl >= 106751990.0) then raise ETimerError.Create('Invalid date/time'); Da := Word64(Trunc(Fl)); Da := Word64(Da * MicroDateTimeFactor); FT := Frac(Fl); FT := FT * MicroDateTimeFactor; Ti := Word64(Trunc(FT)); Result := Word64(Da + Ti); end; function MicroDateTimeToDateTime(const DT: Word64): TDateTime; var Da : Word64; Ti : Word64; Fl : Double; begin Da := DT div MicroDateTimeFactor; Ti := DT; Dec(Ti, Da * MicroDateTimeFactor); Fl := Ti; Fl := Fl / MicroDateTimeFactor; Fl := Fl + Da; Result := Fl; end; function GetMicroDateTimeNow: Word64; begin Result := DateTimeToMicroDateTime(Now); end; { } { GetNowUT } { } {$IFDEF DELPHIXE2_UP} {$DEFINE SupportUniversalTime} function GetNowUT: TDateTime; begin Result := System.DateUtils.TTimeZone.Local.ToUniversalTime(Now); end; {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF WindowsPlatform} {$DEFINE SupportUniversalTime} function GetUTBias: TDateTime; var TZI : TTimeZoneInformation; BiasMin : Integer; begin case GetTimeZoneInformation(TZI) of TIME_ZONE_ID_STANDARD : BiasMin := TZI.StandardBias; TIME_ZONE_ID_DAYLIGHT : BiasMin := TZI.DaylightBias else BiasMin := 0; end; Inc(BiasMin, TZI.Bias); Result := BiasMin / (24 * 60); end; function GetNowUT: TDateTime; begin Result := Now + GetUTBias; end; {$ENDIF} {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF POSIX} {$DEFINE SupportUniversalTime} function GetUTBias: TDateTime; var TV : TTimeVal; TZ : PTimeZone; BiasMin : Integer; begin TZ := nil; fpGetTimeOfDay(@TV, TZ); if Assigned(TZ) then BiasMin := TZ^.tz_minuteswest div 60 else BiasMin := 0; Result := BiasMin / (24 * 60); end; function GetNowUT: TDateTime; begin Result := Now + GetUTBias; end; {$ENDIF} {$ENDIF} {$IFNDEF SupportUniversalTime} function GetNowUT: TDateTime; begin Result := Now; end; {$ENDIF} { } { GetMicroDateTimeNowUT } { } function GetMicroDateTimeNowUT: Word64; begin Result := DateTimeToMicroDateTime(GetNowUT); end; { } { GetMicroDateTimeNowUT(C)ached } { } var NowUTStartInit : Boolean = False; NowUTStartDT : TDateTime = 0.0; NowUTStartMicroTick : Word64 = 0; NowUTStartMicroDT : Word64 = 0; procedure InitNowUTStart; var DT : TDateTime; MT : Word64; begin DT := GetNowUT; MT := GetMicroTick; NowUTStartDT := DT; NowUTStartMicroTick := MT; NowUTStartMicroDT := DateTimeToMicroDateTime(DT); NowUTStartInit := True; end; function GetNowUTC(const ReInit: Boolean): TDateTime; var MT : Word64; begin if ReInit or not NowUTStartInit then InitNowUTStart; MT := GetMicroTick; Result := MicroDateTimeToDateTime(NowUTStartMicroDT + (MT - NowUTStartMicroTick)); end; function GetMicroDateTimeNowUTC(const ReInit: Boolean): Word64; var MT : Word64; begin if ReInit or not NowUTStartInit then InitNowUTStart; MT := GetMicroTick; Result := NowUTStartMicroDT + (MT - NowUTStartMicroTick); end; {$IFDEF QOn}{$Q+}{$ENDIF} { } { Tests } { } {$IFDEF TIMERS_TEST} {$ASSERTIONS ON} procedure Test_MilliTickDelta; begin Assert(MilliTickDelta(0, 10) = 10); Assert(MilliTickDelta(Word64($FFFFFFFFFFFFFFFF), 10) = 11); Assert(MilliTickDelta(10, 0) = -10); Assert(MilliTickDelta(Word64($FFFFFFFFFFFFFFF6), 0) = 10); Assert(MilliTickDeltaU(0, 10) = 10); Assert(MilliTickDeltaU(Word64($FFFFFFFFFFFFFFFF), 10) = 11); end; procedure Test_MilliTickTimer1; var A, B : Word64; I : Integer; begin // test tick timer using sleep A := GetMilliTick; I := 1; repeat Sleep(1); Inc(I); B := GetMilliTick; until (I = 2000) or (B <> A); Assert(B <> A); Assert(I < 100); Assert(MilliTickDelta(A, B) > 0); Assert(MilliTickDelta(A, B) < 100); end; procedure Test_MicroTickTimer1; var A, B : Word64; I : Integer; begin // test tick timer using sleep A := GetMicroTick; I := 1; repeat Sleep(1); Inc(I); B := GetMicroTick; until (I = 2000) or (B <> A); Assert(B <> A); Assert(I < 100); Assert(MicroTickDelta(A, B) > 0); Assert(MicroTickDelta(A, B) < 100000); end; procedure Test_MilliTickTimer2; var A, B : Word64; P, Q : TDateTime; I : Integer; begin // test tick timer using clock A := GetMilliTick; I := 1; P := Now; repeat Inc(I); Q := Now; B := GetMilliTick; until (I = 100000000) or (B <> A) or (Q >= P + 2.0 / (24.0 * 60.0 * 60.0)); // two seconds Assert(B <> A); Assert(MilliTickDelta(A, B) > 0); Assert(MilliTickDelta(A, B) < 100); end; procedure Test_MicroTickTimer2; var A, B : Word64; P, Q : TDateTime; I : Integer; begin // test tick timer using clock A := GetMicroTick; I := 1; P := Now; repeat Inc(I); Q := Now; B := GetMicroTick; until (I = 100000000) or (B <> A) or (Q >= P + 2.0 / (24.0 * 60.0 * 60.0)); // two seconds Assert(B <> A); Assert(MicroTickDelta(A, B) > 0); Assert(MicroTickDelta(A, B) < 100000); end; procedure Test_MicroDateTime1; var DT1 : TDateTime; DT2 : TDateTime; MD1 : Word64; MD2 : Word64; begin // Specific TDateTime DT1 := 43971.5231084028; MD1 := DateTimeToMicroDateTime(DT1); Assert(MD1 = 3799139596566001); Assert(MD1 < $00FFFFFFFFFFFFFF); DT2 := MicroDateTimeToDateTime(MD1); Assert(Abs(DT1 - DT2) < 1.0e-11); MD2 := DateTimeToMicroDateTime(DT2); Assert(MD2 = 3799139596566001); // Zero TDatetime DT1 := 0.0; MD1 := DateTimeToMicroDateTime(DT1); Assert(MD1 = 0); DT2 := MicroDateTimeToDateTime(MD1); Assert(Abs(DT2) < 1.0e-11); end; procedure Test_MicroDateTime2; var MD1 : Word64; MD2 : Word64; D : Int64; begin // NowUT MD1 := GetMicroDateTimeNowUT; Sleep(5); MD2 := GetMicroDateTimeNowUT - MD1; Assert(MD2 > 2000); // 2ms Assert(MD2 < 100000); // 100 ms // NowUTC MD1 := GetMicroDateTimeNowUTC(True); Sleep(5); MD2 := GetMicroDateTimeNowUTC(False) - MD1; Assert(MD2 > 2000); // 2ms Assert(MD2 < 100000); // 100 ms // NowUT / NowUTC drift Sleep(10); MD1 := GetMicroDateTimeNowUT; MD2 := GetMicroDateTimeNowUTC(False); if MD2 >= MD1 then D := MD2 - MD1 else D := MD1 - MD2; Assert(D >= 0); Assert(D < 100000); // 100ms end; procedure Test; begin Test_MilliTickDelta; Test_MilliTickTimer1; Test_MicroTickTimer1; Test_MilliTickTimer2; Test_MicroTickTimer2; Test_MicroDateTime1; Test_MicroDateTime2; end; {$ENDIF} end.