hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
163 values
lang
stringclasses
53 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
112
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
113
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
113
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.05M
avg_line_length
float64
1
966k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
85acd35954619c70e2e3c95d88297a4640dff3dc
5,461
dfm
Pascal
UServerForm.dfm
jr8ppg/zServer
12826a781a4628d5753ea2bebd49ac773b688a97
[ "MIT" ]
3
2020-07-17T07:20:26.000Z
2021-07-27T12:14:58.000Z
UServerForm.dfm
jr8ppg/zServer
12826a781a4628d5753ea2bebd49ac773b688a97
[ "MIT" ]
10
2021-04-27T12:54:54.000Z
2022-03-10T14:13:13.000Z
UServerForm.dfm
jr8ppg/zServer
12826a781a4628d5753ea2bebd49ac773b688a97
[ "MIT" ]
null
null
null
object ServerForm: TServerForm Left = 285 Top = 189 ActiveControl = SendButton Caption = 'ab' ClientHeight = 211 ClientWidth = 344 Color = clBtnFace Constraints.MinHeight = 200 Constraints.MinWidth = 360 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = #65325#65331' '#65328#12468#12471#12483#12463 Font.Style = [] Menu = MainMenu1 OldCreateOrder = True Position = poScreenCenter OnClose = FormClose OnCloseQuery = FormCloseQuery OnCreate = FormCreate OnDestroy = FormDestroy OnShow = FormShow PixelsPerInch = 96 TextHeight = 12 object ClientListBox: TListBox Left = 0 Top = 30 Width = 344 Height = 151 Align = alClient Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = #65325#65331' '#12468#12471#12483#12463 Font.Style = [] ImeName = 'MS-IME97 '#26085#26412#35486#20837#21147#65404#65405#65411#65425 ItemHeight = 12 ParentFont = False TabOrder = 0 end object Panel1: TPanel Left = 0 Top = 0 Width = 344 Height = 30 Align = alTop BevelOuter = bvNone TabOrder = 1 DesignSize = ( 344 30) object Button1: TButton Left = 152 Top = 8 Width = 75 Height = 17 Caption = 'Button1' Font.Charset = SHIFTJIS_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 0 Visible = False OnClick = Button1Click end object Button2: TButton Left = 276 Top = 4 Width = 63 Height = 22 Anchors = [akTop, akRight] Caption = '&Clear' TabOrder = 1 OnClick = Button2Click end object CheckBox2: TCheckBox Left = 6 Top = 7 Width = 113 Height = 17 Caption = 'Monitor chat only' TabOrder = 2 OnClick = CheckBox2Click end end object Panel2: TPanel Left = 0 Top = 181 Width = 344 Height = 30 Align = alBottom BevelOuter = bvNone TabOrder = 2 DesignSize = ( 344 30) object SendButton: TButton Left = 276 Top = 5 Width = 63 Height = 21 Anchors = [akTop, akRight] Caption = '&Send' Default = True TabOrder = 0 OnClick = SendButtonClick end object SendEdit: TEdit Left = 6 Top = 6 Width = 265 Height = 18 TabStop = False Anchors = [akLeft, akTop, akRight] AutoSelect = False AutoSize = False ImeName = 'MS-IME97 '#26085#26412#35486#20837#21147#65404#65405#65411#65425 TabOrder = 1 end end object SrvSocket: TWSocket LineEnd = #13#10 Proto = 'tcp' LocalAddr = '0.0.0.0' LocalAddr6 = '::' LocalPort = '0' SocksLevel = '5' ExclusiveAddr = False ComponentOptions = [] ListenBacklog = 15 OnSessionAvailable = SrvSocketSessionAvailable SocketErrs = wsErrTech Left = 24 Top = 56 end object MainMenu1: TMainMenu Left = 224 Top = 8 object File1: TMenuItem Caption = '&File' object Open1: TMenuItem Caption = '&Open File' OnClick = Open1Click end object MergeFile1: TMenuItem Caption = '&Merge File' Enabled = False OnClick = MergeFile1Click end object mLog: TMenuItem Caption = 'Start &Log' OnClick = mLogClick end object Save1: TMenuItem Caption = '&Save' OnClick = Save1Click end object SaveAs1: TMenuItem Caption = 'Save &As' OnClick = SaveAs1Click end object DeleteDupes1: TMenuItem Caption = 'Delete Dupes' OnClick = DeleteDupes1Click end object N2: TMenuItem Caption = '-' end object Exit1: TMenuItem Caption = 'E&xit' OnClick = Exit1Click end end object Windows1: TMenuItem Caption = '&Windows' OnClick = Windows1Click object ScoreandStatistics1: TMenuItem Caption = '&Score and Statistics' OnClick = ScoreandStatistics1Click end object Multipliers1: TMenuItem Caption = '&Multipliers' OnClick = Multipliers1Click end object Connections1: TMenuItem Caption = '&Connections' OnClick = Connections1Click end object CurrentFrequencies1: TMenuItem Caption = 'Current &Frequencies' OnClick = CurrentFrequencies1Click end object Graph1: TMenuItem Caption = 'Graph' Visible = False OnClick = Graph1Click end end object Help1: TMenuItem Caption = '&Help' object Contents1: TMenuItem Caption = '&Contents' Visible = False end object N1: TMenuItem Caption = '-' Visible = False end object About1: TMenuItem Caption = '&About' OnClick = About1Click end end end object Timer1: TTimer Enabled = False Interval = 50 OnTimer = Timer1Timer Left = 64 Top = 112 end object SaveDialog: TSaveDialog DefaultExt = 'zlo' Filter = 'zLog binary files (*.ZLO)|*.ZLO' Left = 232 Top = 88 end object OpenDialog: TOpenDialog DefaultExt = 'ZLO' Filter = 'zLog binary files (*.ZLO)|*.ZLO' Left = 144 Top = 72 end end
22.945378
81
0.593115
f197c750924d1256b108bad332022ef234d6fec0
1,078
pas
Pascal
core/tests/fireflyalgorithmtestcase.pas
Zawuza/firefly
8941ddf7bb63ef4f4569f642e04d73f7c43f3642
[ "Apache-2.0" ]
1
2018-12-08T06:42:51.000Z
2018-12-08T06:42:51.000Z
core/tests/fireflyalgorithmtestcase.pas
Zawuza/firefly
8941ddf7bb63ef4f4569f642e04d73f7c43f3642
[ "Apache-2.0" ]
null
null
null
core/tests/fireflyalgorithmtestcase.pas
Zawuza/firefly
8941ddf7bb63ef4f4569f642e04d73f7c43f3642
[ "Apache-2.0" ]
null
null
null
unit fireflyalgorithmtestcase; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, fireflyalgorithm, baustellenproblem, jsonproblemparser; type TFireflyAlgorithmTestCase = class(TTestCase) published procedure BasicMovementTest; end; implementation procedure TFireflyAlgorithmTestCase.BasicMovementTest; var LFirefly: TFireflyAlgorithm; LProblem: TBaustellenProblem; LPositionen: TPositionList; begin LProblem := TJSONBaustellenProblemParser.LoadProblem('.\testdata\basicmovement.json'); LPositionen := TPositionList.Create; LPositionen.Add(TAgentPosition.Create); LPositionen[0].I := 0; LPositionen[0].J := 0; LFirefly := TFireflyAlgorithm.Create(LProblem,LPositionen); AssertTrue(LFirefly.Positionen[0].I = 0); AssertTrue(LFirefly.Positionen[0].J = 0); LFirefly.Step; AssertTrue(((LFirefly.Positionen[0].I = 0) and (LFirefly.Positionen[0].J = 1)) or (LFirefly.Positionen[0].I = 1) and (LFirefly.Positionen[0].J = 0)); end; initialization RegisterTest(TFireflyAlgorithmTestCase); end.
23.955556
88
0.761596
473af1e62ee13572142cc18c311053638b55de7c
58,383
pas
Pascal
Source/Z.PascalStrings.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
24
2022-01-20T13:59:38.000Z
2022-03-25T01:11:43.000Z
Source/Z.PascalStrings.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
null
null
null
Source/Z.PascalStrings.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
5
2022-01-20T14:44:24.000Z
2022-02-13T10:07:38.000Z
{ ****************************************************************************** } { * Pascal String imp * } { ****************************************************************************** } unit Z.PascalStrings; {$I Z.Define.inc} interface uses Z.Core; type {$IFDEF FPC} SystemChar = AnsiChar; SystemString = AnsiString; {$ELSE FPC} SystemChar = Char; SystemString = String; {$ENDIF FPC} PSystemChar = ^SystemChar; TArrayChar = array of SystemChar; PSystemString = ^SystemString; PPascalString = ^TPascalString; TOrdChar = (c0to9, c1to9, c0to32, c0to32no10, cLoAtoF, cHiAtoF, cLoAtoZ, cHiAtoZ, cHex, cAtoF, cAtoZ, cVisibled); TOrdChars = set of TOrdChar; TPascalString = record private function GetText: SystemString; procedure SetText(const Value: SystemString); function GetLen: Integer; procedure SetLen(const Value: Integer); function GetChars(index: Integer): SystemChar; procedure SetChars(index: Integer; const Value: SystemChar); function GetBytes: TBytes; procedure SetBytes(const Value: TBytes); function GetPlatformBytes: TBytes; procedure SetPlatformBytes(const Value: TBytes); function GetANSI: TBytes; procedure SetANSI(const Value: TBytes); function GetLast: SystemChar; procedure SetLast(const Value: SystemChar); function GetFirst: SystemChar; procedure SetFirst(const Value: SystemChar); function GetUpperChar(index: Integer): SystemChar; procedure SetUpperChar(index: Integer; const Value: SystemChar); function GetLowerChar(index: Integer): SystemChar; procedure SetLowerChar(index: Integer; const Value: SystemChar); public buff: TArrayChar; {$IFDEF DELPHI} class operator Equal(const Lhs, Rhs: TPascalString): Boolean; class operator NotEqual(const Lhs, Rhs: TPascalString): Boolean; class operator GreaterThan(const Lhs, Rhs: TPascalString): Boolean; class operator GreaterThanOrEqual(const Lhs, Rhs: TPascalString): Boolean; class operator LessThan(const Lhs, Rhs: TPascalString): Boolean; class operator LessThanOrEqual(const Lhs, Rhs: TPascalString): Boolean; class operator Add(const Lhs, Rhs: TPascalString): TPascalString; class operator Add(const Lhs: SystemString; const Rhs: TPascalString): TPascalString; class operator Add(const Lhs: TPascalString; const Rhs: SystemString): TPascalString; class operator Add(const Lhs: SystemChar; const Rhs: TPascalString): TPascalString; class operator Add(const Lhs: TPascalString; const Rhs: SystemChar): TPascalString; class operator Implicit(Value: RawByteString): TPascalString; class operator Implicit(Value: SystemString): TPascalString; class operator Implicit(Value: SystemChar): TPascalString; class operator Implicit(Value: TPascalString): SystemString; class operator Implicit(Value: TPascalString): Variant; class operator Explicit(Value: TPascalString): RawByteString; class operator Explicit(Value: TPascalString): SystemString; class operator Explicit(Value: SystemString): TPascalString; class operator Explicit(Value: SystemChar): TPascalString; class operator Explicit(Value: Variant): TPascalString; class operator Explicit(Value: TPascalString): Variant; {$ENDIF} procedure SwapInstance(var source: TPascalString); function Copy(index, Count: NativeInt): TPascalString; function Same(const p: PPascalString): Boolean; overload; function Same(const t: TPascalString): Boolean; overload; function Same(const t1, t2: TPascalString): Boolean; overload; function Same(const t1, t2, t3: TPascalString): Boolean; overload; function Same(const t1, t2, t3, t4: TPascalString): Boolean; overload; function Same(const t1, t2, t3, t4, t5: TPascalString): Boolean; overload; function Same(const t1, t2, t3, t4, t5, t6: TPascalString): Boolean; overload; function Same(const t1, t2, t3, t4, t5, t6, t7: TPascalString): Boolean; overload; function Same(const t1, t2, t3, t4, t5, t6, t7, t8: TPascalString): Boolean; overload; function Same(const t1, t2, t3, t4, t5, t6, t7, t8, t9: TPascalString): Boolean; overload; function Same(const IgnoreCase: Boolean; const t: TPascalString): Boolean; overload; function ComparePos(const Offset: Integer; const p: PPascalString): Boolean; overload; function ComparePos(const Offset: Integer; const t: TPascalString): Boolean; overload; function ComparePos(const Offset: Integer; const p: PPascalString; IgnoreCase: Boolean): Boolean; overload; function ComparePos(const Offset: Integer; const t: TPascalString; IgnoreCase: Boolean): Boolean; overload; function GetPos(const s: TPascalString; const Offset: Integer = 1): Integer; overload; function GetPos(const s: PPascalString; const Offset: Integer = 1): Integer; overload; function Exists(c: SystemChar): Boolean; overload; function Exists(c: array of SystemChar): Boolean; overload; function StrExists(const s: TPascalString): Boolean; overload; function GetCharCount(c: SystemChar): Integer; function IsVisibledASCII: Boolean; function hash: THash; function Hash64: THash64; property Last: SystemChar read GetLast write SetLast; property First: SystemChar read GetFirst write SetFirst; procedure DeleteLast; procedure DeleteFirst; procedure Delete(idx, cnt: Integer); procedure Clear; procedure Reset; procedure Append(t: TPascalString); overload; procedure Append(c: SystemChar); overload; procedure Append(const Fmt: SystemString; const Args: array of const); overload; function GetString(bPos, ePos: NativeInt): TPascalString; procedure Insert(Text_: SystemString; idx: Integer); procedure FastAsText(var output: SystemString); procedure FastGetBytes(var output: TBytes); property Text: SystemString read GetText write SetText; function LowerText: SystemString; function UpperText: SystemString; function Invert: TPascalString; function TrimChar(const Chars: TPascalString): TPascalString; function DeleteChar(const Chars: TPascalString): TPascalString; overload; function DeleteChar(const Chars: TOrdChars): TPascalString; overload; function ReplaceChar(const Chars: TPascalString; const newChar: SystemChar): TPascalString; overload; function ReplaceChar(const Chars, newChar: SystemChar): TPascalString; overload; function ReplaceChar(const Chars: TOrdChars; const newChar: SystemChar): TPascalString; overload; function BuildPlatformPChar: Pointer; class procedure FreePlatformPChar(p: Pointer); static; class function RandomString(rnd: TRandom; L_: Integer): TPascalString; overload; static; class function RandomString(L_: Integer): TPascalString; overload; static; class function RandomString(rnd: TRandom; L_: Integer; Chars_: TOrdChars): TPascalString; overload; static; class function RandomString(L_: Integer; Chars_: TOrdChars): TPascalString; overload; static; { https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm } function SmithWaterman(const p: PPascalString): Double; overload; function SmithWaterman(const s: TPascalString): Double; overload; property Len: Integer read GetLen write SetLen; property L: Integer read GetLen write SetLen; property Chars[index: Integer]: SystemChar read GetChars write SetChars; default; property UpperChar[index: Integer]: SystemChar read GetUpperChar write SetUpperChar; property LowerChar[index: Integer]: SystemChar read GetLowerChar write SetLowerChar; property Bytes: TBytes read GetBytes write SetBytes; // UTF8 property PlatformBytes: TBytes read GetPlatformBytes write SetPlatformBytes; // system default property ANSI: TBytes read GetANSI write SetANSI; // Ansi Bytes function BOMBytes: TBytes; end; TArrayPascalString = array of TPascalString; PArrayPascalString = ^TArrayPascalString; TArrayPascalStringPtr = array of PPascalString; PArrayPascalStringPtr = ^TArrayPascalStringPtr; TP_String = TPascalString; PP_String = PPascalString; TAtomSystemString = {$IFDEF FPC}specialize {$ENDIF FPC}TAtomVar<SystemString>; TAtomPascalString = {$IFDEF FPC}specialize {$ENDIF FPC}TAtomVar<TPascalString>; function CharIn(c: SystemChar; const SomeChars: array of SystemChar): Boolean; overload; function CharIn(c: SystemChar; const SomeChar: SystemChar): Boolean; overload; function CharIn(c: SystemChar; const s: TPascalString): Boolean; overload; function CharIn(c: SystemChar; const p: PPascalString): Boolean; overload; function CharIn(c: SystemChar; const SomeCharsets: TOrdChars): Boolean; overload; function CharIn(c: SystemChar; const SomeCharset: TOrdChar): Boolean; overload; function CharIn(c: SystemChar; const SomeCharsets: TOrdChars; const SomeChars: TPascalString): Boolean; overload; function CharIn(c: SystemChar; const SomeCharsets: TOrdChars; const p: PPascalString): Boolean; overload; function TextIs(t: TPascalString; const SomeCharsets: TOrdChars): Boolean; overload; function TextIs(t: TPascalString; const SomeCharsets: TOrdChars; const SomeChars: TPascalString): Boolean; overload; function FastHashPSystemString(const s: PSystemString): THash; overload; function FastHash64PSystemString(const s: PSystemString): THash64; overload; function FastHashSystemString(const s: SystemString): THash; overload; function FastHash64SystemString(const s: SystemString): THash64; overload; function FastHashPPascalString(const s: PPascalString): THash; function FastHash64PPascalString(const s: PPascalString): THash64; function PFormat(const Fmt: SystemString; const Args: array of const): SystemString; {$IFDEF FPC} operator := (const s: Variant)r: TPascalString; operator := (const s: AnsiString)r: TPascalString; operator := (const s: RawByteString)r: TPascalString; operator := (const s: UnicodeString)r: TPascalString; operator := (const s: WideString)r: TPascalString; operator := (const s: ShortString)r: TPascalString; operator := (const c: SystemChar)r: TPascalString; operator := (const s: TPascalString)r: AnsiString; operator := (const s: TPascalString)r: RawByteString; operator := (const s: TPascalString)r: UnicodeString; operator := (const s: TPascalString)r: WideString; operator := (const s: TPascalString)r: ShortString; operator := (const s: TPascalString)r: Variant; operator = (const a: TPascalString; const b: TPascalString): Boolean; operator <> (const a: TPascalString; const b: TPascalString): Boolean; operator > (const a: TPascalString; const b: TPascalString): Boolean; operator >= (const a: TPascalString; const b: TPascalString): Boolean; operator < (const a: TPascalString; const b: TPascalString): Boolean; operator <= (const a: TPascalString; const b: TPascalString): Boolean; operator + (const a: TPascalString; const b: TPascalString): TPascalString; operator + (const a: TPascalString; const b: SystemString): TPascalString; operator + (const a: SystemString; const b: TPascalString): TPascalString; operator + (const a: TPascalString; const b: SystemChar): TPascalString; operator + (const a: SystemChar; const b: TPascalString): TPascalString; {$ENDIF FPC} { https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm } // short string likeness and out diff function SmithWatermanCompare(const seq1, seq2: PPascalString; var diff1, diff2: TPascalString; const NoDiffChar: Boolean; const diffChar: SystemChar): Double; overload; function SmithWatermanCompare(const seq1, seq2: PPascalString; var diff1, diff2: TPascalString): Double; overload; function SmithWatermanCompare(const seq1, seq2: TPascalString; var diff1, diff2: TPascalString; const NoDiffChar: Boolean; const diffChar: SystemChar): Double; overload; function SmithWatermanCompare(const seq1, seq2: TPascalString; var diff1, diff2: TPascalString): Double; overload; // short string likeness function SmithWatermanCompare(const seq1, seq2: PPascalString; out Same, Diff: Integer): Double; overload; function SmithWatermanCompare(const seq1, seq2: PPascalString): Double; overload; function SmithWatermanCompare(const seq1, seq2: TPascalString): Double; overload; function SmithWatermanCompare(const seq1: TArrayPascalString; const seq2: TPascalString): Double; overload; // memory likeness function SmithWatermanCompare(const seq1: Pointer; siz1: Integer; const seq2: Pointer; siz2: Integer; out Same, Diff: Integer): Double; overload; function SmithWatermanCompare(const seq1: Pointer; siz1: Integer; const seq2: Pointer; siz2: Integer): Double; overload; // long string likeness function SmithWatermanCompareLongString(const t1, t2: TPascalString; const MinDiffCharWithPeerLine: Integer; out Same, Diff: Integer): Double; overload; function SmithWatermanCompareLongString(const t1, t2: TPascalString): Double; overload; const SystemCharSize = SizeOf(SystemChar); var {$IFDEF CPU64} MaxSmithWatermanMatrix: NativeInt = 10000 * 10; {$ELSE CPU64} MaxSmithWatermanMatrix: NativeInt = 8192; {$ENDIF CPU64} const {$IFDEF FirstCharInZero} FirstCharPos = 0; {$ELSE FirstCharInZero} FirstCharPos = 1; {$ENDIF FirstCharInZero} implementation uses SysUtils, Variants; procedure CombineCharsPP(const c1, c2: TArrayChar; var output: TArrayChar); var LL, rl: Integer; begin LL := length(c1); rl := length(c2); SetLength(output, LL + rl); if LL > 0 then CopyPtr(@c1[0], @output[0], LL * SystemCharSize); if rl > 0 then CopyPtr(@c2[0], @output[LL], rl * SystemCharSize); end; procedure CombineCharsSP(const c1: SystemString; const c2: TArrayChar; var output: TArrayChar); var LL, rl: Integer; begin LL := length(c1); rl := length(c2); SetLength(output, LL + rl); if LL > 0 then CopyPtr(@c1[FirstCharPos], @output[0], LL * SystemCharSize); if rl > 0 then CopyPtr(@c2[0], @output[LL], rl * SystemCharSize); end; procedure CombineCharsPS(const c1: TArrayChar; const c2: SystemString; var output: TArrayChar); var LL, rl: Integer; begin LL := length(c1); rl := length(c2); SetLength(output, LL + rl); if LL > 0 then CopyPtr(@c1[0], @output[0], LL * SystemCharSize); if rl > 0 then CopyPtr(@c2[FirstCharPos], @output[LL], rl * SystemCharSize); end; procedure CombineCharsCP(const c1: SystemChar; const c2: TArrayChar; var output: TArrayChar); var rl: Integer; begin rl := length(c2); SetLength(output, rl + 1); output[0] := c1; if rl > 0 then CopyPtr(@c2[0], @output[1], rl * SystemCharSize); end; procedure CombineCharsPC(const c1: TArrayChar; const c2: SystemChar; var output: TArrayChar); var LL: Integer; begin LL := length(c1); SetLength(output, LL + 1); if LL > 0 then CopyPtr(@c1[0], @output[0], LL * SystemCharSize); output[LL] := c2; end; function CharIn(c: SystemChar; const SomeChars: array of SystemChar): Boolean; var AChar: SystemChar; begin Result := True; for AChar in SomeChars do if AChar = c then Exit; Result := False; end; function CharIn(c: SystemChar; const SomeChar: SystemChar): Boolean; begin Result := c = SomeChar; end; function CharIn(c: SystemChar; const s: TPascalString): Boolean; begin Result := s.Exists(c); end; function CharIn(c: SystemChar; const p: PPascalString): Boolean; begin Result := p^.Exists(c); end; function CharIn(c: SystemChar; const SomeCharset: TOrdChar): Boolean; const ord0 = Ord('0'); ord1 = Ord('1'); ord9 = Ord('9'); ordLA = Ord('a'); ordHA = Ord('A'); ordLF = Ord('f'); ordHF = Ord('F'); ordLZ = Ord('z'); ordHZ = Ord('Z'); var v: Word; begin v := Ord(c); case SomeCharset of c0to9: Result := (v >= ord0) and (v <= ord9); c1to9: Result := (v >= ord1) and (v <= ord9); c0to32: Result := ((v >= 0) and (v <= 32)); c0to32no10: Result := ((v >= 0) and (v <= 32) and (v <> 10)); cLoAtoF: Result := (v >= ordLA) and (v <= ordLF); cHiAtoF: Result := (v >= ordHA) and (v <= ordHF); cLoAtoZ: Result := (v >= ordLA) and (v <= ordLZ); cHiAtoZ: Result := (v >= ordHA) and (v <= ordHZ); cHex: Result := ((v >= ordLA) and (v <= ordLF)) or ((v >= ordHA) and (v <= ordHF)) or ((v >= ord0) and (v <= ord9)); cAtoF: Result := ((v >= ordLA) and (v <= ordLF)) or ((v >= ordHA) and (v <= ordHF)); cAtoZ: Result := ((v >= ordLA) and (v <= ordLZ)) or ((v >= ordHA) and (v <= ordHZ)); cVisibled: Result := (v >= $20) and (v <= $7E); else Result := False; end; end; function CharIn(c: SystemChar; const SomeCharsets: TOrdChars): Boolean; var i: TOrdChar; begin Result := True; for i in SomeCharsets do if CharIn(c, i) then Exit; Result := False; end; function CharIn(c: SystemChar; const SomeCharsets: TOrdChars; const SomeChars: TPascalString): Boolean; begin if CharIn(c, SomeCharsets) then Result := True else Result := CharIn(c, SomeChars); end; function CharIn(c: SystemChar; const SomeCharsets: TOrdChars; const p: PPascalString): Boolean; begin if CharIn(c, SomeCharsets) then Result := True else Result := CharIn(c, p); end; function TextIs(t: TPascalString; const SomeCharsets: TOrdChars): Boolean; var c: SystemChar; begin Result := False; for c in t.buff do if not CharIn(c, SomeCharsets) then Exit; Result := True; end; function TextIs(t: TPascalString; const SomeCharsets: TOrdChars; const SomeChars: TPascalString): Boolean; var c: SystemChar; begin Result := False; for c in t.buff do if not CharIn(c, SomeCharsets, SomeChars) then Exit; Result := True; end; function BytesOfPascalString(const s: TPascalString): TBytes; begin Result := s.Bytes; end; function PascalStringOfBytes(const s: TBytes): TPascalString; begin Result.Bytes := s; end; function FastHashPSystemString(const s: PSystemString): THash; var i: Integer; c: SystemChar; begin Result := 0; {$IFDEF FirstCharInZero} for i := 0 to length(s^) - 1 do {$ELSE FirstCharInZero} for i := 1 to length(s^) do {$ENDIF FirstCharInZero} begin c := s^[i]; if CharIn(c, cHiAtoZ) then inc(c, 32); Result := ((Result shl 7) or (Result shr 25)) + THash(c); end; end; function FastHash64PSystemString(const s: PSystemString): THash64; var i: Integer; c: SystemChar; begin Result := 0; {$IFDEF FirstCharInZero} for i := 0 to length(s^) - 1 do {$ELSE FirstCharInZero} for i := 1 to length(s^) do {$ENDIF FirstCharInZero} begin c := s^[i]; if CharIn(c, cHiAtoZ) then inc(c, 32); Result := ((Result shl 7) or (Result shr 57)) + THash64(c); end; end; function FastHashSystemString(const s: SystemString): THash; begin Result := FastHashPSystemString(@s); end; function FastHash64SystemString(const s: SystemString): THash64; begin Result := FastHash64PSystemString(@s); end; function FastHashPPascalString(const s: PPascalString): THash; var i: Integer; c: SystemChar; begin Result := 0; for i := 1 to s^.Len do begin c := s^[i]; if CharIn(c, cHiAtoZ) then inc(c, 32); Result := ((Result shl 7) or (Result shr 25)) + THash(c); end; end; function FastHash64PPascalString(const s: PPascalString): THash64; var i: Integer; c: SystemChar; begin Result := 0; for i := 1 to s^.Len do begin c := s^[i]; if CharIn(c, cHiAtoZ) then inc(c, 32); Result := ((Result shl 7) or (Result shr 57)) + THash64(c); end; end; function PFormat(const Fmt: SystemString; const Args: array of const): SystemString; begin try Result := Format(Fmt, Args); except Result := Fmt; end; end; function GetSWMVMemory(const xLen, yLen: NativeInt): Pointer; { optimized matrix performance } begin Result := System.AllocMem((xLen + 1) * (yLen + 1) * SizeOf(NativeInt)); end; function GetSWMV(const p: Pointer; const w, x, y: NativeInt): NativeInt; { optimized matrix performance } begin Result := PNativeInt(nativeUInt(p) + ((x + y * (w + 1)) * SizeOf(NativeInt)))^; end; procedure SetSWMV(const p: Pointer; const w, x, y: NativeInt; const v: NativeInt); { optimized matrix performance } begin PNativeInt(nativeUInt(p) + ((x + y * (w + 1)) * SizeOf(NativeInt)))^ := v; end; function GetMax(const i1, i2: NativeInt): NativeInt; begin if i1 > i2 then Result := i1 else Result := i2; end; const SmithWaterman_MatchOk = 1; mismatch_penalty = -1; gap_penalty = -1; function SmithWatermanCompare(const seq1, seq2: PPascalString; var diff1, diff2: TPascalString; const NoDiffChar: Boolean; const diffChar: SystemChar): Double; function InlineMatch(alphaC, betaC: SystemChar; const diffC: SystemChar): Integer; begin if CharIn(alphaC, cLoAtoZ) then dec(alphaC, 32); if CharIn(betaC, cLoAtoZ) then dec(betaC, 32); if alphaC = betaC then Result := SmithWaterman_MatchOk else if (alphaC = diffC) or (betaC = diffC) then Result := gap_penalty else Result := mismatch_penalty; end; var swMatrixPtr: Pointer; i, j, L1, l2: NativeInt; matched, deleted, inserted: NativeInt; score_current, score_diagonal, score_left, score_right: NativeInt; identity: NativeInt; align1, align2: TPascalString; begin L1 := seq1^.Len; l2 := seq2^.Len; if (L1 = 0) or (l2 = 0) or (L1 > MaxSmithWatermanMatrix) or (l2 > MaxSmithWatermanMatrix) then begin Result := -1; Exit; end; { fast build matrix } swMatrixPtr := GetSWMVMemory(L1, l2); if swMatrixPtr = nil then begin diff1 := ''; diff2 := ''; Result := -1; Exit; end; i := 0; while i <= L1 do begin SetSWMV(swMatrixPtr, L1, i, 0, gap_penalty * i); inc(i); end; j := 0; while j <= l2 do begin SetSWMV(swMatrixPtr, L1, 0, j, gap_penalty * j); inc(j); end; { compute matrix } i := 1; while i <= L1 do begin j := 1; while j <= l2 do begin matched := GetSWMV(swMatrixPtr, L1, i - 1, j - 1) + InlineMatch(seq1^[i], seq2^[j], diffChar); deleted := GetSWMV(swMatrixPtr, L1, i - 1, j) + gap_penalty; inserted := GetSWMV(swMatrixPtr, L1, i, j - 1) + gap_penalty; SetSWMV(swMatrixPtr, L1, i, j, GetMax(matched, GetMax(deleted, inserted))); inc(j); end; inc(i); end; { compute align } i := L1; j := l2; align1 := ''; align2 := ''; identity := 0; while (i > 0) and (j > 0) do begin score_current := GetSWMV(swMatrixPtr, L1, i, j); score_diagonal := GetSWMV(swMatrixPtr, L1, i - 1, j - 1); score_left := GetSWMV(swMatrixPtr, L1, i - 1, j); score_right := GetSWMV(swMatrixPtr, L1, i, j - 1); matched := InlineMatch(seq1^[i], seq2^[j], diffChar); if score_current = score_diagonal + matched then begin if matched = SmithWaterman_MatchOk then begin inc(identity); align1.Append(seq1^[i]); align2.Append(seq2^[j]); end else if NoDiffChar then begin align1.Append(diffChar); align2.Append(diffChar); end else begin align1.Append(seq1^[i]); align2.Append(seq2^[j]); end; dec(i); dec(j); end else if score_current = score_left + gap_penalty then begin if NoDiffChar then align1.Append(diffChar) else align1.Append(seq1^[i]); align2.Append(diffChar); dec(i); end else if score_current = score_right + gap_penalty then begin if NoDiffChar then align2.Append(diffChar) else align2.Append(seq2^[j]); align1.Append(diffChar); dec(j); end else raise Exception.Create('matrix error'); // matrix debug time end; System.FreeMemory(swMatrixPtr); while i > 0 do begin if NoDiffChar then align1.Append(diffChar) else align1.Append(seq1^[i]); align2.Append(diffChar); dec(i); end; while j > 0 do begin if NoDiffChar then align2.Append(diffChar) else align2.Append(seq2^[j]); align1.Append(diffChar); dec(j); end; if identity > 0 then Result := identity / align1.Len else Result := -1; diff1 := align1.Invert; diff2 := align2.Invert; end; function SmithWatermanCompare(const seq1, seq2: PPascalString; var diff1, diff2: TPascalString): Double; begin Result := SmithWatermanCompare(seq1, seq2, diff1, diff2, False, '-'); end; function SmithWatermanCompare(const seq1, seq2: TPascalString; var diff1, diff2: TPascalString; const NoDiffChar: Boolean; const diffChar: SystemChar): Double; begin Result := SmithWatermanCompare(@seq1, @seq2, diff1, diff2, NoDiffChar, diffChar); end; function SmithWatermanCompare(const seq1, seq2: TPascalString; var diff1, diff2: TPascalString): Double; begin Result := SmithWatermanCompare(seq1, seq2, diff1, diff2, False, '-'); end; function SmithWatermanCompare(const seq1, seq2: PPascalString; out Same, Diff: Integer): Double; function InlineMatch(alphaC, betaC: SystemChar): NativeInt; begin if CharIn(alphaC, cLoAtoZ) then dec(alphaC, 32); if CharIn(betaC, cLoAtoZ) then dec(betaC, 32); if alphaC = betaC then Result := SmithWaterman_MatchOk else Result := mismatch_penalty; end; var swMatrixPtr: Pointer; i, j, L1, l2: NativeInt; matched, deleted, inserted: NativeInt; score_current, score_diagonal, score_left, score_right: NativeInt; identity, L_: NativeInt; begin L1 := seq1^.Len; l2 := seq2^.Len; if (L1 = 0) or (l2 = 0) or (L1 > MaxSmithWatermanMatrix) or (l2 > MaxSmithWatermanMatrix) then begin Result := -1; Same := 0; Diff := L1 + l2; Exit; end; { fast build matrix } swMatrixPtr := GetSWMVMemory(L1, l2); if swMatrixPtr = nil then begin Result := -1; Exit; end; i := 0; while i <= L1 do begin SetSWMV(swMatrixPtr, L1, i, 0, gap_penalty * i); inc(i); end; j := 0; while j <= l2 do begin SetSWMV(swMatrixPtr, L1, 0, j, gap_penalty * j); inc(j); end; { compute matrix } i := 1; while i <= L1 do begin j := 1; while j <= l2 do begin matched := GetSWMV(swMatrixPtr, L1, i - 1, j - 1) + InlineMatch(seq1^[i], seq2^[j]); deleted := GetSWMV(swMatrixPtr, L1, i - 1, j) + gap_penalty; inserted := GetSWMV(swMatrixPtr, L1, i, j - 1) + gap_penalty; SetSWMV(swMatrixPtr, L1, i, j, GetMax(matched, GetMax(deleted, inserted))); inc(j); end; inc(i); end; { compute align } i := L1; j := l2; identity := 0; L_ := 0; while (i > 0) and (j > 0) do begin score_current := GetSWMV(swMatrixPtr, L1, i, j); score_diagonal := GetSWMV(swMatrixPtr, L1, i - 1, j - 1); score_left := GetSWMV(swMatrixPtr, L1, i - 1, j); score_right := GetSWMV(swMatrixPtr, L1, i, j - 1); matched := InlineMatch(seq1^[i], seq2^[j]); if score_current = score_diagonal + matched then begin if matched = SmithWaterman_MatchOk then inc(identity); inc(L_); dec(i); dec(j); end else if score_current = score_left + gap_penalty then begin inc(L_); dec(i); end else if score_current = score_right + gap_penalty then begin inc(L_); dec(j); end else raise Exception.Create('matrix error'); // matrix debug time end; System.FreeMemory(swMatrixPtr); if identity > 0 then begin Result := identity / (L_ + i + j); Same := identity; Diff := (L_ + i + j) - identity; end else begin Result := -1; Same := 0; Diff := L_ + i + j; end; end; function SmithWatermanCompare(const seq1, seq2: PPascalString): Double; var Same, Diff: Integer; begin Result := SmithWatermanCompare(seq1, seq2, Same, Diff); end; function SmithWatermanCompare(const seq1, seq2: TPascalString): Double; begin Result := SmithWatermanCompare(@seq1, @seq2); end; function SmithWatermanCompare(const seq1: TArrayPascalString; const seq2: TPascalString): Double; var i: Integer; r: Double; begin Result := -1; for i := 0 to length(seq1) - 1 do begin r := SmithWatermanCompare(seq1[i], seq2); if r > Result then Result := r; end; end; function SmithWatermanCompare(const seq1: Pointer; siz1: Integer; const seq2: Pointer; siz2: Integer; out Same, Diff: Integer): Double; function InlineMatch(const alphaB, betaB: Byte): NativeInt; begin if alphaB = betaB then Result := SmithWaterman_MatchOk else Result := mismatch_penalty; end; var swMatrixPtr: Pointer; i, j, L1, l2: NativeInt; matched, deleted, inserted: NativeInt; score_current, score_diagonal, score_left, score_right: NativeInt; identity, L_: NativeInt; begin L1 := siz1; l2 := siz2; if (L1 = 0) or (l2 = 0) or (L1 > MaxSmithWatermanMatrix) or (l2 > MaxSmithWatermanMatrix) then begin Result := -1; Same := 0; Diff := L1 + l2; Exit; end; { fast build matrix } swMatrixPtr := GetSWMVMemory(L1, l2); if swMatrixPtr = nil then begin Result := -1; Exit; end; i := 0; while i <= L1 do begin SetSWMV(swMatrixPtr, L1, i, 0, gap_penalty * i); inc(i); end; j := 0; while j <= l2 do begin SetSWMV(swMatrixPtr, L1, 0, j, gap_penalty * j); inc(j); end; { compute matrix } i := 1; while i <= L1 do begin j := 1; while j <= l2 do begin matched := GetSWMV(swMatrixPtr, L1, i - 1, j - 1) + InlineMatch(PByte(nativeUInt(seq1) + (i - 1))^, PByte(nativeUInt(seq2) + (j - 1))^); deleted := GetSWMV(swMatrixPtr, L1, i - 1, j) + gap_penalty; inserted := GetSWMV(swMatrixPtr, L1, i, j - 1) + gap_penalty; SetSWMV(swMatrixPtr, L1, i, j, GetMax(matched, GetMax(deleted, inserted))); inc(j); end; inc(i); end; { compute align } i := L1; j := l2; identity := 0; L_ := 0; while (i > 0) and (j > 0) do begin score_current := GetSWMV(swMatrixPtr, L1, i, j); score_diagonal := GetSWMV(swMatrixPtr, L1, i - 1, j - 1); score_left := GetSWMV(swMatrixPtr, L1, i - 1, j); score_right := GetSWMV(swMatrixPtr, L1, i, j - 1); matched := InlineMatch(PByte(nativeUInt(seq1) + (i - 1))^, PByte(nativeUInt(seq2) + (j - 1))^); if score_current = score_diagonal + matched then begin if matched = SmithWaterman_MatchOk then inc(identity); inc(L_); dec(i); dec(j); end else if score_current = score_left + gap_penalty then begin inc(L_); dec(i); end else if score_current = score_right + gap_penalty then begin inc(L_); dec(j); end else raise Exception.Create('matrix error'); // matrix debug time end; System.FreeMemory(swMatrixPtr); if identity > 0 then begin Result := identity / (L_ + i + j); Same := identity; Diff := (L_ + i + j) - identity; end else begin Result := -1; Same := 0; Diff := L_ + i + j; end; end; function SmithWatermanCompare(const seq1: Pointer; siz1: Integer; const seq2: Pointer; siz2: Integer): Double; var Same, Diff: Integer; begin Result := SmithWatermanCompare(seq1, siz1, seq2, siz2, Same, Diff); end; function SmithWatermanCompareLongString(const t1, t2: TPascalString; const MinDiffCharWithPeerLine: Integer; out Same, Diff: Integer): Double; type PSRec = ^TSRec; TSRec = record s: TPascalString; end; procedure _FillText(psPtr: PPascalString; outLst: TCore_List); var L_, i: Integer; n: TPascalString; p: PSRec; begin L_ := psPtr^.Len; i := 1; n := ''; while i <= L_ do begin if CharIn(psPtr^[i], [#13, #10]) then begin n := n.DeleteChar(#32#9); if n.Len > 0 then begin new(p); p^.s := n; outLst.Add(p); n := ''; end; repeat inc(i); until (i > L_) or (not CharIn(psPtr^[i], [#13, #10, #32, #9])); end else begin n.Append(psPtr^[i]); inc(i); end; end; n := n.DeleteChar(#32#9); if n.Len > 0 then begin new(p); p^.s := n; outLst.Add(p); end; end; function InlineMatch(const alpha, beta: PSRec; const MinDiffCharWithPeerLine: Integer; var cSame, cDiff: Integer): NativeInt; begin if SmithWatermanCompare(@alpha^.s, @beta^.s, cSame, cDiff) > 0 then begin if cDiff < MinDiffCharWithPeerLine then Result := SmithWaterman_MatchOk else Result := mismatch_penalty; end else Result := mismatch_penalty; end; var lst1, lst2: TCore_List; procedure _Init; begin lst1 := TCore_List.Create; lst2 := TCore_List.Create; _FillText(@t1, lst1); _FillText(@t2, lst2); end; procedure _Free; var i: Integer; begin for i := 0 to lst1.Count - 1 do Dispose(PSRec(lst1[i])); for i := 0 to lst2.Count - 1 do Dispose(PSRec(lst2[i])); DisposeObject([lst1, lst2]); end; var swMatrixPtr: Pointer; i, j, L1, l2: NativeInt; matched, deleted, inserted: NativeInt; score_current, score_diagonal, score_left, score_right: NativeInt; cSame, cDiff, TotalSame, TotalDiff: Integer; begin _Init; L1 := lst1.Count; l2 := lst2.Count; if (L1 = 0) or (l2 = 0) or (L1 > MaxSmithWatermanMatrix) or (l2 > MaxSmithWatermanMatrix) then begin Result := -1; Same := 0; Diff := L1 + l2; _Free; Exit; end; { fast build matrix } swMatrixPtr := GetSWMVMemory(L1, l2); if swMatrixPtr = nil then begin Result := -1; _Free; Exit; end; i := 0; while i <= L1 do begin SetSWMV(swMatrixPtr, L1, i, 0, gap_penalty * i); inc(i); end; j := 0; while j <= l2 do begin SetSWMV(swMatrixPtr, L1, 0, j, gap_penalty * j); inc(j); end; { compute matrix } i := 1; while i <= L1 do begin j := 1; while j <= l2 do begin matched := GetSWMV(swMatrixPtr, L1, i - 1, j - 1) + InlineMatch(PSRec(lst1[i - 1]), PSRec(lst2[j - 1]), MinDiffCharWithPeerLine, cSame, cDiff); deleted := GetSWMV(swMatrixPtr, L1, i - 1, j) + gap_penalty; inserted := GetSWMV(swMatrixPtr, L1, i, j - 1) + gap_penalty; SetSWMV(swMatrixPtr, L1, i, j, GetMax(matched, GetMax(deleted, inserted))); inc(j); end; inc(i); end; { compute align } i := L1; j := l2; TotalSame := 0; TotalDiff := 0; while (i > 0) and (j > 0) do begin score_current := GetSWMV(swMatrixPtr, L1, i, j); score_diagonal := GetSWMV(swMatrixPtr, L1, i - 1, j - 1); score_left := GetSWMV(swMatrixPtr, L1, i - 1, j); score_right := GetSWMV(swMatrixPtr, L1, i, j - 1); matched := InlineMatch(PSRec(lst1[i - 1]), PSRec(lst2[j - 1]), MinDiffCharWithPeerLine, cSame, cDiff); inc(TotalSame, cSame); inc(TotalDiff, cDiff); if score_current = score_diagonal + matched then begin dec(i); dec(j); end else if score_current = score_left + gap_penalty then begin dec(i); end else if score_current = score_right + gap_penalty then begin dec(j); end else raise Exception.Create('matrix error'); // matrix debug time end; System.FreeMemory(swMatrixPtr); _Free; if TotalSame > 0 then begin Result := TotalSame / (TotalSame + TotalDiff); Same := TotalSame; Diff := TotalDiff; end else begin Result := -1; Same := 0; Diff := t2.Len + t1.Len; end; end; function SmithWatermanCompareLongString(const t1, t2: TPascalString): Double; var Same, Diff: Integer; begin Result := SmithWatermanCompareLongString(t1, t2, 5, Same, Diff); end; {$IFDEF FPC} operator := (const s: Variant)r: TPascalString; begin r.Text := s; end; operator := (const s: AnsiString)r: TPascalString; begin r.Text := s; end; operator := (const s: RawByteString)r: TPascalString; begin r.Text := s; end; operator := (const s: UnicodeString)r: TPascalString; begin r.Text := s; end; operator := (const s: WideString)r: TPascalString; begin r.Text := s; end; operator := (const s: ShortString)r: TPascalString; begin r.Text := s; end; operator := (const c: SystemChar)r: TPascalString; begin r.Text := c; end; operator := (const s: TPascalString)r: AnsiString; begin r := s.Text; end; operator := (const s: TPascalString)r: RawByteString; begin r := s.Text; end; operator := (const s: TPascalString)r: UnicodeString; begin r := s.Text; end; operator := (const s: TPascalString)r: WideString; begin r := s.Text; end; operator := (const s: TPascalString)r: ShortString; begin r := s.Text; end; operator := (const s: TPascalString)r: Variant; begin r := s.Text; end; operator = (const a: TPascalString; const b: TPascalString): Boolean; begin Result := a.Text = b.Text; end; operator <> (const a: TPascalString; const b: TPascalString): Boolean; begin Result := a.Text <> b.Text; end; operator > (const a: TPascalString; const b: TPascalString): Boolean; begin Result := a.Text > b.Text; end; operator >= (const a: TPascalString; const b: TPascalString): Boolean; begin Result := a.Text >= b.Text; end; operator < (const a: TPascalString; const b: TPascalString): Boolean; begin Result := a.Text < b.Text; end; operator <= (const a: TPascalString; const b: TPascalString): Boolean; begin Result := a.Text <= b.Text; end; operator + (const a: TPascalString; const b: TPascalString): TPascalString; begin CombineCharsPP(a.buff, b.buff, Result.buff); end; operator + (const a: TPascalString; const b: SystemString): TPascalString; begin CombineCharsPS(a.buff, b, Result.buff); end; operator + (const a: SystemString; const b: TPascalString): TPascalString; begin CombineCharsSP(a, b.buff, Result.buff); end; operator + (const a: TPascalString; const b: SystemChar): TPascalString; begin CombineCharsPC(a.buff, b, Result.buff); end; operator + (const a: SystemChar; const b: TPascalString): TPascalString; begin CombineCharsCP(a, b.buff, Result.buff); end; {$ENDIF} function TPascalString.GetText: SystemString; begin SetLength(Result, length(buff)); if length(buff) > 0 then CopyPtr(@buff[0], @Result[FirstCharPos], length(buff) * SystemCharSize); end; procedure TPascalString.SetText(const Value: SystemString); begin SetLength(buff, length(Value)); if length(buff) > 0 then CopyPtr(@Value[FirstCharPos], @buff[0], length(buff) * SystemCharSize); end; function TPascalString.GetLen: Integer; begin Result := length(buff); end; procedure TPascalString.SetLen(const Value: Integer); begin SetLength(buff, Value); end; function TPascalString.GetChars(index: Integer): SystemChar; begin if (index > length(buff)) or (index <= 0) then Result := #0 else Result := buff[index - 1]; end; procedure TPascalString.SetChars(index: Integer; const Value: SystemChar); begin buff[index - 1] := Value; end; function TPascalString.GetBytes: TBytes; begin SetLength(Result, 0); if length(buff) = 0 then Exit; {$IFDEF FPC} Result := SysUtils.TEncoding.UTF8.GetBytes(Text); {$ELSE} Result := SysUtils.TEncoding.UTF8.GetBytes(buff); {$ENDIF} end; procedure TPascalString.SetBytes(const Value: TBytes); begin SetLength(buff, 0); if length(Value) = 0 then Exit; try Text := SysUtils.TEncoding.UTF8.GetString(Value); except SetPlatformBytes(Value); end; end; function TPascalString.GetPlatformBytes: TBytes; begin SetLength(Result, 0); if length(buff) = 0 then Exit; {$IFDEF FPC} Result := SysUtils.TEncoding.Default.GetBytes(Text); {$ELSE} Result := SysUtils.TEncoding.Default.GetBytes(buff); {$ENDIF} end; procedure TPascalString.SetPlatformBytes(const Value: TBytes); begin SetLength(buff, 0); if length(Value) = 0 then Exit; try Text := SysUtils.TEncoding.Default.GetString(Value); except SetLength(buff, 0); end; end; function TPascalString.GetANSI: TBytes; begin SetLength(Result, 0); if length(buff) = 0 then Exit; {$IFDEF FPC} Result := SysUtils.TEncoding.ANSI.GetBytes(Text); {$ELSE} Result := SysUtils.TEncoding.ANSI.GetBytes(buff); {$ENDIF} end; procedure TPascalString.SetANSI(const Value: TBytes); begin SetLength(buff, 0); if length(Value) = 0 then Exit; try Text := SysUtils.TEncoding.ANSI.GetString(Value); except SetLength(buff, 0); end; end; function TPascalString.GetLast: SystemChar; begin if length(buff) > 0 then Result := buff[length(buff) - 1] else Result := #0; end; procedure TPascalString.SetLast(const Value: SystemChar); begin buff[length(buff) - 1] := Value; end; function TPascalString.GetFirst: SystemChar; begin if length(buff) > 0 then Result := buff[0] else Result := #0; end; procedure TPascalString.SetFirst(const Value: SystemChar); begin buff[0] := Value; end; function TPascalString.GetUpperChar(index: Integer): SystemChar; begin Result := GetChars(index); if CharIn(Result, cLoAtoZ) then Result := SystemChar(Word(Result) xor $0020); end; procedure TPascalString.SetUpperChar(index: Integer; const Value: SystemChar); begin if CharIn(Value, cLoAtoZ) then SetChars(index, SystemChar(Word(Value) xor $0020)) else SetChars(index, Value); end; function TPascalString.GetLowerChar(index: Integer): SystemChar; begin Result := GetChars(index); if CharIn(Result, cHiAtoZ) then Result := SystemChar(Word(Result) or $0020); end; procedure TPascalString.SetLowerChar(index: Integer; const Value: SystemChar); begin if CharIn(Value, cHiAtoZ) then SetChars(index, SystemChar(Word(Value) or $0020)) else SetChars(index, Value); end; {$IFDEF DELPHI} class operator TPascalString.Equal(const Lhs, Rhs: TPascalString): Boolean; begin Result := (Lhs.Len = Rhs.Len) and (Lhs.Text = Rhs.Text); end; class operator TPascalString.NotEqual(const Lhs, Rhs: TPascalString): Boolean; begin Result := not(Lhs = Rhs); end; class operator TPascalString.GreaterThan(const Lhs, Rhs: TPascalString): Boolean; begin Result := Lhs.Text > Rhs.Text; end; class operator TPascalString.GreaterThanOrEqual(const Lhs, Rhs: TPascalString): Boolean; begin Result := Lhs.Text >= Rhs.Text; end; class operator TPascalString.LessThan(const Lhs, Rhs: TPascalString): Boolean; begin Result := Lhs.Text < Rhs.Text; end; class operator TPascalString.LessThanOrEqual(const Lhs, Rhs: TPascalString): Boolean; begin Result := Lhs.Text <= Rhs.Text; end; class operator TPascalString.Add(const Lhs, Rhs: TPascalString): TPascalString; begin CombineCharsPP(Lhs.buff, Rhs.buff, Result.buff); end; class operator TPascalString.Add(const Lhs: SystemString; const Rhs: TPascalString): TPascalString; begin CombineCharsSP(Lhs, Rhs.buff, Result.buff); end; class operator TPascalString.Add(const Lhs: TPascalString; const Rhs: SystemString): TPascalString; begin CombineCharsPS(Lhs.buff, Rhs, Result.buff); end; class operator TPascalString.Add(const Lhs: SystemChar; const Rhs: TPascalString): TPascalString; begin CombineCharsCP(Lhs, Rhs.buff, Result.buff); end; class operator TPascalString.Add(const Lhs: TPascalString; const Rhs: SystemChar): TPascalString; begin CombineCharsPC(Lhs.buff, Rhs, Result.buff); end; class operator TPascalString.Implicit(Value: RawByteString): TPascalString; begin Result.Text := Value; end; class operator TPascalString.Implicit(Value: SystemString): TPascalString; begin Result.Text := Value; end; class operator TPascalString.Implicit(Value: SystemChar): TPascalString; begin Result.Len := 1; Result.buff[0] := Value; end; class operator TPascalString.Implicit(Value: TPascalString): SystemString; begin Result := Value.Text; end; class operator TPascalString.Implicit(Value: TPascalString): Variant; begin Result := Value.Text; end; class operator TPascalString.Explicit(Value: TPascalString): RawByteString; begin Result := Value.Text; end; class operator TPascalString.Explicit(Value: TPascalString): SystemString; begin Result := Value.Text; end; class operator TPascalString.Explicit(Value: TPascalString): Variant; begin Result := Value.Text; end; class operator TPascalString.Explicit(Value: SystemString): TPascalString; begin Result.Text := Value; end; class operator TPascalString.Explicit(Value: Variant): TPascalString; begin Result.Text := VarToStr(Value); end; class operator TPascalString.Explicit(Value: SystemChar): TPascalString; begin Result.Len := 1; Result.buff[0] := Value; end; {$ENDIF} procedure TPascalString.SwapInstance(var source: TPascalString); var tmp: TArrayChar; begin tmp := buff; buff := source.buff; source.buff := tmp; end; function TPascalString.Copy(index, Count: NativeInt): TPascalString; var L_: NativeInt; begin L_ := length(buff); if (index - 1) + Count > L_ then Count := L_ - (index - 1); SetLength(Result.buff, Count); if Count > 0 then CopyPtr(@buff[index - 1], @Result.buff[0], SystemCharSize * Count); end; function TPascalString.Same(const p: PPascalString): Boolean; var i: Integer; s, d: SystemChar; begin Result := (p^.Len = Len); if not Result then Exit; for i := 0 to Len - 1 do begin s := buff[i]; if CharIn(s, cHiAtoZ) then inc(s, 32); d := p^.buff[i]; if CharIn(d, cHiAtoZ) then inc(d, 32); if s <> d then Exit(False); end; end; function TPascalString.Same(const t: TPascalString): Boolean; var i: Integer; s, d: SystemChar; begin Result := (t.Len = Len); if not Result then Exit; for i := 0 to Len - 1 do begin s := buff[i]; if CharIn(s, cHiAtoZ) then inc(s, 32); d := t.buff[i]; if CharIn(d, cHiAtoZ) then inc(d, 32); if s <> d then Exit(False); end; end; function TPascalString.Same(const t1, t2: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2); end; function TPascalString.Same(const t1, t2, t3: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3); end; function TPascalString.Same(const t1, t2, t3, t4: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3) or Same(@t4); end; function TPascalString.Same(const t1, t2, t3, t4, t5: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3) or Same(@t4) or Same(@t5); end; function TPascalString.Same(const t1, t2, t3, t4, t5, t6: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3) or Same(@t4) or Same(@t5) or Same(@t6); end; function TPascalString.Same(const t1, t2, t3, t4, t5, t6, t7: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3) or Same(@t4) or Same(@t5) or Same(@t6) or Same(@t7); end; function TPascalString.Same(const t1, t2, t3, t4, t5, t6, t7, t8: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3) or Same(@t4) or Same(@t5) or Same(@t6) or Same(@t7) or Same(@t8); end; function TPascalString.Same(const t1, t2, t3, t4, t5, t6, t7, t8, t9: TPascalString): Boolean; begin Result := Same(@t1) or Same(@t2) or Same(@t3) or Same(@t4) or Same(@t5) or Same(@t6) or Same(@t7) or Same(@t8) or Same(@t9); end; function TPascalString.Same(const IgnoreCase: Boolean; const t: TPascalString): Boolean; var i: Integer; s, d: SystemChar; begin Result := (t.Len = Len); if not Result then Exit; for i := 0 to Len - 1 do begin s := buff[i]; if IgnoreCase then if CharIn(s, cHiAtoZ) then inc(s, 32); d := t.buff[i]; if IgnoreCase then if CharIn(d, cHiAtoZ) then inc(d, 32); if s <> d then Exit(False); end; end; function TPascalString.ComparePos(const Offset: Integer; const p: PPascalString): Boolean; begin Result := ComparePos(Offset, p, True); end; function TPascalString.ComparePos(const Offset: Integer; const t: TPascalString): Boolean; begin Result := ComparePos(Offset, @t, True); end; function TPascalString.ComparePos(const Offset: Integer; const p: PPascalString; IgnoreCase: Boolean): Boolean; var i, L_: Integer; sourChar, destChar: SystemChar; begin Result := False; i := 1; L_ := p^.Len; if (Offset + L_ - 1) > Len then Exit; while i <= L_ do begin sourChar := GetChars(Offset + i - 1); destChar := p^[i]; if IgnoreCase and CharIn(sourChar, cLoAtoZ) then dec(sourChar, 32); if IgnoreCase and CharIn(destChar, cLoAtoZ) then dec(destChar, 32); if sourChar <> destChar then Exit; inc(i); end; Result := True; end; function TPascalString.ComparePos(const Offset: Integer; const t: TPascalString; IgnoreCase: Boolean): Boolean; var i, L_: Integer; sourChar, destChar: SystemChar; begin Result := False; i := 1; L_ := t.Len; if (Offset + L_) > Len then Exit; while i <= L_ do begin sourChar := GetChars(Offset + i - 1); destChar := t[i]; if IgnoreCase and CharIn(sourChar, cLoAtoZ) then dec(sourChar, 32); if IgnoreCase and CharIn(destChar, cLoAtoZ) then dec(destChar, 32); if sourChar <> destChar then Exit; inc(i); end; Result := True; end; function TPascalString.GetPos(const s: TPascalString; const Offset: Integer = 1): Integer; var i: Integer; begin Result := 0; if s.Len > 0 then for i := Offset to Len - s.Len + 1 do if ComparePos(i, @s) then Exit(i); end; function TPascalString.GetPos(const s: PPascalString; const Offset: Integer = 1): Integer; var i: Integer; begin Result := 0; if s^.Len > 0 then for i := Offset to Len - s^.Len + 1 do if ComparePos(i, s) then Exit(i); end; function TPascalString.Exists(c: SystemChar): Boolean; var i: Integer; begin for i := low(buff) to high(buff) do if buff[i] = c then Exit(True); Result := False; end; function TPascalString.Exists(c: array of SystemChar): Boolean; var i: Integer; begin for i := low(buff) to high(buff) do if CharIn(buff[i], c) then Exit(True); Result := False; end; function TPascalString.StrExists(const s: TPascalString): Boolean; begin Result := GetPos(@s, 1) > 0; end; function TPascalString.GetCharCount(c: SystemChar): Integer; var i: Integer; begin Result := 0; for i := low(buff) to high(buff) do if CharIn(buff[i], c) then inc(Result); end; function TPascalString.IsVisibledASCII: Boolean; var c: SystemChar; begin Result := False; for c in buff do if not CharIn(c, cVisibled) then Exit; Result := True; end; function TPascalString.hash: THash; begin Result := FastHashPPascalString(@Self); end; function TPascalString.Hash64: THash64; begin Result := FastHash64PPascalString(@Self); end; procedure TPascalString.DeleteLast; begin if Len > 0 then SetLength(buff, length(buff) - 1); end; procedure TPascalString.DeleteFirst; begin if Len > 0 then buff := System.Copy(buff, 1, Len); end; procedure TPascalString.Delete(idx, cnt: Integer); begin if (idx + cnt <= Len) then Text := GetString(1, idx) + GetString(idx + cnt, Len + 1) else Text := GetString(1, idx); end; procedure TPascalString.Clear; begin SetLength(buff, 0); end; procedure TPascalString.Reset; begin SetLength(buff, 0); end; procedure TPascalString.Append(t: TPascalString); var r, L_: Integer; begin L_ := length(t.buff); if L_ > 0 then begin r := length(buff); SetLength(buff, r + L_); CopyPtr(@t.buff[0], @buff[r], L_ * SystemCharSize); end; end; procedure TPascalString.Append(c: SystemChar); begin SetLength(buff, length(buff) + 1); buff[length(buff) - 1] := c; end; procedure TPascalString.Append(const Fmt: SystemString; const Args: array of const); begin Append(PFormat(Fmt, Args)); end; function TPascalString.GetString(bPos, ePos: NativeInt): TPascalString; begin if ePos > length(buff) then Result := Self.Copy(bPos, length(buff) - bPos + 1) else Result := Self.Copy(bPos, (ePos - bPos)); end; procedure TPascalString.Insert(Text_: SystemString; idx: Integer); begin Text := GetString(1, idx) + Text_ + GetString(idx + 1, Len); end; procedure TPascalString.FastAsText(var output: SystemString); begin SetLength(output, length(buff)); if length(buff) > 0 then CopyPtr(@buff[0], @output[FirstCharPos], length(buff) * SystemCharSize); end; procedure TPascalString.FastGetBytes(var output: TBytes); begin {$IFDEF FPC} output := SysUtils.TEncoding.UTF8.GetBytes(Text); {$ELSE} output := SysUtils.TEncoding.UTF8.GetBytes(buff); {$ENDIF} end; function TPascalString.LowerText: SystemString; begin Result := LowerCase(Text); end; function TPascalString.UpperText: SystemString; begin Result := UpperCase(Text); end; function TPascalString.Invert: TPascalString; var i, j: Integer; begin SetLength(Result.buff, length(buff)); j := low(Result.buff); for i := high(buff) downto low(buff) do begin Result.buff[j] := buff[i]; inc(j); end; end; function TPascalString.TrimChar(const Chars: TPascalString): TPascalString; var L_, bp, EP: Integer; begin Result := ''; L_ := Len; if L_ > 0 then begin bp := 1; while CharIn(GetChars(bp), @Chars) do begin inc(bp); if (bp > L_) then begin Result := ''; Exit; end; end; if bp > L_ then Result := '' else begin EP := L_; while CharIn(GetChars(EP), @Chars) do begin dec(EP); if (EP < 1) then begin Result := ''; Exit; end; end; Result := GetString(bp, EP + 1); end; end; end; function TPascalString.DeleteChar(const Chars: TPascalString): TPascalString; var c: SystemChar; begin Result := ''; for c in buff do if not CharIn(c, @Chars) then Result.Append(c); end; function TPascalString.DeleteChar(const Chars: TOrdChars): TPascalString; var c: SystemChar; begin Result := ''; for c in buff do if not CharIn(c, Chars) then Result.Append(c); end; function TPascalString.ReplaceChar(const Chars: TPascalString; const newChar: SystemChar): TPascalString; var i: Integer; begin Result.Len := Len; for i := low(buff) to high(buff) do if CharIn(buff[i], Chars) then Result.buff[i] := newChar else Result.buff[i] := buff[i]; end; function TPascalString.ReplaceChar(const Chars, newChar: SystemChar): TPascalString; var i: Integer; begin Result.Len := Len; for i := low(buff) to high(buff) do if CharIn(buff[i], Chars) then Result.buff[i] := newChar else Result.buff[i] := buff[i]; end; function TPascalString.ReplaceChar(const Chars: TOrdChars; const newChar: SystemChar): TPascalString; var i: Integer; begin Result.Len := Len; for i := low(buff) to high(buff) do if CharIn(buff[i], Chars) then Result.buff[i] := newChar else Result.buff[i] := buff[i]; end; function TPascalString.BuildPlatformPChar: Pointer; type TAnsiChar_Buff = array [0 .. MaxInt - 1] of Byte; PAnsiChar_Buff = ^TAnsiChar_Buff; var swap_buff: TBytes; buff_P: PAnsiChar_Buff; begin swap_buff := PlatformBytes; buff_P := GetMemory(length(swap_buff) + 1); if length(swap_buff) > 0 then CopyPtr(@swap_buff[0], buff_P, length(swap_buff)); buff_P^[length(swap_buff)] := 0; SetLength(swap_buff, 0); Result := buff_P; end; class procedure TPascalString.FreePlatformPChar(p: Pointer); begin FreeMemory(p); end; class function TPascalString.RandomString(rnd: TRandom; L_: Integer): TPascalString; var i: Integer; begin Result.L := L_; for i := 1 to L_ do Result[i] := SystemChar(rnd.Rand32($7E - $20) + $20); end; class function TPascalString.RandomString(L_: Integer): TPascalString; var i: Integer; rnd: TMT19937Random; begin Result.L := L_; rnd := TMT19937Random.Create; for i := 1 to L_ do Result[i] := SystemChar(rnd.Rand32($7E - $20) + $20); DisposeObject(rnd); end; class function TPascalString.RandomString(rnd: TRandom; L_: Integer; Chars_: TOrdChars): TPascalString; var i: Integer; tmp: SystemChar; begin Result.L := L_; for i := 1 to L_ do begin repeat tmp := SystemChar(rnd.Rand32($7E - $20) + $20); until CharIn(tmp, Chars_); Result[i] := tmp; end; end; class function TPascalString.RandomString(L_: Integer; Chars_: TOrdChars): TPascalString; var i: Integer; rnd: TMT19937Random; tmp: SystemChar; begin Result.L := L_; rnd := TMT19937Random.Create; for i := 1 to L_ do begin repeat tmp := SystemChar(rnd.Rand32($7E - $20) + $20); until CharIn(tmp, Chars_); Result[i] := tmp; end; DisposeObject(rnd); end; function TPascalString.SmithWaterman(const p: PPascalString): Double; begin Result := SmithWatermanCompare(@Self, @p); end; function TPascalString.SmithWaterman(const s: TPascalString): Double; begin Result := SmithWatermanCompare(@Self, @s); end; function TPascalString.BOMBytes: TBytes; begin {$IFDEF FPC} Result := GetBytes; {$ELSE} Result := SysUtils.TEncoding.UTF8.GetPreamble + GetBytes; {$ENDIF} end; end.
26.586066
153
0.656698
472054daaf8e67e34abfbd4c285fae0934ee07ca
2,815
pas
Pascal
windows/src/global/delphi/general/UKeymanTargets.pas
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
1
2021-03-08T09:31:47.000Z
2021-03-08T09:31:47.000Z
windows/src/global/delphi/general/UKeymanTargets.pas
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
null
null
null
windows/src/global/delphi/general/UKeymanTargets.pas
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
null
null
null
unit UKeymanTargets; interface type TKeymanTarget = ( ktAny, ktWindows, ktMacosx, ktLinux, ktWeb, ktIphone, ktIpad, ktAndroidphone, ktAndroidtablet, ktMobile, ktDesktop, ktTablet); TKeymanTargets = set of TKeymanTarget; const // Note: if these change, update the copied values in KeyboardParser.pas accordingly AllKeymanTargets: TKeymanTargets = [ ktAny, ktWindows, ktMacosx, ktLinux, ktWeb, ktIphone, ktIpad, ktAndroidphone, ktAndroidtablet, ktMobile, ktDesktop, ktTablet ]; TouchKeymanTargets: TKeymanTargets = [ ktWeb, ktIphone, ktIpad, ktAndroidphone, ktAndroidtablet, ktMobile, ktTablet ]; // Compile to .kmx KMXKeymanTargets: TKeymanTargets = [ ktWindows, ktMacosx, ktLinux, ktDesktop ]; // Compile to .js KMWKeymanTargets: TKeymanTargets = [ ktWeb, ktIphone, ktIpad, ktAndroidphone, ktAndroidtablet, ktMobile, ktTablet ]; // Supports .kvks KeymanTargetsUsingKVK: TKeymanTargets = [ ktWindows, ktMacosx, ktLinux, ktDesktop, ktWeb ]; // Other targets? // SKeymanTargets: array[TKeymanTarget] of string = ( 'any', 'windows', 'macosx', 'linux', 'web', 'iphone', 'ipad', 'androidphone', 'androidtablet', 'mobile', 'desktop', 'tablet'); // Friendly names for targets, e.g. for documentation SKeymanTargetNames: array[TKeymanTarget] of string = ( 'All', 'Windows', 'macOS', 'Linux', 'Web', 'iPhone', 'iPad', 'Android phone', 'Android tablet', 'Mobile devices', 'Desktop devices', 'Tablet devices'); function KeymanTargetsToString(ATargets: TKeymanTargets): string; function KeymanTargetsToNames(ATargets: TKeymanTargets): string; function StringToKeymanTargets(ATargets: string): TKeymanTargets; implementation uses System.SysUtils, utilstr; function StringToKeymanTargets(ATargets: string): TKeymanTargets; var s: string; i: TKeymanTarget; begin Result := []; s := StrToken(ATargets, ' '); while s <> '' do begin for i := Low(TKeymanTarget) to High(TKeymanTarget) do if SameText(SKeymanTargets[i], s) then begin Include(Result, i); Break; end; s := StrToken(ATargets, ' '); end; end; function KeymanTargetsToString(ATargets: TKeymanTargets): string; var i: TKeymanTarget; begin Result := ''; for i := Low(TKeymanTarget) to High(TKeymanTarget) do if i in ATargets then Result := Result + SKeymanTargets[i] + ' '; Result := Trim(Result); end; function KeymanTargetsToNames(ATargets: TKeymanTargets): string; var i: TKeymanTarget; begin Result := ''; for i := Low(TKeymanTarget) to High(TKeymanTarget) do begin if i in ATargets then begin if Result <> '' then Result := Result + ', '; Result := Result + SKeymanTargetNames[i]; end; end; end; end.
23.655462
86
0.680995
83fc519c129288d92cf6b59a37127728dc31daee
1,536
pas
Pascal
main/personaddfrm.pas
joshluisaac/onLazarus
c46328f694195a913334c88a791afef023d6a212
[ "Apache-2.0" ]
null
null
null
main/personaddfrm.pas
joshluisaac/onLazarus
c46328f694195a913334c88a791afef023d6a212
[ "Apache-2.0" ]
null
null
null
main/personaddfrm.pas
joshluisaac/onLazarus
c46328f694195a913334c88a791afef023d6a212
[ "Apache-2.0" ]
null
null
null
unit PersonAddFrm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ActnList, StdActns, PersonModel; type { TForm1 } TForm1 = class(TForm) ActionList1: TActionList; saveBtn: TButton; cancelBtn: TButton; firstName: TEdit; middleName: TEdit; lastName: TEdit; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; remarks: TMemo; SearchFind1: TSearchFind; procedure cancelBtnClick(Sender: TObject); procedure firstNameChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure GroupBox1Click(Sender: TObject); procedure LabeledEdit1Change(Sender: TObject); procedure Panel1Click(Sender: TObject); procedure saveBtnClick(Sender: TObject); private public end; var Form1: TForm1; person : Tperson; implementation {$R *.lfm} { TForm1 } procedure TForm1.LabeledEdit1Change(Sender: TObject); begin end; procedure TForm1.Panel1Click(Sender: TObject); begin end; procedure TForm1.saveBtnClick(Sender: TObject); begin remarks.Text:= ''; person := Tperson.create(firstName.Text,middleName.Text,lastName.text); remarks.Lines.Add(person.format()); end; procedure TForm1.firstNameChange(Sender: TObject); begin end; procedure TForm1.FormShow(Sender: TObject); begin remarks.Text:= ''; end; procedure TForm1.GroupBox1Click(Sender: TObject); begin end; procedure TForm1.cancelBtnClick(Sender: TObject); begin Form1.Close; end; end.
16.879121
76
0.723307
6aefdc58c9401b17fcb7553777a9c8efeefa2b01
7,274
pas
Pascal
main.pas
BlackDoomer/Artist
328cbbd5f76c9c76f5d7c6d8250c356411a8ee9b
[ "WTFPL" ]
2
2016-03-06T03:33:56.000Z
2017-10-16T06:25:53.000Z
main.pas
BlackDoomer/Artist
328cbbd5f76c9c76f5d7c6d8250c356411a8ee9b
[ "WTFPL" ]
null
null
null
main.pas
BlackDoomer/Artist
328cbbd5f76c9c76f5d7c6d8250c356411a8ee9b
[ "WTFPL" ]
null
null
null
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, ColorBox, StdCtrls, ComCtrls, Menus, tools; type { TMainForm } TMainForm = class(TForm) DlgOpenImage: TOpenDialog; DlgSaveImage: TSaveDialog; ToolBox: TPanel; LToolBox: TLabel; BtnPen: TSpeedButton; BtnLine: TSpeedButton; BtnRect: TSpeedButton; BtnEllipse: TSpeedButton; BtnEraser: TSpeedButton; BtnFiller: TSpeedButton; FColorBox: TColorBox; LFColorBox: TLabel; BColorBox: TColorBox; LBColorBox: TLabel; PenSize: TTrackBar; LPenSize: TLabel; SolidCB: TCheckBox; Doge: TImage; // :3 ScrollBox: TScrollBox; PaintBox: TPaintBox; MenuBar: TMainMenu; FileMenu: TMenuItem; OpenItem: TMenuItem; SaveItem: TMenuItem; FileSep1: TMenuItem; ExitItem: TMenuItem; EditMenu: TMenuItem; ClearItem: TMenuItem; SizeItem: TMenuItem; AboutItem: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure WorkspaceClick(Sender: TObject); procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBoxPaint(Sender: TObject); procedure BtnEllipseClick(Sender: TObject); procedure BtnEraserClick(Sender: TObject); procedure BtnLineClick(Sender: TObject); procedure BtnPenClick(Sender: TObject); procedure BtnRectClick(Sender: TObject); procedure BtnFillerClick(Sender: TObject); procedure OpenItemClick(Sender: TObject); procedure SaveItemClick(Sender: TObject); procedure ExitItemClick(Sender: TObject); procedure ClearItemClick(Sender: TObject); procedure SizeItemClick(Sender: TObject); procedure AboutItemClick(Sender: TObject); procedure UpdateTool( X, Y: Integer ); private SelTool: ToolEnum; CurTool: TTool; public ImageBuf: TBitMap; //main image buffer end; { Additional routines } procedure ClearImg( image: TBitMap ); var MainForm: TMainForm; implementation uses f_imagesize; {$R *.lfm} { MainForm } procedure TMainForm.FormCreate(Sender: TObject); begin SelTool := TLPEN; CurTool := nil; ScrollBox.DoubleBuffered := True; //enable double buffering ImageBuf := TBitMap.Create(); ImageBuf.Width := PaintBox.Width; ImageBuf.Height := PaintBox.Height; //FILL IT WITH WHITE!!1 ClearImg( ImageBuf ); end; procedure TMainForm.FormDestroy(Sender: TObject); begin ImageBuf.Destroy(); end; procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if not ( MessageDlg('Leaving so soon?', mtConfirmation, mbYesNo, 0) = mrYes ) then CloseAction := caNone; end; procedure TMainForm.BtnPenClick(Sender: TObject); begin SelTool := TLPEN; end; procedure TMainForm.BtnLineClick(Sender: TObject); begin SelTool := TLLINE; end; procedure TMainForm.BtnRectClick(Sender: TObject); begin SelTool := TLRECT; end; procedure TMainForm.BtnEllipseClick(Sender: TObject); begin SelTool := TLELLIPSE; end; procedure TMainForm.BtnEraserClick(Sender: TObject); begin SelTool := TLERASER; end; procedure TMainForm.BtnFillerClick(Sender: TObject); begin SelTool := TCFILLER; end; procedure TMainForm.OpenItemClick(Sender: TObject); begin if DlgOpenImage.Execute() then begin ImageBuf.LoadFromFile( DlgOpenImage.FileName ); PaintBox.Width := ImageBuf.Width; PaintBox.Height := ImageBuf.Height; PaintBox.Invalidate(); end; end; procedure TMainForm.SaveItemClick(Sender: TObject); begin if DlgSaveImage.Execute() then ImageBuf.SaveToFile( ChangeFileExt( DlgSaveImage.FileName, DlgSaveImage.DefaultExt ) ); end; procedure TMainForm.ExitItemClick(Sender: TObject); begin Close(); end; procedure TMainForm.ClearItemClick(Sender: TObject); begin if ( MessageDlg('Are you sure?', mtConfirmation, mbYesNo, 0) = mrYes ) then begin ClearImg( ImageBuf ); PaintBox.Invalidate(); end; end; procedure TMainForm.SizeItemClick(Sender: TObject); begin SizeForm.ShowModal(); end; procedure TMainForm.AboutItemClick(Sender: TObject); begin ShowMessage( 'DAS IST another paint clone called "Artist"' +#13#10 + 'but this one with beautiful girl on icon ^^' +#13#10 + #13#10 + 'by Dmitry D. Chernov who made it last night' ); end; procedure TMainForm.WorkspaceClick(Sender: TObject); begin MainForm.ActiveControl := ScrollBox; end; { PaintBox } procedure TMainForm.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var FColor, BColor: TColor; begin if not (CurTool = nil) then Exit; case Button of mbLeft: FColor := FColorBox.Selected; mbRight: FColor := BColorBox.Selected; else Exit; end; if SolidCB.Checked then BColor := BColorBox.Selected else BColor := clNone; case SelTool of TLPEN: CurTool := TPen.Create( X, Y, FColor, BColor, PenSize.Position ); TLERASER: CurTool := TPen.Create( X, Y, clWhite, clNone, PenSize.Position + 5 ); TLLINE: CurTool := TLine.Create( X, Y, FColor, BColor, PenSize.Position ); TLRECT: CurTool := TRectangle.Create( X, Y, FColor, BColor, PenSize.Position ); TLELLIPSE: CurTool := TEllipse.Create( X, Y, FColor, BColor, PenSize.Position ); TCFILLER: FillAtXY( ImageBuf.Canvas, X, Y, FColor ); end; UpdateTool( X, Y ); end; procedure TMainForm.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin UpdateTool( X, Y ); end; procedure TMainForm.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if not (CurTool = nil) then begin CurTool.Draw( ImageBuf.Canvas ); CurTool.Destroy(); CurTool := nil; end; end; procedure TMainForm.PaintBoxPaint(Sender: TObject); var rect: TRect; begin rect := Bounds( 0, 0, PaintBox.Width, PaintBox.Height ); PaintBox.Canvas.CopyRect( rect, ImageBuf.Canvas, rect ); if not ( (CurTool = nil) or (CurTool is TPen) ) then CurTool.Draw( PaintBox.Canvas ); end; { Additional routines } procedure TMainForm.UpdateTool( X, Y: Integer ); begin if not (CurTool = nil) then begin CurTool.Update(X, Y); if (CurTool is TPen) then CurTool.Draw( ImageBuf.Canvas ); end; PaintBox.Invalidate(); end; procedure ClearImg( image: TBitMap ); begin image.Canvas.Pen.Color := clWhite; image.Canvas.Brush.Color := clWhite; image.Canvas.Rectangle(0, 0, image.Width, image.Height); end; end.
26.071685
78
0.66937
47312b7ec202518e424ccfbeca25fe6b8176efb4
1,846
dfm
Pascal
usersF.dfm
Samson1983/Payout
f62b2d3aad3524d842608bded8d83af30eeb069f
[ "MIT" ]
null
null
null
usersF.dfm
Samson1983/Payout
f62b2d3aad3524d842608bded8d83af30eeb069f
[ "MIT" ]
1
2022-02-23T08:30:18.000Z
2022-02-23T08:30:18.000Z
usersF.dfm
Samson1983/Payout
f62b2d3aad3524d842608bded8d83af30eeb069f
[ "MIT" ]
null
null
null
object Fusers: TFusers Left = 403 Top = 226 BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSingle Caption = #20462#25913#29992#25143#21517#21450#23494#30721 ClientHeight = 172 ClientWidth = 242 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter Visible = True OnClose = FormClose OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 33 Top = 44 Width = 64 Height = 13 AutoSize = False Caption = #26032#29992#25143#21517#65306 end object Label2: TLabel Left = 33 Top = 84 Width = 36 Height = 13 AutoSize = False Caption = #23494#30721#65306 end object Label3: TLabel Left = 33 Top = 116 Width = 60 Height = 13 AutoSize = False Caption = #30830#35748#23494#30721#65306 end object Label4: TLabel Left = 32 Top = 16 Width = 65 Height = 13 AutoSize = False Caption = #21407#29992#25143#21517#65306 end object Label5: TLabel Left = 104 Top = 16 Width = 113 Height = 13 AutoSize = False end object RzEdit1: TRzEdit Left = 97 Top = 44 Width = 121 Height = 21 TabOrder = 0 OnKeyPress = RzEdit1KeyPress end object RzEdit2: TRzEdit Left = 97 Top = 84 Width = 121 Height = 21 PasswordChar = '*' TabOrder = 1 OnKeyPress = RzEdit2KeyPress end object RzEdit3: TRzEdit Left = 97 Top = 116 Width = 121 Height = 21 PasswordChar = '*' TabOrder = 2 OnKeyPress = RzEdit3KeyPress end object RzBitBtn1: TRzBitBtn Left = 144 Top = 144 Caption = #30830#23450 TabOrder = 3 OnClick = RzBitBtn1Click end end
19.431579
60
0.627302
8598e100065d6e1d93826f4370fe51565c990092
51,754
pas
Pascal
Client/fDocItemsEdit.pas
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Client/fDocItemsEdit.pas
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Client/fDocItemsEdit.pas
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
3
2021-06-30T10:11:17.000Z
2021-07-01T09:13:29.000Z
unit fDocItemsEdit; {$WARN UNIT_PLATFORM OFF} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, fEditForm, DB, AbmesFields, Dialogs, fBaseFrame, fDBFrame, fFieldEditFrame, fDateFieldEditFrame, ComCtrls, ToolWin, StdCtrls, AbmesDBCheckBox, JvExStdCtrls, JvDBCombobox, JvExControls, JvComponent, JvDBLookup, DBCtrls, Buttons, Mask, JvExMask, JvToolEdit, JvDBControls, DBClient, AbmesClientDataSet, JvCaptionButton, ActnList, ExtCtrls, fEmployeeFieldEditFrame, fEmployeeFieldEditFrameBald, JvComponentBase, Menus, JvCombobox, JvDragDrop, System.Actions; type TfmDocItemsEdit = class(TEditForm) pnlStorageInfo: TPanel; pnlStorageType: TPanel; lblDocItemStorageType: TLabel; pnlExternalFileStorage: TPanel; lblFileName: TLabel; lblRelativePath: TLabel; edtFileName: TJvDBComboEdit; edtRelativePath: TJvDBComboEdit; pnlInternalFileStorage: TPanel; lblFileExtension: TLabel; edtFileExtension: TDBEdit; edtIsStoredFileChanged: TDBEdit; lblIsStoredFileDataChanged: TLabel; btnImportFromFile: TSpeedButton; btnExportToFile: TSpeedButton; actImportFromFile: TAction; actExportToFile: TAction; cbDocItemStorageType: TJvDBLookupCombo; btnEditStoredFileData: TSpeedButton; actEditStoredFileData: TAction; OpenDialog: TOpenDialog; cdsDocItemPatterns: TAbmesClientDataSet; dsDocItemPatterns: TDataSource; cdsDocItemPatternsDOC_ITEM_PATTERN_CODE: TAbmesFloatField; cdsDocItemPatternsDOC_ITEM_PATTERN_NAME: TAbmesWideStringField; cbPattern: TJvDBLookupCombo; lblPattern: TLabel; grpDocItem: TGroupBox; lblDocItemType: TLabel; cbDocItemType: TJvDBLookupCombo; lblDocItemName: TLabel; edtDocItemName: TDBEdit; lblNotes: TLabel; edtNotes: TDBEdit; grpPhase: TGroupBox; actDevelop: TAction; actAuthorize: TAction; actApprove: TAction; actImportFromTemplate: TAction; btnImportFromTemplate: TSpeedButton; edtDocItemNo: TDBEdit; lblDocItemNo: TLabel; chkIsInactive: TAbmesDBCheckBox; actClearStoredFile: TAction; btnClearStoredFile: TSpeedButton; frDevelopDate: TfrDateFieldEditFrame; frAuthorizeDate: TfrDateFieldEditFrame; frApproveDate: TfrDateFieldEditFrame; actConvertExternalDocItemToInternal: TAction; pnlConvertExternalDocItemToInternal: TPanel; btnConvertExternalDocItemToInternal: TSpeedButton; frDevelopEmployee: TfrEmployeeFieldEditFrameBald; frAuthorizeEmployee: TfrEmployeeFieldEditFrameBald; frApproveEmployee: TfrEmployeeFieldEditFrameBald; btnDocItemAccess: TButton; actDocItemSysRoles: TAction; cdsEmployeeFrameAllEmployees: TAbmesClientDataSet; pnlIsDocItemSysRolesDefault: TPanel; chkIsMirrored: TAbmesDBCheckBox; pnlMirroredDocItemPaths: TPanel; lblMirroredFileName: TLabel; edtMirroredFileName: TJvDBComboEdit; lblMirroredRelativePath: TLabel; edtMirroredRelativePath: TJvDBComboEdit; edtDocsLocalRootPath: TEdit; edtDocItemMirrorsRootPath: TEdit; pnlIsMirrored: TPanel; btnExternalFileOpen: TBitBtn; actExternalFileOpen: TAction; lblChangeDate: TLabel; edtExternalFileChangeDate: TDBEdit; btnExternalFileDelete: TBitBtn; actExternalFileDelete: TAction; btnExternalFileExport: TBitBtn; actExternalFileExport: TAction; sdExternalFileExport: TSaveDialog; btnExternalFileImport: TBitBtn; actExternalFileImport: TAction; odExternalFileImport: TOpenDialog; btnExternalFileNewFromTemplate: TBitBtn; actExternalFileNewFromTemplate: TAction; cdsExtFileChangeDate: TAbmesClientDataSet; dsExtFileChangeDate: TDataSource; cdsExtFileChangeDateEXT_FILE_CHANGE_DATE: TAbmesSQLTimeStampField; frStoredFileChangeEmployee: TfrEmployeeFieldEditFrameBald; lblStoredFileChangeEmployee: TLabel; frStoredFileChangeDate: TfrDateFieldEditFrame; btnOpenStoredFileReadOnly: TSpeedButton; actOpenStoredFileReadOnly: TAction; btnExternalFileEdit: TBitBtn; actExternalFileEdit: TAction; pnlDevelop: TPanel; btnApprove: TSpeedButton; btnAuthorize: TSpeedButton; btnDevelop: TSpeedButton; pnlExternalDocStorage: TPanel; lblExternalStorageDocId: TLabel; btnExternalDocStorageView: TBitBtn; actExternalDocStorageView: TAction; imgDevelopTime: TImage; imgAuthorizeTime: TImage; imgApproveTime: TImage; drpImportFromFile: TJvDropTarget; btnExternalDocStorageEdit: TBitBtn; actExternalDocStorageEdit: TAction; actExternalDocStorageSelect: TAction; actClearExternalStorageDocId: TAction; pnlExternalStorageDocIdButtons: TPanel; btnClearExternalStorageDocId: TSpeedButton; btnExternalDocStorageSelect: TSpeedButton; edtExternalStorageDocId: TDBEdit; cdsExternalStorageDocId: TAbmesClientDataSet; cdsExternalStorageDocIdDOC_ID: TAbmesWideStringField; pnlContentStorage: TPanel; lblContentStorageFileExtention: TLabel; btnContentStorageFileImport: TSpeedButton; btnContentStorageFileExport: TSpeedButton; btnContentStorageFileOpen: TSpeedButton; lblContentStoragePattern: TLabel; btnContentStorageFileImportFromTemplate: TSpeedButton; btnContentStorageFileDelete: TSpeedButton; lblContentStorageChangeEmployee: TLabel; btnContentStorageFileOpenReadOnly: TSpeedButton; edtContentStorageFileExtention: TDBEdit; cbContentStoragePattern: TJvDBLookupCombo; frContentStorageFileChangeEmployee: TfrEmployeeFieldEditFrameBald; frContentStorageFileChangeDate: TfrDateFieldEditFrame; actContentStorageFileOpenReadOnly: TAction; actContentStorageFileOpen: TAction; actContentStorageFileDelete: TAction; actContentStorageFileImportFromTemplate: TAction; actContentStorageFileImport: TAction; actContentStorageFileExport: TAction; procedure edtMirroredRelativePathButtonClick(Sender: TObject); procedure edtMirroredFileNameButtonClick(Sender: TObject); procedure actDocItemSysRolesExecute(Sender: TObject); procedure edtFileNameButtonClick(Sender: TObject); procedure edtRelativePathButtonClick(Sender: TObject); procedure actFormUpdate(Sender: TObject); procedure actImportFromFileExecute(Sender: TObject); procedure actExportToFileExecute(Sender: TObject); procedure actEditStoredFileDataExecute(Sender: TObject); procedure actDevelopExecute(Sender: TObject); procedure actDevelopUpdate(Sender: TObject); procedure actAuthorizeExecute(Sender: TObject); procedure actAuthorizeUpdate(Sender: TObject); procedure actApproveExecute(Sender: TObject); procedure actApproveUpdate(Sender: TObject); procedure actImportFromTemplateExecute(Sender: TObject); procedure actEditStoredFileDataUpdate(Sender: TObject); procedure actImportFromFileUpdate(Sender: TObject); procedure actImportFromTemplateUpdate(Sender: TObject); procedure actExportToFileUpdate(Sender: TObject); procedure actClearStoredFileExecute(Sender: TObject); procedure actClearStoredFileUpdate(Sender: TObject); procedure cbDocItemStorageTypeChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actConvertExternalDocItemToInternalExecute(Sender: TObject); procedure actConvertExternalDocItemToInternalUpdate(Sender: TObject); procedure actExternalFileOpenUpdate(Sender: TObject); procedure actExternalFileOpenExecute(Sender: TObject); procedure actExternalFileDeleteUpdate(Sender: TObject); procedure actExternalFileDeleteExecute(Sender: TObject); procedure actExternalFileExportUpdate(Sender: TObject); procedure actExternalFileExportExecute(Sender: TObject); procedure actExternalFileImportUpdate(Sender: TObject); procedure actExternalFileImportExecute(Sender: TObject); procedure actExternalFileNewFromTemplateUpdate(Sender: TObject); procedure actExternalFileNewFromTemplateExecute(Sender: TObject); procedure dsDataDataChange(Sender: TObject; Field: TField); procedure actOpenStoredFileReadOnlyExecute(Sender: TObject); procedure actOpenStoredFileReadOnlyUpdate(Sender: TObject); procedure actExternalFileEditUpdate(Sender: TObject); procedure actExternalFileEditExecute(Sender: TObject); procedure actExternalDocStorageViewUpdate(Sender: TObject); procedure actExternalDocStorageViewExecute(Sender: TObject); procedure imgTimeMouseLeave(Sender: TObject); procedure imgTimeMouseEnter(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure drpImportFromFileDragAccept(Sender: TJvDropTarget; var Accept: Boolean); procedure drpImportFromFileDragDrop(Sender: TJvDropTarget; var Effect: TJvDropEffect; Shift: TShiftState; X, Y: Integer); procedure actExternalDocStorageEditUpdate(Sender: TObject); procedure actExternalDocStorageEditExecute(Sender: TObject); procedure actClearExternalStorageDocIdUpdate(Sender: TObject); procedure actExternalDocStorageSelectUpdate(Sender: TObject); procedure actClearExternalStorageDocIdExecute(Sender: TObject); procedure actExternalDocStorageSelectExecute(Sender: TObject); procedure actContentStorageFileOpenReadOnlyUpdate(Sender: TObject); procedure actContentStorageFileOpenUpdate(Sender: TObject); procedure actContentStorageFileExportExecute(Sender: TObject); procedure actContentStorageFileDeleteUpdate(Sender: TObject); procedure actContentStorageFileImportFromTemplateExecute(Sender: TObject); procedure actContentStorageFileImportUpdate(Sender: TObject); procedure actContentStorageFileOpenReadOnlyExecute(Sender: TObject); procedure actContentStorageFileOpenExecute(Sender: TObject); procedure actContentStorageFileDeleteExecute(Sender: TObject); procedure actContentStorageFileImportExecute(Sender: TObject); procedure actContentStorageFileExportUpdate(Sender: TObject); procedure actContentStorageFileImportFromTemplateUpdate(Sender: TObject); private FSaveApplicationHintPause: Integer; procedure ChooseRelativePath(ARootPath: string; ARelativePathField: TField); procedure ChooseFileName(ARootPath: string; AFileNameField, ARelativePathField: TField); function IsDocItemSysRolesDefault: Boolean; function ExternalFileName: string; function IsInDevelopPhase: Boolean; procedure UpdateExtFileChangeDateField; function IsAllowedFileType(const AFileName: string): Boolean; protected procedure OpenDataSets; override; procedure CloseDataSets; override; procedure DoApplyUpdates; override; procedure DoCancelUpdates; override; function IsDocModifiedHere: Boolean; override; procedure SetDBFrameReadOnly(AFrame: TDBFrame); override; public procedure Initialize; override; end; implementation uses FileCtrl, Consts, uUtils, uClientTypes, uClientUtils, StrUtils, dMain, dDocClient, uDocUtils, uUserActivityConsts, fDocItemSysRoles, uClientConsts, uLoginContext, fBaseForm, AbmesDialogs, fSelectDocItemTemplate, DateUtils, fDBDataForm, uClientDateTime, uSysRoleClientUtils, uDocItemStorageTypes, uDocClientUtils, fExternalDocStorageDocId, uDocItemStorageBaseTypes; {$R *.dfm} resourcestring SFileNotInLocalRoot = 'Избраният файл не е в конфигурираният Локален път за ИИО (%s)!'; SDirNotInLocalRoot = 'Избраният път не е в конфигурираният път за ИИО (%s)!'; SDocItemSysRolesDefault = 'ИИО без специални Информационни Отговорности за достъп'; SDocItemSysRolesChanged = 'ИИО със специални Информационни Отговорности за достъп'; SDeleteExternalFileQuestion = 'Потвърдете изтриването на файл!'; SExternalFileCouldNotBeDeleted = 'Външният файл не съществува или не може да бъде изтрит.'; SCouldNotCreateFile = 'Файлът %s не може да бъде създаден.'; SExternalFileDoesNotExist = 'Външният файл не съществува.'; SExternalFileExists = 'Външният файл трбва да бъде изтрит преди %s.'; SImport = 'Импорт'; SNewFromTemplate = 'създаване на нов'; SAuthorizeFileNameAndPathRequired = 'При Авторизиране полетата "Име на файл" и "Релативен път" трябва да имат стойност.'; SAuthorizeExternalDocIdRequired = 'При Авторизиране полето "Външен Идентификатор" трябва да има стойност.'; SConfirmClearingExternalDocStorageDocId = 'Потвърдете изчистването на Външен Идентификатор!'; { TfmDocItemsEdit } procedure TfmDocItemsEdit.OpenDataSets; begin inherited; cdsDocItemPatterns.Params.ParamByName('DOC_ITEM_TEMPLATE_TYPE_CODE').AsInteger:= DocItemTemplateTypeToInt(GetDocOwnerTypeTemplateType(dmDocClient.OpenDocOwnerType)); cdsDocItemPatterns.Open; cdsExtFileChangeDate.CreateDataSet; end; procedure TfmDocItemsEdit.CloseDataSets; begin inherited; cdsExtFileChangeDate.Close; cdsDocItemPatterns.Close; end; procedure TfmDocItemsEdit.DoApplyUpdates; begin inherited DoApplyUpdates; Assert(Assigned(dsData.DataSet)); if Assigned(dsData.DataSet.DataSetField) and (dsData.DataSet.DataSetField.DataSet.State in dsEditModes) then begin try dsData.DataSet.DataSetField.DataSet.Post; except CheckEditMode(dsData.DataSet); raise; end; { try } end; { if } end; procedure TfmDocItemsEdit.DoCancelUpdates; begin inherited DoCancelUpdates; Assert(Assigned(dsData.DataSet)); if Assigned(dsData.DataSet.DataSetField) and (dsData.DataSet.DataSetField.DataSet.State in dsEditModes) then dsData.DataSet.DataSetField.DataSet.Cancel; end; function TfmDocItemsEdit.IsAllowedFileType(const AFileName: string): Boolean; var AllowedFileExtensions: TStringList; FileExtension: string; Extension: string; begin Result:= False; FileExtension:= ExtractFileExt(AFileName); FileExtension:= RightStr(FileExtension, Length(FileExtension)-1); AllowedFileExtensions:= TStringList.Create; try AllowedFileExtensions.Delimiter:= ';'; AllowedFileExtensions.DelimitedText:= dsData.DataSet.FieldByName('_DOC_ITEM_TYPE_FILE_EXTENSIONS').AsString; for Extension in AllowedFileExtensions do if SameText(FileExtension, Extension) then Exit(True); finally FreeAndNil(AllowedFileExtensions); end; end; procedure TfmDocItemsEdit.drpImportFromFileDragAccept(Sender: TJvDropTarget; var Accept: Boolean); begin inherited; Accept:= ( (actImportFromFile.Enabled and pnlInternalFileStorage.Visible) or (actContentStorageFileImport.Enabled and pnlContentStorage.Visible) ) and Sender.IsSingleFile and IsAllowedFileType(Sender.SingleFileName); end; procedure TfmDocItemsEdit.drpImportFromFileDragDrop(Sender: TJvDropTarget; var Effect: TJvDropEffect; Shift: TShiftState; X, Y: Integer); begin inherited; if pnlInternalFileStorage.Visible then dmDocClient.DoImportInternalDocItemDataFromFile(Sender.SingleFileName); if pnlContentStorage.Visible then dmDocClient.SetContentStorageFile(Sender.SingleFileName); end; procedure TfmDocItemsEdit.dsDataDataChange(Sender: TObject; Field: TField); begin inherited; if Assigned(Field) and ((Field.FieldName = 'FILE_NAME') or (Field.FieldName = 'RELATIVE_PATH')) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) then UpdateExtFileChangeDateField; imgDevelopTime.Hint:= dsData.DataSet.FieldByName('DEVELOP_TIME').DisplayText; imgAuthorizeTime.Hint:= dsData.DataSet.FieldByName('AUTHORIZE_TIME').DisplayText; imgApproveTime.Hint:= dsData.DataSet.FieldByName('APPROVE_TIME').DisplayText; end; function TfmDocItemsEdit.IsDocModifiedHere: Boolean; begin Assert(Assigned(dsData.DataSet.DataSetField)); Result:= (dsData.DataSet.DataSetField.DataSet.State in dsEditModes); end; procedure TfmDocItemsEdit.ChooseFileName(ARootPath: string; AFileNameField, ARelativePathField: TField); function GetChosenFileExtension(AFileName: string): string; begin Result:= '.' + dsData.DataSet.FieldByName('_FILE_EXTENSION_ABBREV').AsString; if (Result = '.') then Result:= ExtractFileExt(AFileName); end; var s: string; p: Integer; begin OpenDialog.Filter:= dmMain.SvrDoc.GetDocItemTypeFileDialogFilter(dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').AsInteger); OpenDialog.FileName:= AFileNameField.AsString; OpenDialog.InitialDir:= ExcludeTrailingPathDelimiter(ARootPath) + ARelativePathField.AsString; if OpenDialog.Execute then begin OpenDialog.FileName:= ChangeFileExt(OpenDialog.FileName, GetChosenFileExtension(OpenDialog.FileName)); s:= ExtractFilePath(OpenDialog.FileName); if (s[Length(s)-1] <> ':') then SetLength(s, Length(s)-1); p:= Pos(UpperCase(ExcludeTrailingPathDelimiter(ARootPath)), UpperCase(s)); if (p = 1) then begin s:= RightStr(s, Length(s)-Length(ExcludeTrailingPathDelimiter(ARootPath))); if (s = '') then s:= '\'; end { if } else raise Exception.CreateFmt(SFileNotInLocalRoot, [ARootPath]); CheckEditMode(dsData.DataSet); AFileNameField.AsString:= ExtractFileName(OpenDialog.FileName); ARelativePathField.AsString:= s; end; { if } end; procedure TfmDocItemsEdit.edtFileNameButtonClick(Sender: TObject); begin inherited; if (EditMode <> emReadOnly) and not edtFileName.ReadOnly then ChooseFileName( LoginContext.DocsLocalRootPath, dsData.DataSet.FieldByName('FILE_NAME'), dsData.DataSet.FieldByName('RELATIVE_PATH')); end; procedure TfmDocItemsEdit.edtMirroredFileNameButtonClick(Sender: TObject); begin inherited; if (EditMode <> emReadOnly) and not edtMirroredFileName.ReadOnly then ChooseFileName( LoginContext.DocItemMirrorsRootPath, dsData.DataSet.FieldByName('MIRRORED_FILE_NAME'), dsData.DataSet.FieldByName('MIRRORED_RELATIVE_PATH')); end; procedure TfmDocItemsEdit.ChooseRelativePath(ARootPath: string; ARelativePathField: TField); var DirName: string; p: Integer; begin DirName:= ExcludeTrailingPathDelimiter(ARootPath) + ARelativePathField.AsString; if SelectDirectory(SSelectDirCap, '', DirName) then begin p:= Pos(UpperCase(ARootPath), UpperCase(DirName)); if (p = 1) then begin DirName:= RightStr(DirName, Length(DirName)-Length(ARootPath)); if (DirName = '') then DirName:= PathDelim; if (DirName[1] <> PathDelim) then DirName:= PathDelim + DirName; end { if } else raise Exception.CreateFmt(SDirNotInLocalRoot, [ARootPath]); CheckEditMode(dsData.DataSet); ARelativePathField.AsString:= DirName; end; { if } end; procedure TfmDocItemsEdit.edtRelativePathButtonClick(Sender: TObject); begin inherited; if (EditMode <> emReadOnly) and not edtRelativePath.ReadOnly then ChooseRelativePath( LoginContext.DocsLocalRootPath, dsData.DataSet.FieldByName('RELATIVE_PATH')); end; procedure TfmDocItemsEdit.edtMirroredRelativePathButtonClick(Sender: TObject); begin inherited; if (EditMode <> emReadOnly) and not edtMirroredRelativePath.ReadOnly then ChooseRelativePath( LoginContext.DocItemMirrorsRootPath, dsData.DataSet.FieldByName('MIRRORED_RELATIVE_PATH')); end; procedure TfmDocItemsEdit.Initialize; begin inherited; RegisterDateFields(cdsExtFileChangeDate); UpdateExtFileChangeDateField; drpImportFromFile.Control:= Self; end; function TfmDocItemsEdit.IsDocItemSysRolesDefault: Boolean; begin Result:= (dmDocClient.cdsDocItemSysRoles.RecordCount = 1) and (dmDocClient.cdsDocItemSysRolesSYS_ROLE_CODE.AsInteger = DefaultSysRoleCode) and (dmDocClient.cdsDocItemSysRolesDOC_ITEM_ACCESS_LEVEL_CODE.AsInteger = Ord(dialEdit)); end; function TfmDocItemsEdit.IsInDevelopPhase: Boolean; begin Result:= not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actFormUpdate(Sender: TObject); var c: TColor; DocItemStorageBaseType: TDocItemStorageBaseType; ExternalFileStorageControlsEnabled: Boolean; ExternalFileStorageControlsReadOnly: Boolean; ExternalDocStorageControlsEnabled: Boolean; ExternalDocStorageControlsReadOnly: Boolean; begin inherited; c:= ReadOnlyColors[EditMode = emReadOnly]; edtDocItemNo.Color:= c; cbDocItemType.Color:= c; edtDocItemName.Color:= c; edtNotes.Color:= c; cbPattern.Color:= c; SetControlReadOnly( (EditMode = emReadOnly) or not dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull, cbDocItemStorageType); DocItemStorageBaseType:= dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType; pnlConvertExternalDocItemToInternal.Visible:= LoginContext.AllowInternallyStoredDoc and (EditMode <> emInsert) and (DocItemStorageBaseType = disbtExternal); pnlExternalFileStorage.Visible:= (DocItemStorageBaseType = disbtExternal); pnlInternalFileStorage.Visible:= (DocItemStorageBaseType = disbtInternal); pnlExternalDocStorage.Visible:= (DocItemStorageBaseType = disbtCommandStorage); pnlContentStorage.Visible:= (DocItemStorageBaseType = disbtContentStorage); chkIsMirrored.Visible:= (DocItemStorageBaseType = disbtInternal); chkIsMirrored.Enabled:= dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and GetDocOwnerCanMirrorStoredFiles(dmDocClient.OpenDocOwnerType); pnlMirroredDocItemPaths.Visible:= chkIsMirrored.Checked; cbPattern.Visible:= not chkIsMirrored.Checked; lblPattern.Visible:= not chkIsMirrored.Checked; ExternalFileStorageControlsEnabled:= not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull; ExternalFileStorageControlsReadOnly:= not dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; edtFileName.Enabled:= ExternalFileStorageControlsEnabled; edtFileName.ReadOnly:= ExternalFileStorageControlsReadOnly; edtRelativePath.Enabled:= ExternalFileStorageControlsEnabled; edtRelativePath.ReadOnly:= ExternalFileStorageControlsReadOnly; edtMirroredFileName.Enabled:= ExternalFileStorageControlsEnabled; edtMirroredFileName.ReadOnly:= ExternalFileStorageControlsReadOnly; edtMirroredRelativePath.Enabled:= ExternalFileStorageControlsEnabled; edtMirroredRelativePath.ReadOnly:= ExternalFileStorageControlsReadOnly; edtFileName.Color:= ReadOnlyColors[ExternalFileStorageControlsReadOnly]; edtRelativePath.Color:= ReadOnlyColors[ExternalFileStorageControlsReadOnly]; edtMirroredFileName.Color:= ReadOnlyColors[ExternalFileStorageControlsReadOnly]; edtMirroredRelativePath.Color:= ReadOnlyColors[ExternalFileStorageControlsReadOnly]; ExternalDocStorageControlsEnabled:= ExternalFileStorageControlsEnabled; ExternalDocStorageControlsReadOnly:= ExternalFileStorageControlsReadOnly or not ExternalDocStorageControlsEnabled or (dsData.DataSet.FieldByName('_DI_STORAGE_TYPE_SELECT_COMMAND').AsString <> ''); edtExternalStorageDocId.Enabled:= ExternalDocStorageControlsEnabled; SetControlReadOnly(ExternalDocStorageControlsReadOnly, edtExternalStorageDocId); btnExternalDocStorageEdit.Visible:= (dsData.DataSet.FieldByName('_DI_STORAGE_TYPE_EDIT_COMMAND').AsString <> ''); pnlExternalStorageDocIdButtons.Visible:= (dsData.DataSet.FieldByName('_DI_STORAGE_TYPE_SELECT_COMMAND').AsString <> ''); if IsDocItemSysRolesDefault then begin pnlIsDocItemSysRolesDefault.Hint:= SDocItemSysRolesDefault; pnlIsDocItemSysRolesDefault.Color:= clSilver; end else begin pnlIsDocItemSysRolesDefault.Hint:= SDocItemSysRolesChanged; pnlIsDocItemSysRolesDefault.Color:= clRed; end; pnlDevelop.Enabled:= (EditMode <> emReadOnly); end; procedure TfmDocItemsEdit.actEditStoredFileDataExecute(Sender: TObject); begin inherited; with dsData.DataSet do if State in dsEditModes then UpdateRecord; dmDocClient.ExecInternalDocItemData(dietOpenForEdit); end; procedure TfmDocItemsEdit.actEditStoredFileDataUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtInternal) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and not dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull; end; procedure TfmDocItemsEdit.actImportFromTemplateExecute(Sender: TObject); begin inherited; dmDocClient.ImportInternalDocItemDataFromTemplate; end; procedure TfmDocItemsEdit.actImportFromTemplateUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtInternal) and dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actOpenStoredFileReadOnlyExecute(Sender: TObject); begin inherited; with dsData.DataSet do if State in dsEditModes then UpdateRecord; dmDocClient.ExecDocItemDataReadOnly; end; procedure TfmDocItemsEdit.actOpenStoredFileReadOnlyUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtInternal); end; procedure TfmDocItemsEdit.actExternalDocStorageEditExecute(Sender: TObject); begin inherited; dmDocClient.ExecExternalDocStorage(edscEdit); end; procedure TfmDocItemsEdit.actExternalDocStorageEditUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtCommandStorage) and not dsData.DataSet.FieldByName('FILE_NAME').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actExternalDocStorageSelectExecute(Sender: TObject); begin inherited; if ControlIsPressed or ShiftIsPressed then cdsExternalStorageDocId.TempCreateDataSet/ procedure begin cdsExternalStorageDocId.SafeAppend/ cdsExternalStorageDocIdDOC_ID.AssignProc(dsData.DataSet.FieldByName('FILE_NAME')); TfmExternalDocStorageDocId.ShowForm(nil, cdsExternalStorageDocId, emReadOnly); end else dmDocClient.ExecExternalDocStorage(edscSelect); end; procedure TfmDocItemsEdit.actExternalDocStorageSelectUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtCommandStorage) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actExternalDocStorageViewExecute(Sender: TObject); begin inherited; dmDocClient.ExecExternalDocStorage(edscView); end; procedure TfmDocItemsEdit.actExternalDocStorageViewUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtCommandStorage) and not dsData.DataSet.FieldByName('FILE_NAME').IsNull; end; procedure TfmDocItemsEdit.actImportFromFileExecute(Sender: TObject); begin inherited; dmDocClient.ImportInternalDocItemDataFromFile; end; procedure TfmDocItemsEdit.actImportFromFileUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtInternal) and dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actExportToFileExecute(Sender: TObject); begin inherited; dmDocClient.ExportInternalDocItemDataToFile; end; procedure TfmDocItemsEdit.actExportToFileUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtInternal) and not dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull; end; function TfmDocItemsEdit.ExternalFileName: string; var RelativePath: string; begin RelativePath:= dsData.DataSet.FieldByName('RELATIVE_PATH').AsString; if (Length(RelativePath) = 0) or (RelativePath[1] <> PathDelim) then RelativePath:= PathDelim + RelativePath; Result:= MakeFileName( ExcludeTrailingPathDelimiter(LoginContext.DocsLocalRootPath) + RelativePath, dsData.DataSet.FieldByName('FILE_NAME').AsString); end; procedure TfmDocItemsEdit.actExternalFileDeleteExecute(Sender: TObject); begin inherited; if (MessageDlgEx(SDeleteExternalFileQuestion, mtConfirmation, mbOKCancel, 0) = mrOk) then begin if (dsData.DataSet.State in dsEditModes) then dsData.DataSet.UpdateRecord; if not DeleteFile(ExternalFileName) then raise Exception.Create(SExternalFileCouldNotBeDeleted); UpdateExtFileChangeDateField; end; { if } end; procedure TfmDocItemsEdit.actExternalFileDeleteUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) and IsInDevelopPhase; end; procedure TfmDocItemsEdit.actExternalFileEditExecute(Sender: TObject); begin inherited; if (dsData.DataSet.State in dsEditModes) then dsData.DataSet.UpdateRecord; if not FileExists(ExternalFileName) then raise Exception.Create(SExternalFileDoesNotExist); dmDocClient.ExecExternalDocItemData(True); end; procedure TfmDocItemsEdit.actExternalFileEditUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actExternalFileExportExecute(Sender: TObject); var FileExtension: string; begin inherited; if (dsData.DataSet.State in dsEditModes) then dsData.DataSet.UpdateRecord; if not FileExists(ExternalFileName) then raise Exception.Create(SExternalFileDoesNotExist); FileExtension:= ExtractFileExt(dsData.DataSet.FieldByName('FILE_NAME').AsString); FileExtension:= Copy(FileExtension, 2, Length(FileExtension) - 1); sdExternalFileExport.DefaultExt:= FileExtension; sdExternalFileExport.Filter:= dmMain.SvrDoc.GetDocItemTypeFileDialogFilter(dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').AsInteger); if sdExternalFileExport.Execute then if not CopyFile(PChar(ExternalFileName), PChar(sdExternalFileExport.FileName), False) then raise Exception.CreateFmt(SCouldNotCreateFile, [sdExternalFileExport.FileName]); end; procedure TfmDocItemsEdit.actExternalFileExportUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal); end; procedure TfmDocItemsEdit.actExternalFileImportExecute(Sender: TObject); var FileExtension: string; begin inherited; if (dsData.DataSet.State in dsEditModes) then dsData.DataSet.UpdateRecord; if FileExists(ExternalFileName) then raise Exception.CreateFmt(SExternalFileExists, [SImport]); FileExtension:= ExtractFileExt(dsData.DataSet.FieldByName('FILE_NAME').AsString); FileExtension:= Copy(FileExtension, 2, Length(FileExtension) - 1); odExternalFileImport.DefaultExt:= FileExtension; odExternalFileImport.Filter:= dmMain.SvrDoc.GetDocItemTypeFileDialogFilter(dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').AsInteger); if odExternalFileImport.Execute then if not CopyFile(PChar(odExternalFileImport.FileName), PChar(ExternalFileName), False) then raise Exception.CreateFmt(SCouldNotCreateFile, [ExternalFileName]); UpdateExtFileChangeDateField; end; procedure TfmDocItemsEdit.actExternalFileImportUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) and IsInDevelopPhase; end; procedure TfmDocItemsEdit.UpdateExtFileChangeDateField; var ExternalFileChangeDate: TDateTime; begin if cdsExtFileChangeDate.Active then cdsExtFileChangeDate.SafeEdit/ procedure begin if (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) AND (ExtractFileName(ExternalFileName) <> '') and FileExists(ExternalFileName) then begin FileAge(ExternalFileName, ExternalFileChangeDate); cdsExtFileChangeDateEXT_FILE_CHANGE_DATE.AsDateTime:= DateOf(ExternalFileChangeDate); end else cdsExtFileChangeDateEXT_FILE_CHANGE_DATE.Clear; end; end; procedure TfmDocItemsEdit.actExternalFileNewFromTemplateExecute( Sender: TObject); var ChosenTemplateCode: Integer; StoredFileBranchCode: Integer; StoredFileCode: Integer; begin inherited; if (dsData.DataSet.State in dsEditModes) then dsData.DataSet.UpdateRecord; if FileExists(ExternalFileName) then raise Exception.CreateFmt(SExternalFileExists, [SNewFromTemplate]); ChosenTemplateCode:= TfmSelectDocItemTemplate.ShowForm( GetDocOwnerTypeTemplateType(dmDocClient.OpenDocOwnerType), dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').AsInteger); if (ChosenTemplateCode > 0) then begin dmMain.SvrDoc.GetDocItemTemplateStoredFile( ChosenTemplateCode, StoredFileBranchCode, StoredFileCode); WriteVarArrayToFile( dmDocClient.GetStoredFileData(StoredFileBranchCode, StoredFileCode), ExternalFileName); UpdateExtFileChangeDateField; end; { if } end; procedure TfmDocItemsEdit.actExternalFileNewFromTemplateUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) and IsInDevelopPhase; end; procedure TfmDocItemsEdit.actExternalFileOpenExecute(Sender: TObject); begin inherited; if (dsData.DataSet.State in dsEditModes) then dsData.DataSet.UpdateRecord; if not FileExists(ExternalFileName) then raise Exception.Create(SExternalFileDoesNotExist); dmDocClient.ExecExternalDocItemData; end; procedure TfmDocItemsEdit.actExternalFileOpenUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal); end; procedure TfmDocItemsEdit.actClearExternalStorageDocIdExecute(Sender: TObject); begin inherited; ConfirmAction(SConfirmClearingExternalDocStorageDocId); CheckEditMode(dsData.DataSet); dsData.DataSet.FieldByName('FILE_NAME').Clear; end; procedure TfmDocItemsEdit.actClearExternalStorageDocIdUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled:= (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtCommandStorage) and not dsData.DataSet.FieldByName('FILE_NAME').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actClearStoredFileExecute(Sender: TObject); begin inherited; dmDocClient.ClearInternalDocItemData; end; procedure TfmDocItemsEdit.actClearStoredFileUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtInternal) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and not dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull; end; procedure TfmDocItemsEdit.actDevelopExecute(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); if (EditMode = emReadOnly) or (Sender as TAction).Checked then Exit; LoginContext.CheckUserActivity(uaDevelopDocItem); if (dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').AsInteger <> 0) then LoginContext.CheckUserActivity(uaUnapproveDocItem); if (dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').AsInteger <> 0) then LoginContext.CheckUserActivity(uaUnauthorizeDocItem); CheckEditMode(dsData.DataSet); dsData.DataSet.UpdateRecord; dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').AsInteger:= LoginContext.UserCode; dsData.DataSet.FieldByName('DEVELOP_DATE').AsDateTime:= ContextDate(); dsData.DataSet.FieldByName('DEVELOP_TIME').AsDateTime:= ContextTime(); dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').Clear; dsData.DataSet.FieldByName('AUTHORIZE_DATE').Clear; dsData.DataSet.FieldByName('AUTHORIZE_TIME').Clear; dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').Clear; dsData.DataSet.FieldByName('APPROVE_DATE').Clear; dsData.DataSet.FieldByName('APPROVE_TIME').Clear; end; procedure TfmDocItemsEdit.actDevelopUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Checked:= not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; btnDevelop.Down:= (Sender as TAction).Checked; end; procedure TfmDocItemsEdit.actDocItemSysRolesExecute(Sender: TObject); var DocItemSysRolesEditMode: TEditMode; begin inherited; LoginContext.CheckUserActivity(uaDocItemSysRoles); dmDocClient.cdsDocItems.CheckBrowseMode; if (EditMode = emInsert) then DocItemSysRolesEditMode:= emEdit else DocItemSysRolesEditMode:= EditMode; TfmDocItemSysRoles.ShowForm(dmDocClient, nil, DocItemSysRolesEditMode); end; procedure TfmDocItemsEdit.actAuthorizeExecute(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); if (EditMode = emReadOnly) or (Sender as TAction).Checked then Exit; LoginContext.CheckUserActivity(uaAuthorizeDocItem); if (dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').AsInteger <> 0) then LoginContext.CheckUserActivity(uaUnapproveDocItem); CheckEditMode(dsData.DataSet); dsData.DataSet.UpdateRecord; if ( (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) and ( (dsData.DataSet.FieldByName('FILE_NAME').AsString = '') or (dsData.DataSet.FieldByName('RELATIVE_PATH').AsString = '')) ) or ( dsData.DataSet.FieldByName('IS_MIRRORED').AsBoolean and ( (dsData.DataSet.FieldByName('MIRRORED_FILE_NAME').AsString = '') or (dsData.DataSet.FieldByName('MIRRORED_RELATIVE_PATH').AsString = '')) ) then begin raise Exception.Create(SAuthorizeFileNameAndPathRequired); end; { if } if (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtCommandStorage) and (dsData.DataSet.FieldByName('FILE_NAME').AsString = '') then begin raise Exception.Create(SAuthorizeExternalDocIdRequired); end; { if } dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').AsInteger:= LoginContext.UserCode; dsData.DataSet.FieldByName('AUTHORIZE_DATE').AsDateTime:= ContextDate(); dsData.DataSet.FieldByName('AUTHORIZE_TIME').AsDateTime:= ContextTime(); dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').Clear; dsData.DataSet.FieldByName('APPROVE_DATE').Clear; dsData.DataSet.FieldByName('APPROVE_TIME').Clear; end; procedure TfmDocItemsEdit.actAuthorizeUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and ( (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType in [disbtExternal, disbtCommandStorage, disbtContentStorage]) or not dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull ); (Sender as TAction).Checked:= not dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').IsNull; btnAuthorize.Down:= (Sender as TAction).Checked; end; procedure TfmDocItemsEdit.actApproveExecute(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); if (EditMode = emReadOnly) or (Sender as TAction).Checked then Exit; LoginContext.CheckUserActivity(uaApproveDocItem); CheckEditMode(dsData.DataSet); dsData.DataSet.UpdateRecord; dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').AsInteger:= LoginContext.UserCode; dsData.DataSet.FieldByName('APPROVE_DATE').AsDateTime:= ContextDate(); dsData.DataSet.FieldByName('APPROVE_TIME').AsDateTime:= ContextTime(); end; procedure TfmDocItemsEdit.actApproveUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= not dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and ( (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType in [disbtExternal, disbtCommandStorage, disbtContentStorage]) or not dsData.DataSet.FieldByName('FILE_EXTENSION_CODE').IsNull ); (Sender as TAction).Checked:= not dsData.DataSet.FieldByName('APPROVE_EMPLOYEE_CODE').IsNull; btnApprove.Down:= (Sender as TAction).Checked; end; procedure TfmDocItemsEdit.cbDocItemStorageTypeChange(Sender: TObject); begin inherited; if Assigned(cbDocItemStorageType.DataSource) and Assigned(cbDocItemStorageType.DataSource.DataSet) and (cbDocItemStorageType.DataSource.DataSet.State in dsEditModes) then begin with cbDocItemStorageType.DataSource.DataSet do begin UpdateRecord; FieldByName('AUTHORIZE_EMPLOYEE_CODE').Clear; FieldByName('AUTHORIZE_DATE').Clear; FieldByName('AUTHORIZE_TIME').Clear; FieldByName('APPROVE_EMPLOYEE_CODE').Clear; FieldByName('APPROVE_DATE').Clear; FieldByName('APPROVE_TIME').Clear; end; { with } end; end; procedure TfmDocItemsEdit.FormCreate(Sender: TObject); begin inherited; cdsEmployeeFrameAllEmployees.Open; frDevelopDate.FieldNames:= 'DEVELOP_DATE'; frAuthorizeDate.FieldNames:= 'AUTHORIZE_DATE'; frApproveDate.FieldNames:= 'APPROVE_DATE'; frDevelopEmployee.FieldNames:= 'DEVELOP_EMPLOYEE_CODE'; frDevelopEmployee.DocButtonVisible:= False; frDevelopEmployee.OuterAllEmployeesDataSet:= cdsEmployeeFrameAllEmployees; frAuthorizeEmployee.FieldNames:= 'AUTHORIZE_EMPLOYEE_CODE'; frAuthorizeEmployee.DocButtonVisible:= False; frAuthorizeEmployee.OuterAllEmployeesDataSet:= cdsEmployeeFrameAllEmployees; frApproveEmployee.FieldNames:= 'APPROVE_EMPLOYEE_CODE'; frApproveEmployee.DocButtonVisible:= False; frApproveEmployee.OuterAllEmployeesDataSet:= cdsEmployeeFrameAllEmployees; frStoredFileChangeDate.FieldNames:= 'FILE_CHANGE_DATE'; frStoredFileChangeEmployee.FieldNames:= 'FILE_CHANGE_EMPLOYEE_CODE'; frStoredFileChangeEmployee.DocButtonVisible:= False; frStoredFileChangeEmployee.OuterAllEmployeesDataSet:= cdsEmployeeFrameAllEmployees; frContentStorageFileChangeDate.FieldNames:= 'FILE_CHANGE_DATE'; frContentStorageFileChangeEmployee.FieldNames:= 'FILE_CHANGE_EMPLOYEE_CODE'; frContentStorageFileChangeEmployee.DocButtonVisible:= False; frContentStorageFileChangeEmployee.OuterAllEmployeesDataSet:= cdsEmployeeFrameAllEmployees; edtDocsLocalRootPath.Text:= LoginContext.DocsLocalRootPath; edtDocItemMirrorsRootPath.Text:= LoginContext.DocItemMirrorsRootPath; FSaveApplicationHintPause:= Application.HintPause; end; procedure TfmDocItemsEdit.FormDestroy(Sender: TObject); begin inherited; Application.HintPause:= FSaveApplicationHintPause; end; procedure TfmDocItemsEdit.imgTimeMouseEnter(Sender: TObject); begin inherited; Application.HintPause:= 0; end; procedure TfmDocItemsEdit.imgTimeMouseLeave(Sender: TObject); begin inherited; Application.HintPause:= FSaveApplicationHintPause; end; procedure TfmDocItemsEdit.SetDBFrameReadOnly(AFrame: TDBFrame); begin if (AFrame = frDevelopDate) or (AFrame = frAuthorizeDate) or (AFrame = frApproveDate) or (AFrame = frDevelopEmployee) or (AFrame = frAuthorizeEmployee) or (AFrame = frApproveEmployee) or (AFrame = frStoredFileChangeEmployee) or (AFrame = frStoredFileChangeDate) or (AFrame = frContentStorageFileChangeDate) or (AFrame = frContentStorageFileChangeEmployee) then AFrame.ReadOnly:= True else inherited; end; procedure TfmDocItemsEdit.actContentStorageFileDeleteExecute(Sender: TObject); begin inherited; dmDocClient.ClearContentStorage; end; procedure TfmDocItemsEdit.actContentStorageFileDeleteUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtContentStorage) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and not dsData.DataSet.FieldByName('FILE_NAME').IsNull; end; procedure TfmDocItemsEdit.actContentStorageFileExportExecute(Sender: TObject); begin inherited; dmDocClient.ExportContentStorageFile; end; procedure TfmDocItemsEdit.actContentStorageFileExportUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtContentStorage) and not dsData.DataSet.FieldByName('FILE_NAME').IsNull; end; procedure TfmDocItemsEdit.actContentStorageFileImportExecute(Sender: TObject); begin inherited; dmDocClient.ImportContentStorageFromFile; end; procedure TfmDocItemsEdit.actContentStorageFileImportFromTemplateExecute(Sender: TObject); begin inherited; dmDocClient.ImportContentStorageFromTemplate; end; procedure TfmDocItemsEdit.actContentStorageFileImportFromTemplateUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtContentStorage) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actContentStorageFileImportUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtContentStorage) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; procedure TfmDocItemsEdit.actContentStorageFileOpenExecute(Sender: TObject); begin inherited; dmDocClient.ExecContentStorage(dietOpenForEdit); end; procedure TfmDocItemsEdit.actContentStorageFileOpenReadOnlyExecute(Sender: TObject); begin inherited; dmDocClient.ExecDocItemDataReadOnly; end; procedure TfmDocItemsEdit.actContentStorageFileOpenReadOnlyUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtContentStorage) and not dsData.DataSet.FieldByName('FILE_NAME').IsNull; end; procedure TfmDocItemsEdit.actContentStorageFileOpenUpdate(Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtContentStorage) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull and not dsData.DataSet.FieldByName('FILE_NAME').IsNull; end; procedure TfmDocItemsEdit.actConvertExternalDocItemToInternalExecute( Sender: TObject); begin inherited; dmDocClient.ConvertExternalDocItemToInternal; end; procedure TfmDocItemsEdit.actConvertExternalDocItemToInternalUpdate( Sender: TObject); begin inherited; Assert(Assigned(dsData.DataSet)); (Sender as TAction).Enabled:= (EditMode <> emReadOnly) and not dsData.DataSet.FieldByName('DOC_ITEM_TYPE_CODE').IsNull and (dsData.DataSet.FieldByName('_DI_STORAGE_BASE_TYPE_CODE').AsDocItemStorageBaseType = disbtExternal) and not dsData.DataSet.FieldByName('DEVELOP_EMPLOYEE_CODE').IsNull and dsData.DataSet.FieldByName('AUTHORIZE_EMPLOYEE_CODE').IsNull; end; end.
37.099642
154
0.770105
6a8ddeeb6b4c7d1c413511014e11109d4cf6597f
1,512
dpr
Pascal
samples/vcMulticast/source/vcMCSource.dpr
cupples/vcp
0ade74b23dab087582942acb9673e7dbdca88d92
[ "Apache-2.0" ]
27
2018-04-17T07:56:29.000Z
2022-03-16T15:40:43.000Z
samples/vcMulticast/source/vcMCSource.dpr
cupples/vcp
0ade74b23dab087582942acb9673e7dbdca88d92
[ "Apache-2.0" ]
5
2018-05-17T20:04:55.000Z
2021-10-06T09:08:24.000Z
samples/vcMulticast/source/vcMCSource.dpr
cupples/vcp
0ade74b23dab087582942acb9673e7dbdca88d92
[ "Apache-2.0" ]
16
2018-04-17T07:56:32.000Z
2021-09-03T09:33:50.000Z
(* Copyright 2018 Alex Shamray 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. *) (* ---------------------------------------------- vcMCSource.dpr vcMulticast Source demo application - project source ---------------------------------------------- Copyright (c) 2005-2010 Lake of Soft All rights reserved http://lakeofsoft.com/ ---------------------------------------------- created by: Lake, 01 Oct 2005 modified by: Lake, Oct 2005 ---------------------------------------------- *) {$I unaDef.inc } program vcMCSource; uses Forms, u_vcMCsource_main in 'u_vcMCsource_main.pas' {c_form_main}; {$R *.res} // tell we are OK with XP themes {$IFDEF __BEFORE_D7__ } {$R unaWindowsXP.res } {$ELSE } {$R WindowsXP.res } {$ENDIF __BEFORE_D7__ } begin Application.Initialize; Application.Title := 'VC 2.5 Pro - Multicast Source demo'; Application.CreateForm(Tc_form_main, c_form_main); Application.Run; end.
22.235294
73
0.604497
83872a6ce36997b516639a7114f0c81af2fa7aee
3,885
pas
Pascal
Server/Modules/FHIR.Server.HackingHealth.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
Server/Modules/FHIR.Server.HackingHealth.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
Server/Modules/FHIR.Server.HackingHealth.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
unit FHIR.Server.HackingHealth; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, FHIR.Base.Lang, FHIR.R3.Resources, FHIR.R3.Utilities, FHIR.CdsHooks.Server; type THackingHealthBNPLogic = class (TCDSHooksProcessor) private // function aTestIsBNP : boolean; // function clinicIsED : boolean; // function hasDyspnoea : boolean; // function isDyspnoea(cond : TFhirCondition) : boolean; public function execute : boolean; override; end; implementation { THackingHealthBNPLogic } //function THackingHealthBNPLogic.aTestIsBNP: boolean; ////var //// res : TFHIRResource; //// req : TFhirProcedureRequest; //begin // result := false; // raise EFHIRException.create('to do'); //(* for res in request.context do // if res is TFhirProcedureRequest then // begin // req := res as TFhirProcedureRequest; // if req.code.text = 'BNP' then // exit(true); // end;*) //end; // //function THackingHealthBNPLogic.clinicIsED: boolean; ////var //// enc : TFhirEncounter; //begin // raise EFHIRException.create('to do'); //(* if not request.preFetch.ContainsKey('encounter') then // result := false // else // begin // enc := request.preFetch['encounter'].resource as TFhirEncounter; // result := (enc.class_ <> nil) and (enc.class_.code = 'emergency'); // end;*) //end; // function THackingHealthBNPLogic.execute: boolean; begin result := false; // if (aTestIsBNP) then // begin // if not clinicIsED then // addCard('BNP will not be paid by Medicare because this is not an emergency presentation', '', 'warning', 'MBS rules', '') // else if not hasDyspnoea then // addCard('BNP will not be paid by Medicare if the patient does not have Dyspnoea', '', 'warning', 'MBS rules', ''); // end; end; //function THackingHealthBNPLogic.hasDyspnoea: boolean; ////var //// bnd : TFhirBundle; //// be : TFhirBundleEntry; //begin // raise EFHIRException.create('to do'); //(* bnd := request.preFetch['problems'].resource as TFhirBundle; // result := false; // for be in bnd.entryList do // if (be.resource <> nil) and (be.resource is TFhirCondition) then // if isDyspnoea(be.resource as TFhirCondition) then // exit(true);*) //end; // //function THackingHealthBNPLogic.isDyspnoea(cond: TFhirCondition): boolean; //begin // result := cond.code.text = 'Dyspnoea'; //end; // end.
33.782609
129
0.724839
472f0a251e520dce63f78ef6a83a91baaeac8483
30,636
pas
Pascal
server/healthcard_generator.pas
grahamegrieve/fhirserver
28f69977bde75490adac663e31a3dd77bc016f7c
[ "BSD-3-Clause" ]
132
2015-02-02T00:22:40.000Z
2021-08-11T12:08:08.000Z
server/healthcard_generator.pas
grahamegrieve/fhirserver
28f69977bde75490adac663e31a3dd77bc016f7c
[ "BSD-3-Clause" ]
113
2015-03-20T01:55:20.000Z
2021-10-08T16:15:28.000Z
server/healthcard_generator.pas
grahamegrieve/fhirserver
28f69977bde75490adac663e31a3dd77bc016f7c
[ "BSD-3-Clause" ]
49
2015-04-11T14:59:43.000Z
2021-03-30T10:29:18.000Z
unit healthcard_generator; { Copyright (c) 2001-2021, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {$i fhir.inc} interface uses SysUtils, Classes, DateUtils, Graphics, {$IFDEF FPC} FPImage, FPWritePNG, {$ELSE} Vcl.Imaging.pngimage, {$ENDIF} fsl_base, fsl_utilities, fsl_http, fsl_json, fsl_crypto, fhir_qrcode, fhir_objects, fhir_common, fhir_healthcard, fhir_utilities, fhir_uris, fhir4_types, fhir4_resources, fhir4_json, fhir4_utilities, fhir4_factory, session, storage, server_context; type TCardMaker = class (TFslObject) private FManager: TFHIROperationEngine; FRequest : TFHIRRequest; FCovid: boolean; FPatientId: String; FLinks: TFslStringDictionary; FIssues : TStringList; FDisplays: boolean; procedure linkResource(index : integer; ref : String); function serverContext : TFHIRServerContext; public constructor Create(manager: TFHIROperationEngine; request : TFHIRRequest; issues : TStringList); destructor Destroy; override; property links : TFslStringDictionary read FLinks; property covid : boolean read FCovid write FCovid; property patientId : String read FPatientId write FPatientId; property displays : boolean read FDisplays write FDisplays; function findPatient : TFHIRPatient; function makePatient(patient : TFHIRPatient) : TFHIRPatient; end; TVciImmunizationCardMaker = class (TCardMaker) private function isIncludedCoding(c : TFHIRCoding) : boolean; public function findImmunizations : TFslList<TFHIRImmunization>; function isRelevantImmunization(imm : TFhirImmunization) : boolean; function makeImmunization(imm : TFhirImmunization) : TFhirImmunization; function makeBundle : TFHIRBundle; end; TVciLaboratoryCardMaker = class (TCardMaker) private function loincCode(obs : TFHIRObservation) : String; function DoSortObservations(sender : TObject; const L, R: TFHIRObservation): Integer; public function findObservations : TFslList<TFHIRObservation>; function isRelevantObservation(obs : TFHIRObservation) : boolean; function makeObservation(obs : TFHIRObservation) : TFHIRObservation; function makeBundle : TFHIRBundle; end; THealthCardGenerator = class (TFslObject) private FIssuerUrl : String; FJwk : TJWK; FManager : TFHIROperationEngine; FRequest : TFHIRRequest; FPatientId: String; FParams: TFhirParameters; FSince : TFslDateTime; // FHealthCardJWS: string; FCards: TFslList<THealthcareCard>; FIssues : TStringList; procedure SetParams(const Value: TFhirParameters); function signCard(bundle : TFHIRBundle; types : TCredentialTypeSet) : THealthcareCard; procedure makeImmunizationCard(covid : boolean); procedure makeLaboratoryCard(covid : boolean); function processParams : TCredentialTypeSet; procedure SetManager(const Value: TFHIROperationEngine); public constructor Create(manager: TFHIROperationEngine; request : TFHIRRequest; key : TJWK); destructor Destroy; override; property patientId : String read FPatientId write FPatientId; property params : TFhirParameters read FParams write SetParams; procedure process; property cards : TFslList<THealthcareCard> read FCards; property issues : TStringList read FIssues; property IssuerURL : String read FIssuerUrl write FIssuerUrl; end; TParameterCheckType = (f_name, f_date, f_numeric, f_text); THealthCardFormGenerator = class (TFslObject) private FIssuerUrl : String; FJwk : TJWK; FVpr2: String; FVpr3: String; FVpr1: String; FIhi: String; FVacc2: String; FVacc3: String; FId: String; FVacc1: String; FVdate2: String; FFamily: String; FVdate3: String; Fissues: TStringList; FVdate1: String; FExp: String; FVlot2: String; FDob: String; FVlot3: String; FGiven: String; FVlot1: String; procedure checkParam(value, name: String; required: boolean; minLength, maxLength: integer; checkType: TParameterCheckType); function makePatient : TFHIRPatient; function makeImmunization(date, vacc, lot, pr : String) : TFhirImmunization; function makeBundle : TFHIRBundle; public constructor Create(key : TJWK); destructor Destroy; override; function checkInput(vars : THTTPParameters) : boolean; function generateCard : THealthcareCard; property IssuerURL : String read FIssuerUrl write FIssuerUrl; property issues : TStringList read Fissues; property family : String read FFamily write FFamily; property given : String read FGiven write FGiven; property dob : String read FDob write FDob; property ihi : String read FIhi write FIhi; property vdate1 : String read FVdate1 write FVdate1; property vacc1 : String read FVacc1 write FVacc1; property vlot1 : String read FVlot1 write FVlot1; property vpr1 : String read FVpr1 write FVpr1; property vdate2 : String read FVdate2 write FVdate2; property vacc2 : String read FVacc2 write FVacc2; property vlot2 : String read FVlot2 write FVlot2; property vpr2 : String read FVpr2 write FVpr2; property vdate3 : String read FVdate3 write FVdate3; property vacc3 : String read FVacc3 write FVacc3; property vlot3 : String read FVlot3 write FVlot3; property vpr3 : String read FVpr3 write FVpr3; property id : String read FId write FId; property exp : String read FExp write FExp; end; implementation { THealthCardGenerator } constructor THealthCardGenerator.Create(manager: TFHIROperationEngine; request : TFHIRRequest; key : TJWK); begin inherited Create; FManager := manager; FCards := TFslList<THealthcareCard>.create; FIssues := TStringList.create; FJwk := key; key.checkThumbprintIsSHA256Hash; FRequest := request; end; destructor THealthCardGenerator.Destroy; begin FRequest.Free; FJwk.Free; FIssues.free; FCards.free; FParams.Free; FManager.Free; inherited; end; procedure THealthCardGenerator.makeImmunizationCard(covid : boolean); var engine : TVciImmunizationCardMaker; bnd : TFhirBundle; card : THealthcareCard; begin engine := TVciImmunizationCardMaker.Create(FManager.link, FRequest.link, FIssues); try engine.covid := covid; engine.patientId := FPatientId; engine.displays := params.bool['displays']; bnd := engine.makeBundle; try if bnd <> nil then begin if covid then card := signCard(bnd, [ctCovidCard, ctImmunizationCard]) else card := signCard(bnd, [ctImmunizationCard]); card.links.assign(engine.links); end; finally bnd.Free; end; finally engine.Free; end; end; procedure THealthCardGenerator.makeLaboratoryCard(covid: boolean); var engine : TVciLaboratoryCardMaker; bnd : TFhirBundle; card : THealthcareCard; begin engine := TVciLaboratoryCardMaker.Create(FManager.link, FRequest.link, FIssues); try engine.covid := covid; engine.patientId := FPatientId; bnd := engine.makeBundle; try if bnd <> nil then begin if covid then card := signCard(bnd, [ctCovidCard, ctLabCard]) else card := signCard(bnd, [ctLabCard]); card.links.assign(engine.links); end; finally bnd.Free; end; finally engine.Free; end; end; function THealthCardGenerator.processParams : TCredentialTypeSet; var p : TFhirParametersParameter; begin result := []; for p in params.parameterList do begin if p.name = 'credentialType' then begin if p.value.primitiveValue = 'https://smarthealth.cards#health-card' then result := result + [ctHealthCard] else if p.value.primitiveValue = 'https://smarthealth.cards#covid19' then result := result + [ctCovidCard] else if p.value.primitiveValue = 'https://smarthealth.cards#immunization' then result := result + [ctImmunizationCard] else if p.value.primitiveValue = 'https://smarthealth.cards#laboratory' then result := result + [ctLabCard] else raise EFslException.Create('Unknown credentialType value "'+p.value.primitiveValue+'"'); end else if p.name = '_since' then begin if not TFslDateTime.isValidXmlDate(p.value.primitiveValue) then raise EFslException.Create('Unknown _since value "'+p.value.primitiveValue+'"'); FSince := TFslDateTime.fromXML(p.value.primitiveValue) end else if not StringArrayExistsSensitive(['images', 'displays'], p.name) then raise EFslException.Create('Unknown parameter "'+p.name+'"'); end; if result = [] then raise EFslException.Create('no credentialType parameter found'); end; procedure THealthCardGenerator.process; var cts : TCredentialTypeSet; covid : boolean; begin if PatientId = '' then raise EFslException.Create('No Patient ID found'); if params = nil then raise EFslException.Create('No Parameters found'); cts := processParams; covid := ctCovidCard in cts; if (ctHealthCard in cts) or not (ctLabCard in cts) then makeImmunizationCard(covid); if (ctHealthCard in cts) or not (ctImmunizationCard in cts) then makeLaboratoryCard(covid); end; procedure THealthCardGenerator.SetManager(const Value: TFHIROperationEngine); begin FManager.Free; FManager := Value; end; procedure THealthCardGenerator.SetParams(const Value: TFhirParameters); begin FParams.Free; FParams := Value; end; function THealthCardGenerator.signCard(bundle: TFHIRBundle; types : TCredentialTypeSet) : THealthcareCard; var key : integer; util : THealthcareCardUtilities; begin result := TFHIRHealthcareCardR4.Create; try result.Bundle := bundle.Link; result.issueDate := TFslDateTime.makeUTC; key := FManager.Storage.issueHealthCardKey; result.id := inttostr(key); result.issuer := ExcludeTrailingSlash(FIssuerUrl); result.types := types; util := THealthcareCardUtilities.create; try util.Factory := TFHIRFactoryR4.Create; util.sign(result, FJwk); FManager.storage.logHealthCard(key, shcSrcFromResources, result.issueDate, IntToStr(result.issueDate.toNbf), util.hash(result), PatientId, TEncoding.UTF8.GetBytes(bundle.asJson)); result.image := util.generateImage(result); finally util.Free; end; FCards.add(result.link); finally result.Free; end; end; { TCardMaker } constructor TCardMaker.Create(manager: TFHIROperationEngine; request : TFHIRRequest; issues : TStringList); begin inherited Create; FManager := manager; FRequest := request; FIssues := issues; FLinks := TFslStringDictionary.create; end; destructor TCardMaker.Destroy; begin FLinks.Free; FRequest.Free; FManager.Free; inherited; end; function TCardMaker.findPatient: TFHIRPatient; var ns : boolean; begin result := FManager.GetResourceById(FRequest, 'Patient', FRequest.id, '', ns) as TFHIRPatient; end; procedure TCardMaker.linkResource(index: integer; ref: String); begin links.add('resource:'+inttostr(index), ref); end; function TCardMaker.makePatient(patient: TFHIRPatient): TFHIRPatient; var n : TFhirHumanName; begin result := TFHIRPatient.Create; try if patient.hasNameList then begin n := result.nameList.Append; n.family := patient.nameList[0].family; if patient.nameList[0].hasGivenList then n.givenList.add(patient.nameList[0].givenList[0].clone); end; result.birthDate := patient.birthDate; result.link; finally result.Free; end; end; function TCardMaker.serverContext: TFHIRServerContext; begin result := (FManager.ServerContextObject as TFHIRServerContext) end; { TVciImmunizationCardMaker } function TVciImmunizationCardMaker.findImmunizations: TFslList<TFHIRImmunization>; var bw : TFhirBundleW; bnd : TFhirBundle; be : TFhirBundleEntry; begin result := TFslList<TFHIRImmunization>.create; try bw := FManager.DoSearch(FRequest, 'Immunization', 'patient='+FPatientId+'&_sort=date'); try bnd := bw.Resource as TFhirBundle; for be in bnd.entryList do if (be.resource <> nil) and (be.resource is TFhirImmunization) then result.Add((be.resource as TFhirImmunization).link); finally bw.Free; end; result.Link; finally result.Free; end; end; function TVciImmunizationCardMaker.isIncludedCoding(c: TFHIRCoding): boolean; begin result := StringArrayExists([URI_CVX, URI_GTIN, URI_SNOMED, 'http://id.who.int/icd/release/11/mms','https://www.humanservices.gov.au/organisations/health-professionals/enablers/air-vaccine-code-formats','http://www.whocc.no/atc'], c.system) end; function TVciImmunizationCardMaker.isRelevantImmunization(imm: TFhirImmunization): boolean; var c : TFHIRCoding; begin result := false; if imm.occurrence is TFhirDateTime then if imm.vaccineCode <> nil then for c in imm.vaccineCode.codingList do if isIncludedCoding(c) then exit(true); end; function TVciImmunizationCardMaker.makeBundle: TFHIRBundle; var bundle : TFhirBundle; pat : TFhirPatient; immList : TFslList<TFhirImmunization>; imm : TFhirImmunization; i : integer; begin bundle := TFhirBundle.Create(BundleTypeCollection); try pat := findPatient; try linkResource(0, 'Patient/'+pat.id); bundle.entryList.Append('resource:0').resource := makePatient(pat); finally pat.Free; end; i := 1; immList := findImmunizations; try for imm in immList do if isRelevantImmunization(imm) then begin bundle.entryList.Append('resource:'+inttostr(i)).resource := makeImmunization(imm); linkResource(i, 'Immunization/'+imm.id); inc(i); end; finally immList.Free; end; if bundle.entryList.Count >= 2 then result := bundle.Link else begin FIssues.Add('No Immunizations found'); result := nil; end; finally bundle.Free; end; end; function TVciImmunizationCardMaker.makeImmunization(imm: TFhirImmunization): TFhirImmunization; var c, t : TFHIRCoding; i : integer; actor, a : TFhirReference; p : TResourceWithReference; s : String; begin result := TFhirImmunization.create; try result.status := imm.status; result.vaccineCode := TFhirCodeableConcept.Create; for c in imm.vaccineCode.codingList do if isIncludedCoding(c) then begin t := result.vaccineCode.codingList.append; t.code := c.code; t.system := c.system; if displays then begin t.display := c.display; if (t.display = '') then t.display := serverContext.TerminologyServer.getDisplayForCode(FRequest.Lang, t.system, c.version, t.code); end; end; result.patient := TFhirReference.Create('resource:0'); result.occurrence := imm.occurrence.Link; if (imm.manufacturer <> nil) and (imm.manufacturer.identifier <> nil) then begin result.manufacturer := TFhirReference.Create; result.manufacturer.identifier := TFhirIdentifier.Create; result.manufacturer.identifier.system := imm.manufacturer.identifier.system; result.manufacturer.identifier.value := imm.manufacturer.identifier.value; end; result.lotNumber := imm.lotNumber; for i := 0 to imm.performerList.Count - 1 do begin actor := imm.performerList[i].actor; if actor <> nil then begin if actor.display <> '' then begin a := TFhirReference.create; result.performerList.Append.actor := a; a.display := actor.display; break; end else if actor.reference <> '' then begin p := FManager.LookupReference(FRequest, actor.reference); if (p <> nil) then begin s := serverContext.Factory.describe(p.Resource); if (s <> '') then begin a := TFhirReference.create; result.performerList.Append.actor := a; a.display := s; break; end; end; end; end; end; result.isSubpotentElement := imm.isSubpotentElement.link; result.Link; finally result.Free; end; end; { TVciLaboratoryCardMaker } function TVciLaboratoryCardMaker.DoSortObservations(sender: TObject; const L, R: TFHIRObservation): Integer; var ld, rd : TFslDateTime; begin ld := (l.effective as TFhirDateTime).value; rd := (r.effective as TFhirDateTime).value; result := ld.compare(rd); end; function TVciLaboratoryCardMaker.loincCode(obs: TFHIRObservation): String; var c : TFHIRCoding; begin result := ''; for c in obs.code.codingList do if c.system = URI_LOINC then exit(c.code); end; function TVciLaboratoryCardMaker.findObservations: TFslList<TFHIRObservation>; var bw : TFhirBundleW; bnd : TFhirBundle; be : TFhirBundleEntry; begin result := TFslList<TFHIRObservation>.create; try bw := FManager.DoSearch(FRequest, 'Observation', 'patient='+FPatientId+'&_sort=date'); try bnd := bw.Resource as TFhirBundle; for be in bnd.entryList do if (be.resource <> nil) and (be.resource is TFHIRObservation) then result.Add((be.resource as TFHIRObservation).link); finally bw.Free; end; result.Link; finally result.Free; end; end; function TVciLaboratoryCardMaker.isRelevantObservation(obs: TFHIRObservation): boolean; var code : String; c : TFHIRCodingW; ctxt : TFHIRServerContext; begin // it's relevant if it's a LOINC observation for a genetic material, antibodies, or antigens code := loincCode(obs); if (code = '') then exit(false); if (obs.subject = nil) or (obs.subject.reference = '') or (obs.effectiveElement = nil) then exit(false); if (obs.value = nil) or not StringArrayExistsSensitive(['CodeableConcept', 'Quantity', 'string'], obs.value.fhirType) then exit(false); ctxt := serverContext; c := ctxt.Factory.wrapCoding(ctxt.Factory.makeCoding(URI_LOINC, code)); try if covid then result := ctxt.TerminologyServer.codeInValueSet(c, 'http://test.fhir.org/r4/ValueSet/Covid19Labs') else result := ctxt.TerminologyServer.codeInValueSet(c, 'http://test.fhir.org/r4/ValueSet/InfectiousDiseaseLabsLabs'); finally c.Free; end; end; function TVciLaboratoryCardMaker.makeBundle: TFHIRBundle; var bundle : TFhirBundle; pat : TFhirPatient; obsList : TFslList<TFhirObservation>; map : TFslMap<TFhirObservation>; obs : TFhirObservation; i : integer; begin bundle := TFhirBundle.Create(BundleTypeCollection); try pat := findPatient; try linkResource(0, 'Patient/'+pat.id); bundle.entryList.Append('resource:0').resource := makePatient(pat); finally pat.Free; end; obsList := findObservations; try map := TFslMap<TFhirObservation>.create; try for obs in obsList do if isRelevantObservation(obs) then map.AddOrSetValue(loincCode(obs), obs.Link); obsList.Clear; for obs in map.Values do obsList.Add(obs.link); finally map.Free; end; obsList.SortE(DoSortObservations); i := 1; for obs in obsList do begin bundle.entryList.Append('resource:'+inttostr(i)).resource := makeObservation(obs); linkResource(i, 'Observation/'+obs.id); inc(i); end; finally obsList.Free; end; if bundle.entryList.Count >= 2 then result := bundle.Link else begin FIssues.Add('No Observations found'); result := nil; end; finally bundle.Free; end; end; function TVciLaboratoryCardMaker.makeObservation(obs: TFHIRObservation): TFHIRObservation; var p : TResourceWithReference; s : String; i : integer; rs, rt : TFhirObservationReferenceRange; begin result := TFHIRObservation.Create; try result.status := obs.status; result.code := TFhirCodeableConcept.Create(URI_LOINC, loincCode(obs)); result.subject := TFhirReference.Create('resource:0'); result.effective := obs.effective.Link; for i := 0 to obs.performerList.Count - 1 do begin if obs.performerList[0].display <> '' then begin result.performerList.Append.display := obs.performerList[0].display; break; end else if obs.performerList[0].reference <> '' then begin p := FManager.LookupReference(FRequest, obs.performerList[0].reference); if (p <> nil) then begin s := serverContext.Factory.describe(p.Resource); if (s <> '') then begin result.performerList.Append.display := s; break; end; end; end; end; result.value := obs.value.Link; for rs in obs.referenceRangeList do begin rt := result.referenceRangeList.Append; rt.low := rs.low.Link; rt.high := rs.high.Link; rt.text := rs.text; if (rs.type_ <> nil) and (rs.type_.text <> '') then begin rt.type_ := TFhirCodeableConcept.Create; rt.text := rs.type_.text; end; end; result.Link; finally result.Free; end; end; { THealthCardFormGenerator } constructor THealthCardFormGenerator.Create(key: TJWK); begin inherited Create; FJwk := key; FIssues := TStringList.Create; end; destructor THealthCardFormGenerator.Destroy; begin FIssues.Free; FJwk.Free; inherited; end; function THealthCardFormGenerator.generateCard: THealthcareCard; var key : integer; util : THealthcareCardUtilities; begin result := TFHIRHealthcareCardR4.Create; try result.Bundle := makeBundle; result.issueDate := TFslDateTime.makeUTC; // result.id := inttostr(key); result.issuer := ExcludeTrailingSlash(FIssuerUrl); result.types := [ctCovidCard, ctImmunizationCard]; util := THealthcareCardUtilities.create; try util.Factory := TFHIRFactoryR4.Create; util.sign(result, FJwk); // FManager.storage.logHealthCard(key, shcSrcFromResources, result.issueDate, IntToStr(result.issueDate.toNbf), util.hash(result), PatientId, TEncoding.UTF8.GetBytes(bundle.asJson)); result.image := util.generateImage(result); finally util.Free; end; result.link; finally result.Free; end; end; function THealthCardFormGenerator.makeBundle: TFHIRBundle; var bundle : TFhirBundle; imm : TFhirImmunization; i : integer; begin bundle := TFhirBundle.Create(BundleTypeCollection); try bundle.entryList.Append('resource:0').resource := makePatient(); bundle.entryList.Append('resource:1').resource := makeImmunization(vdate1, vacc1, vlot1, vpr1); imm := makeImmunization(vdate2, vacc2, vlot2, vpr2); if (imm <> nil) then begin bundle.entryList.Append('resource:2').resource := imm; imm := makeImmunization(vdate3, vacc3, vlot3, vpr3); if (imm <> nil) then bundle.entryList.Append('resource:3').resource := imm; end; result := bundle.Link; finally bundle.Free; end; end; function THealthCardFormGenerator.makeImmunization(date, vacc, lot, pr : String): TFhirImmunization; var c : TFHIRCoding; prf : TFhirImmunizationPerformer; begin if (date = '') and (vacc = '') then result := nil else begin result := TFhirImmunization.create; try result.status := ImmunizationStatusCompleted; result.vaccineCode := TFhirCodeableConcept.Create; c := result.vaccineCode.codingList.append; c.system := 'http://hl7.org/fhir/sid/cvx'; c.code := vacc; result.patient := TFhirReference.Create('resource:0'); result.lotNumber := lot; if (pr <> '') then begin prf := result.performerList.Append; prf.actor := TFhirReference.create; prf.actor.display := pr; end; if TFslDateTime.isValidDate('yyyy-mm-dd', date) then result.occurrence := TFhirDateTime.Create(TFslDateTime.fromFormat('yyyy-mm-dd', date)) else result.occurrence := TFhirDateTime.Create(TFslDateTime.fromFormat('dd-mm-yyyy', date)); result.Link; finally result.Free; end; end; end; function THealthCardFormGenerator.makePatient(): TFHIRPatient; var n : TFhirHumanName; s : String; begin result := TFHIRPatient.Create; try n := result.nameList.Append; n.family := family; for s in given.Split([' ']) do n.givenList.add(s); if TFslDateTime.isValiddate('yyyy-mm-dd', dob) then result.birthDate := TFslDateTime.fromFormat('yyyy-mm-dd', dob) else result.birthDate := TFslDateTime.fromFormat('dd-mm-yyyy', dob); result.link; finally result.Free; end; end; function THealthCardFormGenerator.checkInput(vars: THTTPParameters): boolean; begin family := vars['family']; given := vars['given']; dob := vars['dob']; ihi := vars['ihi']; vdate1 := vars['vdate1']; vacc1 := vars['vacc1']; vlot1 := vars['vlot1']; vpr1 := vars['vpr1']; vdate2 := vars['vdate2']; vacc2 := vars['vacc2']; vlot2 := vars['vlot2']; vpr2 := vars['vpr2']; vdate3 := vars['vdate3']; vacc3 := vars['vacc3']; vlot3 := vars['vlot3']; vpr3 := vars['vpr3']; id := vars['id']; exp := vars['exp']; checkParam(family, 'family', true, 1, 40, f_name); checkParam(given, 'given', true, 1, 40, f_name); checkParam(dob, 'dob', true, 10, 10, f_date); checkParam(ihi, 'given', false, 16, 16, f_numeric); // if (vdate1 <> '') or (vacc1 <> '') or (vlot1 <> '') or (vpr1 <> '') then have to have at least a first // begin checkParam(vdate1, 'vdate1', true, 10, 10, f_date); checkParam(vacc1, 'vacc1', true, 3, 3, f_numeric); checkParam(vlot1, 'vlot1', false, 1, 15, f_text); checkParam(vpr1, 'vpr1', false, 1, 40, f_text); if (vdate2 <> '') or (vacc2 <> '') or (vlot2 <> '') or (vpr2 <> '') then begin checkParam(vdate2, 'vdate2', true, 10, 10, f_date); checkParam(vacc2, 'vacc2', true, 3, 3, f_numeric); checkParam(vlot2, 'vlot2', false, 1, 15, f_text); checkParam(vpr2, 'vpr2', false, 1, 40, f_text); if (vdate3 <> '') or (vacc3 <> '') or (vlot3 <> '') or (vpr3 <> '') then begin checkParam(vdate3, 'vdate3', true, 10, 10, f_date); checkParam(vacc3, 'vacc3', true, 3, 3, f_numeric); checkParam(vlot3, 'vlot3', false, 1, 15, f_text); checkParam(vpr3, 'vpr3', false, 1, 40, f_text); end; end; result := Fissues.Count = 0; end; procedure THealthCardFormGenerator.checkParam(value, name : String; required : boolean; minLength, maxLength : integer; checkType : TParameterCheckType); var ch : char; begin if value = '' then begin if required then issues.Add('Parameter '+name+' needs to have a value') end else begin if value.length < minLength then issues.Add('<li>Parameter '+name+' minimum length is '+inttostr(minLength)+' ("'+EncodeXML(value)+'")</li>'); if value.length > maxLength then issues.Add('<li>Parameter '+name+' maximum length is '+inttostr(maxLength)+' ("'+EncodeXML(value)+'")</li>'); case checkType of f_name: for ch in value do begin if not CharInSet(ch, ['a'..'z', 'A'..'Z', '-', '`', '''', ' ']) then begin issues.Add('Parameter '+name+' illegal char "'+EncodeXML(ch)+'"</li>'); break end; end; f_date: if not TFslDateTime.isValiddate('yyyy-mm-dd', value) and not TFslDateTime.isValiddate('dd-mm-yyyy', value) then issues.Add('<li>Parameter '+name+' illegal date "'+EncodeXML(value)+'"</li>'); f_numeric: for ch in value do begin if not CharInSet(ch, ['0'..'9']) then begin issues.Add('<li>Parameter '+name+' illegal char "'+EncodeXML(ch)+'"</li>'); break end; end; f_text: for ch in value do begin if (ord(ch) < 32) or (ord(ch) > 126) then begin issues.Add('<li>Parameter '+name+' illegal char "'+EncodeXML(ch)+'"</li>'); break end; end; end; end; end; end.
31.261224
189
0.659747
47255b8ecd3f2542d58130feb51326824ef113b5
405
dpr
Pascal
Sample/Sample.dpr
novuslogic/DelphiLibSass
1a3cad16603d4aac27f9b99f242e433d7b559083
[ "Apache-2.0" ]
8
2017-07-07T11:25:57.000Z
2021-03-04T02:12:10.000Z
Sample/Sample.dpr
novuslogic/DelphiLibSass
1a3cad16603d4aac27f9b99f242e433d7b559083
[ "Apache-2.0" ]
null
null
null
Sample/Sample.dpr
novuslogic/DelphiLibSass
1a3cad16603d4aac27f9b99f242e433d7b559083
[ "Apache-2.0" ]
8
2017-07-10T00:56:44.000Z
2021-12-02T04:25:57.000Z
program Sample; uses Vcl.Forms, Main in 'Main.pas' {frmMain}, DelphiLibSass in '..\Source\core\DelphiLibSass.pas', DelphiLibSassCommon in '..\Source\core\DelphiLibSassCommon.pas', DelphiLibSassLib in '..\Source\core\DelphiLibSassLib.pas'; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TfrmMain, frmMain); Application.Run; end.
22.5
66
0.74321
f133723216cefd0b45958773cc5800b11e7cdd75
11,903
pas
Pascal
src/libraries/synapse/synaip.pas
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
384
2016-07-16T10:07:28.000Z
2021-12-29T11:22:56.000Z
src/libraries/synapse/synaip.pas
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
165
2016-09-11T11:06:04.000Z
2021-12-05T23:31:55.000Z
src/libraries/synapse/synaip.pas
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
210
2016-08-26T14:49:47.000Z
2022-02-22T18:06:33.000Z
{==============================================================================| | Project : Ararat Synapse | 001.002.001 | |==============================================================================| | Content: IP address support procedures and functions | |==============================================================================| | Copyright (c)2006-2010, Lukas Gebauer | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are met: | | | | Redistributions of source code must retain the above copyright notice, this | | list of conditions and the following disclaimer. | | | | Redistributions in binary form must reproduce the above copyright notice, | | this list of conditions and the following disclaimer in the documentation | | and/or other materials provided with the distribution. | | | | Neither the name of Lukas Gebauer nor the names of its contributors may | | be used to endorse or promote products derived from this software without | | specific prior written permission. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | | ARE DISCLAIMED. IN NO EVENT SHALL THE 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. | |==============================================================================| | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).| | Portions created by Lukas Gebauer are Copyright (c) 2006-2010. | | All Rights Reserved. | |==============================================================================| | Contributor(s): | |==============================================================================| | History: see HISTORY.HTM from distribution package | | (Found at URL: http://www.ararat.cz/synapse/) | |==============================================================================} {:@abstract(IP adress support procedures and functions)} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$Q-} {$R-} {$H+} {$IFDEF UNICODE} {$WARN IMPLICIT_STRING_CAST OFF} {$WARN IMPLICIT_STRING_CAST_LOSS OFF} {$WARN SUSPICIOUS_TYPECAST OFF} {$ENDIF} unit synaip; interface uses SysUtils, SynaUtil; type {:binary form of IPv6 adress (for string conversion routines)} TIp6Bytes = array [0..15] of Byte; {:binary form of IPv6 adress (for string conversion routines)} TIp6Words = array [0..7] of Word; {:Returns @TRUE, if "Value" is a valid IPv4 address. Cannot be a symbolic Name!} function IsIP(const Value: string): Boolean; {:Returns @TRUE, if "Value" is a valid IPv6 address. Cannot be a symbolic Name!} function IsIP6(const Value: string): Boolean; {:Returns a string with the "Host" ip address converted to binary form.} function IPToID(Host: string): Ansistring; {:Convert IPv6 address from their string form to binary byte array.} function StrToIp6(value: string): TIp6Bytes; {:Convert IPv6 address from binary byte array to string form.} function Ip6ToStr(value: TIp6Bytes): string; {:Convert IPv4 address from their string form to binary.} function StrToIp(value: string): integer; {:Convert IPv4 address from binary to string form.} function IpToStr(value: integer): string; {:Convert IPv4 address to reverse form.} function ReverseIP(Value: AnsiString): AnsiString; {:Convert IPv6 address to reverse form.} function ReverseIP6(Value: AnsiString): AnsiString; {:Expand short form of IPv6 address to long form.} function ExpandIP6(Value: AnsiString): AnsiString; implementation {==============================================================================} function IsIP(const Value: string): Boolean; var TempIP: string; function ByteIsOk(const Value: string): Boolean; var x, n: integer; begin x := StrToIntDef(Value, -1); Result := (x >= 0) and (x < 256); // X may be in correct range, but value still may not be correct value! // i.e. "$80" if Result then for n := 1 to length(Value) do if not (AnsiChar(Value[n]) in ['0'..'9']) then begin Result := False; Break; end; end; begin TempIP := Value; Result := False; if not ByteIsOk(Fetch(TempIP, '.')) then Exit; if not ByteIsOk(Fetch(TempIP, '.')) then Exit; if not ByteIsOk(Fetch(TempIP, '.')) then Exit; if ByteIsOk(TempIP) then Result := True; end; {==============================================================================} function IsIP6(const Value: string): Boolean; var TempIP: string; s,t: string; x: integer; partcount: integer; zerocount: integer; First: Boolean; begin TempIP := Value; Result := False; if Value = '::' then begin Result := True; Exit; end; partcount := 0; zerocount := 0; First := True; while tempIP <> '' do begin s := fetch(TempIP, ':'); if not(First) and (s = '') then Inc(zerocount); First := False; if zerocount > 1 then break; Inc(partCount); if s = '' then Continue; if partCount > 8 then break; if tempIP = '' then begin t := SeparateRight(s, '%'); s := SeparateLeft(s, '%'); x := StrToIntDef('$' + t, -1); if (x < 0) or (x > $ffff) then break; end; x := StrToIntDef('$' + s, -1); if (x < 0) or (x > $ffff) then break; if tempIP = '' then if not((PartCount = 1) and (ZeroCount = 0)) then Result := True; end; end; {==============================================================================} function IPToID(Host: string): Ansistring; var s: string; i, x: Integer; begin Result := ''; for x := 0 to 3 do begin s := Fetch(Host, '.'); i := StrToIntDef(s, 0); Result := Result + AnsiChar(i); end; end; {==============================================================================} function StrToIp(value: string): integer; var s: string; i, x: Integer; begin Result := 0; for x := 0 to 3 do begin s := Fetch(value, '.'); i := StrToIntDef(s, 0); Result := (256 * Result) + i; end; end; {==============================================================================} function IpToStr(value: integer): string; var x1, x2: word; y1, y2: byte; begin Result := ''; x1 := value shr 16; x2 := value and $FFFF; y1 := x1 div $100; y2 := x1 mod $100; Result := inttostr(y1) + '.' + inttostr(y2) + '.'; y1 := x2 div $100; y2 := x2 mod $100; Result := Result + inttostr(y1) + '.' + inttostr(y2); end; {==============================================================================} function ExpandIP6(Value: AnsiString): AnsiString; var n: integer; s: ansistring; x: integer; begin Result := ''; if value = '' then exit; x := countofchar(value, ':'); if x > 7 then exit; if value[1] = ':' then value := '0' + value; if value[length(value)] = ':' then value := value + '0'; x := 8 - x; s := ''; for n := 1 to x do s := s + ':0'; s := s + ':'; Result := replacestring(value, '::', s); end; {==============================================================================} function StrToIp6(Value: string): TIp6Bytes; var IPv6: TIp6Words; Index: Integer; n: integer; b1, b2: byte; s: string; x: integer; begin for n := 0 to 15 do Result[n] := 0; for n := 0 to 7 do Ipv6[n] := 0; Index := 0; Value := ExpandIP6(value); if value = '' then exit; while Value <> '' do begin if Index > 7 then Exit; s := fetch(value, ':'); if s = '@' then break; if s = '' then begin IPv6[Index] := 0; end else begin x := StrToIntDef('$' + s, -1); if (x > 65535) or (x < 0) then Exit; IPv6[Index] := x; end; Inc(Index); end; for n := 0 to 7 do begin b1 := ipv6[n] div 256; b2 := ipv6[n] mod 256; Result[n * 2] := b1; Result[(n * 2) + 1] := b2; end; end; {==============================================================================} //based on routine by the Free Pascal development team function Ip6ToStr(value: TIp6Bytes): string; var i, x: byte; zr1,zr2: set of byte; zc1,zc2: byte; have_skipped: boolean; ip6w: TIp6words; begin zr1 := []; zr2 := []; zc1 := 0; zc2 := 0; for i := 0 to 7 do begin x := i * 2; ip6w[i] := value[x] * 256 + value[x + 1]; if ip6w[i] = 0 then begin include(zr2, i); inc(zc2); end else begin if zc1 < zc2 then begin zc1 := zc2; zr1 := zr2; zc2 := 0; zr2 := []; end; end; end; if zc1 < zc2 then begin zr1 := zr2; end; SetLength(Result, 8*5-1); SetLength(Result, 0); have_skipped := false; for i := 0 to 7 do begin if not(i in zr1) then begin if have_skipped then begin if Result = '' then Result := '::' else Result := Result + ':'; have_skipped := false; end; Result := Result + IntToHex(Ip6w[i], 1) + ':'; end else begin have_skipped := true; end; end; if have_skipped then if Result = '' then Result := '::0' else Result := Result + ':'; if Result = '' then Result := '::0'; if not (7 in zr1) then SetLength(Result, Length(Result)-1); Result := LowerCase(result); end; {==============================================================================} function ReverseIP(Value: AnsiString): AnsiString; var x: Integer; begin Result := ''; repeat x := LastDelimiter('.', Value); Result := Result + '.' + Copy(Value, x + 1, Length(Value) - x); Delete(Value, x, Length(Value) - x + 1); until x < 1; if Length(Result) > 0 then if Result[1] = '.' then Delete(Result, 1, 1); end; {==============================================================================} function ReverseIP6(Value: AnsiString): AnsiString; var ip6: TIp6bytes; n: integer; x, y: integer; begin ip6 := StrToIP6(Value); x := ip6[15] div 16; y := ip6[15] mod 16; Result := IntToHex(y, 1) + '.' + IntToHex(x, 1); for n := 14 downto 0 do begin x := ip6[n] div 16; y := ip6[n] mod 16; Result := Result + '.' + IntToHex(y, 1) + '.' + IntToHex(x, 1); end; end; {==============================================================================} end.
28.13948
80
0.48954
83645d292df42f646299fcd39b8259f36b02b5d4
3,178
pas
Pascal
gif/Demo/Thread/main.pas
commandus/util
05c89c3f7418ee790b79c053d2b4dee3c8c3ce96
[ "MIT" ]
null
null
null
gif/Demo/Thread/main.pas
commandus/util
05c89c3f7418ee790b79c053d2b4dee3c8c3ce96
[ "MIT" ]
null
null
null
gif/Demo/Thread/main.pas
commandus/util
05c89c3f7418ee790b79c053d2b4dee3c8c3ce96
[ "MIT" ]
null
null
null
unit main; //////////////////////////////////////////////////////////////////////////////// // // // Project: TGIFImage demo application. // // Description: Displays a GIF without the TImage component. // // Copyright (c) 1997-99 Anders Melander. // // All rights reserved. // // Formatting: 2 space indent, 8 space tabs, 80 columns. // // // //////////////////////////////////////////////////////////////////////////////// // // // Note: When running this demo on Windows 95/98, the multiple thread demo // // may appear to hang when a large number of threads are created and // // destroyed. This isn't the case, its just takes a long time for the // // threads to shut down. // // // //////////////////////////////////////////////////////////////////////////////// interface uses GIFImage, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TFormMain = class(TForm) Panel1: TPanel; Label1: TLabel; Label2: TLabel; ButtonSingle: TBitBtn; ButtonExit: TBitBtn; ButtonMultiple: TBitBtn; ImageBackground: TImage; ButtonNative: TBitBtn; procedure ButtonExitClick(Sender: TObject); procedure ButtonMultipleClick(Sender: TObject); procedure ButtonSingleClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonNativeClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.DFM} uses Single, Multiple, Native; procedure TFormMain.ButtonExitClick(Sender: TObject); begin Close; end; procedure TFormMain.ButtonSingleClick(Sender: TObject); begin with TFormSingle.Create(self) do try ShowModal; finally Free; end; end; procedure TFormMain.ButtonMultipleClick(Sender: TObject); begin with TFormMultiple.Create(self) do try ShowModal; finally Free; end; end; procedure TFormMain.ButtonNativeClick(Sender: TObject); begin with TFormNative.Create(self) do try ShowModal; finally Free; end; end; procedure TFormMain.FormCreate(Sender: TObject); begin if not(Assigned(ImageBackground.Picture.Graphic)) then begin ButtonSingle.Enabled := False; ButtonMultiple.Enabled := False; ShowMessage('No GIF to display.'+#13+ 'ImageBackground is empty!'+#13+#13+ 'Did you forget to install TGIFImage'+#13+ 'before you loaded the form?'+#13+#13+ 'See the release notes for more info.'); end; end; end.
29.425926
81
0.503461
f11315c9807dfb58f2c4c6bc0f07a7f360d702c3
1,434
pas
Pascal
Ext2D_Engine_Sources/Ext2D Engine Tools Sources/Source/Color Spy/Main.pas
delphi-pascal-archive/ext2d_engine
ca891630602c02baa512104d2289d471e239c67d
[ "Unlicense" ]
null
null
null
Ext2D_Engine_Sources/Ext2D Engine Tools Sources/Source/Color Spy/Main.pas
delphi-pascal-archive/ext2d_engine
ca891630602c02baa512104d2289d471e239c67d
[ "Unlicense" ]
null
null
null
Ext2D_Engine_Sources/Ext2D Engine Tools Sources/Source/Color Spy/Main.pas
delphi-pascal-archive/ext2d_engine
ca891630602c02baa512104d2289d471e239c67d
[ "Unlicense" ]
null
null
null
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls; type TSpyForm = class(TForm) sbSelectColor: TSpeedButton; sbAbout: TSpeedButton; ColorView: TShape; labColor: TLabel; eColor: TEdit; labRed: TLabel; bev1: TBevel; labGreen: TLabel; labBlue: TLabel; eRed: TEdit; eGreen: TEdit; eBlue: TEdit; ColorDialog: TColorDialog; procedure sbAboutClick(Sender: TObject); procedure sbSelectColorClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var SpyForm: TSpyForm; implementation {$R *.dfm} uses About; procedure TSpyForm.sbAboutClick(Sender: TObject); begin AboutForm.ShowModal; end; procedure TSpyForm.sbSelectColorClick(Sender: TObject); var col : TColor; ec : Word; r, g, b : Byte; begin if ColorDialog.Execute then begin col := ColorDialog.Color; r := Round(GetRValue(col) / 255 * $1F); g := Round(GetGValue(col) / 255 * $3F); b := Round(GetBValue(col) / 255 * $1F); ec := b or (g shl 5) or (r shl 11); eColor.Text := '$' + IntToHex(ec, 4); eRed.Text := '$' + IntToHex(r, 2); eGreen.Text := '$' + IntToHex(g, 2); eBlue.Text := '$' + IntToHex(b, 2); ColorView.Brush.Color := col; end; end; end.
21.088235
77
0.613668
f1254ba4e5f17405de1fa1c89105134f3be1d407
383
pas
Pascal
Intersection.pas
igororeshin/Homeworks
18f8737ba407d0eadf825be91c2d2c3b6978d075
[ "Apache-2.0" ]
null
null
null
Intersection.pas
igororeshin/Homeworks
18f8737ba407d0eadf825be91c2d2c3b6978d075
[ "Apache-2.0" ]
null
null
null
Intersection.pas
igororeshin/Homeworks
18f8737ba407d0eadf825be91c2d2c3b6978d075
[ "Apache-2.0" ]
null
null
null
const n = 4; var a1, a2: array [1..n] of integer; i, j: integer; begin for i := 1 to n do begin readln(a1[i]); end; for i := 1 to n do begin readln(a2[i]); end; for i := 1 to n do begin j := 1; while a1[j] <=a2 [i] do begin if a1[j] = a2[i] then begin write(a1[j], ', '); end; if j < n then j := j + 1 else break; end; end; end.
11.606061
33
0.496084
f1d31500ab48d00514148ed3cdb9dfacef810899
972
pas
Pascal
uBadInjection.pas
NickHodges/diidcode
fcba7769fddb930536e6b087d43522aab63ccc6b
[ "CC0-1.0" ]
1
2021-08-03T05:24:45.000Z
2021-08-03T05:24:45.000Z
uBadInjection.pas
NickHodges/diidcode
fcba7769fddb930536e6b087d43522aab63ccc6b
[ "CC0-1.0" ]
null
null
null
uBadInjection.pas
NickHodges/diidcode
fcba7769fddb930536e6b087d43522aab63ccc6b
[ "CC0-1.0" ]
1
2021-08-03T05:24:46.000Z
2021-08-03T05:24:46.000Z
unit uBadInjection; interface uses VCL.Graphics , Spring ; type IPaintGunTip = interface procedure SprayCar(aColor: TColor); end; TPaintGunTip = class(TInterfacedObject, IPaintGunTip) procedure SprayCar(aColor: TColor); end; TCarPaintingRobot = class private FPaintGunTip: IPaintGunTip; public constructor Create(aPaintGunTip: IPaintGunTip); procedure PaintCar(aColor: TColor); end; implementation constructor TCarPaintingRobot.Create(aPaintGunTip: IPaintGunTip); begin Guard.CheckNotNull(aPaintGunTip, 'aPaintGunTip'); FPaintGunTip := aPaintGunTip; end; procedure TCarPaintingRobot.PaintCar(aColor: TColor); begin FPaintGunTip.SprayCar(aColor); // Uh oh -- what to do now? How do we free the tip? // and even if we could, what then? // How would we get a new one? end; procedure TPaintGunTip.SprayCar(aColor: TColor); begin Writeln('Spray the car with ', ColorToString(aColor)); end; end.
17.357143
65
0.728395
6a5503ad25c6b206c2b9195e1ae193636652b6e8
919
pas
Pascal
screenshotter.pas
globalpolicy/ScreenTextFinder
479c12bef1ab4cf89d8d6d41ab36af1de07dddfc
[ "MIT" ]
1
2021-11-10T02:14:23.000Z
2021-11-10T02:14:23.000Z
screenshotter.pas
globalpolicy/ScreenTextFinder
479c12bef1ab4cf89d8d6d41ab36af1de07dddfc
[ "MIT" ]
null
null
null
screenshotter.pas
globalpolicy/ScreenTextFinder
479c12bef1ab4cf89d8d6d41ab36af1de07dddfc
[ "MIT" ]
2
2021-11-07T11:37:18.000Z
2021-11-10T02:14:25.000Z
unit screenshotter; interface uses Windows, PNGImage, Graphics, Sysutils; function GetScreenShot(): TPngImage; implementation function GetScreenShot(): TPngImage; var deviceContext: cardinal; pngScreenshot: TPngImage; bmpScreenshot: Graphics.TBitMap; screenHeight: integer; screenWidth: integer; begin screenHeight := GetSystemMetrics(SM_CYSCREEN); screenWidth := GetSystemMetrics(SM_CXSCREEN); deviceContext := GetDC(0); bmpScreenshot := Graphics.TBitMap.Create(); bmpScreenshot.Height := screenHeight; bmpScreenshot.Width := screenWidth; BitBlt(bmpScreenshot.Canvas.Handle, 0, 0, screenWidth, screenHeight, deviceContext, 0, 0, SRCCOPY); pngScreenshot := TPngImage.Create(); pngScreenshot.Assign(bmpScreenshot); {$IFDEF DEBUG} pngScreenshot.SaveToFile('saved.png'); {$ENDIF} Result := pngScreenshot; bmpScreenshot.Free(); end; end.
23.564103
71
0.725789
f117207cdcc47602381ed645c563f19265f323e1
1,092
pas
Pascal
windows/src/developer/setup/httpuploader_messageprocessor_windows.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/developer/setup/httpuploader_messageprocessor_windows.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/developer/setup/httpuploader_messageprocessor_windows.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
(* Name: httpuploader_messageprocessor_windows Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 4 Jun 2007 Modified Date: 23 Aug 2007 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 04 Jun 2007 - mcdurdin - Initial version 23 Aug 2007 - mcdurdin - Initial version from Desktop *) unit httpuploader_messageprocessor_windows; interface implementation uses httpuploader, SysUtils; type THTTPUploader_MessageProcessor_Windows = class(THTTPUploader_MessageProcessor) public procedure ProcessMessages; override; end; { THTTPUploader_MessageProcessor_Forms } procedure THTTPUploader_MessageProcessor_Windows.ProcessMessages; begin // Application.ProcessMessages; end; initialization FHTTPUploader_MessageProcessor := THTTPUploader_MessageProcessor_Windows.Create; finalization FHTTPUploader_MessageProcessor.Free; FHTTPUploader_MessageProcessor := nil; end.
22.75
82
0.71337
f1ea2c6e77630e091edf98a0db22ff8aa8637ffb
3,989
pas
Pascal
package/indy-10.2.0.3/fpc/IdTrivialFTPBase.pas
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
1
2022-02-28T11:28:18.000Z
2022-02-28T11:28:18.000Z
package/indy-10.2.0.3/fpc/IdTrivialFTPBase.pas
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
null
null
null
package/indy-10.2.0.3/fpc/IdTrivialFTPBase.pas
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
null
null
null
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 2/7/2004 7:20:18 PM JPMugaas DotNET to go!! and YES - I want fries with that :-). Rev 1.3 2004.02.03 5:44:38 PM czhower Name changes Rev 1.2 10/25/2003 06:52:18 AM JPMugaas Updated for new API changes and tried to restore some functionality. Rev 1.1 2003.10.12 6:36:48 PM czhower Now compiles. Rev 1.0 11/13/2002 08:03:38 AM JPMugaas } unit IdTrivialFTPBase; interface {$i IdCompilerDefines.inc} uses IdGlobal, IdUDPBase, IdUDPClient, SysUtils; type TIdTFTPMode = (tfNetAscii, tfOctet); type WordStr = string[2]; // Procs function MakeAckPkt(const BlockNumber: Word): string; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; const ErrNumber: Word; ErrorString: string); overload; procedure SendError(UDPClient: TIdUDPClient; const ErrNumber: Word; ErrorString: string); overload; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; E: Exception); overload; procedure SendError(UDPClient: TIdUDPClient; E: Exception); overload; const // TFTP opcodes TFTP_RRQ = 1; TFTP_WRQ = 2; TFTP_DATA = 3; TFTP_ACK = 4; TFTP_ERROR = 5; TFTP_OACK = 6; // see RFC 1782 and 1783 const // various MaxWord = High(Word); hdrsize = 4; // TFTP Headersize on DATA packets (opcode + block#) sBlockSize = 'blksize'#0; {Do not Localize} // TFTP RFC 1782/1783 allows an optional blocksize to be specified // A blocksize of 8192 bytes generates far less ACK packets than 512 bytes blocks const // tftp error codes ErrUndefined = 0; ErrFileNotFound = 1; ErrAccessViolation = 2; ErrAllocationExceeded = 3; ErrIllegalOperation = 4; ErrUnknownTransferID = 5; ErrFileAlreadyExists = 6; ErrNoSuchUser = 7; ErrOptionNegotiationFailed = 8; implementation uses IdGlobalProtocols, IdExceptionCore, IdStack; function MakeAckPkt(const BlockNumber: Word): string; begin Result := WordToStr(GStack.HostToNetwork(TFTP_ACK)) + WordToStr(GStack.HostToNetwork(BlockNumber)); end; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; const ErrNumber: Word; ErrorString: string); begin UDPBase.Send(APeerIP, APort, WordToStr(GStack.HostToNetwork(Word(TFTP_ERROR))) + WordToStr(ErrNumber) + ErrorString + #0); end; procedure SendError(UDPClient: TIdUDPClient; const ErrNumber: Word; ErrorString: string); begin SendError(UDPClient, UDPClient.Host, UDPClient.Port, ErrNumber, ErrorString); end; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; E: Exception); var ErrNumber: Word; begin ErrNumber := ErrUndefined; if E is EIdTFTPFileNotFound then begin ErrNumber := ErrFileNotFound; end; if E is EIdTFTPAccessViolation then begin ErrNumber := ErrAccessViolation; end; if E is EIdTFTPAllocationExceeded then begin ErrNumber := ErrAllocationExceeded; end; if E is EIdTFTPIllegalOperation then begin ErrNumber := ErrIllegalOperation; end; if E is EIdTFTPUnknownTransferID then begin ErrNumber := ErrUnknownTransferID; end; if E is EIdTFTPFileAlreadyExists then begin ErrNumber := ErrFileAlreadyExists; end; if E is EIdTFTPNoSuchUser then begin ErrNumber := ErrNoSuchUser; end; if E is EIdTFTPOptionNegotiationFailed then begin ErrNumber := ErrOptionNegotiationFailed; end; SendError(UDPBase, APeerIP, APort, ErrNumber, E.Message); end; procedure SendError(UDPClient: TIdUDPClient; E: Exception); begin SendError(UDPClient, UDPClient.Host, UDPClient.Port, E); end; end.
26.771812
136
0.71622
836be2b85a44350ff645ccaec0b28c2055dedec2
13,669
pas
Pascal
BaseNcoding/src/BaseUnits/BcpBase1024.pas
Xor-el/BaseNcodingPascal
3621b7f25b5d24be114c0067b269628a5bc0434f
[ "MIT" ]
28
2017-05-09T18:09:52.000Z
2022-01-13T18:27:58.000Z
BaseNcoding/src/BaseUnits/BcpBase1024.pas
Xor-el/BaseNcodingPascal
3621b7f25b5d24be114c0067b269628a5bc0434f
[ "MIT" ]
3
2018-07-05T18:59:28.000Z
2018-08-14T11:14:40.000Z
BaseNcoding/src/BaseUnits/BcpBase1024.pas
Xor-el/BaseNcodingPascal
3621b7f25b5d24be114c0067b269628a5bc0434f
[ "MIT" ]
12
2017-09-12T21:26:11.000Z
2022-03-17T13:00:32.000Z
unit BcpBase1024; {$I ..\Include\BaseNcoding.inc} interface uses {$IFDEF SCOPEDUNITNAMES} System.SysUtils {$ELSE} SysUtils {$ENDIF} {$IFDEF FPC} , fgl {$ENDIF} , BcpBase, BcpIBaseInterfaces, BcpBaseNcodingTypes, BcpUtils; type TBase1024 = class sealed(TBase, IBase1024) public const DefaultAlphabet: array [0 .. 1023] of TBaseNcodingChar = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ª', 'µ', 'º', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'ĸ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ŋ', 'ŋ', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƀ', 'Ɓ', 'Ƃ', 'ƃ', 'Ƅ', 'ƅ', 'Ɔ', 'Ƈ', 'ƈ', 'Ɖ', 'Ɗ', 'Ƌ', 'ƌ', 'ƍ', 'Ǝ', 'Ə', 'Ɛ', 'Ƒ', 'ƒ', 'Ɠ', 'Ɣ', 'ƕ', 'Ɩ', 'Ɨ', 'Ƙ', 'ƙ', 'ƚ', 'ƛ', 'Ɯ', 'Ɲ', 'ƞ', 'Ɵ', 'Ơ', 'ơ', 'Ƣ', 'ƣ', 'Ƥ', 'ƥ', 'Ʀ', 'Ƨ', 'ƨ', 'Ʃ', 'ƪ', 'ƫ', 'Ƭ', 'ƭ', 'Ʈ', 'Ư', 'ư', 'Ʊ', 'Ʋ', 'Ƴ', 'ƴ', 'Ƶ', 'ƶ', 'Ʒ', 'Ƹ', 'ƹ', 'ƺ', 'ƻ', 'Ƽ', 'ƽ', 'ƾ', 'ƿ', 'ǀ', 'ǁ', 'ǂ', 'ǃ', 'DŽ', 'Dž', 'dž', 'LJ', 'Lj', 'lj', 'NJ', 'Nj', 'nj', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'ǝ', 'Ǟ', 'ǟ', 'Ǡ', 'ǡ', 'Ǣ', 'ǣ', 'Ǥ', 'ǥ', 'Ǧ', 'ǧ', 'Ǩ', 'ǩ', 'Ǫ', 'ǫ', 'Ǭ', 'ǭ', 'Ǯ', 'ǯ', 'ǰ', 'DZ', 'Dz', 'dz', 'Ǵ', 'ǵ', 'Ƕ', 'Ƿ', 'Ǹ', 'ǹ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ', 'Ȁ', 'ȁ', 'Ȃ', 'ȃ', 'Ȅ', 'ȅ', 'Ȇ', 'ȇ', 'Ȉ', 'ȉ', 'Ȋ', 'ȋ', 'Ȍ', 'ȍ', 'Ȏ', 'ȏ', 'Ȑ', 'ȑ', 'Ȓ', 'ȓ', 'Ȕ', 'ȕ', 'Ȗ', 'ȗ', 'Ș', 'ș', 'Ț', 'ț', 'Ȝ', 'ȝ', 'Ȟ', 'ȟ', 'Ƞ', 'ȡ', 'Ȣ', 'ȣ', 'Ȥ', 'ȥ', 'Ȧ', 'ȧ', 'Ȩ', 'ȩ', 'Ȫ', 'ȫ', 'Ȭ', 'ȭ', 'Ȯ', 'ȯ', 'Ȱ', 'ȱ', 'Ȳ', 'ȳ', 'ȴ', 'ȵ', 'ȶ', 'ȸ', 'ȹ', 'Ⱥ', 'Ȼ', 'ȼ', 'Ƚ', 'Ⱦ', 'ȿ', 'ɀ', 'Ɂ', 'ɂ', 'Ƀ', 'Ʉ', 'Ʌ', 'Ɇ', 'ɇ', 'Ɉ', 'ɉ', 'Ɋ', 'ɋ', 'Ɍ', 'ɍ', 'Ɏ', 'ɏ', 'ɐ', 'ɑ', 'ɒ', 'ɓ', 'ɔ', 'ɕ', 'ɖ', 'ɗ', 'ɘ', 'ə', 'ɚ', 'ɛ', 'ɜ', 'ɝ', 'ɞ', 'ɟ', 'ɠ', 'ɡ', 'ɢ', 'ɣ', 'ɤ', 'ɥ', 'ɦ', 'ɧ', 'ɨ', 'ɩ', 'ɪ', 'ɫ', 'ɬ', 'ɭ', 'ɮ', 'ɯ', 'ɰ', 'ɱ', 'ɲ', 'ɳ', 'ɴ', 'ɵ', 'ɶ', 'ɷ', 'ɸ', 'ɹ', 'ɺ', 'ɻ', 'ɼ', 'ɽ', 'ɾ', 'ɿ', 'ʀ', 'ʁ', 'ʂ', 'ʃ', 'ʄ', 'ʅ', 'ʆ', 'ʇ', 'ʈ', 'ʉ', 'ʊ', 'ʋ', 'ʌ', 'ʍ', 'ʎ', 'ʏ', 'ʐ', 'ʑ', 'ʒ', 'ʓ', 'ʔ', 'ʕ', 'ʖ', 'ʗ', 'ʘ', 'ʙ', 'ʚ', 'ʛ', 'ʜ', 'ʝ', 'ʞ', 'ʟ', 'ʠ', 'ʡ', 'ʢ', 'ʣ', 'ʤ', 'ʥ', 'ʦ', 'ʧ', 'ʨ', 'ʩ', 'ʪ', 'ʫ', 'ʬ', 'ʭ', 'ʮ', 'ʯ', 'ʰ', 'ʱ', 'ʲ', 'ʳ', 'ʴ', 'ʵ', 'ʶ', 'ʷ', 'ʸ', 'ʹ', 'ʺ', 'ʻ', 'ʼ', 'ʽ', 'ʾ', 'ʿ', 'ˀ', 'ˁ', 'ˆ', 'ˇ', 'ˈ', 'ˉ', 'ˊ', 'ˋ', 'ˌ', 'ˍ', 'ˎ', 'ˏ', 'ː', 'ˑ', 'ˠ', 'ˡ', 'ˢ', 'ˣ', 'ˤ', 'ˬ', 'ˮ', 'ʹ', 'ͺ', 'ͻ', 'ͼ', 'ͽ', 'Ά', 'Έ', 'Ή', 'Ί', 'Ό', 'Ύ', 'Ώ', 'ΐ', 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'Ϊ', 'Ϋ', 'ά', 'έ', 'ή', 'ί', 'ΰ', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϊ', 'ϋ', 'ό', 'ύ', 'ώ', 'ϐ', 'ϑ', 'ϒ', 'ϓ', 'ϔ', 'ϕ', 'ϖ', 'ϗ', 'Ϙ', 'ϙ', 'Ϛ', 'ϛ', 'Ϝ', 'ϝ', 'Ϟ', 'ϟ', 'Ϡ', 'ϡ', 'Ϣ', 'ϣ', 'Ϥ', 'ϥ', 'Ϧ', 'ϧ', 'Ϩ', 'ϩ', 'Ϫ', 'ϫ', 'Ϭ', 'ϭ', 'Ϯ', 'ϯ', 'ϰ', 'ϱ', 'ϲ', 'ϳ', 'ϴ', 'ϵ', 'Ϸ', 'ϸ', 'Ϲ', 'Ϻ', 'ϻ', 'ϼ', 'Ͻ', 'Ͼ', 'Ͽ', 'Ѐ', 'Ё', 'Ђ', 'Ѓ', 'Є', 'Ѕ', 'І', 'Ї', 'Ј', 'Љ', 'Њ', 'Ћ', 'Ќ', 'Ѝ', 'Ў', 'Џ', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я', 'ѐ', 'ё', 'ђ', 'ѓ', 'є', 'ѕ', 'і', 'ї', 'ј', 'љ', 'њ', 'ћ', 'ќ', 'ѝ', 'ў', 'џ', 'Ѡ', 'ѡ', 'Ѣ', 'ѣ', 'Ѥ', 'ѥ', 'Ѧ', 'ѧ', 'Ѩ', 'ѩ', 'Ѫ', 'ѫ', 'Ѭ', 'ѭ', 'Ѯ', 'ѯ', 'Ѱ', 'ѱ', 'Ѳ', 'ѳ', 'Ѵ', 'ѵ', 'Ѷ', 'ѷ', 'Ѹ', 'ѹ', 'Ѻ', 'ѻ', 'Ѽ', 'ѽ', 'Ѿ', 'ѿ', 'Ҁ', 'ҁ', 'Ҋ', 'ҋ', 'Ҍ', 'ҍ', 'Ҏ', 'ҏ', 'Ґ', 'ґ', 'Ғ', 'ғ', 'Ҕ', 'ҕ', 'Җ', 'җ', 'Ҙ', 'ҙ', 'Қ', 'қ', 'Ҝ', 'ҝ', 'Ҟ', 'ҟ', 'Ҡ', 'ҡ', 'Ң', 'ң', 'Ҥ', 'ҥ', 'Ҧ', 'ҧ', 'Ҩ', 'ҩ', 'Ҫ', 'ҫ', 'Ҭ', 'ҭ', 'Ү', 'ү', 'Ұ', 'ұ', 'Ҳ', 'ҳ', 'Ҵ', 'ҵ', 'Ҷ', 'ҷ', 'Ҹ', 'ҹ', 'Һ', 'һ', 'Ҽ', 'ҽ', 'Ҿ', 'ҿ', 'Ӏ', 'Ӂ', 'ӂ', 'Ӄ', 'ӄ', 'Ӆ', 'ӆ', 'Ӈ', 'ӈ', 'Ӊ', 'ӊ', 'Ӌ', 'ӌ', 'Ӎ', 'ӎ', 'ӏ', 'Ӑ', 'ӑ', 'Ӓ', 'ӓ', 'Ӕ', 'ӕ', 'Ӗ', 'ӗ', 'Ә', 'ә', 'Ӛ', 'ӛ', 'Ӝ', 'ӝ', 'Ӟ', 'ӟ', 'Ӡ', 'ӡ', 'Ӣ', 'ӣ', 'Ӥ', 'ӥ', 'Ӧ', 'ӧ', 'Ө', 'ө', 'Ӫ', 'ӫ', 'Ӭ', 'ӭ', 'Ӯ', 'ӯ', 'Ӱ', 'ӱ', 'Ӳ', 'ӳ', 'Ӵ', 'ӵ', 'Ӷ', 'ӷ', 'Ӹ', 'ӹ', 'Ӻ', 'ӻ', 'Ӽ', 'ӽ', 'Ӿ', 'ӿ', 'Ԁ', 'ԁ', 'Ԃ', 'ԃ', 'Ԅ', 'ԅ', 'Ԇ', 'ԇ', 'Ԉ', 'ԉ', 'Ԋ', 'ԋ', 'Ԍ', 'ԍ', 'Ԏ', 'ԏ', 'Ԑ', 'ԑ', 'Ԓ', 'ԓ', 'Ԛ', 'ԛ', 'Ԝ', 'ԝ', 'Ա', 'Բ', 'Գ', 'Դ', 'Ե', 'Զ', 'Է', 'Ը', 'Թ', 'Ժ', 'Ի', 'Լ', 'Խ', 'Ծ', 'Կ', 'Հ', 'Ձ', 'Ղ', 'Ճ', 'Մ', 'Յ', 'Ն', 'Շ', 'Ո', 'Չ', 'Պ', 'Ջ', 'Ռ', 'Ս', 'Վ', 'Տ', 'Ր', 'Ց', 'Ւ', 'Փ', 'Ք'); DefaultSpecial = TBaseNcodingChar('='); constructor Create(_Alphabet: TBaseNcodingString = ''; _Special: TBaseNcodingChar = DefaultSpecial; _textEncoding: TEncoding = Nil); function GetHaveSpecial: Boolean; override; function Encode(data: TBytes): TBaseNcodingString; override; function Decode(const data: TBaseNcodingString): TBytes; override; end; implementation constructor TBase1024.Create(_Alphabet: TBaseNcodingString = ''; _Special: TBaseNcodingChar = DefaultSpecial; _textEncoding: TEncoding = Nil); begin if _Alphabet = '' then begin SetString(_Alphabet, PBaseNcodingChar(@DefaultAlphabet[0]), Length(DefaultAlphabet)); end; Inherited Create(1024, _Alphabet, _Special, _textEncoding); end; function TBase1024.GetHaveSpecial: Boolean; begin result := True; end; function TBase1024.Encode(data: TBytes): TBaseNcodingString; var dataLength, i, x1, x2, x3, x4, x5, length5, tempInt: Integer; {$IFNDEF FPC} tempResult: TStringBuilder; {$ELSE} tempResult: TFPGList<TBaseNcodingString>; uS: TBaseNcodingString; {$ENDIF} begin if ((data = Nil) or (Length(data) = 0)) then begin result := (''); Exit; end; dataLength := Length(data); {$IFDEF FPC} tempResult := TFPGList<TBaseNcodingString>.Create; tempResult.Capacity := (dataLength + 4) div 5 * 4 + 1; {$ELSE} tempResult := TStringBuilder.Create((dataLength + 4) div 5 * 4 + 1); {$ENDIF} try length5 := (dataLength div 5) * 5; i := 0; while i < length5 do begin x1 := data[i]; x2 := data[i + 1]; x3 := data[i + 2]; x4 := data[i + 3]; x5 := data[i + 4]; {$IFDEF FPC} tempResult.Add(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Add(Alphabet[((x2 shr 2) or ((x3 and $0F) shl 6)) + 1]); tempResult.Add(Alphabet[((x3 shr 4) or ((x4 and $3F) shl 4)) + 1]); tempResult.Add(Alphabet[((x4 shr 6) or (x5 shl 2)) + 1]); {$ELSE} tempResult.Append(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Append(Alphabet[((x2 shr 2) or ((x3 and $0F) shl 6)) + 1]); tempResult.Append(Alphabet[((x3 shr 4) or ((x4 and $3F) shl 4)) + 1]); tempResult.Append(Alphabet[((x4 shr 6) or (x5 shl 2)) + 1]); {$ENDIF} inc(i, 5); end; tempInt := dataLength - length5; Case tempInt of 1: begin x1 := data[i]; {$IFDEF FPC} tempResult.Add(Alphabet[(x1) + 1]); tempResult.Add(StringOfChar(Special, 4)); {$ELSE} tempResult.Append(Alphabet[(x1) + 1]); tempResult.Append(Special, 4); {$ENDIF} end; 2: begin x1 := data[i]; x2 := data[i + 1]; {$IFDEF FPC} tempResult.Add(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Add(Alphabet[(x2 shr 2) + 1]); tempResult.Add(StringOfChar(Special, 3)); {$ELSE} tempResult.Append(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Append(Alphabet[(x2 shr 2) + 1]); tempResult.Append(Special, 3); {$ENDIF} end; 3: begin x1 := data[i]; x2 := data[i + 1]; x3 := data[i + 2]; {$IFDEF FPC} tempResult.Add(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Add(Alphabet[((x2 shr 2) or ((x3 and $0F) shl 6)) + 1]); tempResult.Add(Alphabet[(x3 shr 4) + 1]); tempResult.Add(StringOfChar(Special, 2)); {$ELSE} tempResult.Append(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Append(Alphabet[((x2 shr 2) or ((x3 and $0F) shl 6)) + 1]); tempResult.Append(Alphabet[(x3 shr 4) + 1]); tempResult.Append(Special, 2); {$ENDIF} end; 4: begin x1 := data[i]; x2 := data[i + 1]; x3 := data[i + 2]; x4 := data[i + 3]; {$IFDEF FPC} tempResult.Add(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Add(Alphabet[((x2 shr 2) or ((x3 and $0F) shl 6)) + 1]); tempResult.Add(Alphabet[((x3 shr 4) or ((x4 and $3F) shl 4)) + 1]); tempResult.Add(Alphabet[(x4 shr 6) + 1]); tempResult.Add(Special); {$ELSE} tempResult.Append(Alphabet[(x1 or ((x2 and $03) shl 8)) + 1]); tempResult.Append(Alphabet[((x2 shr 2) or ((x3 and $0F) shl 6)) + 1]); tempResult.Append(Alphabet[((x3 shr 4) or ((x4 and $3F) shl 4)) + 1]); tempResult.Append(Alphabet[(x4 shr 6) + 1]); tempResult.Append(Special); {$ENDIF} end; end; {$IFDEF FPC} result := ''; for uS in tempResult do begin result := result + uS; end; {$ELSE} result := tempResult.ToString; {$ENDIF} finally tempResult.Free; end; end; function TBase1024.Decode(const data: TBaseNcodingString): TBytes; var lastSpecialInd, tailLength, i, srcInd, x1, x2, x3, x4, length5: Integer; begin if TUtils.IsNullOrEmpty(data) then begin result := Nil; Exit; end; lastSpecialInd := Length(data); while (data[lastSpecialInd] = Special) do begin dec(lastSpecialInd); end; tailLength := Length(data) - lastSpecialInd; SetLength(result, (Length(data) div 4) * 5 - tailLength); i := 0; srcInd := 0; length5 := (Length(data) div 4 - 1) * 5; while i < length5 do begin x1 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x3 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x4 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2)); result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4)); result[i + 3] := Byte((x3 shr 4) and $3F or (x4 shl 6)); result[i + 4] := Byte(x4 shr 2); inc(i, 5); end; if (tailLength = 0) then begin x1 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x3 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x4 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2)); result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4)); result[i + 3] := Byte((x3 shr 4) and $3F or (x4 shl 6)); result[i + 4] := Byte(x4 shr 2); end; Case (tailLength) of 4: begin x1 := FInvAlphabet[Ord(data[(srcInd) + 1])]; result[i] := Byte(x1); end; 3: begin x1 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[(srcInd) + 1])]; result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2)); end; 2: begin x1 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x3 := FInvAlphabet[Ord(data[(srcInd) + 1])]; result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2)); result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4)); end; 1: begin x1 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x3 := FInvAlphabet[Ord(data[(srcInd) + 1])]; inc(srcInd); x4 := FInvAlphabet[Ord(data[(srcInd) + 1])]; result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2)); result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4)); result[i + 3] := Byte((x3 shr 4) and $3F or (x4 shl 6)); end; end; end; end.
36.353723
80
0.408808
4709ef9bb655894852ab34fae2e3d806c8b4a811
3,312
pas
Pascal
MyTunes/FMX/Views/View.Album.pas
grijjy/MvvmStarterKit
b46b17a5bcf87de1a0b83e23fe171c5beb62e1b2
[ "BSD-2-Clause" ]
46
2018-01-21T21:05:35.000Z
2021-07-21T15:44:08.000Z
MyTunes/FMX/Views/View.Album.pas
juliomar/MvvmStarterKit
b46b17a5bcf87de1a0b83e23fe171c5beb62e1b2
[ "BSD-2-Clause" ]
1
2018-11-27T18:03:57.000Z
2018-11-27T18:03:57.000Z
MyTunes/FMX/Views/View.Album.pas
juliomar/MvvmStarterKit
b46b17a5bcf87de1a0b83e23fe171c5beb62e1b2
[ "BSD-2-Clause" ]
15
2018-01-22T16:02:32.000Z
2022-01-11T04:41:13.000Z
unit View.Album; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ListBox, FMX.Layouts, FMX.Edit, FMX.ScrollBox, FMX.Memo, FMX.DateTimeCtrls, FMX.Colors, Grijjy.Mvvm.Controls.Fmx, // MUST be listed AFTER all other FMX.* units! Grijjy.Mvvm.Views.Fmx, ViewModel.Album; type TViewAlbum = class(TgoFormView<TViewModelAlbum>) ToolBar: TToolBar; ButtonCancel: TButton; ButtonOK: TButton; ListBox: TListBox; ListBoxItemTitle: TListBoxItem; EditTitle: TEdit; ListBoxItemArtist: TListBoxItem; EditArtist: TEdit; ListBoxItemRecordLabel: TListBoxItem; EditRecordLabel: TEdit; ListBoxItemCopyright: TListBoxItem; EditCopyright: TEdit; ListBoxItemReleaseDate: TListBoxItem; DateEditReleaseDate: TDateEdit; ListBoxItemNotes: TListBoxItem; MemoNotes: TMemo; ListBoxItemTracks: TListBoxItem; ListBoxItemBackgroundColor: TListBoxItem; ComboColorBoxBackground: TComboColorBox; procedure ListBoxItemTracksClick(Sender: TObject); protected { TgoFormView } procedure SetupView; override; end; implementation uses System.SysConst, Grijjy.Mvvm.Rtti, Grijjy.Mvvm.Types, Grijjy.Mvvm.DataBinding, Grijjy.Mvvm.ViewFactory, Converter.TitleToCaption; {$R *.fmx} {$R *.iPhone4in.fmx IOS} {$R *.NmXhdpiPh.fmx ANDROID} {$R *.Windows.fmx MSWINDOWS} {$R *.Macintosh.fmx MACOS} type { Prefix an album title with the text 'Album: ' } TTrackCountToText = class(TgoValueConverter) public class function ConvertSourceToTarget(const ASource: TgoValue): TgoValue; override; end; { TViewAlbum } procedure TViewAlbum.ListBoxItemTracksClick(Sender: TObject); begin ViewModel.EditTracks; end; procedure TViewAlbum.SetupView; begin { Bind properties } Binder.Bind(ViewModel.Album, 'Title', Self, 'Caption', TgoBindDirection.OneWay, [], TTitleToCaption); Binder.Bind(ViewModel.Album, 'Title', EditTitle, 'Text', TgoBindDirection.TwoWay, [TgoBindFlag.TargetTracking]); Binder.Bind(ViewModel.Album, 'Artist', EditArtist, 'Text', TgoBindDirection.TwoWay, [TgoBindFlag.TargetTracking]); Binder.Bind(ViewModel.Album, 'RecordLabel', EditRecordLabel, 'Text'); Binder.Bind(ViewModel.Album, 'Copyright', EditCopyright, 'Text'); Binder.Bind(ViewModel.Album, 'ReleaseDate', DateEditReleaseDate, 'Date'); Binder.Bind(ViewModel.Album, 'BackgroundColor', ComboColorBoxBackground, 'Color'); Binder.Bind(ViewModel.Album, 'Notes', MemoNotes, 'Text'); Binder.Bind(ViewModel.Album, 'TrackCount', ListBoxItemTracks.ItemData, 'Detail', TgoBindDirection.OneWay, [], TTrackCountToText); Binder.Bind(ViewModel.Album, 'IsValid', ButtonOK, 'Enabled', TgoBindDirection.OneWay); end; { TTrackCountToText } class function TTrackCountToText.ConvertSourceToTarget( const ASource: TgoValue): TgoValue; var Count: Integer; begin Assert(ASource.ValueType = TgoValueType.Ordinal); Count := ASource.AsOrdinal; case Count of 0: Result := 'No tracks'; 1: Result := '1 track'; else Result := Count.ToString + ' tracks'; end; end; initialization TgoViewFactory.Register(TViewAlbum, 'Album'); end.
26.07874
86
0.735809
83b7853b6419f8fc085e56bba94f4845638a2ff8
5,630
dfm
Pascal
windows/source/frmAboutU.dfm
vhanla/delphi-library-helper
0d0e5ceb4de1ba917961b87a0875b3f4ab5bc756
[ "Apache-2.0" ]
1
2019-05-13T12:39:21.000Z
2019-05-13T12:39:21.000Z
windows/source/frmAboutU.dfm
vhanla/delphi-library-helper
0d0e5ceb4de1ba917961b87a0875b3f4ab5bc756
[ "Apache-2.0" ]
null
null
null
windows/source/frmAboutU.dfm
vhanla/delphi-library-helper
0d0e5ceb4de1ba917961b87a0875b3f4ab5bc756
[ "Apache-2.0" ]
2
2019-05-13T12:39:23.000Z
2020-02-07T18:44:09.000Z
object frmAbout: TfrmAbout Left = 200 Top = 108 BorderStyle = bsDialog Caption = 'About' ClientHeight = 272 ClientWidth = 298 Color = clBtnFace ParentFont = True OldCreateOrder = True Position = poScreenCenter OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel AlignWithMargins = True Left = 3 Top = 3 Width = 292 Height = 219 Align = alClient BevelInner = bvRaised BevelOuter = bvLowered ParentColor = True TabOrder = 0 object Comments: TLabel AlignWithMargins = True Left = 5 Top = 111 Width = 282 Height = 13 Align = alTop Alignment = taCenter Caption = 'Comments' Layout = tlCenter WordWrap = True IsControl = True ExplicitWidth = 50 end object Bevel1: TBevel AlignWithMargins = True Left = 5 Top = 96 Width = 282 Height = 9 Align = alTop Shape = bsTopLine end object Panel3: TPanel Left = 2 Top = 2 Width = 288 Height = 91 Align = alTop BevelOuter = bvNone TabOrder = 0 object Panel4: TPanel AlignWithMargins = True Left = 3 Top = 3 Width = 90 Height = 85 Align = alLeft BevelOuter = bvNone TabOrder = 0 object ProgramIcon: TImage AlignWithMargins = True Left = 3 Top = 3 Width = 84 Height = 79 Align = alClient Picture.Data = { 0954506E67496D61676589504E470D0A1A0A0000000D49484452000000400000 00400806000000AA6971DE00000006624B474400FF00FF00FFA0BDA793000002 B54944415478DAED9ACF6B134114C7BB4B36D6250A22A227E9419A930AE6D2B3 1EF51AC9263186A5841AA51EFC07F22F5835D2A5CAB224BB62AE7AD4B397148A A78820F556B014A12C31091BBFA339C8D2CC6E3686C98FF7856167C8DB79EF7D 66E6CD422B2D2DB824D101881601101D80681100D10188160110E9BC582C2EB3 A7699AED850290CBE5AE4A92F4A8DFEF6B7F82902407FDE7F57AFDF3DC022895 4A8AEBBA1A12DDC43035C4AC09185BAAAA3A866174E702403A9DBEA0288A8EC4 36305C09F9DA3780DA467BE538CE8F9904806DBE86471949DC45F2A7A2CC8177 7FE1DDB7E856713C3E4D3D006C7315DB3C8BC01F607823C09C25F402B6C8512A A3BF1660BF0BDB6A229160C7C39D2A00F97CFE3A827B826E1A6D99637A84640D 59965F5B96F5E5DF1F0A85C2AAE7793AE62961788E33C731E6B0F1ACD66AB53D 610070B64FE36CDF43302CE05480F91E5BBD6EB76B371A8D639EA1AEEB67DAED B606480FF1CEB580799BB031E2F1B815F52A1D194026935989C5621B705CC4F0 22C79455F137B07B6ADB76334A70D96C3605C08F995B3485637A003B133BE825 7CED4F0280A469DA1DAC0ABBC26EA2C91CDBEF6CB5D14C54F0832889FB850FA6 4B9D4EE7FEA0565CE6987A681F01620BBEDFA1DF1F0B00CEE5F95EAFB70EC7EB 185EE19832471F98E36432F9BE52A978FF2371BF30AFDC6AB56E0F16E25640FC 5FB1083BD8AD3BA837872303C0F67B86C40BE89EE53871D957DCD2DF82B43B89 A487098597DD32E5C1D7A4CA31FD8966E11ADD1C0900EE71DEF6095DD426ADB0 4513004ECC352A809913012000046034007EF981F8279CF6DF87890010000240 00080001200004800010000240000800012000048000100002400008C04913CE BAE8EF020480008C07206C519916858D9F00849D60D6450008000118EFFF03E6 5504407400A245004407205A04407400A2B5F0007E031919446E3EDC48050000 000049454E44AE426082} Stretch = True IsControl = True ExplicitLeft = 8 ExplicitTop = 8 ExplicitWidth = 65 ExplicitHeight = 57 end end object Panel5: TPanel AlignWithMargins = True Left = 99 Top = 3 Width = 186 Height = 85 Align = alClient BevelOuter = bvNone TabOrder = 1 object ProductName: TLabel Left = 0 Top = 0 Width = 186 Height = 56 Align = alClient Alignment = taCenter Caption = 'Product Name' WordWrap = True IsControl = True ExplicitWidth = 67 ExplicitHeight = 13 end object CompanyName: TLabel AlignWithMargins = True Left = 3 Top = 72 Width = 180 Height = 13 Align = alBottom Alignment = taCenter Caption = 'Company Name' IsControl = True ExplicitWidth = 75 end object Version: TLabel Left = 0 Top = 56 Width = 186 Height = 13 Align = alBottom Alignment = taCenter Caption = '0.0.0.0' IsControl = True ExplicitWidth = 36 end end end object memoCredits: TMemo AlignWithMargins = True Left = 5 Top = 127 Width = 282 Height = 87 Align = alClient Alignment = taCenter Lines.Strings = ( 'Development' 'Tristan Marlow' '' 'Icons from Icons8') ReadOnly = True TabOrder = 1 ExplicitLeft = 8 end end object Panel2: TPanel AlignWithMargins = True Left = 3 Top = 228 Width = 292 Height = 41 Align = alBottom BevelInner = bvRaised BevelOuter = bvLowered TabOrder = 1 object OKButton: TButton AlignWithMargins = True Left = 102 Top = 5 Width = 88 Height = 31 Margins.Left = 100 Margins.Right = 100 Align = alClient Caption = 'OK' Default = True ModalResult = 1 TabOrder = 0 end end end
28.434343
76
0.623979
f128179ba54fbd235cd6443ad18de0be20059408
6,767
pas
Pascal
comps/GR32/GR32_Dsgn_ColorPicker.pas
cmacro/mgui
598e9613220e9af4f4ceba26caaab7523ec7b6fd
[ "MIT" ]
12
2019-11-09T11:44:47.000Z
2022-03-01T23:38:30.000Z
comps/GR32/GR32_Dsgn_ColorPicker.pas
cmacro/mgui
598e9613220e9af4f4ceba26caaab7523ec7b6fd
[ "MIT" ]
1
2019-11-08T08:27:34.000Z
2019-11-08T08:43:51.000Z
Src/Graphics32/Source/GR32_Dsgn_ColorPicker.pas
ryujt/ryulib-delphi
a59d308d6535de6a2fdb1ac49ded981849031c60
[ "MIT" ]
15
2019-10-15T12:34:29.000Z
2021-02-23T08:25:48.000Z
unit GR32_Dsgn_ColorPicker; (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 or LGPL 2.1 with linking exception * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Alternatively, the contents of this file may be used under the terms of the * Free Pascal modified version of the GNU Lesser General Public License * Version 2.1 (the "FPC modified LGPL License"), in which case the provisions * of this license are applicable instead of those above. * Please see the file LICENSE.txt for additional information concerning this * license. * * The Original Code is Graphics32 * * The Initial Developer of the Original Code is * Alex A. Denisov * * Portions created by the Initial Developer are Copyright (C) 2000-2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Christian-W. Budde * * ***** END LICENSE BLOCK ***** *) interface {$I GR32.inc} uses Classes, SysUtils, {$IFDEF FPC} RTLConsts, LazIDEIntf, PropEdits, Graphics, Dialogs, Forms, Spin, ExtCtrls, StdCtrls, Controls, {$IFDEF Windows} Windows, Registry, {$ENDIF} {$ELSE} Consts, DesignIntf, DesignEditors, VCLEditors, StdCtrls, Controls, Windows, Registry, Graphics, Dialogs, Forms, ExtCtrls, Spin, {$ENDIF} GR32, GR32_ColorPicker, GR32_ColorSwatch; type TFormColorPicker = class(TForm) ButtonCancel: TButton; ButtonOK: TButton; ButtonPickFromScreen: TButton; CheckBoxWebSafe: TCheckBox; ColorPickerAlpha: TColorPickerComponent; ColorPickerBlue: TColorPickerComponent; ColorPickerGreen: TColorPickerComponent; ColorPickerGTK: TColorPickerGTK; ColorPickerRed: TColorPickerComponent; ColorSwatch: TColorSwatch; ColorSwatchAqua: TColorSwatch; ColorSwatchBlack: TColorSwatch; ColorSwatchBlue: TColorSwatch; ColorSwatchFuchsia: TColorSwatch; ColorSwatchGreen: TColorSwatch; ColorSwatchRed: TColorSwatch; ColorSwatchWhite: TColorSwatch; ColorSwatchYellow: TColorSwatch; EditColor: TEdit; LabelAlpha: TLabel; LabelBlue: TLabel; LabelGreen: TLabel; LabelPalette: TLabel; LabelPreview: TLabel; LabelRed: TLabel; LabelWebColor: TLabel; PanelControl: TPanel; SpinEditAlpha: TSpinEdit; SpinEditBlue: TSpinEdit; SpinEditGreen: TSpinEdit; SpinEditRed: TSpinEdit; procedure ButtonPickFromScreenClick(Sender: TObject); procedure ColorPickerChanged(Sender: TObject); procedure SpinEditColorChange(Sender: TObject); procedure CheckBoxWebSafeClick(Sender: TObject); procedure EditColorChange(Sender: TObject); procedure ColorSwatchClick(Sender: TObject); private FColor: TColor32; FScreenColorPickerForm: TScreenColorPickerForm; FLockChanged: integer; procedure UpdateColor; procedure ScreenColorPickerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SetColor32(const Value: TColor32); public property Color: TColor32 read FColor write SetColor32; end; implementation {$R *.dfm} { TFormColorPicker } procedure TFormColorPicker.ButtonPickFromScreenClick(Sender: TObject); begin FScreenColorPickerForm := TScreenColorPickerForm.Create(Application); try FScreenColorPickerForm.OnMouseMove := ScreenColorPickerMouseMove; if FScreenColorPickerForm.ShowModal = mrOk then Color := FScreenColorPickerForm.SelectedColor; finally FreeAndNil(FScreenColorPickerForm); end; end; procedure TFormColorPicker.CheckBoxWebSafeClick(Sender: TObject); begin ColorPickerGTK.WebSafe := CheckBoxWebSafe.Checked; ColorPickerRed.WebSafe := CheckBoxWebSafe.Checked; ColorPickerGreen.WebSafe := CheckBoxWebSafe.Checked; ColorPickerBlue.WebSafe := CheckBoxWebSafe.Checked; ColorPickerAlpha.WebSafe := CheckBoxWebSafe.Checked; end; procedure TFormColorPicker.ColorPickerChanged(Sender: TObject); begin if (FLockChanged > 0) then exit; Inc(FLockChanged); try if (Sender = ColorPickerGTK) then Color := ColorPickerGTK.SelectedColor or ColorPickerAlpha.SelectedColor else Color := (ColorPickerRed.SelectedColor and $00FF0000) or (ColorPickerGreen.SelectedColor and $0000FF00) or (ColorPickerBlue.SelectedColor and $000000FF) or (ColorPickerAlpha.SelectedColor and $FF000000); finally Dec(FLockChanged); end; end; procedure TFormColorPicker.ColorSwatchClick(Sender: TObject); begin Color := TColorSwatch(Sender).Color; end; procedure TFormColorPicker.EditColorChange(Sender: TObject); var ColorText: string; Value: Integer; begin if (FLockChanged > 0) then exit; Inc(FLockChanged); try ColorText := StringReplace(EditColor.Text, '#', '$', []); if TryStrToInt(ColorText, Value) then Color := Value; finally Dec(FLockChanged); end; end; procedure TFormColorPicker.ScreenColorPickerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Color := FScreenColorPickerForm.SelectedColor; end; procedure TFormColorPicker.SetColor32(const Value: TColor32); begin if FColor <> Value then begin FColor := Value; UpdateColor; end; end; procedure TFormColorPicker.SpinEditColorChange(Sender: TObject); begin if (FLockChanged > 0) then exit; Inc(FLockChanged); try Color := SpinEditAlpha.Value shl 24 + SpinEditRed.Value shl 16 + SpinEditGreen.Value shl 8 + SpinEditBlue.Value; finally Dec(FLockChanged); end; end; procedure TFormColorPicker.UpdateColor; var R, G, B, A: Byte; SelStart: Integer; begin // disable OnChange handler Inc(FLockChanged); try // update spin edits Color32ToRGBA(FColor, R, G, B, A); SpinEditRed.Value := R; SpinEditGreen.Value := G; SpinEditBlue.Value := B; SpinEditAlpha.Value := A; // update color edit SelStart := EditColor.SelStart; EditColor.Text := '#' + IntToHex(FColor, 8); EditColor.SelStart := SelStart; ColorPickerRed.SelectedColor := FColor and $00FF0000; ColorPickerGreen.SelectedColor := FColor and $0000FF00; ColorPickerBlue.SelectedColor := FColor and $000000FF; ColorPickerAlpha.SelectedColor := FColor and $FF000000; ColorPickerGTK.SelectedColor := FColor; ColorSwatch.Color := FColor; finally // re-enable OnChange handler Dec(FLockChanged); end; end; end.
27.176707
80
0.731196
4732fa19dcc0e34bd4ae51015ccd2f576f840b64
614
dfm
Pascal
demos/DBDemo/ServerModule.dfm
fuadhs88/Delphi-GCharts
3ab84c0ac5c13386e9903f44dd7ef536b6e18733
[ "Apache-2.0" ]
40
2021-09-20T08:44:57.000Z
2022-02-20T17:43:50.000Z
demos/DBDemo/ServerModule.dfm
MorphineLLF/Delphi-GCharts
3ab84c0ac5c13386e9903f44dd7ef536b6e18733
[ "Apache-2.0" ]
1
2021-11-15T03:11:12.000Z
2021-12-18T01:58:46.000Z
demos/DBDemo/ServerModule.dfm
MorphineLLF/Delphi-GCharts
3ab84c0ac5c13386e9903f44dd7ef536b6e18733
[ "Apache-2.0" ]
7
2021-09-22T00:12:44.000Z
2022-02-28T12:43:29.000Z
object UniServerModule: TUniServerModule OldCreateOrder = False TempFolder = 'temp\' Title = 'New Application' SuppressErrors = [] Bindings = <> SSL.SSLOptions.RootCertFile = 'root.pem' SSL.SSLOptions.CertFile = 'cert.pem' SSL.SSLOptions.KeyFile = 'key.pem' SSL.SSLOptions.Method = sslvTLSv1_1 SSL.SSLOptions.SSLVersions = [sslvTLSv1_1] SSL.SSLOptions.Mode = sslmUnassigned SSL.SSLOptions.VerifyMode = [] SSL.SSLOptions.VerifyDepth = 0 ConnectionFailureRecovery.ErrorMessage = 'Connection Error' ConnectionFailureRecovery.RetryMessage = 'Retrying...' Height = 150 Width = 215 end
30.7
61
0.745928
f1e19cacf0adf2939da51b8440a4accb7eee55f2
2,371
pas
Pascal
CryptoLib/src/Math/EC/Endo/ClpGlvTypeAParameters.pas
MarkG55/CryptoLib4Pascal
740f1e7ac86ac9cf009a8010d4384368e7abe6fb
[ "MIT" ]
148
2018-02-08T23:36:43.000Z
2022-03-16T01:33:20.000Z
CryptoLib/src/Math/EC/Endo/ClpGlvTypeAParameters.pas
tondrej/CryptoLib4Pascal
33a540094aa24d22d84d502319e4d01f7c3e8163
[ "MIT" ]
28
2018-08-09T04:14:18.000Z
2022-03-31T05:23:51.000Z
CryptoLib/src/Math/EC/Endo/ClpGlvTypeAParameters.pas
tondrej/CryptoLib4Pascal
33a540094aa24d22d84d502319e4d01f7c3e8163
[ "MIT" ]
46
2018-03-18T17:25:59.000Z
2022-02-07T16:52:15.000Z
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpGlvTypeAParameters; {$I ..\..\..\Include\CryptoLib.inc} interface uses ClpBigInteger, ClpIGlvTypeAParameters, ClpIScalarSplitParameters, ClpCryptoLibTypes; type TGlvTypeAParameters = class sealed(TInterfacedObject, IGlvTypeAParameters) strict private var FI, Flambda: TBigInteger; FsplitParams: IScalarSplitParameters; function GetLambda: TBigInteger; inline; function GetI: TBigInteger; inline; function GetSplitParams: IScalarSplitParameters; inline; public constructor Create(const I, lambda: TBigInteger; const splitParams: IScalarSplitParameters); property lambda: TBigInteger read GetLambda; property I: TBigInteger read GetI; property splitParams: IScalarSplitParameters read GetSplitParams; end; implementation { TGlvTypeAParameters } constructor TGlvTypeAParameters.Create(const I, lambda: TBigInteger; const splitParams: IScalarSplitParameters); begin Inherited Create(); FI := I; Flambda := lambda; FsplitParams := splitParams; end; function TGlvTypeAParameters.GetI: TBigInteger; begin Result := FI; end; function TGlvTypeAParameters.GetLambda: TBigInteger; begin Result := Flambda; end; function TGlvTypeAParameters.GetSplitParams: IScalarSplitParameters; begin Result := FsplitParams; end; end.
28.914634
87
0.550822
f1a5b5b0689e70de890fbfd97d0a098f76b7d2e0
2,202
pas
Pascal
turtle/lottrp05.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
turtle/lottrp05.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
turtle/lottrp05.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
(* ┌───────────────────────────────────────────────────────────┐ │ Programated by Vladimir Zahoransky │ │ Vladko software │ │ Contact : zahoran@cezap.ii.fmph.uniba.sk │ │ Program tema : Move turtles! │ └───────────────────────────────────────────────────────────┘ *) { This program is easy to undestand. Just move all turtles, but for all use one command. The lenght of move is a coeficient. This program show how to do with dynamical turtles. Just in two cycles init (with pridajkor) all turtles. Define scale for turtles and make relation for coeficients. Then in two cycles move turtles. } Uses DynKor,DynVelaKor; Const d=40; u=pi/4; Type PMyTur=^MyTur; MyTur=Object(kor) k:real; Constructor init(x,y,u:real); Procedure koef(kk:real); Procedure dopredu(d:real);virtual; End; Constructor MyTur.init(x,y,u:real); Begin Inherited init(x,y,u); k:=1; End; Procedure MyTur.koef(kk:real); Begin k:=kk; End; Procedure MyTur.dopredu(d:real); Begin Inherited dopredu(d*k); End; Var v:velakor; i,j,px,py:integer; y,x,dx:real; begin y:=d/sin(u); py:=trunc(480/y); x:=d/cos(u); px:=trunc(640/x); with v do Begin Init; For i:=1 to py do Begin Pridajkor(new(PMyTur,init(0-320,i*d/sin(u)-240, u/pi*180))); PMyTur(k[pk])^.koef((480-i*d/sin(u))/cos(u)); End; For i:=py+1 to py+px do pridajkor(new(PMyTur,init((i-py-1)*d/ cos(u)-320,0-240,u/pi*180))); j:=px; dx:=480*sin(u)/cos(u); While (dx+j*x>640) do dec(j); For i:=py+1 to py+j do PMyTur(k[i])^.koef(480/cos(u)); For i:=py+j+1 to py+px do PMyTur(k[i])^.koef((640-(i-py)*d/cos(u))/cos(u)); Ukaz; Pd; CakajKlaves; Dopredu(1); CakajKlaves; Koniec; End; End. 
28.230769
78
0.464578
8356fa9ccc560cc34ec1a193774ffb762f5c922e
7,049
pas
Pascal
Engine/Libs/FastMM/FastMM4Messages.pas
RadiianArts/TERRA-Engine
965184178dda836197c436ef47e048e1db5382af
[ "Apache-2.0" ]
104
2015-01-18T02:02:11.000Z
2022-02-22T11:53:06.000Z
Engine/Libs/FastMM/FastMM4Messages.pas
maciej-izak-tests/TERRA-Engine
7ef17e6b67968a40212fbb678135af0000246097
[ "Apache-2.0" ]
13
2015-07-18T18:53:15.000Z
2021-10-04T10:31:01.000Z
Engine/Libs/FastMM/FastMM4Messages.pas
maciej-izak-tests/TERRA-Engine
7ef17e6b67968a40212fbb678135af0000246097
[ "Apache-2.0" ]
47
2015-01-17T21:50:12.000Z
2022-02-15T13:49:02.000Z
{ Fast Memory Manager: Messages English translation by Pierre le Riche. } unit FastMM4Messages; interface {$Include FastMM4Options.inc} const {The name of the debug info support DLL} FullDebugModeLibraryName = 'FastMM_FullDebugMode.dll'; {Event log strings} LogFileExtension = '_MemoryManager_EventLog.txt'#0; CRLF = #13#10; EventSeparator = '--------------------------------'; {Class name messages} UnknownClassNameMsg = 'Unknown'; {Memory dump message} MemoryDumpMsg = #13#10#13#10'Current memory dump of 256 bytes starting at pointer address '; {Block Error Messages} BlockScanLogHeader = 'Allocated block logged by LogAllocatedBlocksToFile. The size is: '; ErrorMsgHeader = 'FastMM has detected an error during a '; GetMemMsg = 'GetMem'; FreeMemMsg = 'FreeMem'; ReallocMemMsg = 'ReallocMem'; BlockCheckMsg = 'free block scan'; OperationMsg = ' operation. '; BlockHeaderCorruptedMsg = 'The block header has been corrupted. '; BlockFooterCorruptedMsg = 'The block footer has been corrupted. '; FreeModifiedErrorMsg = 'FastMM detected that a block has been modified after being freed. '; FreeModifiedDetailMsg = #13#10#13#10'Modified byte offsets (and lengths): '; DoubleFreeErrorMsg = 'An attempt has been made to free/reallocate an unallocated block.'; WrongMMFreeErrorMsg = 'An attempt has been made to free/reallocate a block that was allocated through a different FastMM instance. Check your memory manager sharing settings.'; PreviousBlockSizeMsg = #13#10#13#10'The previous block size was: '; CurrentBlockSizeMsg = #13#10#13#10'The block size is: '; PreviousObjectClassMsg = #13#10#13#10'The block was previously used for an object of class: '; CurrentObjectClassMsg = #13#10#13#10'The block is currently used for an object of class: '; PreviousAllocationGroupMsg = #13#10#13#10'The allocation group was: '; PreviousAllocationNumberMsg = #13#10#13#10'The allocation number was: '; CurrentAllocationGroupMsg = #13#10#13#10'The allocation group is: '; CurrentAllocationNumberMsg = #13#10#13#10'The allocation number is: '; BlockErrorMsgTitle = 'Memory Error Detected'; VirtualMethodErrorHeader = 'FastMM has detected an attempt to call a virtual method on a freed object. An access violation will now be raised in order to abort the current operation.'; InterfaceErrorHeader = 'FastMM has detected an attempt to use an interface of a freed object. An access violation will now be raised in order to abort the current operation.'; BlockHeaderCorruptedNoHistoryMsg = ' Unfortunately the block header has been corrupted so no history is available.'; FreedObjectClassMsg = #13#10#13#10'Freed object class: '; VirtualMethodName = #13#10#13#10'Virtual method: '; VirtualMethodOffset = 'Offset +'; VirtualMethodAddress = #13#10#13#10'Virtual method address: '; {Stack trace messages} CurrentThreadIDMsg = #13#10#13#10'The current thread ID is 0x'; CurrentStackTraceMsg = ', and the stack trace (return addresses) leading to this error is:'; ThreadIDPrevAllocMsg = #13#10#13#10'This block was previously allocated by thread 0x'; ThreadIDAtAllocMsg = #13#10#13#10'This block was allocated by thread 0x'; ThreadIDAtFreeMsg = #13#10#13#10'The block was previously freed by thread 0x'; ThreadIDAtObjectAllocMsg = #13#10#13#10'The object was allocated by thread 0x'; ThreadIDAtObjectFreeMsg = #13#10#13#10'The object was subsequently freed by thread 0x'; StackTraceMsg = ', and the stack trace (return addresses) at the time was:'; {Installation Messages} AlreadyInstalledMsg = 'FastMM4 is already installed.'; AlreadyInstalledTitle = 'Already installed.'; OtherMMInstalledMsg = 'FastMM4 cannot be installed since another third party memory ' + 'manager has already installed itself.'#13#10'If you want to use FastMM4, ' + 'please make sure that FastMM4.pas is the very first unit in the "uses"' + #13#10'section of your project''s .dpr file.'; OtherMMInstalledTitle = 'Cannot install FastMM4 - Another memory manager is already installed'; MemoryAllocatedMsg = 'FastMM4 cannot install since memory has already been ' + 'allocated through the default memory manager.'#13#10'FastMM4.pas MUST ' + 'be the first unit in your project''s .dpr file, otherwise memory may ' + 'be allocated'#13#10'through the default memory manager before FastMM4 ' + 'gains control. '#13#10#13#10'If you are using an exception trapper ' + 'like MadExcept (or any tool that modifies the unit initialization ' + 'order),'#13#10'go into its configuration page and ensure that the ' + 'FastMM4.pas unit is initialized before any other unit.'; MemoryAllocatedTitle = 'Cannot install FastMM4 - Memory has already been allocated'; {Leak checking messages} LeakLogHeader = 'A memory block has been leaked. The size is: '; LeakMessageHeader = 'This application has leaked memory. '; SmallLeakDetail = 'The small block leaks are' {$ifdef HideExpectedLeaksRegisteredByPointer} + ' (excluding expected leaks registered by pointer)' {$endif} + ':'#13#10; LargeLeakDetail = 'The sizes of leaked medium and large blocks are' {$ifdef HideExpectedLeaksRegisteredByPointer} + ' (excluding expected leaks registered by pointer)' {$endif} + ': '; BytesMessage = ' bytes: '; AnsiStringBlockMessage = 'AnsiString'; UnicodeStringBlockMessage = 'UnicodeString'; LeakMessageFooter = #13#10 {$ifndef HideMemoryLeakHintMessage} + #13#10'Note: ' {$ifdef RequireIDEPresenceForLeakReporting} + 'This memory leak check is only performed if Delphi is currently running on the same computer. ' {$endif} {$ifdef FullDebugMode} {$ifdef LogMemoryLeakDetailToFile} + 'Memory leak detail is logged to a text file in the same folder as this application. ' {$else} + 'Enable the "LogMemoryLeakDetailToFile" to obtain a log file containing detail on memory leaks. ' {$endif} {$else} + 'To obtain a log file containing detail on memory leaks, enable the "FullDebugMode" and "LogMemoryLeakDetailToFile" conditional defines. ' {$endif} + 'To disable this memory leak check, undefine "EnableMemoryLeakReporting".'#13#10 {$endif} + #0; LeakMessageTitle = 'Memory Leak Detected'; {$ifdef UseOutputDebugString} FastMMInstallMsg = 'FastMM has been installed.'; FastMMInstallSharedMsg = 'Sharing an existing instance of FastMM.'; FastMMUninstallMsg = 'FastMM has been uninstalled.'; FastMMUninstallSharedMsg = 'Stopped sharing an existing instance of FastMM.'; {$endif} {$ifdef DetectMMOperationsAfterUninstall} InvalidOperationTitle = 'MM Operation after uninstall.'; InvalidGetMemMsg = 'FastMM has detected a GetMem call after FastMM was uninstalled.'; InvalidFreeMemMsg = 'FastMM has detected a FreeMem call after FastMM was uninstalled.'; InvalidReallocMemMsg = 'FastMM has detected a ReallocMem call after FastMM was uninstalled.'; InvalidAllocMemMsg = 'FastMM has detected an AllocMem call after FastMM was uninstalled.'; {$endif} implementation end.
49.992908
186
0.744219
f1c49706cfa7e7629957342a5f945d278511dfc7
1,873
pas
Pascal
src/modules/imc3/imc3_util.pas
mrook/grendel
428e2518868bcd459201e92e5338bae90b95fb59
[ "BSD-3-Clause" ]
null
null
null
src/modules/imc3/imc3_util.pas
mrook/grendel
428e2518868bcd459201e92e5338bae90b95fb59
[ "BSD-3-Clause" ]
null
null
null
src/modules/imc3/imc3_util.pas
mrook/grendel
428e2518868bcd459201e92e5338bae90b95fb59
[ "BSD-3-Clause" ]
null
null
null
{ Delphi IMC3 Client - Various utility functions Based on client code by Samson of Alsherok. $Id: imc3_util.pas,v 1.1 2003/12/12 13:19:56 ***REMOVED*** Exp $ } unit imc3_util; interface uses imc3_const, chars, player; procedure sendToPlayer(pl : GPlayer; buf : string); function fishToAnsi(buf : string) : string; function I3PERM(ch : GCharacter) : I3_PERMISSIONS; implementation uses SysUtils, StrUtils, constants; procedure sendToPlayer(pl : GPlayer; buf : string); var t : string; begin t := fishToAnsi(buf); { Reset color to stop bleeding } pl.sendBuffer(t + #27'[0m'); end; function fishToAnsi(buf : string) : string; var x, inbuf, cp, cp2, len : integer; t, col : string; begin inbuf := 1; Result := ''; col := ''; { catch the trivial case first (for speed) } cp := Pos('%^', buf); if (cp = 0) then begin Result := buf; exit; end; while (cp > 0) do begin cp2 := PosEx('%^', buf, cp + 2); if (cp2 = 0) then { unmatched single %^ } break; len := cp2 - cp + 2; if (len = 4) then begin col := '%^'; end else begin t := Copy(buf, cp, len); for x := 1 to I3MAX_ANSI do if (t = I3_ANSI_CONVERSION[x][2]) then begin col := I3_ANSI_CONVERSION[x][3]; break; end; end; t := Copy(buf, inbuf, cp - inbuf); Result := Result + t; Result := Result + col; inbuf := cp2 + 2; cp := PosEx('%^', buf, inbuf); end; Result := Result + Copy(buf, cp2 + 2, length(buf)); end; function I3PERM(ch : GCharacter) : I3_PERMISSIONS; begin Result := I3PERM_NOTSET; if (ch.level < LEVEL_START) then Result := I3PERM_NONE else if (ch.level <= LEVEL_MAX) then Result := I3PERM_MORT else if (ch.level <= LEVEL_BUILD) then Result := I3PERM_ADMIN else if (ch.level <= LEVEL_MAX_IMMORTAL) then Result := I3PERM_IMP; end; end.
16.008547
65
0.610251
85e6dca62c238de0881e7ed04f13960b61d8740f
28,572
pas
Pascal
Source/PXL.Classes.pas
LongDirtyAnimAlf/AsphyrePXL
9151ff88eca1fa01dce083b09e7ea20076f6d334
[ "Apache-2.0" ]
4
2020-04-24T07:43:43.000Z
2021-08-29T08:36:08.000Z
Source/PXL.Classes.pas
LongDirtyAnimAlf/AsphyrePXL
9151ff88eca1fa01dce083b09e7ea20076f6d334
[ "Apache-2.0" ]
null
null
null
Source/PXL.Classes.pas
LongDirtyAnimAlf/AsphyrePXL
9151ff88eca1fa01dce083b09e7ea20076f6d334
[ "Apache-2.0" ]
2
2020-08-18T09:42:33.000Z
2021-04-22T08:15:27.000Z
unit PXL.Classes; (* * This file is part of Asphyre Framework, also known as Platform eXtended Library (PXL). * Copyright (c) 2015 - 2017 Yuriy Kotsarenko. All rights reserved. * * 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. *) {< Extensions and utility classes that extend functionality of streams and provide ways for reading assets. } interface {$INCLUDE PXL.Config.inc} {$IFNDEF PASDOC} {$IF DEFINED(FPC) AND DEFINED(ANDROID)} {$DEFINE ANDROID_ASSETS} {$ENDIF} {$ENDIF} uses {$IFDEF ANDROID_ASSETS} Android.AssetManager, {$ENDIF} Classes, PXL.TypeDef, PXL.Types; type {$IFDEF ANDROID_ASSETS} EAssetManagerNotSpecified = class(EStreamError); {$ENDIF} { Extensions to TStream class for reading and writing different values depending on platform. Although TStream in recent versions of FPC and Delphi introduced similar functions, this extension class provides a more comprehensive and unified set of functions that work across all platforms. } TStreamHelper = class helper for TStream public type { Value stored as unsigned 8-bit integer, but represented as unsigned 32-bit or 64-bit value depending on platform. } TStreamByte = SizeUInt; { Value stored as unsigned 16-bit integer, but represented as unsigned 32-bit or 64-bit value depending on platform. } TStreamWord = SizeUInt; { Value stored as unsigned 32-bit integer, but represented as unsigned 32-bit or 64-bit value depending on platform. } TStreamLongWord = {$IF SIZEOF(SizeUInt) >= 4} SizeUInt {$ELSE} LongWord {$ENDIF}; { Value stored and represented as unsigned 64-bit integer. } TStreamUInt64 = UInt64; { Value stored as 8-bit signed integer, but represented as signed 32-bit or 64-bit value depending on platform. } TStreamShortInt = SizeInt; { Value stored as 16-bit signed integer, but represented as signed 32-bit or 64-bit value depending on platform. } TStreamSmallInt = SizeInt; { Value stored as 32-bit signed integer, but represented as signed 32-bit or 64-bit value depending on platform. } TStreamLongInt = {$IF SIZEOF(SizeInt) >= 4} SizeInt {$ELSE} LongInt {$ENDIF}; { Value stored and represented as signed 64-bit integer. } TStreamInt64 = Int64; { Value stored and represented as 32-bit (single-precision) floating-point. } TStreamSingle = Single; { Value stored and represented as 64-bit (double-precision) floating-point. } TStreamDouble = Double; { Value stored as 8-bit unsigned integer, but represented as Boolean. } TStreamByteBool = Boolean; { Value stored as unsigned 8-bit integer, but represented as signed 32-bit or 64-bit index depending on platform. } TStreamByteIndex = SizeInt; { Value stored as unsigned 16-bit integer, but represented as signed 32-bit or 64-bit index depending on platform. } TStreamWordIndex = {$IF SIZEOF(SizeInt) >= 4} SizeInt {$ELSE} LongInt {$ENDIF}; public { Saves 8-bit unsigned integer to the stream. If the value is outside of [0..255] range, it will be clamped. } procedure PutByte(const Value: TStreamByte); inline; { Loads 8-bit unsigned integer from the stream. } function GetByte: TStreamByte; inline; { Saves 16-bit unsigned integer to the stream. If the value is outside of [0..65535] range, it will be clamped. } procedure PutWord(const Value: TStreamWord); inline; { Loads 16-bit unsigned integer value from the stream. } function GetWord: TStreamWord; inline; { Saves 32-bit unsigned integer to the stream. } procedure PutLongWord(const Value: TStreamLongWord); inline; { Loads 32-bit unsigned integer from the stream. } function GetLongWord: TStreamLongWord; inline; { Saves 64-bit unsigned integer to the stream. } procedure PutUInt64(const Value: TStreamUInt64); inline; { Loads 64-bit unsigned integer from the stream. } function GetUInt64: TStreamUInt64; inline; { Saves 8-bit signed integer to the stream. If the value is outside of [-128..127] range, it will be clamped. } procedure PutShortInt(const Value: TStreamShortInt); inline; { Loads 8-bit signed integer from the stream. } function GetShortInt: TStreamShortInt; inline; { Saves 16-bit signed integer to the stream. If the value is outside of [-32768..32767] range, it will be clamped. } procedure PutSmallInt(const Value: TStreamSmallInt); inline; { Loads 16-bit signed integer from the stream. } function GetSmallInt: TStreamSmallInt; inline; { Saves 32-bit signed integer to the stream. } procedure PutLongInt(const Value: TStreamLongInt); inline; { Loads 32-bit signed integer from the stream. } function GetLongInt: TStreamLongInt; inline; { Saves 64-bit signed integer to the stream. } procedure PutInt64(const Value: TStreamInt64); inline; { Loads 64-bit signed integer from the stream. } function GetInt64: TStreamInt64; inline; { Saves 32-bit floating-point value (single-precision) to the stream. } procedure PutSingle(const Value: TStreamSingle); inline; { Loads 32-bit floating-point value (single-precision) from the stream. } function GetSingle: TStreamSingle; inline; { Saves 64-bit floating-point value (double-precision) to the stream. } procedure PutDouble(const Value: TStreamDouble); inline; { Loads 64-bit floating-point value (double-precision) from the stream. } function GetDouble: TStreamDouble; inline; { Saves @bold(Boolean) value to the stream as 8-bit unsigned integer. A value of @False is saved as 255, while @True is saved as 0. } procedure PutByteBool(const Value: TStreamByteBool); inline; { Loads @bold(Boolean) value from the stream previously saved by @link(PutByteBool). The resulting value is treated as 8-bit unsigned integer with values of [0..127] considered as @True and values of [128..255] considered as @False. } function GetByteBool: TStreamByteBool; inline; { Saves 8-bit unsigned index to the stream. A value of -1 (and other negative values) is stored as 255. Positive numbers that are outside of [0..254] range will be clamped. } procedure PutByteIndex(const Value: TStreamByteIndex); inline; { Loads 8-bit unsigned index from the stream. The range of returned values is [0..254], the value of 255 is returned as -1. } function GetByteIndex: TStreamByteIndex; inline; { Saves 16-bit unsigned index to the stream. A value of -1 (and other negative values) is stored as 65535. Positive numbers that are outside of [0..65534] range will be clamped. } procedure PutWordIndex(const Value: TStreamWordIndex); inline; { Loads 16-bit unsigned index from the stream. The range of returned values is [0..65534], the value of 65535 is returned as -1. } function GetWordIndex: TStreamWordIndex; inline; { Saves 2D integer point to the stream. Each coordinate is saved as 8-bit unsigned integer. } procedure PutBytePoint2px(const Value: TPoint2i); { Loads 2D integer point from the stream. Each coordinate is loaded as 8-bit unsigned integer. } function GetBytePoint2px: TPoint2i; { Saves 2D integer point to the stream. Each coordinate is saved as 16-bit unsigned integer. } procedure PutWordPoint2px(const Value: TPoint2i); { Loads 2D integer point from the stream. Each coordinate is loaded as 16-bit unsigned integer.} function GetWordPoint2px: TPoint2i; { Saves 2D integer point to the stream. Each coordinate is saved as 32-bit signed integer. } procedure PutLongPoint2px(const Value: TPoint2i); { Loads 2D integer point from the stream. Each coordinate is loaded as 32-bit signed integer. } function GetLongPoint2px: TPoint2i; { Saves floating-point value as 8-bit signed byte to the stream using 1:3:4 fixed-point format with values outside of [-8..7.9375] range will be clamped. } procedure PutFloat34(const Value: Single); { Loads floating-point value as 8-bit signed byte from the stream using 1:3:4 fixed-point format. The possible values are in [-8..7.9375] range. } function GetFloat34: Single; { Saves floating-point value as 8-bit signed byte to the stream using 1:4:3 fixed-point format with values outside of [-16..15.875] range will be clamped. } procedure PutFloat43(const Value: Single); { Loads floating-point value as 8-bit signed byte from the stream using 1:4:3 fixed-point format. The possible values are in [-16..15.875] range. } function GetFloat43: Single; { Saves two floating-point values as a single 8-bit unsigned byte to the stream with each value having 4-bits. Values outside of [-8..7] range will be clamped. } procedure PutFloats44(const Value1, Value2: Single); { Loads two floating-point values as a single 8-bit unsigned byte from the stream with each value having 4-bits. The possible values are in [-8..7] range. } procedure GetFloats44(out Value1, Value2: Single); { Saves two floating-point values as a single 8-bit unsigned byte to the stream with each value stored in fixed-point 1:2:1 format. Values outside of [-4..3.5] range will be clamped. } procedure PutFloats3311(const Value1, Value2: Single); { Loads two floating-point values as a single 8-bit unsigned byte from the stream with each value stored in fixed-point 1:2:1 format. The possible values are in [-4..3.5] range. } procedure GetFloats3311(out Value1, Value2: Single); { Saves Unicode string to the stream in UTF-8 encoding. The resulting UTF-8 string is limited to a maximum of 255 characters; therefore, for certain charsets the actual string is limited to either 127 or even 85 characters in worst case. If MaxCount is not zero, the input string will be limited to the given number of characters. } procedure PutShortString(const Text: UniString; const MaxCount: Integer = 0); { Loads Unicode string from the stream in UTF-8 encoding previously saved by @link(PutShortString). } function GetShortString: UniString; { Saves Unicode string to the stream in UTF-8 encoding. The resulting UTF-8 string is limited to a maximum of 65535 characters; therefore, for certain charsets the actual string is limited to either 32767 or even 21845 characters in worst case. If MaxCount is not zero, the input string will be limited to the given number of characters. } procedure PutMediumString(const Text: UniString; const MaxCount: Integer = 0); { Loads Unicode string from the stream in UTF-8 encoding previously saved by @link(PutMediumString). } function GetMediumString: UniString; { Stores Unicode string to the stream in UTF-8 encoding. } procedure PutLongString(const Text: UniString); { Loads Unicode string from the stream in UTF-8 encoding previously saved by @link(PutLongString). } function GetLongString: UniString; end; { Special stream type that is used to read assets on Android platform. This stream serves no purpose on other platforms. } TAssetStream = class(TStream) private FFileName: StdString; {$IFDEF ANDROID_ASSETS} FAsset: PAAsset; FFileSize: Int64; {$ENDIF} protected { @exclude } function GetSize: Int64; override; public { Creates instance of asset stream to read from the specified file, which must be located in /assets sub-folder of current Android package. } constructor Create(const AFileName: StdString); { @exclude } destructor Destroy; override; { @exclude } function Read(var Buffer; Count: LongInt): LongInt; override; { @exclude } function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; { Asset file name, which must be located in /assets sub-folder. } property FileName: StdString read FFilename; {$IFDEF ANDROID_ASSETS} public property Asset: PAAsset read FAsset; private class var FAssetManager: PAAssetManager; public class property AssetManager: PAAssetManager read FAssetManager write FAssetManager; {$ENDIF} end; { A quick method for replacing "\" with "/" and vice-versa depending on platform. This calls makes sure that the provided path uses correct path delimiter. } function CrossFixFileName(const FileName: StdString): StdString; implementation uses {$IFDEF DELPHI_NEXTGEN} SysUtils, {$ENDIF} RTLConsts, PXL.Consts; {$REGION 'Globals'} {$IFDEF DELPHI_NEXTGEN} const DefaultCodePage = 65001; // UTF-8 function StringToBytes(const Text: string): TBytes; var ByteCount: Integer; begin if Text.IsEmpty then Exit(nil); ByteCount := LocaleCharsFromUnicode(DefaultCodePage, 0, Pointer(Text), Length(Text), nil, 0, nil, nil); SetLength(Result, ByteCount); LocaleCharsFromUnicode(DefaultCodePage, 0, Pointer(Text), Length(Text), Pointer(Result), ByteCount, nil, nil); end; function BytesToString(const Bytes: TBytes): string; var TextLength: Integer; begin if Length(Bytes) < 1 then Exit(string.Empty); TextLength := UnicodeFromLocaleChars(DefaultCodePage, 0, Pointer(Bytes), Length(Bytes), nil, 0); if TextLength < 1 then Exit(string.Empty); SetLength(Result, TextLength); UnicodeFromLocaleChars(DefaultCodePage, 0, Pointer(Bytes), Length(Bytes), Pointer(Result), TextLength); end; {$ENDIF} function CrossFixFileName(const FileName: StdString): StdString; const {$IFDEF MSWINDOWS} PrevChar = '/'; NewChar = '\'; {$ELSE} PrevChar = '\'; NewChar = '/'; {$ENDIF} var I: Integer; begin Result := FileName; UniqueString(Result); for I := 1 to Length(Result) do if Result[I] = PrevChar then Result[I] := NewChar; end; {$ENDREGION} {$REGION 'TStreamHelper'} procedure TStreamHelper.PutByte(const Value: TStreamByte); var ByteValue: Byte; begin if Value <= High(Byte) then ByteValue := Value else ByteValue := High(Byte); WriteBuffer(ByteValue, SizeOf(Byte)); end; function TStreamHelper.GetByte: TStreamByte; var ByteValue: Byte; begin ReadBuffer(ByteValue, SizeOf(Byte)); Result := ByteValue; end; procedure TStreamHelper.PutWord(const Value: TStreamWord); {$IF SIZEOF(TStream.TStreamWord) > 2} var WordValue: Word; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamWord) > 2} if Value <= High(Word) then WordValue := Value else WordValue := High(Word); WriteBuffer(WordValue, SizeOf(Word)); {$ELSE} WriteBuffer(Value, SizeOf(Word)); {$ENDIF} end; function TStreamHelper.GetWord: TStreamWord; {$IF SIZEOF(TStream.TStreamWord) > 2} var WordValue: Word; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamWord) > 2} ReadBuffer(WordValue, SizeOf(Word)); Result := WordValue; {$ELSE} ReadBuffer(Result, SizeOf(Word)); {$ENDIF} end; procedure TStreamHelper.PutLongWord(const Value: TStreamLongWord); {$IF SIZEOF(TStream.TStreamLongWord) > 4} var LongWordValue: LongWord; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamLongWord) > 4} if Value <= High(LongWord) then LongWordValue := Value else LongWordValue := High(LongWord); WriteBuffer(LongWordValue, SizeOf(LongWord)); {$ELSE} WriteBuffer(Value, SizeOf(LongWord)); {$ENDIF} end; function TStreamHelper.GetLongWord: TStreamLongWord; {$IF SIZEOF(TStream.TStreamLongWord) > 4} var LongWordValue: LongWord; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamLongWord) > 4} ReadBuffer(LongWordValue, SizeOf(LongWord)); Result := LongWordValue; {$ELSE} ReadBuffer(Result, SizeOf(LongWord)); {$ENDIF} end; procedure TStreamHelper.PutUInt64(const Value: TStreamUInt64); begin WriteBuffer(Value, SizeOf(UInt64)); end; function TStreamHelper.GetUInt64: TStreamUInt64; begin ReadBuffer(Result, SizeOf(UInt64)); end; procedure TStreamHelper.PutShortInt(const Value: TStreamShortInt); var ShortValue: ShortInt; begin if Value < Low(ShortInt) then ShortValue := Low(ShortInt) else if Value > High(ShortInt) then ShortValue := High(ShortInt) else ShortValue := Value; WriteBuffer(ShortValue, SizeOf(ShortInt)); end; function TStreamHelper.GetShortInt: TStreamShortInt; var ShortValue: ShortInt; begin ReadBuffer(ShortValue, SizeOf(ShortInt)); Result := ShortValue; end; procedure TStreamHelper.PutSmallInt(const Value: TStreamSmallInt); {$IF SIZEOF(TStream.TStreamSmallInt) > 2} var SmallValue: SmallInt; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamSmallInt) > 2} if Value < Low(SmallInt) then SmallValue := Low(SmallInt) else if Value > High(SmallInt) then SmallValue := High(SmallInt) else SmallValue := Value; WriteBuffer(SmallValue, SizeOf(SmallInt)); {$ELSE} WriteBuffer(Value, SizeOf(SmallInt)); {$ENDIF} end; function TStreamHelper.GetSmallInt: TStreamSmallInt; {$IF SIZEOF(TStream.TStreamSmallInt) > 2} var SmallValue: SmallInt; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamSmallInt) > 2} ReadBuffer(SmallValue, SizeOf(SmallInt)); Result := SmallValue; {$ELSE} ReadBuffer(Result, SizeOf(SmallInt)); {$ENDIF} end; procedure TStreamHelper.PutLongInt(const Value: TStreamLongInt); {$IF SIZEOF(TStream.TStreamLongInt) > 4} var LongValue: LongInt; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamLongInt) > 4} if Value < Low(LongInt) then LongValue := Low(LongInt) else if Value > High(LongInt) then LongValue := High(LongInt) else LongValue := Value; WriteBuffer(LongValue, SizeOf(LongInt)); {$ELSE} WriteBuffer(Value, SizeOf(LongInt)); {$ENDIF} end; function TStreamHelper.GetLongInt: TStreamLongInt; {$IF SIZEOF(TStream.TStreamLongInt) > 4} var LongValue: LongInt; {$ENDIF} begin {$IF SIZEOF(TStream.TStreamLongInt) > 4} ReadBuffer(LongValue, SizeOf(LongInt)); Result := LongValue; {$ELSE} ReadBuffer(Result, SizeOf(LongInt)); {$ENDIF} end; procedure TStreamHelper.PutInt64(const Value: TStreamInt64); begin WriteBuffer(Value, SizeOf(Int64)); end; function TStreamHelper.GetInt64: TStreamInt64; begin ReadBuffer(Result, SizeOf(Int64)); end; procedure TStreamHelper.PutSingle(const Value: TStreamSingle); begin WriteBuffer(Value, SizeOf(Single)); end; function TStreamHelper.GetSingle: TStreamSingle; begin ReadBuffer(Result, SizeOf(Single)); end; procedure TStreamHelper.PutDouble(const Value: TStreamDouble); begin WriteBuffer(Value, SizeOf(Double)); end; function TStreamHelper.GetDouble: TStreamDouble; begin ReadBuffer(Result, SizeOf(Double)); end; procedure TStreamHelper.PutByteBool(const Value: TStreamByteBool); var ByteValue: Byte; begin ByteValue := 255; if Value then ByteValue := 0; WriteBuffer(ByteValue, SizeOf(Byte)); end; function TStreamHelper.GetByteBool: TStreamByteBool; var ByteValue: Byte; begin ReadBuffer(ByteValue, SizeOf(Byte)); Result := ByteValue < 128; end; procedure TStreamHelper.PutByteIndex(const Value: TStreamByteIndex); var ByteValue: Byte; begin if Value < 0 then ByteValue := 255 else if Value > 254 then ByteValue := 254 else ByteValue := Value; WriteBuffer(ByteValue, SizeOf(Byte)); end; function TStreamHelper.GetByteIndex: TStreamByteIndex; var ByteValue: Byte; begin Result := -1; if (Read(ByteValue, SizeOf(Byte)) = SizeOf(Byte)) and (ByteValue <> 255) then Result := ByteValue; end; procedure TStreamHelper.PutWordIndex(const Value: TStreamWordIndex); var WordValue: Word; begin if Value < 0 then WordValue := 65535 else if Value > 65534 then WordValue := 65534 else WordValue := Value; Write(WordValue, SizeOf(Word)); end; function TStreamHelper.GetWordIndex: TStreamWordIndex; var WordValue: Word; begin Result := -1; if (Read(WordValue, SizeOf(Word)) = SizeOf(Word)) and (WordValue <> 65535) then Result := WordValue; end; procedure TStreamHelper.PutBytePoint2px(const Value: TPoint2i); var ByteValue: Byte; begin if Value.X <> Undefined2i.X then ByteValue := Saturate(Value.X, 0, 254) else ByteValue := 255; Write(ByteValue, SizeOf(Byte)); if Value.Y <> Undefined2i.Y then ByteValue := Saturate(Value.Y, 0, 254) else ByteValue := 255; Write(ByteValue, SizeOf(Byte)); end; function TStreamHelper.GetBytePoint2px: TPoint2i; var ByteValue1, ByteValue2: Byte; ValueInvalid: Boolean; begin ValueInvalid := False; if Read(ByteValue1, SizeOf(Byte)) <> SizeOf(Byte) then ValueInvalid := True; if Read(ByteValue2, SizeOf(Byte)) <> SizeOf(Byte) then ValueInvalid := True; if (ByteValue1 = 255) or (ByteValue2 = 255) or ValueInvalid then Exit(Undefined2i); Result.X := ByteValue1; Result.Y := ByteValue2; end; procedure TStreamHelper.PutWordPoint2px(const Value: TPoint2i); var InpValue: TStreamWordIndex; WordValue: Word; begin if Value.X <> Undefined2i.X then begin InpValue := Value.X; WordValue := Saturate(InpValue, 0, 65534) end else WordValue := 65535; Write(WordValue, SizeOf(Word)); if Value.Y <> Undefined2i.Y then begin InpValue := Value.Y; WordValue := Saturate(InpValue, 0, 65534) end else WordValue := 65535; Write(WordValue, SizeOf(Word)); end; function TStreamHelper.GetWordPoint2px: TPoint2i; var WordValue1, WordValue2: Word; ValueInvalid: Boolean; begin ValueInvalid := False; if Read(WordValue1, SizeOf(Word)) <> SizeOf(Word) then ValueInvalid := True; if Read(WordValue2, SizeOf(Word)) <> SizeOf(Word) then ValueInvalid := True; if (WordValue1 = 65535) or (WordValue2 = 65535) or ValueInvalid then Exit(Undefined2i); Result.X := WordValue1; Result.Y := WordValue2; end; procedure TStreamHelper.PutLongPoint2px(const Value: TPoint2i); begin PutLongInt(Value.X); PutLongInt(Value.Y); end; function TStreamHelper.GetLongPoint2px: TPoint2i; begin Result.X := GetLongInt; Result.Y := GetLongInt; end; procedure TStreamHelper.PutFloat34(const Value: Single); begin PutShortInt(Saturate(Round(Value * 16), -128, 127)); end; function TStreamHelper.GetFloat34: Single; begin Result := GetShortInt / 16; end; procedure TStreamHelper.PutFloat43(const Value: Single); begin PutShortInt(Saturate(Round(Value * 8), -128, 127)); end; function TStreamHelper.GetFloat43: Single; begin Result := GetShortInt / 8; end; procedure TStreamHelper.PutFloats44(const Value1, Value2: Single); var Temp1, Temp2: Integer; begin Temp1 := Saturate(Round(Value1), -8, 7) + 8; Temp2 := Saturate(Round(Value2), -8, 7) + 8; PutByte(Temp1 or (Temp2 shl 4)); end; procedure TStreamHelper.GetFloats44(out Value1, Value2: Single); var Temp: Integer; begin Temp := GetByte; Value1 := (Temp and $0F) - 8; Value2 := (Temp shr 4) - 8; end; procedure TStreamHelper.PutFloats3311(const Value1, Value2: Single); var Temp1, Temp2: Integer; begin Temp1 := Saturate(Round(Value1 * 2), -8, 7) + 8; Temp2 := Saturate(Round(Value2 * 2), -8, 7) + 8; PutByte(Temp1 or (Temp2 shl 4)); end; procedure TStreamHelper.GetFloats3311(out Value1, Value2: Single); var Temp: Integer; begin Temp := GetByte; Value1 := ((Temp and $0F) - 8) / 2; Value2 := ((Temp shr 4) - 8) / 2; end; {$IFDEF DELPHI_NEXTGEN} procedure TStreamHelper.PutShortString(const Text: UniString; const MaxCount: Integer); var Count: Integer; Bytes: TBytes; begin Bytes := StringToBytes(Text); Count := Length(Bytes); if Count > 255 then Count := 255; if (MaxCount > 0) and (MaxCount < Count) then Count := MaxCount; PutByte(Count); Write(Pointer(Bytes)^, Count); end; function TStreamHelper.GetShortString: UniString; var Count: Integer; Bytes: TBytes; begin Count := GetByte; SetLength(Bytes, Count); if Read(Pointer(Bytes)^, Count) = Count then Result := BytesToString(Bytes) else Result := string.Empty; end; procedure TStreamHelper.PutMediumString(const Text: UniString; const MaxCount: Integer); var Count: Integer; Bytes: TBytes; begin Bytes := StringToBytes(Text); Count := Length(Bytes); if Count > 65535 then Count := 65535; if (MaxCount > 0) and (MaxCount < Count) then Count := MaxCount; PutWord(Count); Write(Pointer(Bytes)^, Count); end; function TStreamHelper.GetMediumString: UniString; var Count: Integer; Bytes: TBytes; begin Count := GetWord; SetLength(Bytes, Count); if Read(Pointer(Bytes)^, Count) = Count then Result := BytesToString(Bytes) else Result := string.Empty; end; procedure TStreamHelper.PutLongString(const Text: UniString); var Count: Integer; Bytes: TBytes; begin Bytes := StringToBytes(Text); Count := Length(Bytes); PutLongInt(Count); Write(Pointer(Bytes)^, Count); end; function TStreamHelper.GetLongString: UniString; var Count: Integer; Bytes: TBytes; begin Count := GetLongInt; SetLength(Bytes, Count); if Read(Pointer(Bytes)^, Count) = Count then Result := BytesToString(Bytes) else Result := string.Empty; end; {$ELSE} procedure TStreamHelper.PutShortString(const Text: UniString; const MaxCount: Integer); var Count: Integer; ShortText: AnsiString; begin ShortText := UTF8Encode(Text); Count := Length(ShortText); if Count > 255 then Count := 255; if (MaxCount > 0) and (MaxCount < Count) then Count := MaxCount; PutByte(Count); Write(Pointer(ShortText)^, Count); end; function TStreamHelper.GetShortString: UniString; var Count: Integer; ShortText: AnsiString; begin Count := GetByte; SetLength(ShortText, Count); if Read(Pointer(ShortText)^, Count) <> Count then Exit(''); {$IFDEF FPC} Result := UTF8Decode(ShortText); {$ELSE} Result := UTF8ToWideString(ShortText); {$IFEND} end; procedure TStreamHelper.PutMediumString(const Text: UniString; const MaxCount: Integer); var Count: Integer; MediumText: AnsiString; begin MediumText := UTF8Encode(Text); Count := Length(MediumText); if Count > 65535 then Count := 65535; if (MaxCount > 0) and (MaxCount < Count) then Count := MaxCount; PutWord(Count); Write(Pointer(MediumText)^, Count); end; function TStreamHelper.GetMediumString: UniString; var Count: Integer; MediumText: AnsiString; begin Count := GetWord; SetLength(MediumText, Count); if Read(Pointer(MediumText)^, Count) <> Count then Exit(''); {$IFDEF FPC} Result := UTF8Decode(MediumText); {$ELSE} Result := UTF8ToWideString(MediumText); {$IFEND} end; procedure TStreamHelper.PutLongString(const Text: UniString); var Count: Integer; LongText: AnsiString; begin LongText := UTF8Encode(Text); Count := Length(LongText); PutLongInt(Count); Write(Pointer(LongText)^, Count); end; function TStreamHelper.GetLongString: UniString; var Count: Integer; LongText: AnsiString; begin Count := GetLongInt; SetLength(LongText, Count); if Read(Pointer(LongText)^, Count) <> Count then Exit(''); {$IFDEF FPC} Result := UTF8Decode(LongText); {$ELSE} Result := UTF8ToWideString(LongText); {$IFEND} end; {$ENDIF} {$ENDREGION} {$REGION 'TAssetStream'} constructor TAssetStream.Create(const AFileName: StdString); begin inherited Create; FFileName := AFileName; {$IFDEF ANDROID_ASSETS} if FAssetManager = nil then raise EAssetManagerNotSpecified.Create(SAssetManagerNotSpecified); FAsset := AAssetManager_open(FAssetManager, PAnsiChar(FFileName), AASSET_MODE_STREAMING); if FAsset = nil then raise EFOpenError.CreateResFmt(@SFOpenError, [FFileName]); FFileSize := AAsset_getLength64(FAsset); {$ELSE} inherited Create; {$ENDIF} end; destructor TAssetStream.Destroy; begin {$IFDEF ANDROID_ASSETS} if FAsset <> nil then begin AAsset_close(FAsset); FAsset := nil; end; FFileSize := 0; {$ENDIF} inherited; end; function TAssetStream.GetSize: Int64; begin {$IFDEF ANDROID_ASSETS} Result := FFileSize; {$ELSE} Result := inherited; {$ENDIF} end; function TAssetStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin {$IFDEF ANDROID_ASSETS} Result := AAsset_seek64(FAsset, Offset, Ord(Origin)); {$ELSE} Result := inherited; {$ENDIF} end; function TAssetStream.Read(var Buffer; Count: LongInt): LongInt; begin {$IFDEF ANDROID_ASSETS} Result := AAsset_read(FAsset, @Buffer, Count); {$ELSE} Result := inherited; {$ENDIF} end; {$ENDREGION} end.
27.03122
122
0.721336
f1780961ae15da39b94fbae3bf5ad9a9e4ccdfdf
1,085
pas
Pascal
PascalParser/Source/ProjectIndexer.ParsedUnits.pas
ProHolz/ElementsDelphiTools
dca0c4d6171428ea2671ace6d3bc5f68e6f147af
[ "MIT" ]
5
2019-02-21T14:07:28.000Z
2021-04-21T18:59:59.000Z
PascalParser/Source/ProjectIndexer.ParsedUnits.pas
ProHolz/ElementsDelphiTools
dca0c4d6171428ea2671ace6d3bc5f68e6f147af
[ "MIT" ]
1
2019-03-04T12:27:59.000Z
2019-03-04T12:27:59.000Z
PascalParser/Source/ProjectIndexer.ParsedUnits.pas
ProHolz/ElementsDelphiTools
dca0c4d6171428ea2671ace6d3bc5f68e6f147af
[ "MIT" ]
4
2019-09-07T12:48:54.000Z
2021-04-23T13:34:34.000Z
namespace ProHolz.Ast; interface type TUnitParsedEvent = public block (Sender: Object; const UnitName: String; const FileName: String; var SyntaxTree: TSyntaxNode; SyntaxTreeFromParser: Boolean; var doAbort: Boolean); TUnitInfo = public record public Name: not nullable String := ''; Path: not nullable String := ''; SyntaxTree: TSyntaxNode; end; TParsedUnits = public class(List<TUnitInfo>) public constructor; empty; method Initialize(ParsedUnits: TParsedUnitsCache; UnitPaths: TUnitPathsCache); end; implementation { TProjectIndexer.TParsedUnits } method TParsedUnits.Initialize(ParsedUnits: TParsedUnitsCache; UnitPaths: TUnitPathsCache); begin RemoveAll; for kv in ParsedUnits.Keys do begin if ParsedUnits[kv] = nil then continue; //for kv var info : TUnitInfo; info.Name := kv as not nullable; info.SyntaxTree := ParsedUnits[kv]; var unitpath := if UnitPaths.ContainsKey(kv+'.pas') then UnitPaths[kv+'.pas'] else ''; info.Path := String(unitpath); Add(info); end; end; end.
24.659091
181
0.702304
4705828099e854692453d6829e2108400672e0e3
4,386
pas
Pascal
QIP Infium SDK/u_common.pas
liborm85/qip-plugin-rss-news
ccf1cb4d9dd515f6daf7b83bc79f4de8d0659dd6
[ "MIT" ]
null
null
null
QIP Infium SDK/u_common.pas
liborm85/qip-plugin-rss-news
ccf1cb4d9dd515f6daf7b83bc79f4de8d0659dd6
[ "MIT" ]
null
null
null
QIP Infium SDK/u_common.pas
liborm85/qip-plugin-rss-news
ccf1cb4d9dd515f6daf7b83bc79f4de8d0659dd6
[ "MIT" ]
null
null
null
{*************************************} { } { QIP INFIUM SDK } { Copyright(c) Ilham Z. } { ilham@qip.ru } { http://www.qip.im } { } {*************************************} { This module is common for core, protos and plugins, thats why some records can be here and some in u_plugin_info } unit u_common; interface uses Windows; type {Plugin specific options which will be saved in profile} TPluginSpecific = record Bool1 : Boolean; Bool2 : Boolean; Bool3 : Boolean; Bool4 : Boolean; Bool5 : Boolean; Bool6 : Boolean; Bool7 : Boolean; Bool8 : Boolean; Bool9 : Boolean; Bool10 : Boolean; Param1 : DWord; Param2 : DWord; Param3 : DWord; Param4 : DWord; Param5 : DWord; Param6 : DWord; Param7 : DWord; Param8 : DWord; Param9 : DWord; Param10 : DWord; Wstr1 : WideString; //Max length = 65535 after encoding to UTF8 Wstr2 : WideString; //Max length = 65535 after encoding to UTF8 Wstr3 : WideString; //Max length = 65535 after encoding to UTF8 Wstr4 : WideString; //Max length = 65535 after encoding to UTF8 Wstr5 : WideString; //Max length = 65535 after encoding to UTF8 Wstr6 : WideString; //Max length = 65535 after encoding to UTF8 Wstr7 : WideString; //Max length = 65535 after encoding to UTF8 Wstr8 : WideString; //Max length = 65535 after encoding to UTF8 Wstr9 : WideString; //Max length = 65535 after encoding to UTF8 Wstr10 : WideString; //Max length = 65535 after encoding to UTF8 end; pPluginSpecific = ^TPluginSpecific; {Adding button below avatar in msg and chat windows} TAddBtnInfo = record BtnIcon : HICON; //size must be 16x16, if you creating new HICON then after adding button dont forget to destroy it in your plugin. BtnPNG : LongInt; //size must be 16x16, LongInt(TPngObject) from PngImage library, delphi only. Else have to be 0. After adding button dont forget to destroy it in your plugin. BtnHint : WideString; //hint of the button. BtnData : LongInt; //pointer of plugin specified data, will be returned on click. Since sdk 1.6. end; pAddBtnInfo = ^TAddBtnInfo; {plugins only} TBtnClick = record BtnData : LongInt; //pointer of plugin specified data. Since sdk 1.6. RightClick : Boolean; //in case if user right clicked on btn end; pBtnClick = ^TBtnClick; //QIP Colors, delphi bgr TQipColors = record AccBtnText : integer; AccBtn : integer; AccBtnGrad : integer; AccBtnFrameL : integer; AccBtnFrameD : integer; Divider : integer; Group : integer; Counter : integer; Online : integer; Offline : integer; NotInList : integer; OffMsg : integer; Focus : integer; FocusGrad : integer; FocusFrame : integer; Hint : integer; HintGrad : integer; HintFrame : integer; IncEvents : integer; OutEvents : integer; FadeTitle : integer; FadeText : integer; TabBorder : integer; TabBorderDrk : integer; TabInactive : integer; TabInactGrad : integer; TabActive : integer; TabActGrad : integer; TabActLiTop : integer; TabActLight : integer; TabFontInact : integer; TabFontAct : integer; ChatTopic : integer; ChatTime : integer; ChatOwnNick : integer; ChatContNick : integer; ChatOwnText : integer; ChatContText : integer; ChatJoined : integer; ChatLeft : integer; ChatDiscon : integer; ChatNotice : integer; ChatHighLi : integer; ChatInfoText : integer; ChatActText : integer; ChatKickText : integer; ChatModeText : integer; BgPicClOff : Boolean; BgPicMsgOff : Boolean; BgPicChatOff : Boolean; BgClColor : integer; BgMsgColor : integer; BgChatColor : integer; end; pQipColors = ^TQipColors; implementation end.
32.977444
184
0.572959
4745dd9b645b74fc0d12496ffa243c3d79703c35
20,513
pas
Pascal
Projects/Stemma.p/Source/frm_EditEvents.pas
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
11
2017-06-17T05:13:45.000Z
2021-07-11T13:18:48.000Z
Projects/Stemma.p/Source/frm_EditEvents.pas
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
2
2019-03-05T12:52:40.000Z
2021-12-03T12:34:26.000Z
Projects/Stemma.p/Source/frm_EditEvents.pas
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
6
2017-09-07T09:10:09.000Z
2022-02-19T20:19:58.000Z
unit frm_EditEvents; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Grids, Menus, FMUtils, fra_Citations, fra_Documents, StrUtils, LCLType, Buttons, Spin, ExtCtrls, fra_Phrase, fra_Date, fra_Memo; type enumEventEditType = ( eEET_EditExisting, eEET_New, eEET_AddBirth, eEET_AddBaptism, eEET_AddDeath, eEET_AddBurial); { TfrmEditEvents } TfrmEditEvents = class(TForm) Button1: TBitBtn; Button2: TBitBtn; fraDate1: TfraDate; fraDocuments1: TfraDocuments; fraEdtCitations1: TfraEdtCitations; fraMemo1: TfraMemo; fraPhrase1: TfraPhrase; L3: TEdit; L4: TEdit; L0: TEdit; LA: TEdit; Label1: TLabel; Label11: TLabel; Label8: TLabel; mnuEventsMain: TMainMenu; MenuItem1: TMenuItem; MenuItem11: TMenuItem; MenuItem12: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; ModifierTemoin: TMenuItem; AjouterTemoin: TMenuItem; No: TSpinEdit; P2: TMemo; Panel1: TPanel; pnlPlaceLeft: TPanel; pnlBottom: TPanel; Splitter1: TSplitter; SupprimerTemoin: TMenuItem; L1: TEdit; L2: TEdit; mnuWitnes: TPopupMenu; Role: TEdit; TableauTemoins: TStringGrid; X: TCheckBox; YY: TEdit; Y: TComboBox; procedure AjouterTemoinClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure fraDate1Click(Sender: TObject); procedure fraMemo1EditingDone(Sender: TObject); procedure MenuItem11Click(Sender: TObject); procedure MenuItem12Click(Sender: TObject); // procedure Supprimer1Click(Sender: TObject); procedure SupprimerTemoinClick(Sender: TObject); procedure TableauTemoinsDblClick(Sender: TObject); procedure TableauTemoinsDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; {%H-}aState: TGridDrawState); procedure YChange(Sender: TObject); private FEditType: enumEventEditType; function GetID: longint; function GetIdEventType: integer; procedure SetEditType(AValue: enumEventEditType); { private declarations } public property EditType: enumEventEditType read FEditType write SetEditType; Property idEvent:longint read GetID; property idEventType:integer read GetIdEventType; { public declarations } end; function PopulateTemoins(idEvent:integer):string; var frmEditEvents: TfrmEditEvents; { TODO : Ajouter la possibilité de mettre un témoin principal ou non, afficher le nombre de témoins } implementation uses frm_Events, frm_Main, dm_GenData, frm_Explorer, frm_EditWitness, cls_Translation,dateutils; {$R *.lfm} { TfrmEditEvents } procedure TfrmEditEvents.TableauTemoinsDblClick(Sender: TObject); begin if TableauTemoins.Row>0 then begin // Enregistrer le témoin par défaut si no.text='0' if no.text='0' then Button1Click(Sender); frmEditWitness.idWitness:=ptrint(TableauTemoins.Objects[0,frmEditEvents.TableauTemoins.Row]); If frmEditWitness.Showmodal=mrOK then PopulateTemoins(no.Value); end; end; procedure TfrmEditEvents.TableauTemoinsDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); begin if aCol=0 then begin (Sender as TStringGrid).Canvas.Font.Color := (Sender as TStringGrid).Canvas.Brush.Color; (Sender as TStringGrid).Canvas.TextOut(aRect.Left+2,aRect.Top+2,(Sender as TStringGrid).Cells[aCol,aRow]); end; if (((Sender as TStringGrid).Cells[4,aRow]='*') and (aCol>0)) then begin // if (Sender as TStringGrid).Row=aRow then // (Sender as TStringGrid).Canvas.Brush.Color := clBlue // else // (Sender as TStringGrid).Canvas.Brush.Color := clYellow; // (Sender as TStringGrid).Canvas.FillRect(aRect); (Sender as TStringGrid).Canvas.Font.Bold := true; (Sender as TStringGrid).Canvas.TextOut(aRect.Left+2,aRect.Top+2,(Sender as TStringGrid).Cells[aCol,aRow]); end; end; procedure TfrmEditEvents.YChange(Sender: TObject); var roledefaut, roles, phrase, lPhrase, lRole:string; j:integer; lidType, lidWitness: integer; begin lidType:=ptrint(Y.Items.Objects[Y.ItemIndex]); dmgendata.GetTypePhraseRole(lidType, phrase, roles); if AnsiPos('|',Roles)>0 then RoleDefaut:=Copy(Roles,1,AnsiPos('|',Roles)-1) else RoleDefaut:=Roles; for j:=1 to TableauTemoins.Rowcount-1 do begin if AnsiPos(TableauTemoins.Cells[1,j],Roles)<1 then begin TableauTemoins.Cells[1,j]:=RoleDefaut; if TableauTemoins.Cells[2,j]=frmStemmaMainForm.sID then Role.Text:=RoleDefaut; lidWitness:=ptrint(TableauTemoins.Objects[0,j]); lPhrase := ''; lRole:= RoleDefaut; dmgendata.UpdateWitnessPhraseRole(lidWitness, lRole, lPhrase); dmGenData.SaveModificationTime(strtoint(TableauTemoins.Cells[2,j])); end; end; If fraPhrase1.isDefault Then fraPhrase1.Text:=DecodePhrase(frmStemmaMainForm.iID,Role.Text,phrase,'E',No.Value); end; function TfrmEditEvents.GetID: longint; begin trystrtoint(No.Text,result); end; function TfrmEditEvents.GetIdEventType: integer; begin result := PtrInt(y.Items.Objects[y.ItemIndex]); end; procedure TfrmEditEvents.SetEditType(AValue: enumEventEditType); begin if FEditType=AValue then Exit; FEditType:=AValue; end; procedure TfrmEditEvents.FormShow(Sender: TObject); var sPlace,phrase, sArticle, sState, sCountry, sDetail, sCity, sRegion, sEventType, lPhrase, lRoles, lMemo, lDate, lSDate:string; lidEvent, lidPlace: Integer; lDSExists, lPrefered: Boolean; LidType: LongInt; procedure FindTypeItem(FindTypeID:PtrInt); var j:integer; begin for j:=0 to Y.Items.Count-1 do if PtrInt(Y.Items.Objects[j])=FindTypeID then Y.ItemIndex:=j; end; begin ActiveControl:=fraDate1.edtDateForPresentation; frmStemmaMainForm.SetHistoryToActual(Sender); Caption:=Translation.Items[165]; Button1.Caption:=Translation.Items[152]; Button2.Caption:=Translation.Items[164]; Label1.Caption:=Translation.Items[166]; //Label3.Caption:=Translation.Items[171]; //Label4.Caption:=Translation.Items[172]; //Label5.Caption:=Translation.Items[144]; //Label6.Caption:=Translation.Items[173]; Label8.Caption:=Translation.Items[170]; //Label9.Caption:=Translation.Items[168]; //Label10.Caption:=Translation.Items[169]; Label11.Caption:=Translation.Items[167]; //Label12.Caption:=Translation.Items[298]; TableauTemoins.Cells[1,0]:=Translation.Items[175]; TableauTemoins.Cells[3,0]:=Translation.Items[176]; fraDocuments1.tblDocuments.Cells[2,0]:=Translation.Items[154]; fraDocuments1.tblDocuments.Cells[4,0]:=Translation.Items[201]; fraEdtCitations1.Clear; fraEdtCitations1.CType:='E'; //fraDocuments1.mniDocumentAdd.Caption:=Translation.Items[224]; //fraDocuments1.mniDocumentEdit.Caption:=Translation.Items[225]; //fraDocuments1.mniDocumentUnlink.Caption:=Translation.Items[226]; AjouterTemoin.Caption:=Translation.Items[224]; ModifierTemoin.Caption:=Translation.Items[225]; SupprimerTemoin.Caption:=Translation.Items[226]; MenuItem1.Caption:=Translation.Items[227]; MenuItem2.Caption:=Translation.Items[228]; MenuItem3.Caption:=Translation.Items[224]; MenuItem4.Caption:=Translation.Items[225]; MenuItem5.Caption:=Translation.Items[226]; MenuItem6.Caption:=Translation.Items[224]; MenuItem7.Caption:=Translation.Items[225]; MenuItem8.Caption:=Translation.Items[226]; //mniDocumentView.Caption:=Translation.Items[181]; // Populate le ComboBox if FEditType <> eEET_EditExisting then begin if FEditType in [eEET_AddBirth,eEET_AddBaptism] then dmGenData.GetTypeList(Y.Items,'B') else if FEditType in [eEET_AddDeath,eEET_AddBurial] then dmGenData.GetTypeList(Y.Items,'D') else dmGenData.GetTypeList(Y.Items,['B','D','M','X','Z']); end else begin lIdEvent:=frmEvents.idEvent; sEventType:=dmGenData.GetEventType(lIdEvent); dmGenData.GetTypeList(Y.Items,sEventType); end; // Populate la form if FEditType <> eEET_EditExisting then begin frmEditEvents.Caption:=Translation.Items[30]; TableauTemoins.RowCount:=2; TableauTemoins.Cells[0,1]:='0'; case FEditType of eEET_New: begin Y.ItemIndex:=0; X.Checked:=false; end; eEET_AddBirth: begin // Mettre le bon Y.ItemIndex // Trouver si ce doit être un primaire ou non FindTypeItem(100); lDSExists:=dmGenData.PreferedEventWitnessExists(frmStemmaMainForm.iID, 'B'); X.Checked:= not lDSExists; end; eEET_AddBaptism: begin // Mettre le bon Y.ItemIndex // Trouver si ce doit être un primaire ou non FindTypeItem(110); lDSExists:=dmGenData.PreferedEventWitnessExists(frmStemmaMainForm.iID, 'B'); X.Checked:= not lDSExists ; end; eEET_AddDeath: begin // Mettre le bon Y.ItemIndex // Trouver si ce doit être un primaire ou non FindTypeItem(200); lDSExists:=dmGenData.PreferedEventWitnessExists(frmStemmaMainForm.iID, 'D'); X.Checked:= not lDSExists ; end; eEET_AddBurial: begin // Mettre le bon Y.ItemIndex // Trouver si ce doit être un primaire ou non FindTypeItem(210); lDSExists:=dmGenData.PreferedEventWitnessExists(frmStemmaMainForm.iID, 'D'); X.Checked:= not lDSExists; end; end; {Case} // Trouver le type de témoin par défaut dmGenData.GetTypePhraseRole(idEventType,lPhrase,lRoles); if AnsiPos('|',lRoles)>0 then TableauTemoins.Cells[1,1]:=ANSIToUTF8(Copy(lRoles,1,AnsiPos('|',lRoles)-1)) else TableauTemoins.Cells[1,1]:=lRoles; TableauTemoins.Cells[2,1]:=frmStemmaMainForm.sID; TableauTemoins.Cells[3,1]:=dmGenData.GetIndividuumName(frmStemmaMainForm.iID); TableauTemoins.Cells[4,1]:='1'; fraMemo1.Text:=''; fraPhrase1.clear; fraDate1.clear; No.Value:=0; Role.Text:=TableauTemoins.Cells[1,1]; LA.Text:=''; L0.Text:=''; L1.Text:=''; L2.Text:=''; L3.Text:=''; L4.Text:=''; YY.Text:=''; fraPhrase1.isDefault:=true; end else begin lidEvent:=frmEvents.idEvent; dmGenData.GetEventData(lidEvent, LidType,lidPlace, lPrefered, lSDate, lDate, lMemo, sPlace); FindTypeItem(LidType); No.Value:=lidEvent; X.Checked:=lPrefered; fraMemo1.Text:=lMemo; // Aller chercher L0-L4 de L DecodePlace(sPlace,sArticle ,sDetail,sCity,sRegion,sCountry,sState); LA.Text:=sArticle; L0.Text:=sDetail; L1.Text:=sCity; L2.Text:=sRegion; L3.text:=sCountry; L4.text:=sState; fraDate1.Date:=lDate; fraDate1.SortDate:=lSDate; // Aller chercher P, Role et témoins de W phrase:=PopulateTemoins(no.Value); end; if length(phrase)=0 then begin fraPhrase1.isDefault:=true; phrase:=dmGenData.GetTypePhrase(idEventType); end; fraPhrase1.Text:=DecodePhrase(frmStemmaMainForm.iID,Role.Text,Phrase,'E',No.Value); // Populate le tableau de citations if no.Value=0 then fraEdtCitations1.clear else fraEdtCitations1.LinkID:=no.Value; // Populate le tableau de documents fraDocuments1.DocType:='E'; fraDocuments1.idLink:=No.Value; if no.text='0' then fraDocuments1.clear else fraDocuments1.Populate; end; procedure TfrmEditEvents.fraDate1Click(Sender: TObject); begin end; procedure TfrmEditEvents.fraMemo1EditingDone(Sender: TObject); begin frmStemmaMainForm.AppendHistoryData('M',fraMemo1.Text); end; procedure TfrmEditEvents.MenuItem11Click(Sender: TObject); begin Button1Click(Sender); ModalResult:=mrOk; end; procedure TfrmEditEvents.MenuItem12Click(Sender: TObject); var liResult:integer; temp, sArticle, sDetail, sCity, sRegion, sCountry, sState, lsResult:string; begin // Traitement de F3 pour les lieus if ActiveControl.Name=LA.Name then begin liResult := frmStemmaMainForm.RetreiveFromHistoyID('L'); if liResult<>-1 then begin temp:=dmgendata.GetPlaceName(liResult); if ANSIPos('<'+CTagNameArticle+'>',temp)>0 then LA.text:=Copy(temp,ANSIPos('<'+CTagNameArticle+'>',temp)+length(CTagNameArticle)+2,AnsiPos('</'+CTagNameArticle+'>',temp)-ANSIPos('<'+CTagNameArticle+'>',temp)-length(CTagNameArticle)-2) else LA.text:=''; end; end else if (ActiveControl.Name=L0.Name) or (ActiveControl.Name=L1.Name) or (ActiveControl.Name=L2.Name) or (ActiveControl.Name=L3.Name) or (ActiveControl.Name=L4.Name) then begin liResult := frmStemmaMainForm.RetreiveFromHistoyID('L'); if liResult<>-1 then begin temp:=dmgendata.GetPlaceName(liResult); DecodePlace(temp,sArticle,sDetail,sCity,sRegion,sCountry,sState); L0.Text:=sDetail; L1.text:=sCity; L2.text:=sRegion; L3.text:=sCountry; L4.text:=sState; end; end else if ActiveControl.Name = fraDate1.edtDateForSorting.Name then begin lsResult := frmStemmaMainForm.RetreiveFromHistoy('SD'); if lsResult <> '' then fraDate1.SortDate := lsResult; end else if ActiveControl.Name = fraDate1.edtDateForPresentation.Name then begin lsResult := frmStemmaMainForm.RetreiveFromHistoy('PD'); if lsResult <> '' then fraDate1.Date := lsResult; end else if ActiveControl.Name = fraMemo1.edtMemoText.Name then begin lsResult := frmStemmaMainForm.RetreiveFromHistoy('M'); if lsResult <> '' then fraMemo1.Text := lsResult; end; end; procedure TfrmEditEvents.Button1Click(Sender: TObject); var Lieu1,Lieu2,lEvType, lDate, lSortDate, lInfo, DateEv:string; valide:boolean; lidInd,idPlace, lIdPlace, lidEvent:integer; lPrefered: boolean; begin // Vérifie qu'il y a au moins 1 témoin valide:=TableauTemoins.RowCount>1; if not valide then begin Application.MessageBox(pchar(Translation.Items[301]),pchar(Translation.Items[124]),MB_OK) end else begin fraDate1.Finishediting(Sender,ActiveControl); // Trouve le lieu équivalent !!! LA.Text:=trim(LA.Text); L0.Text:=trim(L0.Text); L1.Text:=trim(L1.Text); L2.Text:=trim(L2.Text); L3.Text:=trim(L3.Text); L4.Text:=trim(L4.Text); Lieu1:='!TMG|'+trim(LA.Text+' '+L0.Text)+'|'+L1.Text+'|'+L2.Text+'|'+L3.Text+'|'+L4.Text+'||||'; Lieu2:=''; if Length(LA.TexT)>0 then Lieu2:='<'+CTagNameArticle+'>'+LA.Text+'</'+CTagNameArticle+'>'; if Length(L0.TexT)>0 then Lieu2:=Lieu2+'<'+CTagNameDetail+'>'+L0.Text+'</'+CTagNameDetail+'>'; L1.Text:=trim(L1.Text); if Length(L1.TexT)>0 then Lieu2:=Lieu2+'<' + CTagNamePlace + '>'+L1.Text+'</' + CTagNamePlace + '>'; L2.Text:=trim(L2.Text); if Length(L2.TexT)>0 then Lieu2:=Lieu2+'<' + CTagNameRegion + '>'+L2.Text+'</' + CTagNameRegion + '>'; L3.Text:=trim(L3.Text); if Length(L3.TexT)>0 then Lieu2:=Lieu2+'<' + CTagNameCountry + '>'+L3.Text+'</' + CTagNameCountry + '>'; L4.Text:=trim(L4.Text); if Length(L4.TexT)>0 then Lieu2:=Lieu2+'<' + CTagNameState + '>'+L4.Text+'</' + CTagNameState + '>'; Lieu1:=AnsiReplaceStr(AnsiReplaceStr(AnsiReplaceStr(Lieu1,'\','\\'),'"','\"'),'''','\'''); Lieu2:=AnsiReplaceStr(AnsiReplaceStr(AnsiReplaceStr(Lieu2,'\','\\'),'"','\"'),'''','\'''); idPlace:=dmGenData.GetPlaceID(Lieu2); if idplace=-1 then begin idPlace:=dmGenData.GetPlaceID(Lieu1); if idPlace = -1 then // Ajoute le lieu dans la table idPlace:=dmGenData.SavePlaceData(0,Lieu2); end; if idPlace>1 then begin frmStemmaMainForm.AppendHistoryData('L',idPlace); end; {SetVarInitHere} lIdPlace:=idPlace; lInfo:=trim(fraMemo1.Text); lDate:=fraDate1.Date; lSortDate:=fraDate1.SortDate; lPrefered:=X.Checked; lidEvent:=no.Value; no.Value:=dmGenData.SaveEventData(lidEvent,idEventType,lIdPlace,lPrefered, lInfo, lDate, lSortDate); if lidEvent=0 then begin lidEvent:=no.Value; // Ajoute le témoin qui a été ajouté par défaut dans le tableau lidInd :=dmGenData.AppendWitness(TableauTemoins.Cells[1,1],'',ptrint(TableauTemoins.Objects[2,1]),no.Value,true); TableauTemoins.Objects[0,1]:=Tobject(ptrint(lidInd)); TableauTemoins.Cells[0,1]:=inttostr(lidInd); end else lidInd:=ptrint(TableauTemoins.Objects[2,1]); // Sauvegarder les modifications pour tous les témoins de l'événements // UPDATE DÉCÈS si la date est il y a 100 ans !!! if (copy(fraDate1.Date,1,1)='1') and not (fraDate1.Date='100000000030000000000') then dateev:=Copy(fraDate1.Date,2,4) else if (copy(fraDate1.SortDate,1,1)='1') and not (fraDate1.SortDate='100000000030000000000') then dateev:=Copy(fraDate1.SortDate,2,4) else dateev:=FormatDateTime('YYYY',now); dmgendata.UpdateIndNotLivingByEvent(lidEvent,strtoint(DateEv), Sender); dmgendata.UpdateIndModificationTimesByEvent(lidEvent); // Modifier la ligne de l'explorateur si naissance frmStemmaMainForm ou décès principal dmGenData.GetEventExtData(lidEvent, lEvType, lDate, lPrefered); if (lEvType='B') then begin dmGenData.UpdateNameI3(lDate,lidInd); // fr: Update date de tri de relation // en: Update sort-date of relationship dmGenData.UpdateRelationSortdate(lidInd, lDate); end else if (lEvType='D') then begin dmGenData.UpdateNameI4(lDate, lidInd); // UPDATE DÉCÈS!!! dmGenData.UpdateIndLiving(lidInd,'N',Sender); end; if (lidInd>0) and ((lEvType='B') or ((lEvType='D'))) and (lPrefered) and (X.Checked) then begin if frmStemmaMainForm.actWinExplorer.Checked then frmExplorer.UpdateIndexDates(lEvType,lDate,lidInd); end; end; end; procedure TfrmEditEvents.AjouterTemoinClick(Sender: TObject); begin // Ajouter un témoin à l'événement If no.text='0' then Button1Click(Sender); // dmGenData.PutCode('A',no.text); frmEditWitness.idWitness:=0; frmEditWitness.idEvent:=no.value; If frmEditWitness.Showmodal=mrOK then PopulateTemoins(no.Value); end; procedure TfrmEditEvents.SupprimerTemoinClick(Sender: TObject); begin If (TableauTemoins.RowCount>1) and (TableauTemoins.Row>0) then // Il faudra qu'il reste au moins un témoin if Application.MessageBox(Pchar(Translation.Items[32]+ TableauTemoins.Cells[3,TableauTemoins.Row]+' ('+ TableauTemoins.Cells[1,TableauTemoins.Row]+')'+Translation.Items[28]),pchar(SConfirmation),MB_YESNO)=IDYES then begin // Exécuter SAVEMODIFICATIONTIME pour le témoin supprimer dmGenData.SaveModificationTime(ptrint(TableauTemoins.Objects[2,TableauTemoins.Row])); dmGenData.DeleteWitness(ptrint(TableauTemoins.Objects[0,TableauTemoins.Row])); TableauTemoins.DeleteRow(TableauTemoins.Row); // Sauvegarder les modifications pour tous les témoins de l'événements dmGenData.UpdateIndModificationTimesByEvent(no.Value); end; end; function PopulateTemoins(idEvent:integer):string; var lMainRole: string; begin dmGenData.FillTableWitness(idEvent,frmStemmaMainForm.iID, frmEditEvents.TableauTemoins, lMainRole, result); frmEditEvents.Role.text:=lMainRole; end; end.
33.794069
201
0.661629
474f2f9216cb7a46cfe66026b67a6b629be9f919
61,871
pas
Pascal
Libraries/KControls/source/kpagecontrol.pas
jomael/Concepts
82d18029e41d55e897d007f826c021cdf63e53f8
[ "Apache-2.0" ]
62
2016-01-20T16:26:25.000Z
2022-02-28T14:25:52.000Z
Libraries/KControls/source/kpagecontrol.pas
jomael/Concepts
82d18029e41d55e897d007f826c021cdf63e53f8
[ "Apache-2.0" ]
null
null
null
Libraries/KControls/source/kpagecontrol.pas
jomael/Concepts
82d18029e41d55e897d007f826c021cdf63e53f8
[ "Apache-2.0" ]
20
2016-09-08T00:15:22.000Z
2022-01-26T13:13:08.000Z
{ @abstract(This file is part of the KControls component suite for Delphi and Lazarus.) @author(Tomas Krysl) Copyright (c) 2020 Tomas Krysl<BR><BR> <B>License:</B><BR> This code is licensed under BSD 3-Clause Clear License, see file License.txt or https://spdx.org/licenses/BSD-3-Clause-Clear.html. } unit kpagecontrol; // lowercase name because of Lazarus/Linux {$include kcontrols.inc} {$WEAKPACKAGEUNIT ON} interface uses {$IFDEF FPC} LCLType, LCLIntf, LMessages, LCLProc, {$ELSE} Windows, Messages, {$ENDIF} Classes, Controls, Graphics, ExtCtrls, Forms, StdCtrls, ComCtrls, Contnrs, ImgList, Buttons, KFunctions, KControls, KButtons; type TKTabOption = (toDrag, toDragUndock, toBrightTopColors); TKTabOptions = set of TKTabOption; const cDefaultScrollButtonSize = 20; cDefaultTabPadding = 2; cDefaultTabHeight = 24; cDefaultTabPosition = tpTop; cDefaultTabWidth = 0; cDefaultTabOptions = [toDrag]; cDefaultHotTop = clGradientActiveCaption; cDefaultHotBottom = clGradientInactiveCaption; cDefaultNormalTop = clBtnFace; cDefaultNormalBottom = clBtnHighlight; cDefaultNormalText = clBtnText; cDefaultSelectedTop = clActiveCaption; cDefaultSelectedBottom = clActiveCaption; cDefaultSelectedText = clCaptionText; cDefaultTabBorder = clBtnShadow; ciHotTop = TKColorIndex(0); ciHotBottom = TKColorIndex(1); ciNormalTop = TKColorIndex(2); ciNormalBottom = TKColorIndex(3); ciNormalText = TKColorIndex(4); ciSelectedTop = TKColorIndex(5); ciSelectedBottom = TKColorIndex(6); ciSelectedText = TKColorIndex(7); ciTabBorder = TKColorIndex(8); ciMaxIndex = ciTabBorder; type TKTabColors = class(TKCustomColors) protected { Returns color specification structure for given index. } function GetColorSpec(Index: TKColorIndex): TKColorSpec; override; { Returns maximum color index. } function GetMaxIndex: Integer; override; published property HotTop: TColor index ciHotTop read GetColor write SetColor default cDefaultHotTop; property HotBottom: TColor index ciHotBottom read GetColor write SetColor default cDefaultHotBottom; property NormalTop: TColor index ciNormalTop read GetColor write SetColor default cDefaultNormalTop; property NormalBottom: TColor index ciNormalBottom read GetColor write SetColor default cDefaultNormalBottom; property NormalText: TColor index ciNormalText read GetColor write SetColor default cDefaultNormalText; property SelectedTop: TColor index ciSelectedTop read GetColor write SetColor default cDefaultSelectedTop; property SelectedBottom: TColor index ciSelectedBottom read GetColor write SetColor default cDefaultSelectedBottom; property SelectedText: TColor index ciSelectedText read GetColor write SetColor default cDefaultSelectedText; property TabBorder: TColor index ciTabBorder read GetColor write SetColor default cDefaultTabBorder; end; TKTabState = (tsNormal, tsHot, tsSelected); TKTabInfo = record CloseHeight, CloseWidth, ImageHeight, ImageWidth, ImagePadding, LeftPadding, RightPadding, TabExtent, TextPadding, TextWidth: Integer; end; TKTabPaintInfo = record TabRect: TRect; ImageRect: TRect; TextRect: TRect; CloseRect: TRect; end; TKTabPanel = class; TKTabPanelOptions = class(TPersistent) private FCloseButtonIndex: TImageIndex; FColors: TKTabColors; FLeftButtonIndex: TImageIndex; FOptions: TKTabOptions; FPadding: Integer; FRightButtonIndex: TImageIndex; FScrollButtonSize: Integer; procedure SetCloseButtonIndex(const Value: TImageIndex); procedure SetColors(const Value: TKTabColors); procedure SetOptions(const Value: TKTabOptions); procedure SetLeftButtonIndex(const Value: TImageIndex); procedure SetPadding(const Value: Integer); procedure SetRightButtonIndex(const Value: TImageIndex); procedure SetScrollButtonSize(const Value: Integer); public FPanel: TKTabPanel; constructor Create(APanel: TKTabPanel); destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure UpdateTabPanel; published property CloseButtonIndex: TImageIndex read FCloseButtonIndex write SetCloseButtonIndex default -1; property Colors: TKTabColors read FColors write SetColors; property Options: TKTabOptions read FOptions write SetOptions default cDefaultTabOptions; property LeftButtonIndex: TImageIndex read FLeftButtonIndex write SetLeftButtonIndex default -1; property Padding: Integer read FPadding write SetPadding default cDefaultTabPadding; property RightButtonIndex: TImageIndex read FRightButtonIndex write SetRightButtonIndex default -1; property ScrollButtonSize: Integer read FScrollButtonSize write SetScrollButtonSize default cDefaultScrollButtonSize; end; TKCustomPageControl = class; { TKTabPanel } TKTabPanel = class(TKCustomControl) private FFirstVisibleTab: Integer; FOptions: TKTabPanelOptions; FPageControl: TKCustomPageControl; procedure CMCursorChanged(var Message: TLMessage); message CM_CURSORCHANGED; function GetTabs(Index: Integer): TKString; procedure SetFirstVisibleTab(Value: Integer); procedure SetOptions(const Value: TKTabPanelOptions); procedure SetPageControl(const Value: TKCustomPageControl); protected FAllTabsExtent: Integer; FDraggedTab: Integer; FDraggedPos: TPoint; FFullyVisibleTabsExtent: Integer; FInvisibleTabsExtent: Integer; FLastDraggedTab: Integer; FLastFullyVisibleTab: Integer; FLeftScrollButton: TKSpeedButton; FMaxFirstVisibleTab: Integer; FMouseIndex: Integer; FMouseInCloseButton: Boolean; FPageToClose: Integer; FRightScrollButton: TKSpeedButton; FScrolling: Boolean; FTabAreaExtent: Integer; FVisibleTabsExtent: Integer; function GetTabInfo(ACanvas: TCanvas; ATabIndex: Integer; out Info: TKTabInfo): Boolean; virtual; function GetTabPaintInfo(ACanvas: TCanvas; ATabIndex: Integer; out Info: TKTabPaintInfo): Boolean; virtual; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure LeftScrollButtonClick(Sender: TObject); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseFormLeave; override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseMoveCaptured(Shift: TShiftState; X, Y: Integer); virtual; procedure MouseOver(Shift: TShiftState; X, Y: Integer); virtual; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function PaintTab(ACanvas: TCanvas; ATabIndex: Integer): Boolean; virtual; procedure PaintTabBackground(ACanvas: TCanvas; const ARect: TRect; AState: TKTabState); virtual; procedure PaintTabCloseButton(ACanvas: TCanvas; const ARect: TRect); virtual; procedure PaintTabImage(ACanvas: TCanvas; const ARect: TRect; ATabIndex: Integer); virtual; procedure PaintTabText(ACanvas: TCanvas; const ARect: TRect; ATabIndex: Integer; AState: TKTabState); virtual; procedure PaintAfterTabs(ACanvas: TCanvas; ALastTabIndex: Integer); virtual; procedure PaintToCanvas(ACanvas: TCanvas); override; procedure RightScrollButtonClick(Sender: TObject); procedure UpdateTabPanelLayout(ACanvas: TCanvas); virtual; procedure UpdateSize; override; procedure UpdateScrollRange; virtual; procedure UpdateTabPanel; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function IndexOfTabAt(X, Y: Integer): Integer; virtual; function TabRect(AIndex: Integer): TRect; virtual; property FirstVisibleTab: Integer read FFirstVisibleTab write SetFirstVisibleTab; property Options: TKTabPanelOptions read FOptions write SetOptions; property PageControl: TKCustomPageControl read FPageControl write SetPageControl; property Tabs[Index: Integer]: TKString read GetTabs; end; { TKTabSheet } TKTabSheet = class(TWinControl) private FImageIndex: TImageIndex; FPageControl: TKCustomPageControl; FHighlighted: Boolean; FOnHide: TNotifyEvent; FOnShow: TNotifyEvent; function GetPageIndex: Integer; procedure SetHighlighted(Value: Boolean); procedure SetImageIndex(Value: TImageIndex); procedure SetPageControl(APageControl: TKCustomPageControl); procedure SetPageIndex(Value: Integer); procedure CMShowingChanged(var Message: TLMessage); message CM_SHOWINGCHANGED; procedure CMTextChanged(var Message: TLMessage); message CM_TEXTCHANGED; procedure WMEraseBkgnd(var Message: TLMEraseBkgnd); message LM_ERASEBKGND; procedure WMPaint(var Msg: TLMPaint); message LM_PAINT; protected procedure CreateParams(var Params: TCreateParams); override; procedure DoHide; dynamic; procedure DoShow; dynamic; procedure ReadState(Reader: TReader); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property PageControl: TKCustomPageControl read FPageControl write SetPageControl; published property BorderWidth; property Caption; property DragMode; property Enabled; property Font; property Height stored False; property Highlighted: Boolean read FHighlighted write SetHighlighted default False; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex default 0; property Left stored False; property Constraints; property PageIndex: Integer read GetPageIndex write SetPageIndex stored False; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Top stored False; property Visible stored False; property Width stored False; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnHide: TNotifyEvent read FOnHide write FOnHide; property OnMouseDown; {$IFDEF COMPILER9_UP} property OnMouseEnter; property OnMouseLeave; {$ENDIF} property OnMouseMove; property OnMouseUp; property OnResize; property OnShow: TNotifyEvent read FOnShow write FOnShow; property OnStartDrag; end; TKTabSheets = class(TObjectList) private function GetItem(Index: Integer): TKTabSheet; procedure SetItem(Index: Integer; const Value: TKTabSheet); public function Add(AItem: TKTabSheet): Integer; function IndexOf(AItem: TKTabSheet): Integer; property Items[Index: Integer]: TKTabSheet read GetItem write SetItem; default; end; TKTabClickEvent = procedure(Sender: TObject; TabIndex: Integer) of object; TKTabCloseQueryEvent = procedure(Sender: TObject; TabIndex: Integer; var CanClose: Boolean) of object; { TKCustomPageControl } TKCustomPageControl = class(TKCustomControl) private FActivateNewDocked: Boolean; FActivePageIndex: Integer; FDisabledImages: TImageList; FHotTrack: Boolean; FImages: TImageList; FPages: TKTabSheets; FTabHeight: Integer; FTabPanel: TKTabPanel; FTabPosition: TTabPosition; FTabWidth: Integer; FOnChange: TNotifyEvent; FOnChanging: TTabChangingEvent; FOnGetImageIndex: TTabGetImageEvent; FOnTabClick: TKTabClickEvent; FOnTabCloseQuery: TKTabCloseQueryEvent; function GetActivePage: TKTabSheet; function GetPage(Index: Integer): TKTabSheet; function GetPageCount: Integer; procedure SetActivePageIndex(const Value: Integer); procedure SetDisabledImages(const Value: TImageList); procedure SetHotTrack(const Value: Boolean); procedure SetImages(const Value: TImageList); procedure SetTabHeight(const Value: Integer); procedure SetTabPanel(const Value: TKTabPanel); procedure SetTabPanelOptions(const Value: TKTabPanelOptions); procedure SetTabPosition(Value: TTabPosition); procedure SetTabWidth(const Value: Integer); procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY; {$IFDEF FPC} procedure CMDesignHitTest(var Message: TCMDesignHitTest); message CM_DESIGNHITTEST; {$ELSE} procedure CMDockNotification(var Message: TCMDockNotification); message CM_DOCKNOTIFICATION; procedure CMDockClient(var Message: TCMDockClient); message CM_DOCKCLIENT; procedure CMUnDockClient(var Message: TCMUnDockClient); message CM_UNDOCKCLIENT; {$ENDIF} procedure WMEraseBkgnd(var Msg: TLMessage); message LM_ERASEBKGND; function GetTabPanelOptions: TKTabPanelOptions; protected FDeletingPage: Boolean; FLoadedActivePageIndex: Integer; FNewDockSheet: TKTabSheet; FUndockingPage: TKTabSheet; function CanChange: Boolean; virtual; procedure Change; virtual; procedure ChangeActivePage(Page: TKTabSheet); virtual; procedure DoAddDockClient(Client: TControl; const ARect: TRect); override; procedure DockOver(Source: TDragDockObject; X, Y: Integer; State: TDragState; var Accept: Boolean); override; procedure DoRemoveDockClient(Client: TControl); override; procedure DoTabClick(AIndex: Integer); virtual; procedure DoTabClose(AIndex: Integer); virtual; procedure FreePage(Page: TKTabSheet); virtual; function GetImageIndex(TabIndex: Integer): Integer; virtual; function GetPageFromDockClient(Client: TControl): TKTabSheet; procedure GetSiteInfo(Client: TControl; var InfluenceRect: TRect; MousePos: TPoint; var CanDock: Boolean); override; procedure InsertPage(Page: TKTabSheet); virtual; procedure Loaded; override; {$IFDEF FPC} procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; {$ENDIF} procedure MovePage(CurIndex, NewIndex: Integer); procedure PaintToCanvas(ACanvas: TCanvas); override; function ReleasePage(Index: Integer): TKTabSheet; virtual; procedure RemovePage(Page: TKTabSheet); virtual; procedure SetActivePage(Page: TKTabSheet); procedure SetChildOrder(Child: TComponent; Order: Integer); override; procedure ShowControl(AControl: TControl); override; procedure UpdateAllDesignerFlags; procedure UpdateDesignerFlags(APageIndex: integer); procedure UpdateTabPanel; virtual; procedure UpdateTabPanelPosition; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function AddPage(AOwner: TComponent): TKTabSheet; virtual; procedure DeletePage(AIndex: Integer); overload; virtual; procedure DeletePage(APage: TKTabSheet); overload; virtual; function FindNextPage(CurPage: TKTabSheet; GoForward: Boolean): TKTabSheet; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; function IndexOfTabAt(X, Y: Integer): Integer; procedure SelectNextPage(GoForward: Boolean); function TabRect(Index: Integer): TRect; property ActivateNewDocked: Boolean read FActivateNewDocked write FActivateNewDocked default True; property ActivePage: TKTabSheet read GetActivePage write SetActivePage; property ActivePageIndex: Integer read FActivePageIndex write SetActivePageIndex default -1; property DisabledImages: TImageList read FDisabledImages write SetDisabledImages; property HotTrack: Boolean read FHotTrack write SetHotTrack default True; property Images: TImageList read FImages write SetImages; property ImageIndex[Index: Integer]: Integer read GetImageIndex; property PageCount: Integer read GetPageCount; property Pages[Index: Integer]: TKTabSheet read GetPage; property TabPosition: TTabPosition read FTabPosition write SetTabPosition default cDefaultTabPosition; property TabHeight: Integer read FTabHeight write SetTabHeight default cDefaultTabHeight; property TabPanel: TKTabPanel read FTabPanel write SetTabPanel; property TabPanelOptions: TKTabPanelOptions read GetTabPanelOptions write SetTabPanelOptions; property TabWidth: Integer read FTabWidth write SetTabWidth default cDefaultTabWidth; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TTabChangingEvent read FOnChanging write FOnChanging; property OnGetImageIndex: TTabGetImageEvent read FOnGetImageIndex write FOnGetImageIndex; property OnTabClick: TKTabClickEvent read FOnTabClick write FOnTabClick; property OnTabCloseQuery: TKTabCloseQueryEvent read FOnTabCloseQuery write FOnTabCloseQuery; end; TKPageControl = class(TKCustomPageControl) published property ActivateNewDocked; property ActivePageIndex; property Align; property Anchors; property BiDiMode; property BorderStyle default bsNone; property Constraints; property DisabledImages; property DockSite; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HotTrack; property Images; // property MultiLine; property ParentBackground; property ParentBiDiMode; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; // property RaggedRight; // property ScrollOpposite; property ShowHint; // property Style; property TabHeight; property TabOrder; property TabPanelOptions; property TabPosition; property TabStop; property TabWidth; property Visible; property OnChange; property OnChanging; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnGetSiteInfo; property OnMouseDown; {$IFDEF COMPILER9_UP} property OnMouseEnter; property OnMouseLeave; {$ENDIF} property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnTabClick; property OnUnDock; end; implementation uses SysUtils {$IFDEF USE_THEMES} , Themes {$IFNDEF FPC} , UxTheme {$ENDIF} {$ENDIF} , KGraphics; { TKTabColors } function TKTabColors.GetColorSpec(Index: TKColorIndex): TKColorSpec; begin case Index of ciNormalTop: begin Result.Def := cDefaultNormalTop; Result.Name := ''; end; ciNormalBottom: begin Result.Def := cDefaultNormalBottom; Result.Name := ''; end; ciNormalText: begin Result.Def := cDefaultNormalText; Result.Name := ''; end; ciSelectedTop: begin Result.Def := cDefaultSelectedTop; Result.Name := ''; end; ciSelectedBottom: begin Result.Def := cDefaultSelectedBottom; Result.Name := ''; end; ciSelectedText: begin Result.Def := cDefaultSelectedText; Result.Name := ''; end; ciHotTop: begin Result.Def := cDefaultHotTop; Result.Name := ''; end; ciHotBottom: begin Result.Def := cDefaultHotBottom; Result.Name := ''; end; ciTabBorder: begin Result.Def := cDefaultTabBorder; Result.Name := ''; end; else Result := inherited GetColorSpec(Index); end; end; function TKTabColors.GetMaxIndex: Integer; begin Result := ciMaxIndex; end; { TKTabPanelOptions } constructor TKTabPanelOptions.Create(APanel: TKTabPanel); begin FPanel := APanel; FColors := TKTabColors.Create(FPanel); FCloseButtonIndex := -1; FLeftButtonIndex := -1; FOptions := cDefaultTabOptions; FPadding := cDefaultTabPadding; FRightButtonIndex := -1; FScrollButtonSize := cDefaultScrollButtonSize; end; destructor TKTabPanelOptions.Destroy; begin FColors.Free; inherited; end; procedure TKTabPanelOptions.Assign(Source: TPersistent); begin inherited; if Source is TKTabPanelOptions then begin CloseButtonIndex := TKTabPanelOptions(Source).CloseButtonIndex; Colors := TKTabPanelOptions(Source).Colors; Options := TKTabPanelOptions(Source).Options; LeftButtonIndex := TKTabPanelOptions(Source).LeftButtonIndex; Padding := TKTabPanelOptions(Source).Padding; RightButtonIndex := TKTabPanelOptions(Source).RightButtonIndex; ScrollButtonSize := TKTabPanelOptions(Source).ScrollButtonSize; end; end; procedure TKTabPanelOptions.SetCloseButtonIndex(const Value: TImageIndex); begin if Value <> FCloseButtonIndex then begin FCloseButtonIndex := Value; UpdateTabPanel; end; end; procedure TKTabPanelOptions.SetColors(const Value: TKTabColors); begin FColors.Assign(Value); end; procedure TKTabPanelOptions.SetLeftButtonIndex(const Value: TImageIndex); begin if Value <> FLeftButtonIndex then begin FLeftButtonIndex := Value; UpdateTabPanel; end; end; procedure TKTabPanelOptions.SetOptions(const Value: TKTabOptions); begin if Value <> FOptions then begin FOptions := Value; UpdateTabPanel; end; end; procedure TKTabPanelOptions.SetPadding(const Value: Integer); begin if Value <> Fpadding then begin FPadding := Value; UpdateTabPanel; end; end; procedure TKTabPanelOptions.SetRightButtonIndex(const Value: TImageIndex); begin if Value <> FRightButtonIndex then begin FRightButtonIndex := Value; UpdateTabPanel; end; end; procedure TKTabPanelOptions.SetScrollButtonSize(const Value: Integer); begin if Value <> FScrollButtonSize then begin FScrollButtonSize := Value; UpdateTabPanel; end; end; procedure TKTabPanelOptions.UpdateTabPanel; begin if FPanel <> nil then FPanel.UpdateTabPanel; end; { TKTabPanel } constructor TKTabPanel.Create(AOwner: TComponent); begin inherited; BorderStyle := bsNone; ControlStyle := ControlStyle - [csCaptureMouse]; {$IFDEF FPC} ControlStyle := ControlStyle + [csDesignInteractive]; {$ENDIF} DoubleBuffered := True; //SetSubComponent(True); FAllTabsExtent := 0; FFirstVisibleTab := 0; FFullyVisibleTabsExtent := 0; FInvisibleTabsExtent := 0; FLeftScrollButton := TKSpeedButton.Create(Self); FLeftScrollButton.FocusRect := False; FLeftScrollButton.Visible := False; FLeftScrollButton.OnClick := LeftScrollButtonClick; FLeftScrollButton.Parent := Self; FMaxFirstVisibleTab := 0; FMouseIndex := -1; FMouseInCloseButton := False; FPageControl := nil; FOptions := TKTabPanelOptions.Create(Self); FRightScrollButton := TKSpeedButton.Create(Self); FRightScrollButton.FocusRect := False; FRightScrollButton.Visible := False; FRightScrollButton.OnClick := RightScrollButtonClick; FRightScrollButton.Parent := Self; FScrolling := False; FVisibleTabsExtent := 0; UpdateTabPanel; end; destructor TKTabPanel.Destroy; begin FOptions.Free; inherited; end; procedure TKTabPanel.CMCursorChanged(var Message: TLMessage); begin {$IFDEF FPC} SetTempCursor(Screen.Cursors[Cursor]); {$ELSE} Windows.SetCursor(Screen.Cursors[Cursor]); {$ENDIF} end; function TKTabPanel.GetTabInfo(ACanvas: TCanvas; ATabIndex: Integer; out Info: TKTabInfo): Boolean; var Page: TKTabSheet; ImageIndex: Integer; begin if FPageControl <> nil then begin Page := FPageControl.Pages[ATabIndex]; ImageIndex := FPageControl.GetImageIndex(ATabIndex); if (FPageControl.Images <> nil) and (ImageIndex >= 0) and (ImageIndex < FPageControl.Images.Count) then begin Info.ImageWidth := FPageControl.Images.Width; Info.ImageHeight := FPageControl.Images.Height; end else begin Info.ImageWidth := 0; Info.ImageHeight := 0; end; if Info.ImageWidth <> 0 then Info.ImagePadding := FOptions.Padding else Info.ImagePadding := 0; if FPageControl.TabWidth <> 0 then Info.TextWidth := FPageControl.TabWidth else Info.TextWidth := ACanvas.TextWidth(Page.Caption); if Info.TextWidth <> 0 then Info.TextPadding := FOptions.Padding else Info.TextPadding := 0; if (FPageControl.Images <> nil) and (FOptions.CloseButtonIndex >= 0) and (FOptions.CloseButtonIndex < FPageControl.Images.Count) then begin Info.CloseWidth := FPageControl.Images.Width; Info.CloseHeight := FPageControl.Images.Height; end else begin Info.CloseHeight := 0; Info.CloseWidth := 0; end; Info.LeftPadding := 2 * FOptions.Padding; Info.RightPadding := 2 * FOptions.Padding; Info.TabExtent := Info.LeftPadding + Info.ImageWidth + Info.ImagePadding + Info.TextWidth + Info.TextPadding + Info.CloseWidth + Info.RightPadding; Result := True; end else Result := False; end; function TKTabPanel.GetTabPaintInfo(ACanvas: TCanvas; ATabIndex: Integer; out Info: TKTabPaintInfo): Boolean; var I, Extent, Limit, ScrollButtonExtent: Integer; TI: TKTabInfo; begin Result := False; if (FPageControl <> nil) and (ATabIndex >= 0) and (ATabIndex < FPageControl.PageCount) then begin if FAllTabsExtent > Width then begin ScrollButtonExtent := 2 * FOptions.Padding + FOptions.ScrollButtonSize; Extent := ScrollButtonExtent - FInvisibleTabsExtent; Limit := Width - ScrollButtonExtent; end else begin Extent := -FInvisibleTabsExtent; Limit := Width; end; I := 0; while I <= ATabIndex do begin GetTabInfo(ACanvas, I, TI); if (I = ATabIndex) and (Extent < Limit) then begin Info.TabRect := Rect(Extent, 0, Extent + TI.TabExtent, Height); Info.ImageRect.TopLeft := Point(Extent + TI.LeftPadding, (Height - TI.ImageHeight) div 2); Info.ImageRect.BottomRight := Point(Info.ImageRect.Left + TI.ImageWidth, Info.ImageRect.Top + TI.ImageHeight); Info.TextRect.TopLeft := Point(Extent + TI.LeftPadding + TI.ImageWidth + TI.ImagePadding, 0); Info.TextRect.BottomRight := Point(Info.TextRect.Left + TI.TextWidth, Info.TextRect.Top + Height); Info.CloseRect.TopLeft := Point(Extent + TI.LeftPadding + TI.ImageWidth + TI.ImagePadding + TI.TextWidth + TI.TextPadding, (Height - TI.CloseHeight) div 2); Info.CloseRect.BottomRight := Point(Info.CloseRect.Left + TI.CloseWidth, Info.CloseRect.Top + TI.CloseHeight); Result := True; end; Inc(Extent, TI.TabExtent); Inc(I); end; end; end; function TKTabPanel.GetTabs(Index: Integer): TKString; begin if (FPageControl <> nil) and (Index >= 0) and (Index < FPageControl.PageCount) then Result := FPageControl.Pages[Index].Caption else Result := ''; end; function TKTabPanel.IndexOfTabAt(X, Y: Integer): Integer; var I: Integer; Info: TKTabPaintInfo; Pt: TPoint; begin Result := -1; if FPageControl <> nil then begin Pt := Point(X, Y); for I := 0 to FPageControl.PageCount - 1 do if getTabPaintInfo(Canvas, I, Info) then if PtInRect(Info.TabRect, Pt) then begin Result := I; Exit; end; end; end; procedure TKTabPanel.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_ESCAPE) and MouseCapture then begin Cursor := crDefault; MouseCapture := False; end; end; procedure TKTabPanel.LeftScrollButtonClick(Sender: TObject); begin FirstVisibleTab := FirstVisibleTab - 1; end; procedure TKTabPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; Info: TKTabPaintInfo; MousePt: TPoint; begin inherited; FPageToClose := -1; FDraggedTab := -1; FLastDraggedTab := -1; if (FPageControl <> nil) and (Button = mbLeft) then begin MouseCapture := True; MousePt := Point(X, Y); for I := 0 to FPageControl.PageCount - 1 do if getTabPaintInfo(Canvas, I, Info) then begin {if I > FLastFullyVisibleTab then FirstVisibleTab := FFirstVisibleTab + I - FLastFullyVisibleTab;} if PtInRect(Info.CloseRect, MousePt) then begin FPageToClose := I; Break; end else if PtInRect(Info.TabRect, MousePt) then begin if toDrag in FOptions.Options then begin FDraggedTab := I; FDraggedPos := MousePt; if CanFocus then SetFocus; end; FPageControl.DoTabClick(I); FPageControl.ActivePageIndex := I; Break; end; end; end; end; procedure TKTabPanel.MouseFormLeave; var MousePt: TPoint; begin inherited; MousePt := ScreenToClient(Mouse.CursorPos); MouseOver([], MousePt.X, MousePt.Y); end; procedure TKTabPanel.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if MouseCapture then MouseMoveCaptured(Shift, X, Y) else MouseOver(Shift, X, Y); end; procedure TKTabPanel.MouseMoveCaptured(Shift: TShiftState; X, Y: Integer); var I: Integer; MousePt: TPoint; R: TRect; Info: TKTabPaintInfo; begin if FPageControl <> nil then begin if FDraggedTab >= 0 then begin MousePt := Point(X, Y); R := Rect(FDraggedPos.X - 5, FDraggedPos.Y - 5, FDraggedPos.X + 5, FDraggedPos.Y + 5); if not PtInRect(R, MousePt) then begin Cursor := crDrag; // move the tab while dragging for I := 0 to FPageControl.PageCount - 1 do if getTabPaintInfo(Canvas, I, Info) then if PtInRect(Info.TabRect, MousePt) then if I = FDraggedTab then FLastDraggedTab := -1 else if FLastDraggedTab < 0 then begin FPageControl.MovePage(FDraggedTab, I); FLastDraggedTab := FDraggedTab; FDraggedTab := I; Exit; end; end; // allow undock outside of tab area + some margin if toDragUndock in FOptions.Options then begin R := ClientRect; InflateRect(R, 50, 50); if not PtInRect(R, MousePt) then begin Cursor := crDefault; MouseCapture := False; if FPageControl.Pages[FDraggedTab].ControlCount > 0 then FPageControl.Pages[FDraggedTab].Controls[0].BeginDrag(True, 0); end; end; end; end; end; procedure TKTabPanel.MouseOver(Shift: TShiftState; X, Y: Integer); var I, NewMouseIndex: Integer; NewMouseInCloseButton: Boolean; MousePt: TPoint; Info, OldInfo: TKTabPaintInfo; begin if FPageControl <> nil then begin NewMouseIndex := -1; MousePt := Point(X, Y); for I := 0 to FPageControl.PageCount - 1 do if getTabPaintInfo(Canvas, I, Info) then begin if PtInRect(Info.TabRect, MousePt) then begin NewMouseIndex := I; Break; end end; if NewMouseIndex <> FMouseIndex then begin if FMouseIndex >= 0 then if getTabPaintInfo(Canvas, FMouseIndex, OldInfo) then InvalidateRectArea(OldInfo.TabRect); FMouseIndex := NewMouseIndex; if FMouseIndex >= 0 then InvalidateRectArea(Info.TabRect); end else if NewMouseIndex >= 0 then begin NewMouseInCloseButton := PtInRect(Info.CloseRect, MousePt); if NewMouseInCloseButton <> FMouseInCloseButton then begin FMouseInCloseButton := NewMouseInCloseButton; InvalidateRectArea(Info.CloseRect); end; end; end; end; procedure TKTabPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; Info: TKTabPaintInfo; begin inherited; if (FPageControl <> nil) and (Button = mbLeft) and MouseCapture then begin MouseCapture := False; Cursor := crDefault; for I := 0 to FPageControl.PageCount - 1 do if getTabPaintInfo(Canvas, I, Info) then begin if (FPageToClose = I) and PtInRect(Info.CloseRect, Point(X, Y)) then begin FPageControl.DoTabClose(I); Break; end end; end; end; procedure TKTabPanel.PaintAfterTabs(ACanvas: TCanvas; ALastTabIndex: Integer); var ScrollButtonExtent: Integer; R: TRect; T, B, L: Integer; begin if FPageControl <> nil then begin ACanvas.Pen.Color := FOptions.Colors.TabBorder; T := 0; B := 0; L := 0; case FPageControl.TabPosition of tpTop: begin T := 0; B := Height - 1; L := B; end; tpBottom: begin T := 1; B := Height; L := 0; end; tpLeft: begin { TODO } T := 0; B := Height - 1; L := B; end; tpRight: begin { TODO } T := 1; B := Height; L := 0; end; end; with ACanvas do begin if FAllTabsExtent <= Width then begin MoveTo(FAllTabsExtent, L); LineTo(Width, L); end else begin // paint background for scroll buttons // this will erase part of the last visible tab Brush.Color := Color; ScrollButtonExtent := 2 * FOptions.Padding + FOptions.ScrollButtonSize; R := Rect(0, T, ScrollButtonExtent, B); FillRect(R); MoveTo(R.Left, L); LineTo(R.Right, L); R := Rect(Width - ScrollButtonExtent, T, Width, B); FillRect(R); if FFullyVisibleTabsExtent = 0 then MoveTo(R.Left, L) else MoveTo(FFullyVisibleTabsExtent + ScrollButtonExtent, L); LineTo(R.Right, L); end; end; end; end; function TKTabPanel.PaintTab(ACanvas: TCanvas; ATabIndex: Integer): Boolean; var Info: TKTabPaintInfo; State: TKTabState; MousePt: TPoint; begin Result := getTabPaintInfo(ACanvas, ATabIndex, Info); if Result then begin MousePt := ScreenToClient(Mouse.CursorPos); if FPageControl.ActivePageIndex = ATabIndex then State := tsSelected else if not MouseCapture and FPageControl.HotTrack and PtInRect(Info.TabRect, MousePt) then State := tsHot else State := tsNormal; if not IsRectEmpty(Info.TabRect) then with ACanvas do begin PaintTabBackground(ACanvas, Info.TabRect, State); if not IsRectEmpty(Info.ImageRect) then PaintTabImage(ACanvas, Info.ImageRect, ATabIndex); if not IsRectEmpty(Info.TextRect) then PaintTabText(ACanvas, Info.TextRect, ATabIndex, State); if not IsRectEmpty(Info.CloseRect) then PaintTabCloseButton(ACanvas, Info.CloseRect); end; end; end; procedure TKTabPanel.PaintTabBackground(ACanvas: TCanvas; const ARect: TRect; AState: TKTabState); var R: TRect; Descent: Integer; StartColor, EndColor: TColor; begin if (FPageControl <> nil) and not IsRectEmpty(ARect) then with ACanvas do begin Pen.Color := FOptions.Colors.TabBorder; R := ARect; if AState = tsSelected then Descent := 1 else Descent := 2; case FPageControl.TabPosition of tpTop: begin MoveTo(R.Left, R.Bottom - 1); LineTo(R.Left, R.Top + 2 + Descent); LineTo(R.Left + 2, R.Top + Descent); LineTo(R.Right - 2, R.Top + Descent); LineTo(R.Right, R.Top + 2 + Descent); LineTo(R.Right, R.Bottom - 1); if AState <> tsSelected then LineTo(R.Left, R.Bottom - 1); R := Rect(R.Left + 2, R.Top + 2 + Descent, R.Right - 1, R.Bottom); end; tpBottom: begin MoveTo(R.Left, R.Top); LineTo(R.Left, R.Bottom - 2 - Descent); LineTo(R.Left + 2, R.Bottom - Descent); LineTo(R.Right - 2, R.Bottom - Descent); LineTo(R.Right, R.Bottom - 2 - Descent); LineTo(R.Right, R.Top); if AState <> tsSelected then LineTo(R.Left, R.Top); R := Rect(R.Left + 2, R.Top + 1, R.Right - 1, R.Bottom - 1 - Descent); end; tpLeft: {TODO}; tpRight: {TODO}; end; case AState of tsHot: begin StartColor := FOptions.Colors.HotTop; EndColor := FOptions.Colors.HotBottom; end; tsSelected: begin StartColor := FOptions.Colors.SelectedTop; EndColor := FOptions.Colors.SelectedBottom; end else StartColor := FOptions.Colors.NormalTop; EndColor := FOptions.Colors.NormalBottom; end; if toBrightTopColors in FOptions.Options then EndColor := BrightColor(ColorToRGB(StartColor), 0.75, bsOfTop); DrawGradientRect(ACanvas, R, ColorToRGB(StartColor), ColorToRGB(EndColor), 10, False); // simulate rounded corners Canvas.Pixels[R.Left, R.Top] := clBtnFace; Canvas.Pixels[R.Right - 1, R.Top] := clBtnFace; end; end; procedure TKTabPanel.PaintTabCloseButton(ACanvas: TCanvas; const ARect: TRect); var Images: TImageList; MousePt: TPoint; begin if (FPageControl <> nil) and not IsRectEmpty(ARect) then with ACanvas do begin MousePt := ScreenToClient(Mouse.CursorPos); if (not MouseCapture and PtInRect(ARect, MousePt)) or (FPageControl.DisabledImages = nil) then Images := FPageControl.Images else Images := FPageControl.DisabledImages; Images.Draw(ACanvas, ARect.Left, ARect.Top, FOptions.CloseButtonIndex); end; end; procedure TKTabPanel.PaintTabText(ACanvas: TCanvas; const ARect: TRect; ATabIndex: Integer; AState: TKTabState); var TextBox: TKTextBox; begin if (FPageControl <> nil) and (ATabIndex >= 0) and (ATabIndex < FPageControl.PageCount) and not IsRectEmpty(ARect) then with ACanvas do begin TextBox := TKTextBox.Create; try if AState = tsSelected then Font.Color := FOptions.Colors.SelectedText else Font.Color := FOptions.Colors.NormalText; TextBox.HAlign := halLeft; TextBox.VAlign := valCenter; TextBox.Text := FPageControl.Pages[ATabIndex].Caption; TextBox.Draw(ACanvas, ARect); finally TextBox.Free; end; end end; procedure TKTabPanel.PaintTabImage(ACanvas: TCanvas; const ARect: TRect; ATabIndex: Integer); begin if (FPageControl <> nil) and (ATabIndex >= 0) and (ATabIndex < FPageControl.PageCount) and not IsRectEmpty(ARect) then begin FPageControl.Images.Draw(ACanvas, ARect.Left, ARect.Top, FPageControl.GetImageIndex(ATabIndex)); end end; procedure TKTabPanel.PaintToCanvas(ACanvas: TCanvas); var I: Integer; begin inherited; if FPageControl <> nil then with ACanvas do begin I := 0; while (I < FPageControl.PageCount) and PaintTab(ACanvas, I) do Inc(I); PaintAfterTabs(ACanvas, I - 1); end; end; procedure TKTabPanel.RightScrollButtonClick(Sender: TObject); begin FirstVisibleTab := FirstVisibleTab + 1; end; procedure TKTabPanel.SetFirstVisibleTab(Value: Integer); begin Value := MinMax(Value, 0, FMaxFirstVisibleTab); if Value <> FFirstVisibleTab then begin FScrolling := True; try FFirstVisibleTab := Value; UpdateTabPanel; finally FScrolling := False; end; end; end; procedure TKTabPanel.SetPageControl(const Value: TKCustomPageControl); begin if Value <> FPageControl then begin FPageControl := Value; UpdateTabPanel; end; end; procedure TKTabPanel.SetOptions(const Value: TKTabPanelOptions); begin FOptions.Assign(Value); end; function TKTabPanel.TabRect(AIndex: Integer): TRect; var Info: TKTabPaintInfo; begin Result := CreateEmptyRect; if FPageControl <> nil then if getTabPaintInfo(Canvas, AIndex, Info) then Result := Info.TabRect; end; procedure TKTabPanel.UpdateScrollRange; var R: TRect; begin UpdateTabPanelLayout(Canvas); if FAllTabsExtent > Width then begin R.TopLeft := Point(FOptions.Padding, (Height - FOptions.ScrollButtonSize) div 2); R.BottomRight := Point(R.Left + FOptions.ScrollButtonSize, R.Top + FOptions.ScrollButtonSize); FLeftScrollButton.BoundsRect := R; FLeftScrollButton.Visible := True; R.TopLeft := Point(Width - FOptions.Padding - FOptions.ScrollButtonSize, (Height - FOptions.ScrollButtonSize) div 2); R.BottomRight := Point(R.Left + FOptions.ScrollButtonSize, R.Top + FOptions.ScrollButtonSize); FRightScrollButton.BoundsRect := R; FRightScrollButton.Visible := True; end else begin FLeftScrollButton.Visible := False; FRightScrollButton.Visible := False; end; Invalidate; end; procedure TKTabPanel.UpdateSize; begin inherited; UpdateScrollRange; end; procedure TKTabPanel.UpdateTabPanel; begin if FPageControl <> nil then begin FLeftScrollButton.Images := FPageControl.Images; FRightScrollButton.Images := FPageControl.Images; end; FLeftScrollButton.ImageIndex := FOptions.LeftButtonIndex; FRightScrollButton.ImageIndex := FOptions.RightButtonIndex; UpdateScrollRange; end; procedure TKTabPanel.UpdateTabPanelLayout(ACanvas: TCanvas); var I, ScrollButtonExtent, ActivePageExtent, ActivePagePos: Integer; MaxFirstVisibleTabSet: Boolean; TI: TKTabInfo; begin FMouseIndex := -1; FMouseInCloseButton := False; FAllTabsExtent := 0; FInvisibleTabsExtent := 0; FMaxFirstVisibleTab := 0; FLastFullyVisibleTab := 0; FVisibleTabsExtent := 0; FFullyVisibleTabsExtent := 0; if FPageControl <> nil then begin MaxFirstVisibleTabSet := False; ScrollButtonExtent := 2 * FOptions.Padding + FOptions.ScrollButtonSize; ActivePageExtent := 0; ActivePagePos := 0; // calculate extent of all tabs and initialize some helper variables for I := FPageControl.PageCount - 1 downto 0 do if GetTabInfo(ACanvas, I, TI) then begin Inc(FAllTabsExtent, TI.TabExtent); if not MaxFirstVisibleTabSet and (FAllTabsExtent > Width - 2 * ScrollButtonExtent) then begin FMaxFirstVisibleTab := I + 1; MaxFirstVisibleTabSet := True; end; if I = FPageControl.ActivePageIndex then ActivePageExtent := TI.TabExtent else if I < FPageControl.ActivePageIndex then Inc(ActivePagePos, TI.TabExtent); end; if FAllTabsExtent <= Width then begin FTabAreaExtent := Width; FMaxFirstVisibleTab := 0; end else FTabAreaExtent := Width - 2 * ScrollButtonExtent; // limit important tab indexes FMaxFirstVisibleTab := MinMax(FMaxFirstVisibleTab, 0, FPageControl.PageCount - 1); FFirstVisibleTab := MinMax(FFirstVisibleTab, 0, FMaxFirstVisibleTab); // ensure active page is visible if hidden to the left, do only when FirstVisibleTab is not being set explictly if not FScrolling then begin if (FPageControl.ActivePageIndex >= 0) and (FPageControl.ActivePageIndex < FFirstVisibleTab) then FFirstVisibleTab := FPageControl.ActivePageIndex; end; // calculate invisible tabs to the left for I := 0 to FFirstVisibleTab - 1 do if GetTabInfo(ACanvas, I, TI) then Inc(FInvisibleTabsExtent, TI.TabExtent); // ensure active page is visible if hidden to the right, do only when FirstVisibleTab is not being set explictly if not FScrolling then begin while (FFirstVisibleTab < FMaxFirstVisibleTab) and (FTabAreaExtent > ActivePageExtent) and (ActivePagePos + ActivePageExtent - FInvisibleTabsExtent > FTabAreaExtent) do begin if GetTabInfo(ACanvas, FFirstVisibleTab, TI) then Inc(FinvisibleTabsExtent, TI.TabExtent); Inc(FFirstVisibleTab); end; end; // calculate remaining tabs, including invisible ones to the right for I := FFirstVisibleTab to FPageControl.PageCount - 1 do if GetTabInfo(ACanvas, I, TI) then begin Inc(FVisibleTabsExtent, TI.TabExtent); if FVisibleTabsExtent < FTabAreaExtent then begin FFullyVisibleTabsExtent := FVisibleTabsExtent; FLastFullyVisibleTab := I; end; end; end; end; { TKTabSheet } constructor TKTabSheet.Create(AOwner: TComponent); begin inherited Create(AOwner); Align := alClient; {$IFDEF FPC} ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csDesignFixedBounds, csDoubleClicks, csDesignInteractive]; {$ELSE} ControlStyle := [csAcceptsControls, csOpaque]; {$ENDIF} Visible := False; FHighlighted := False; end; procedure TKTabSheet.CMTextChanged(var Message: TLMessage); begin if FPageControl <> nil then FPageControl.UpdateTabPanel; end; procedure TKTabSheet.WMEraseBkgnd(var Message: TLMEraseBkgnd); begin {$IFDEF FPC} if Message.DC <> 0 then EraseBackground(Message.DC); {$ELSE} inherited; {$ENDIF} end; procedure TKTabSheet.WMPaint(var Msg: TLMPaint); {$IFDEF FPC} var Notebook: TKCustomPageControl; {$ENDIF} begin {$IFDEF FPC} if Parent is TKCustomPageControl then begin NoteBook := TKCustomPageControl(Parent); if (NoteBook.ActivePageIndex >= 0) and (NoteBook.Pages[NoteBook.ActivePageIndex] = Self) then inherited; end else {$ENDIF} inherited; end; procedure TKTabSheet.CMShowingChanged(var Message: TLMessage); begin inherited; if Showing then begin try DoShow except Application.HandleException(Self); end; end else if not Showing then begin try DoHide; except Application.HandleException(Self); end; end; end; destructor TKTabSheet.Destroy; begin if FPageControl <> nil then begin if FPageControl.FUndockingPage = Self then FPageControl.FUndockingPage := nil; FPageControl.RemovePage(Self); end; inherited Destroy; end; procedure TKTabSheet.DoHide; begin if Assigned(FOnHide) then FOnHide(Self); end; procedure TKTabSheet.DoShow; begin if Assigned(FOnShow) then FOnShow(Self); end; function TKTabSheet.GetPageIndex: Integer; begin if FPageControl <> nil then Result := FPageControl.FPages.IndexOf(Self) else Result := -1; end; procedure TKTabSheet.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params.WindowClass do style := style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TKTabSheet.ReadState(Reader: TReader); begin inherited ReadState(Reader); if Reader.Parent is TKCustomPageControl then PageControl := TKCustomPageControl(Reader.Parent); end; procedure TKTabSheet.SetHighlighted(Value: Boolean); begin if Value <> FHighLighted then begin FHighlighted := Value; if FPageControl <> nil then FPageControl.UpdateTabPanel; end; end; procedure TKTabSheet.SetImageIndex(Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; if FPageControl <> nil then FPageControl.UpdateTabPanel; end; end; procedure TKTabSheet.SetPageControl(APageControl: TKCustomPageControl); begin if FPageControl <> APageControl then begin if FPageControl <> nil then FPageControl.RemovePage(Self); FPageControl := APageControl; if FPageControl <> nil then FPageControl.InsertPage(Self); end; end; procedure TKTabSheet.SetPageIndex(Value: Integer); begin if FPageControl <> nil then begin Value := MinMax(Value, 0, FPageControl.PageCount - 1); FPageControl.MovePage(PageIndex, Value); end; end; { TKTabSheets } function TKTabSheets.Add(AItem: TKTabSheet): Integer; begin Result := inherited Add(AItem); end; function TKTabSheets.GetItem(Index: Integer): TKTabSheet; begin Result := TKTabSheet(inherited GetItem(Index)); end; function TKTabSheets.IndexOf(AItem: TKTabSheet): Integer; begin Result := inherited IndexOf(AItem); end; procedure TKTabSheets.SetItem(Index: Integer; const Value: TKTabSheet); begin inherited SetItem(Index, Value); end; { TKCustomPageControl } constructor TKCustomPageControl.Create(AOwner: TComponent); begin inherited Create(AOwner); BorderStyle := bsNone; ControlStyle := ControlStyle + [csOpaque, csDoubleClicks]; {$IFDEF FPC} ControlStyle := ControlStyle + [csDesignInteractive]; {$ENDIF} Width := 400; Height := 300; FActivateNewDocked := True; FActivePageIndex := -1; FDeletingPage := False; FDisabledImages := nil; FHotTrack := True; FImages := nil; FLoadedActivePageIndex := -1; FPages := TKTabSheets.Create; FPages.OwnsObjects := False; FTabHeight := cDefaultTabHeight; FTabPosition := cDefaultTabPosition; FTabWidth := cDefaultTabWidth; FOnChange := nil; FOnChanging := nil; FOnGetImageIndex := nil; FOnTabClick := nil; FTabPanel := TKTabPanel.Create(nil); UpdateTabPanelPosition; end; destructor TKCustomPageControl.Destroy; begin FreeAndNil(FTabPanel); while FPages.Count > 0 do FPages[0].PageControl := nil; FPages.Free; inherited Destroy; end; function TKCustomPageControl.AddPage(AOwner: TComponent): TKTabSheet; begin Result := TKTabSheet.Create(AOwner); Result.PageControl := Self; end; procedure TKCustomPageControl.DeletePage(AIndex: Integer); begin FreePage(ReleasePage(AIndex)); end; procedure TKCustomPageControl.DeletePage(APage: TKTabSheet); begin FreePage(ReleasePage(FPages.IndexOf(APage))); end; function TKCustomPageControl.CanChange: Boolean; begin Result := True; if Assigned(FOnChanging) and not (csDestroying in ComponentState) then FOnChanging(Self, Result); end; procedure TKCustomPageControl.Change; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TKCustomPageControl.ChangeActivePage(Page: TKTabSheet); var ParentForm: TCustomForm; CurPage: TKTabSheet; Index: Integer; begin Index := FPages.IndexOf(Page); if (Index >= 0) and (Index <> FActivePageIndex) and CanChange then begin CurPage := ActivePage; if CurPage <> nil then CurPage.Visible := False; FActivePageIndex := Index; CurPage := ActivePage; if CurPage <> nil then begin CurPage.BringToFront; CurPage.Visible := True; ParentForm := GetParentForm(Self); if (ParentForm <> nil) and (CurPage <> nil) and (ParentForm.ActiveControl = CurPage) then begin CurPage.SelectFirst; if Page.CanFocus then ParentForm.ActiveControl := Page else ParentForm.ActiveControl := Self; end; end; Change; UpdateAllDesignerFlags; UpdateTabPanel; end; end; procedure TKCustomPageControl.CMDialogKey(var Message: TCMDialogKey); begin if (Focused {$IFnDEF FPC} or IsChild(Handle, GetFocus) {$ENDIF}) and (Message.CharCode = VK_TAB) and (GetKeyState(VK_CONTROL) < 0) then begin SelectNextPage(GetKeyState(VK_SHIFT) >= 0); Message.Result := 1; end else inherited; end; {$IFDEF FPC} procedure TKCustomPageControl.CMDesignHitTest(var Message: TCMDesignHitTest); begin Message.Result := 1; end; {$ELSE} procedure TKCustomPageControl.CMDockClient(var Message: TCMDockClient); var DockCtl: TControl; I: Integer; begin with Message do begin Result := 0; DockCtl := DockSource.Control; { First, look and see if the page is already docked. If it is, then simply move the page index to the end } for I := 0 to PageCount - 1 do begin if DockCtl.Parent = Pages[I] then begin { We did find it; just move the page to the end } Pages[I].PageIndex := PageCount - 1; Exit; end; end; FNewDockSheet := TKTabSheet.Create(Self); try try if DockCtl is TCustomForm then FNewDockSheet.Caption := TCustomForm(DockCtl).Caption; FNewDockSheet.PageControl := Self; DockCtl.Dock(Self, DockSource.DockRect); except FNewDockSheet.Free; raise; end; if DockCtl.Visible then if FActivateNewDocked then ActivePage := FNewDockSheet else UpdateTabPanel; DockCtl.Align := alClient; finally FNewDockSheet := nil; end; end; end; procedure TKCustomPageControl.CMDockNotification(var Message: TCMDockNotification); var I: Integer; S: TKString; Page: TKTabSheet; begin Page := GetPageFromDockClient(Message.Client); if Page <> nil then case Message.NotifyRec.ClientMsg of WM_SETTEXT: begin S := PChar(Message.NotifyRec.MsgLParam); // Search for first CR/LF and end string there for I := 1 to Length(S) do if CharInSetEx(S[I], [#13, #10]) then begin SetLength(S, I - 1); Break; end; Page.Caption := S; end; end; inherited; end; procedure TKCustomPageControl.CMUnDockClient(var Message: TCMUnDockClient); var Page: TKTabSheet; begin with Message do begin Result := 0; Page := GetPageFromDockClient(Client); if Page <> nil then begin FUndockingPage := Page; Client.Align := alNone; end; end; end; {$ENDIF} function TKCustomPageControl.ReleasePage(Index: Integer): TKTabSheet; var NextPage: TKTabSheet; begin Result := nil; if not FDeletingPage and (Index >= 0) and (Index < FPages.Count) then begin FDeletingPage := True; try Result := FPages[Index]; NextPage := FindNextPage(Result, True); if NextPage = Result then NextPage := nil; Result.Parent := nil; Result.PageControl := nil; FPages.Delete(Index); if (Index = FActivePageIndex) or (FActivePageIndex >= FPages.Count) then FActivePageIndex := -1; ActivePage := NextPage; UpdateTabPanel; finally FDeletingPage := False; end; end; end; procedure TKCustomPageControl.FreePage(Page: TKTabSheet); begin {$IFDEF FPC} Application.ReleaseComponent(Page); {$ELSE} Page.Free; {$ENDIF} end; procedure TKCustomPageControl.DoAddDockClient(Client: TControl; const ARect: TRect); begin if FNewDockSheet <> nil then Client.Parent := FNewDockSheet; end; procedure TKCustomPageControl.DockOver(Source: TDragDockObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var R: TRect; begin GetWindowRect(Handle, R); Source.DockRect := R; DoDockOver(Source, X, Y, State, Accept); end; procedure TKCustomPageControl.DoRemoveDockClient(Client: TControl); begin if (FUndockingPage <> nil) and not (csDestroying in ComponentState) then begin RemovePage(FUndockingPage); FUndockingPage := nil; end; end; procedure TKCustomPageControl.DoTabClick(AIndex: Integer); begin if Assigned(FOnTabClick) then FOnTabClick(Self, AIndex); end; procedure TKCustomPageControl.DoTabClose(AIndex: Integer); var CanClose: Boolean; begin CanClose := True; if Assigned(FOnTabCloseQuery) then FOnTabCloseQuery(Self, AIndex, CanClose); if CanClose then DeletePage(AIndex); end; function TKCustomPageControl.FindNextPage(CurPage: TKTabSheet; GoForward: Boolean): TKTabSheet; var I, StartIndex: Integer; begin if FPages.Count <> 0 then begin StartIndex := FPages.IndexOf(CurPage); if StartIndex = -1 then if GoForward then StartIndex := FPages.Count - 1 else StartIndex := 0; I := StartIndex; repeat if GoForward then begin Inc(I); if I = FPages.Count then I := 0; end else begin if I = 0 then I := FPages.Count; Dec(I); end; Result := FPages[I]; if Result <> nil then Exit; until I = StartIndex; end; Result := nil; end; function TKCustomPageControl.GetActivePage: TKTabSheet; begin if FActivePageIndex >= 0 then Result := FPages[FActivePageIndex] else Result := nil; end; procedure TKCustomPageControl.GetChildren(Proc: TGetChildProc; Root: TComponent); var I: Integer; begin for I := 0 to FPages.Count - 1 do Proc(TComponent(FPages[I])); end; function TKCustomPageControl.GetImageIndex(TabIndex: Integer): Integer; begin Result := FPages[TabIndex].ImageIndex; if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, TabIndex, Result); end; function TKCustomPageControl.GetPageFromDockClient(Client: TControl): TKTabSheet; var I: Integer; begin Result := nil; for I := 0 to PageCount - 1 do begin if (Client.Parent = Pages[I]) and (Client.HostDockSite = Self) then begin Result := Pages[I]; Exit; end; end; end; function TKCustomPageControl.GetPage(Index: Integer): TKTabSheet; begin Result := TKTabSheet(FPages[Index]); end; function TKCustomPageControl.GetPageCount: Integer; begin Result := FPages.Count; end; procedure TKCustomPageControl.GetSiteInfo(Client: TControl; var InfluenceRect: TRect; MousePos: TPoint; var CanDock: Boolean); begin CanDock := GetPageFromDockClient(Client) = nil; inherited GetSiteInfo(Client, InfluenceRect, MousePos, CanDock); end; function TKCustomPageControl.GetTabPanelOptions: TKTabPanelOptions; begin if FTabPanel <> nil then Result := FTabPanel.Options else Result := nil; end; function TKCustomPageControl.IndexOfTabAt(X, Y: Integer): Integer; begin if FTabPanel <> nil then Result := FTabPanel.IndexOfTabAt(X, Y) else Result := -1; end; procedure TKCustomPageControl.InsertPage(Page: TKTabSheet); begin FPages.Add(Page); Page.PageControl := Self; Page.Parent := Self; end; procedure TKCustomPageControl.Loaded; begin inherited; ActivePageIndex := FLoadedActivePageIndex; end; {$IFDEF FPC} procedure TKCustomPageControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MousePt: TPoint; Form: TCustomForm; begin if (csDesigning in ComponentState) and (FTabPanel <> nil) then begin MousePt := Point(X,Y); if PtInRect(FTabPanel.BoundsRect, MousePt) then begin MousePt := FTabPanel.ScreenToClient(ClientToScreen(MousePt)); FTabPanel.MouseDown(Button, Shift, MousePt.X, MousePt.Y); Form := GetParentForm(Self); if Form <> nil then Form.Designer.SelectOnlyThisComponent(Self); end else inherited; end else inherited; end; {$ENDIF} procedure TKCustomPageControl.MovePage(CurIndex, NewIndex: Integer); begin FPages.Move(CurIndex, NewIndex); if CurIndex = FActivePageIndex then FActivePageIndex := NewIndex else if NewIndex = FActivePageIndex then FActivePageIndex := CurIndex; UpdateTabPanel; end; procedure TKCustomPageControl.PaintToCanvas(ACanvas: TCanvas); begin if FPages.Count = 0 then ACanvas.FillRect(ClientRect); end; procedure TKCustomPageControl.RemovePage(Page: TKTabSheet); begin ReleasePage(FPages.IndexOf(Page)); end; procedure TKCustomPageControl.SelectNextPage(GoForward: Boolean); var Page: TKTabSheet; begin Page := FindNextPage(ActivePage, GoForward); if (Page <> nil) and (Page <> ActivePage) then ActivePage := Page; end; procedure TKCustomPageControl.SetActivePage(Page: TKTabSheet); begin if (Page <> nil) and (Page.PageControl <> Self) then Exit; ChangeActivePage(Page); end; procedure TKCustomPageControl.SetActivePageIndex(const Value: Integer); begin if csLoading in ComponentState then FLoadedActivePageIndex := Value else if (Value >= 0) and (Value < PageCount) then ActivePage := Pages[Value] else ActivePage := nil; end; procedure TKCustomPageControl.SetChildOrder(Child: TComponent; Order: Integer); begin TKTabSheet(Child).PageIndex := Order; end; procedure TKCustomPageControl.SetDisabledImages(const Value: TImageList); begin if FDisabledImages <> Value then begin FDisabledImages := Value; UpdateTabPanel; end; end; procedure TKCustomPageControl.SetHotTrack(const Value: Boolean); begin if Value <> FHotTrack then begin FHotTrack := Value; UpdateTabPanel; end; end; procedure TKCustomPageControl.SetImages(const Value: TImageList); begin if FImages <> Value then begin FImages := Value; UpdateTabPanel; end; end; procedure TKCustomPageControl.SetTabHeight(const Value: Integer); begin if Value <> FTabHeight then begin FTabHeight := Value; UpdateTabPanelPosition; end; end; procedure TKCustomPageControl.SetTabPanel(const Value: TKTabPanel); begin FTabPanel.Assign(Value); UpdateTabPanelPosition; end; procedure TKCustomPageControl.SetTabPanelOptions(const Value: TKTabPanelOptions); begin if FTabPanel <> nil then FTabPanel.Options := Value; end; procedure TKCustomPageControl.SetTabPosition(Value: TTabPosition); begin // these not supported yet if Value in [tpLeft, tpRight] then Exit; if Value <> FTabPosition then begin FTabPosition := Value; UpdateTabPanelPosition; end; end; procedure TKCustomPageControl.SetTabWidth(const Value: Integer); begin if Value <> FTabWidth then begin FTabWidth := Value; UpdateTabPanel; end; end; procedure TKCustomPageControl.ShowControl(AControl: TControl); begin if (AControl is TKTabSheet) and (TKTabSheet(AControl).PageControl = Self) then ActivePage := TKTabSheet(AControl); inherited ShowControl(AControl); end; function TKCustomPageControl.TabRect(Index: Integer): TRect; begin if FTabPanel <> nil then Result := FTabPanel.TabRect(Index) else Result := CreateEmptyRect; end; procedure TKCustomPageControl.UpdateAllDesignerFlags; var i: integer; begin for i := 0 to FPages.Count - 1 do UpdateDesignerFlags(i); end; procedure TKCustomPageControl.UpdateDesignerFlags(APageIndex: integer); var CurPage: TKTabSheet; begin CurPage := Pages[APageIndex]; if APageIndex <> FActivePageIndex then CurPage.ControlStyle := CurPage.ControlStyle + [csNoDesignVisible] else CurPage.ControlStyle := CurPage.ControlStyle - [csNoDesignVisible]; end; procedure TKCustomPageControl.UpdateTabPanel; begin if (FTabPanel <> nil) and not (csDestroying in ComponentState) then begin FTabPanel.UpdateTabPanel; end; end; procedure TKCustomPageControl.UpdateTabPanelPosition; begin if FTabPanel <> nil then begin case FTabPosition of tpBottom: begin FTabPanel.Align := alBottom; FTabPanel.Height := FTabHeight; end; tpTop: begin FTabPanel.Align := alTop; FTabPanel.Height := FTabHeight; end; tpLeft: begin FTabPanel.Align := alLeft; FTabPanel.Width := FTabHeight; end; tpRight: begin FTabPanel.Align := alRight; FTabPanel.Width := FTabHeight; end; end; FTabPanel.PageControl := Self; FTabPanel.Parent := Self; end; end; procedure TKCustomPageControl.WMEraseBkgnd(var Msg: TLMessage); begin Msg.Result := 1; end; end.
29.020169
174
0.711189
83a3067425266e1a187af7d284cafb99158f7a53
3,916
pas
Pascal
NSToolBar/MainForm.pas
rzhghost/DelphiComponent_FMX
73c19c6ae96e37241dea05050392a5deae0c83f5
[ "MIT" ]
2
2020-03-31T08:22:53.000Z
2021-03-09T04:53:34.000Z
NSToolBar/MainForm.pas
rzhghost/DelphiComponent_FMX
73c19c6ae96e37241dea05050392a5deae0c83f5
[ "MIT" ]
null
null
null
NSToolBar/MainForm.pas
rzhghost/DelphiComponent_FMX
73c19c6ae96e37241dea05050392a5deae0c83f5
[ "MIT" ]
null
null
null
unit MainForm; { The Cocoa toolbar control is fixed to the top of the form and (for a few OS X releases now) visually integrates with the title bar. To use it, you need to create a delegate object. In this project, the CCR.CocoaToolbar unit does the the necessary. The button glyphs have been set up via Project|Deployment - after selecting 'All configurations - OS X platform' from the combo box at the top, click the button one in from the left to add new files to the outputted application 'bundle'. Once added, click on the 'Remote path' cell, press F2, and change the value from Contents\MacOS to Contents\Resources. (The glyphs I've used come from Mark James' 'Silk' set - http://www.famfamfam.com/lab/icons/silk/.) Unfortunately, one thing I have not been able to get working is the built-in toolbar customisation dialog. More exactly, if you uncomment the two lines below that call setAllowsUserCustomization and setAutosavesConfiguration, they will work up until the point the user goes to show the customisation dialog. Go to show it regardless, and the application will hang. Chris Rolliston, July 2012 http://delphifoundations.com/ } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Memo, FMX.Menus, CCR.CocoaToolbar, FMX.Controls.Presentation, FMX.ScrollBox; type TfrmNSToolbarDemo = class(TForm) memEditor: TMemo; dlgOpen: TOpenDialog; MainMenu1: TMainMenu; MenuItem1: TMenuItem; itmFileOpen: TMenuItem; procedure FormCreate(Sender: TObject); procedure itmFileOpenClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FHelper: TNSToolbarHelper; end; var frmNSToolbarDemo: TfrmNSToolbarDemo; implementation uses Macapi.AppKit; {$R *.fmx} procedure TfrmNSToolbarDemo.FormCreate(Sender: TObject); var Item: TNSToolbarHelperItem; begin itmFileOpen.ShortCut := scCommand or Ord('O'); { Both toolbar and toolbar items have textual identifiers in the Cocoa system, and my wrapper code reflects that. } FHelper := TNSToolbarHelper.Create('DocumentToolbar'); //open command - use the corresponding menu item's OnClick handler Item := FHelper.AddItem('FileOpen'); Item.SetCaptionImageAndHint('Open', 'Open.png', 'Open file'); Item.OnClick := itmFileOpenClick; //copy command - ensure the button is enabled and disabled as appropriate Item := FHelper.AddItem('EditCopy'); Item.SetCaptionImageAndHint('Copy', 'Copy.png', 'Copy selected text'); Item.OnClick := procedure (Sender: TObject) begin memEditor.CopyToClipboard; end; Item.OnUpdate := procedure (Sender: TNSToolbarHelperItem; var EnableItem: Boolean) begin EnableItem := (memEditor.SelLength > 0); end; //add a flexible spacer to right align the remaining button FHelper.AddFlexibleSpaceItem; //add a button onto the end of the toolbar Item := FHelper.AddItem('Info'); Item.SetCaptionImageAndHint('Info', 'Info.png', 'App information'); Item.OnClick := procedure (Sender: TObject) begin MessageDlg('FireMonkey NSToolbar Demo', TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], 0); end; //configure the toolbar appropriately, and attach it to the form {$IF CompilerVersion >= 24} //requires XE3 hotfix 1!!! FHelper.Toolbar.setAllowsUserCustomization(True); FHelper.Toolbar.setAutosavesConfiguration(True); {$IFEND} FHelper.Toolbar.setSizeMode(NSToolbarSizeModeSmall); FHelper.Attach(Self); end; procedure TfrmNSToolbarDemo.FormDestroy(Sender: TObject); begin FHelper.Free; end; procedure TfrmNSToolbarDemo.itmFileOpenClick(Sender: TObject); begin if dlgOpen.Execute then memEditor.Lines.LoadFromFile(dlgOpen.FileName); end; end.
35.926606
96
0.728039
f184598fda2be5c07c7e9f5941b612616728165e
2,636
pas
Pascal
windows/src/ext/jedi/jvcl/help/tools/DtxTool/Frames/FrmZipOptions.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/help/tools/DtxTool/Frames/FrmZipOptions.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/help/tools/DtxTool/Frames/FrmZipOptions.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
unit FrmZipOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, Mask, JvExMask, JvToolEdit, JvSpin, HelpBuild, HelpBuildData, ComCtrls, JvMaskEdit, JvCheckedMaskEdit, JvDatePickerEdit; type TFrameZipOptions = class(TFrame) Label1: TLabel; edtZipExec: TJvFilenameEdit; Label2: TLabel; spnMaxInZip: TJvSpinEdit; Label3: TLabel; edtDate: TJvDatePickerEdit; edtTime: TDateTimePicker; rbtDtxFilterTimestamp: TRadioButton; rbtDtxFilterAll: TRadioButton; procedure ChangeEvent(Sender: TObject); private FHelpBuilder: THelpBuilder; FSettingOptions: Boolean; procedure Init; procedure GetOptions; procedure SetOptions; protected property HelpBuilder: THelpBuilder read FHelpBuilder; public class function Build(AHelpBuilder: THelpBuilder; Client: TWinControl): TFrameZipOptions; end; implementation uses Core, FrmUnzipOptions; {$R *.dfm} //=== { TFrameZipOptions } ================================================= class function TFrameZipOptions.Build(AHelpBuilder: THelpBuilder; Client: TWinControl): TFrameZipOptions; begin Result := Self.Create(Client); // AHelpBuilder.PackageInstaller.Translate(Result); Result.FHelpBuilder := AHelpBuilder; Result.Parent := Client; Result.Align := alClient; Result.Init; end; procedure TFrameZipOptions.GetOptions; begin if FSettingOptions then Exit; HelpBuilder.Data.MaxFilesInZip := spnMaxInZip.AsInteger; HelpBuilder.Data.WZZipFileName := edtZipExec.Text; if rbtDtxFilterAll.Checked then HelpBuilder.Data.MinDateForZippedFiles := 0 else HelpBuilder.Data.MinDateForZippedFiles := Trunc(edtDate.Date) + Frac(edtTime.Time); end; procedure TFrameZipOptions.Init; begin SetOptions; end; procedure TFrameZipOptions.SetOptions; var HasTimestamp: Boolean; begin FSettingOptions := True; try spnMaxInZip.AsInteger := HelpBuilder.Data.MaxFilesInZip; edtZipExec.Text := HelpBuilder.Data.WZZipFileName; HasTimestamp := HelpBuilder.Data.MinDateForZippedFiles > 0; rbtDtxFilterAll.Checked := not HasTimestamp; rbtDtxFilterTimestamp.Checked := HasTimestamp; if HasTimestamp then begin edtDate.Date := Trunc(HelpBuilder.Data.MinDateForZippedFiles); edtTime.Time := Frac(HelpBuilder.Data.MinDateForZippedFiles); end else begin edtDate.Date := Trunc(Now); edtTime.Time := Frac(Now); end; finally FSettingOptions := False; end; end; procedure TFrameZipOptions.ChangeEvent(Sender: TObject); begin GetOptions; end; end.
24.407407
92
0.73217
61d71570cf311c76e37178ea2d3a41892b62ba35
8,438
pas
Pascal
library/fhir/tests/fhir_tests_diff.pas
atkins126/fhirserver
b6c2527f449ba76ce7c06d6b1c03be86cf4235aa
[ "BSD-3-Clause" ]
null
null
null
library/fhir/tests/fhir_tests_diff.pas
atkins126/fhirserver
b6c2527f449ba76ce7c06d6b1c03be86cf4235aa
[ "BSD-3-Clause" ]
null
null
null
library/fhir/tests/fhir_tests_diff.pas
atkins126/fhirserver
b6c2527f449ba76ce7c06d6b1c03be86cf4235aa
[ "BSD-3-Clause" ]
null
null
null
unit fhir_tests_diff; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {$I fhir.inc} interface uses SysUtils, Classes, {$IFDEF FPC} FPCUnit, TestRegistry, {$ELSE} DUnitX.TestFramework, {$ENDIF} fsl_utilities, fsl_stream, fsl_tests, fsl_http, fhir_objects, fhir_parser, fhir_factory, fhir_common, FHIR.Version.Parser, {$IFDEF FHIR2} FHIR.R2.Tests.Worker, fhir2_resources, fhir2_types, fhir2_factory, fhir2_common, {$ENDIF} {$IFDEF FHIR3} FHIR.R3.Tests.Worker, fhir3_resources, fhir3_types, fhir3_factory, fhir3_common, {$ENDIF} {$IFDEF FHIR4} fhir4_tests_worker, fhir4_resources, fhir4_types, fhir4_factory, fhir4_common, {$ENDIF} fhir_diff, fsl_xml; {$IFNDEF FPC} Type [TextFixture] TDifferenceEngineTests = Class (TObject) Private Published End; DifferenceEngineTestCaseAttribute = class (CustomTestCaseSourceAttribute) protected function GetCaseInfoArray : TestCaseInfoArray; override; end; [TextFixture] TDifferenceEngineTest = Class (TObject) private tests : TMXmlElement; function makeFactory : TFHIRFactory; function findTest(index : integer) : TMXmlElement; function parseResource(elem : TMXmlElement) : TFhirResource; function AsXml(res : TFHIRResource) : String; procedure CompareXml(name, mode : String; expected, obtained : TFHIRResource); procedure execCase(name : String; mode : String; input : TFhirResource; diff : TFhirParameters; output : TFhirResource); Published [SetupFixture] Procedure SetUp; [TearDownFixture] procedure TearDown; [DifferenceEngineTestCase] procedure DifferenceEngineTest(Name : String); protected function sizeInBytesV : cardinal; override; End; {$ENDIF} implementation {$IFNDEF FPC} { DifferenceEngineTestCaseAttribute } function DifferenceEngineTestCaseAttribute.GetCaseInfoArray: TestCaseInfoArray; var test : TMXmlElement; tests : TMXmlElement; i : integer; s : String; begin tests := TMXmlParser.ParseFile(FHIR_TESTING_FILE(4, 'patch', 'fhir-path-tests.xml'), [xpDropWhitespace]); try test := tests.document.first; i := 0; while test <> nil do begin if test.NodeType = ntElement then begin s := test.attribute['name']; SetLength(result, i+1); result[i].Name := s; SetLength(result[i].Values, 1); result[i].Values[0] := inttostr(i); inc(i); end; test := test.nextElement; end; finally tests.free; end; end; { TDifferenceEngineTest } function TDifferenceEngineTest.findTest(index : integer): TMXmlElement; var test : TMXmlElement; i : integer; begin test := tests.document.first; i := 0; while test <> nil do begin if test.NodeType = ntElement then begin if i = index then exit(test); inc(i); end; test := test.nextElement; end; result := nil; end; function TDifferenceEngineTest.makeFactory: TFHIRFactory; begin {$IFDEF FHIR2} result := TFHIRFactoryR2.Create; {$ENDIF} {$IFDEF FHIR3} result := TFHIRFactoryR3.Create; {$ENDIF} {$IFDEF FHIR4} result := TFHIRFactoryR4.Create; {$ENDIF} end; procedure TDifferenceEngineTest.DifferenceEngineTest(Name: String); var test : TMXmlElement; input, output : TFhirResource; diff : TFhirParameters; begin test := findTest(StrToInt(name)); input := parseResource(test.element('input')); try output := parseResource(test.element('output')); try diff := parseResource(test.element('diff')) as TFHIRParameters; try execCase(test.attribute['name'], test.attribute['mode'], input, diff, output); finally diff.Free; end; finally output.free; end; finally input.Free; end; end; function TDifferenceEngineTest.AsXml(res: TFHIRResource): String; var p : TFHIRXmlComposer; s : TStringStream; begin p := TFHIRXmlComposer.Create(nil, OutputStylePretty, THTTPLanguages.create('en')); try s := TStringStream.Create; try p.Compose(s, res); result := s.DataString; finally s.Free; end; finally p.Free; end; end; procedure TDifferenceEngineTest.CompareXml(name, mode : String; expected, obtained: TFHIRResource); var e, o : String; begin e := asXml(expected); o := asXml(obtained); StringToFile(e, 'c:\temp\expected.xml', TEncoding.UTF8); StringToFile(o, 'c:\temp\obtained.xml', TEncoding.UTF8); Assert.IsTrue(e = o, mode+' does not match for '+name); end; procedure TDifferenceEngineTest.execCase(name: String; mode : String; input: TFhirResource; diff: TFhirParameters; output: TFhirResource); var engine : TDifferenceEngine; delta : TFhirParametersW; outcome : TFhirResource; html : String; w : TFhirParametersW; begin if (mode = 'both') or (mode = 'reverse') then begin engine := TDifferenceEngine.Create(TTestingWorkerContext4.Use, makeFactory); try delta := engine.generateDifference(input, output, html); try compareXml(name, 'Difference', diff, delta.Resource as TFHIRParameters); finally delta.Free; end; finally engine.free; end; end; if (mode = 'both') or (mode = 'forwards') then begin engine := TDifferenceEngine.Create(TTestingWorkerContext4.Use, makeFactory); try {$IFDEF FHIR2} w := TFhirParameters2.create(diff.link); {$ELSE} {$IFDEF FHIR3} w := TFhirParameters3.create(diff.link); {$ELSE} w := TFhirParameters4.create(diff.link); {$ENDIF} {$ENDIF} try outcome := engine.applyDifference(input, w) as TFhirResource; try compareXml(name, 'Output', output, outcome); finally outcome.Free; end; finally w.free; end; finally engine.free; end; end; end; function TDifferenceEngineTest.parseResource(elem: TMXmlElement): TFhirResource; var p : TFHIRXmlParser; begin p := TFHIRXmlParser.Create(nil, THTTPLanguages.create('en')); try p.Element := elem.firstElement.Link; p.Parse; result := p.resource.Link as TFHIRResource; finally p.Free; end; end; procedure TDifferenceEngineTest.setup; begin tests := TMXmlParser.ParseFile(FHIR_TESTING_FILE(4, 'patch', 'fhir-path-tests.xml'), [xpResolveNamespaces]); end; procedure TDifferenceEngineTest.TearDown; begin tests.Free; end; initialization TDUnitX.RegisterTestFixture(TDifferenceEngineTest); TDUnitX.RegisterTestFixture(TDifferenceEngineTests); {$ENDIF} function TDifferenceEngineTest.sizeInBytesV : cardinal; begin result := inherited sizeInBytesV; inc(result, tests.sizeInBytes); end; end.
28.410774
139
0.685589
6aed8319fe4ca6184aa1e24922d9b75689988610
9,558
pas
Pascal
Source/dwsExprList.pas
caxsf/dwscript
410a0416db3d4baf984e041b9cbf5707f2f8895f
[ "Condor-1.1" ]
null
null
null
Source/dwsExprList.pas
caxsf/dwscript
410a0416db3d4baf984e041b9cbf5707f2f8895f
[ "Condor-1.1" ]
null
null
null
Source/dwsExprList.pas
caxsf/dwscript
410a0416db3d4baf984e041b9cbf5707f2f8895f
[ "Condor-1.1" ]
null
null
null
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { The Initial Developer of the Original Code is Matthias } { Ackermann. For other initial contributors, see contributors.txt } { Subsequent portions Copyright Creative IT. } { } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsExprList; {$I dws.inc} interface uses dwsUtils, dwsXPlatform, dwsDateTime, dwsErrors, dwsSymbols; type // TExprBaseListExec // PExprBaseListRec = ^TExprBaseListRec; TExprBaseListRec = record private FList : TTightList; function GetExprBase(const x : Integer) : TExprBase; inline; procedure SetExprBase(const x : Integer; expr : TExprBase); public procedure Clean; procedure Clear; function Add(expr : TExprBase) : Integer; inline; procedure Insert(idx : Integer;expr : TExprBase); inline; procedure Delete(index : Integer); procedure Assign(const src : TExprBaseListRec); property ExprBase[const x : Integer] : TExprBase read GetExprBase write SetExprBase; default; property Count : Integer read FList.FCount; end; // TExprBaseListExec // TExprBaseListExec = record private FList : PObjectTightList; FCount : Integer; FExec : TdwsExecution; FExpr : TExprBase; procedure SetListRec(const lr : TExprBaseListRec); inline; function GetExprBase(const x : Integer): TExprBase; {$IFNDEF VER200}inline;{$ENDIF} // D2009 Compiler bug workaround procedure SetExprBase(const x : Integer; expr : TExprBase); inline; function GetAsInteger(const x : Integer) : Int64; inline; procedure SetAsInteger(const x : Integer; const value : Int64); function GetAsBoolean(const x : Integer) : Boolean; inline; procedure SetAsBoolean(const x : Integer; const value : Boolean); function GetAsFloat(const x : Integer) : Double; inline; procedure SetAsFloat(const x : Integer; const value : Double); function GetAsString(const x : Integer) : String; inline; procedure SetAsString(const x : Integer; const value : String); function GetAsDataString(const x : Integer) : RawByteString; inline; procedure SetAsDataString(const x : Integer; const value : RawByteString); function GetAsFileName(const x : Integer) : String; function GetFormatSettings : TdwsFormatSettings; inline; public property ListRec : TExprBaseListRec write SetListRec; property List : PObjectTightList read FList; property Count : Integer read FCount; property Exec : TdwsExecution read FExec write FExec; property FormatSettings : TdwsFormatSettings read GetFormatSettings; property Expr : TExprBase read FExpr write FExpr; property ExprBase[const x : Integer] : TExprBase read GetExprBase write SetExprBase; default; procedure EvalAsVariant(const x : Integer; var result : Variant); inline; procedure EvalAsString(const x : Integer; var result : String); inline; function AsChar(x : Integer; default : WideChar) : WideChar; property AsInteger[const x : Integer] : Int64 read GetAsInteger write SetAsInteger; property AsBoolean[const x : Integer] : Boolean read GetAsBoolean write SetAsBoolean; property AsFloat[const x : Integer] : Double read GetAsFloat write SetAsFloat; property AsString[const x : Integer] : String read GetAsString write SetAsString; property AsDataString[const x : Integer] : RawByteString read GetAsDataString write SetAsDataString; property AsFileName[const x : Integer] : String read GetAsFileName; end; TSortedExprBaseList = class(TSortedList<TExprBase>); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ TExprBaseListRec ------------------ // ------------------ // Clean // procedure TExprBaseListRec.Clean; begin FList.Clean; end; // Clear // procedure TExprBaseListRec.Clear; begin FList.Clear; end; // Add // function TExprBaseListRec.Add(expr : TExprBase) : Integer; begin Result:=FList.Add(expr); end; // Insert // procedure TExprBaseListRec.Insert(idx : Integer;expr : TExprBase); begin FList.Insert(0, expr); end; // Delete // procedure TExprBaseListRec.Delete(index : Integer); begin FList.Delete(index); end; // Assign // procedure TExprBaseListRec.Assign(const src : TExprBaseListRec); begin FList.Assign(src.FList); end; // GetExprBase // function TExprBaseListRec.GetExprBase(const x : Integer): TExprBase; begin Result:=TExprBase(FList.List[x]); end; // SetExprBase // procedure TExprBaseListRec.SetExprBase(const x : Integer; expr : TExprBase); begin FList.List[x]:=expr; end; // ------------------ // ------------------ TExprBaseListExec ------------------ // ------------------ // SetListRec // procedure TExprBaseListExec.SetListRec(const lr : TExprBaseListRec); var p : PTightList; begin p := @lr.FList; FCount := p^.Count; FList := p^.List; end; // GetExprBase // function TExprBaseListExec.GetExprBase(const x: Integer): TExprBase; begin Result:=TExprBase(FList[x]); end; // SetExprBase // procedure TExprBaseListExec.SetExprBase(const x : Integer; expr : TExprBase); begin FList[x]:=expr; end; // GetAsInteger // function TExprBaseListExec.GetAsInteger(const x : Integer) : Int64; begin Result:=ExprBase[x].EvalAsInteger(Exec); end; // SetAsInteger // procedure TExprBaseListExec.SetAsInteger(const x : Integer; const value : Int64); begin ExprBase[x].AssignValueAsInteger(Exec, value); end; // GetAsBoolean // function TExprBaseListExec.GetAsBoolean(const x : Integer) : Boolean; begin Result:=ExprBase[x].EvalAsBoolean(Exec); end; // SetAsBoolean // procedure TExprBaseListExec.SetAsBoolean(const x : Integer; const value : Boolean); begin ExprBase[x].AssignValueAsBoolean(Exec, value); end; // GetAsFloat // function TExprBaseListExec.GetAsFloat(const x : Integer) : Double; begin Result:=ExprBase[x].EvalAsFloat(Exec); end; // SetAsFloat // procedure TExprBaseListExec.SetAsFloat(const x : Integer; const value : Double); begin ExprBase[x].AssignValueAsFloat(Exec, value); end; // GetAsString // function TExprBaseListExec.GetAsString(const x : Integer) : String; begin ExprBase[x].EvalAsString(Exec, Result); end; // SetAsString // procedure TExprBaseListExec.SetAsString(const x : Integer; const value : String); begin ExprBase[x].AssignValueAsString(Exec, value); end; // GetAsDataString // function TExprBaseListExec.GetAsDataString(const x : Integer) : RawByteString; begin ScriptStringToRawByteString(GetAsString(x), Result); end; // SetAsDataString // procedure TExprBaseListExec.SetAsDataString(const x : Integer; const value : RawByteString); begin ExprBase[x].AssignValueAsString(Exec, RawByteStringToScriptString(value)); end; // GetAsFileName // function TExprBaseListExec.GetAsFileName(const x : Integer) : String; begin Result:=Exec.ValidateFileName(AsString[x]); end; // GetFormatSettings // function TExprBaseListExec.GetFormatSettings : TdwsFormatSettings; begin Result:=Exec.FormatSettings; end; // EvalAsVariant // procedure TExprBaseListExec.EvalAsVariant(const x : Integer; var result : Variant); begin ExprBase[x].EvalAsVariant(Exec, result); end; // EvalAsString // procedure TExprBaseListExec.EvalAsString(const x : Integer; var result : String); begin ExprBase[x].EvalAsString(Exec, result); end; // AsChar // function TExprBaseListExec.AsChar(x : Integer; default : WideChar) : WideChar; var s : String; begin EvalAsString(x, s); Result := FirstWideCharOfString(s, default) end; end.
30.43949
126
0.598347
83c15dca0053c84b9b68646d258a45c00c8c75ce
14,640
pas
Pascal
src/tests/texteditor/UnitMain.pas
ddem43/pasvulkan
739b004741da322559d310bd4478c36859b75891
[ "Zlib" ]
151
2016-03-03T22:20:58.000Z
2022-03-11T03:10:17.000Z
src/tests/texteditor/UnitMain.pas
ddem43/pasvulkan
739b004741da322559d310bd4478c36859b75891
[ "Zlib" ]
22
2016-09-30T15:59:08.000Z
2021-12-29T20:00:18.000Z
src/tests/texteditor/UnitMain.pas
ddem43/pasvulkan
739b004741da322559d310bd4478c36859b75891
[ "Zlib" ]
30
2016-04-16T01:12:37.000Z
2022-03-08T10:45:11.000Z
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2018, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement 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. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit UnitMain; {$ifdef fpc} {$mode delphi} {$else} {$legacyifend on} {$endif} {$if defined(Win32) or defined(Win64)} {$define Windows} {$ifend} {$scopedenums on} interface uses SysUtils,Classes,PasVulkan.Types,PasVulkan.TextEditor,UnitConsole; var AbstractTextEditor:TpvTextEditor=nil; AbstractTextEditorView:TpvTextEditor.TView; OverwriteMode:boolean=false; procedure Main; implementation var FileName:TpvUTF8String; function RepChar(const aChar:Char;const aCount:Int32):string; var Index:Int32; begin SetLength(result,aCount); for Index:=1 to aCount do begin result[Index]:=aChar; end; end; procedure DisplayKeys; procedure AddFKey(const aFKeyNr:byte;const aName:string); begin Console.TextBackground(TConsole.TColor.Black); Console.TextColor(TConsole.TColor.LightGray); Console.Write(UTF8String(IntToStr(aFKeyNr))); Console.TextBackground(TConsole.TColor.Cyan); Console.TextColor(TConsole.TColor.Black); Console.Write(UTF8String(aName)); Console.TextBackground(TConsole.TColor.Black); Console.TextColor(TConsole.TColor.LightGray); Console.Write(UTF8String(' ')); end; begin Console.GotoXY(1,Console.Height); AddFKey(1,'Help'); AddFKey(2,'Save'); AddFKey(3,'Find'); AddFKey(4,'Repl'); AddFKey(5,'Refr'); if AbstractTextEditorView.LineWrap=0 then begin AddFKey(6,'Wrap'); end else begin AddFKey(6,'UnWr'); end; AddFKey(7,'InsL'); AddFKey(8,'DelL'); AddFKey(9,'Load'); AddFKey(10,'Quit'); AddFKey(11,'Mark'); AddFKey(12,' '); while Console.WhereX<Console.Width do begin Console.Write(' '); end; Console.Write(' '); end; procedure ClearEditScreen; var Index:Int32; begin Console.TextBackground(TConsole.TColor.Blue); Console.TextColor(TConsole.TColor.LightGray); for Index:=2 to Console.Height-1 do begin Console.GotoXY(1,Index); Console.Write(UTF8String(RepChar(#32,Console.Width))); end; Console.TextBackground(TConsole.TColor.Black); Console.TextColor(TConsole.TColor.LightGray); end; procedure ResetScreen; begin Console.TextBackground(TConsole.TColor.Blue); Console.TextColor(TConsole.TColor.LightGray); Console.ClrScr; Console.TextBackground(TConsole.TColor.Black); Console.TextColor(TConsole.TColor.LightGray); Console.CursorOff; Console.TextBackground(TConsole.TColor.Cyan); Console.TextColor(TConsole.TColor.Black); Console.GotoXY(1,1); Console.Write(UTF8String(RepChar(#32,Console.Width))); Console.GotoXY(2,1); Console.Write(FileName); Console.GotoXY(Console.Width-6,1); Console.Write('['); Console.Write('-'); Console.Write('-'); Console.Write('-'); if OverwriteMode then begin Console.Write('O'); end else begin Console.Write('-'); end; Console.Write(']'); DisplayKeys; Console.TextBackground(TConsole.TColor.Black); Console.TextColor(TConsole.TColor.LightGray); end; procedure UpdateScreen; var x,y,i:Int32; BufferItem:TpvTextEditor.TView.PBufferItem; begin ResetScreen; AbstractTextEditorView.VisibleAreaWidth:=Console.Width; AbstractTextEditorView.VisibleAreaHeight:=Console.Height-2; AbstractTextEditorView.NonScrollVisibleAreaWidth:=Console.Width; AbstractTextEditorView.NonScrollVisibleAreaHeight:=Console.Height-2; AbstractTextEditorView.UpdateBuffer; Console.TextBackground(TConsole.TColor.Cyan); Console.TextColor(TConsole.TColor.Black); Console.GotoXY(Console.Width-40,1); Console.Write(UTF8String('Line: '+IntToStr(AbstractTextEditorView.LineColumn.Line))); Console.GotoXY(Console.Width-25,1); Console.Write(UTF8String('Column: '+IntToStr(AbstractTextEditorView.LineColumn.Column))); Console.GotoXY(1,2); Console.TextBackground(TConsole.TColor.Blue); Console.TextColor(TConsole.TColor.LightGray); //Console.TextColor(TConsole.TColor.LightCyan); i:=0; for y:=0 to AbstractTextEditorView.VisibleAreaHeight-1 do begin for x:=0 to AbstractTextEditorView.VisibleAreaWidth-1 do begin if i<length(AbstractTextEditorView.Buffer) then begin BufferItem:=@AbstractTextEditorView.Buffer[i]; if (BufferItem^.Attribute and TpvTextEditor.TSyntaxHighlighting.TAttributes.Highlight)<>0 then begin // Console.HighVideo; Console.TextBackground(TConsole.TColor.LightBlue); end else begin // Console.NormVideo; Console.TextBackground(TConsole.TColor.Blue); end; case BufferItem^.Attribute and TpvTextEditor.TSyntaxHighlighting.TAttributes.Mask of TpvTextEditor.TSyntaxHighlighting.TAttributes.String_:begin Console.TextColor(TConsole.TColor.LightCyan); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Operator:begin Console.TextColor(TConsole.TColor.LightGreen); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Delimiter:begin Console.TextColor(TConsole.TColor.LightGreen); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Symbol:begin Console.TextColor(TConsole.TColor.LightGreen); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Number:begin Console.TextColor(TConsole.TColor.LightMagenta); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Identifier:begin Console.TextColor(TConsole.TColor.Yellow); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Keyword:begin Console.TextColor(TConsole.TColor.White); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Comment:begin Console.TextColor(TConsole.TColor.LightGray); end; TpvTextEditor.TSyntaxHighlighting.TAttributes.Preprocessor:begin Console.TextColor(TConsole.TColor.LightRed); end; else begin Console.TextColor(TConsole.TColor.DarkGray); end; end; Console.WriteCodePointToBuffer(x+1,y+2,BufferItem^.CodePoint); end; inc(i); end; end; Console.GotoXY(AbstractTextEditorView.Cursor.x+1,AbstractTextEditorView.Cursor.y+2); if OverwriteMode then begin Console.CursorBig; end else begin Console.CursorOn; end; Console.Flush; end; procedure Main; var c:Int32; RegularExpression:TpvTextEditor.TRegularExpression; p,l:TpvSizeInt; FileExtension:TpvUTF8String; begin AbstractTextEditor:=TpvTextEditor.Create; try AbstractTextEditorView:=AbstractTextEditor.CreateView; if ParamCount>0 then begin FileName:=ParamStr(1); FileExtension:=TpvUTF8String(ExtractFileExt(FileName)); try AbstractTextEditor.LoadFromFile(ParamStr(1)); except end; end else begin FileName:='noname.txt'; FileExtension:='.txt'; end; AbstractTextEditor.SyntaxHighlighting:=TpvTextEditor.TSyntaxHighlighting.GetSyntaxHighlightingClassByFileExtension(FileExtension).Create(AbstractTextEditor); //AbstractTextEditor.Text:='//0123 3.14159e+0 $1337c0de if then { bla }'; //AbstractTextEditor.Text:='''//0123 3.14159e+0 $1337c0de if then { bla }'#13#10'bla'; //AbstractTextEditor.Text:='#ifdef test'#13#10'#define bla(x) \'#13#10' if(x){\'#13#10' }'#13#10'void main(){'#13#10'}'#13#10'#endif'; repeat UpdateScreen; if {Console.KeyPressed}true then begin c:=Console.ReadKey; case c of 0:begin // Code escape if Console.KeyPressed then begin c:=Console.ReadKey; case c of 82:begin // Insert OverwriteMode:=not OverwriteMode; end; 83:begin // Delete AbstractTextEditorView.Delete; end; 71:begin // Home AbstractTextEditorView.MoveToLineBegin; end; 79:begin // End AbstractTextEditorView.MoveToLineEnd; end; 73:begin // Page up AbstractTextEditorView.MovePageUp; end; 81:begin // Page down AbstractTextEditorView.MovePageDown; end; 72:begin // Up AbstractTextEditorView.MoveUp; end; 80:begin // Down AbstractTextEditorView.MoveDown; end; 75:begin // Left AbstractTextEditorView.MoveLeft; end; 77:begin // Right AbstractTextEditorView.MoveRight; end; 60:begin // F2 AbstractTextEditor.SaveToFile(ParamStr(1)); end; 61:begin // F3 RegularExpression:=TpvTextEditor.TRegularExpression.Create(AbstractTextEditor,'\$[0-9]+',[]); try if RegularExpression.FindNext(p,l,AbstractTextEditorView.CodePointIndex+1) then begin AbstractTextEditorView.CodePointIndex:=p; end; finally RegularExpression.Free; end; end; 64:begin // F6 if AbstractTextEditorView.LineWrap=0 then begin AbstractTextEditorView.LineWrap:=AbstractTextEditorView.NonScrollVisibleAreaWidth; end else begin AbstractTextEditorView.LineWrap:=0; end; end; 65:begin // F7 AbstractTextEditorView.InsertLine; end; 66:begin // F8 AbstractTextEditorView.DeleteLine; end; 68:begin // F10 break; end; $fffe:begin // Resize if AbstractTextEditorView.LineWrap<>0 then begin AbstractTextEditorView.LineWrap:=Console.Width; AbstractTextEditorView.EnsureCursorIsVisible(true); end; end; end; end; end; 3:begin // CTRL-C end; 8:begin // Backspace AbstractTextEditorView.Backspace; end; 13:begin AbstractTextEditorView.Enter(OverwriteMode); end; 17:begin // Ctrl-Q break; end; 25:begin // Ctrl-Y AbstractTextEditor.Redo(AbstractTextEditorView); end; 26:begin // Ctrl-Z AbstractTextEditor.Undo(AbstractTextEditorView); end; 27:begin // Escape end; else begin AbstractTextEditorView.InsertCodePoint(c,OverwriteMode); end; end; { end else begin Sleep(10);} end; until false; finally AbstractTextEditor.Free; end; Console.TextBackground(TConsole.TColor.Black); Console.TextColor(TConsole.TColor.LightGray); Console.ClrScr; Console.GotoXY(1,1); Console.Flush; end; end.
33.424658
160
0.584973
171a3c0c7c8e9fe19eb996b154cc3a14372f5db4
1,931
pas
Pascal
php4AppIntf.pas
bgarrels/php4delphi
041fed9bb6898faed25076f6ff893bfee93e41cd
[ "PHP-3.0" ]
19
2015-08-10T15:42:28.000Z
2021-11-23T02:04:02.000Z
php4AppIntf.pas
bgarrels/php4delphi
041fed9bb6898faed25076f6ff893bfee93e41cd
[ "PHP-3.0" ]
2
2018-06-22T12:45:58.000Z
2020-11-30T09:05:57.000Z
php4AppIntf.pas
bgarrels/php4delphi
041fed9bb6898faed25076f6ff893bfee93e41cd
[ "PHP-3.0" ]
13
2015-05-02T14:39:20.000Z
2021-11-18T19:50:05.000Z
{*******************************************************} { PHP4Applications } { } { Delphi interface for PHP4Applications } { } { Author: } { Serhiy Perevoznyk } { serge_perevoznyk@hotmail.com } { http://users.chello.be/ws36637 } {*******************************************************} unit php4AppIntf; interface function InitRequest : integer; stdcall; procedure DoneRequest(RequestID : integer); stdcall; procedure RegisterVariable(RequestID : integer; AName : PChar; AValue : PChar); stdcall; function ExecutePHP(RequestID : integer; FileName : PChar) : integer; stdcall; function ExecuteCode(RequestID : integer; ACode : PChar) : integer; stdcall; function GetResultText(RequestID : integer; Buffer : PChar; BufLen : integer) : integer; stdcall; function GetVariable(RequestID : integer; AName : PChar; Buffer : PChar; BufLen : integer) : integer; stdcall; procedure SaveToFile(RequestID : integer; AFileName : PChar); stdcall; function GetVariableSize(RequestID : integer; AName : PChar) : integer; stdcall; function GetResultBufferSize(RequestID : integer) : integer; stdcall; implementation function InitRequest; external 'php4app.dll'; procedure DoneRequest; external 'php4app.dll'; procedure RegisterVariable; external 'php4app.dll'; function ExecutePHP; external 'php4app.dll'; function ExecuteCode; external 'php4app.dll'; function GetResultText; external 'php4app.dll'; function GetVariable; external 'php4app.dll'; procedure SaveToFile; external 'php4app.dll'; function GetVariableSize; external 'php4app.dll'; function GetResultBufferSize; external 'php4app.dll'; end.
48.275
112
0.596582
f1f4a5ceb3e11ef6fc12e8a649d33998a9401793
3,317
dpr
Pascal
tutorial/delphi/DelphiClient/DelphiClient.dpr
shivam00/thrift
d81e9e3d22c130ef5ddba7b06fb9802267d9d1d7
[ "Apache-2.0" ]
2
2018-09-30T09:37:22.000Z
2020-05-07T01:53:04.000Z
tutorial/delphi/DelphiClient/DelphiClient.dpr
shivam00/thrift
d81e9e3d22c130ef5ddba7b06fb9802267d9d1d7
[ "Apache-2.0" ]
null
null
null
tutorial/delphi/DelphiClient/DelphiClient.dpr
shivam00/thrift
d81e9e3d22c130ef5ddba7b06fb9802267d9d1d7
[ "Apache-2.0" ]
null
null
null
(* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. *) program DelphiClient; {$APPTYPE CONSOLE} {$D 'Copyright (c) 2012 The Apache Software Foundation'} uses SysUtils, Generics.Collections, Thrift in '..\..\..\lib\delphi\src\Thrift.pas', Thrift.Collections in '..\..\..\lib\delphi\src\Thrift.Collections.pas', Thrift.Exception in '..\..\..\lib\delphi\src\Thrift.Exception.pas', Thrift.Utils in '..\..\..\lib\delphi\src\Thrift.Utils.pas', Thrift.Stream in '..\..\..\lib\delphi\src\Thrift.Stream.pas', Thrift.Protocol in '..\..\..\lib\delphi\src\Thrift.Protocol.pas', Thrift.Server in '..\..\..\lib\delphi\src\Thrift.Server.pas', Thrift.Transport in '..\..\..\lib\delphi\src\Thrift.Transport.pas', Shared in '..\..\gen-delphi\Shared.pas', Tutorial in '..\..\gen-delphi\Tutorial.pas'; type DelphiTutorialClient = class public class procedure Main; end; //--- DelphiTutorialClient --------------------------------------- class procedure DelphiTutorialClient.Main; var transport : ITransport; protocol : IProtocol; client : TCalculator.Iface; work : IWork; sum, quotient, diff : Integer; log : ISharedStruct; begin try transport := TSocketImpl.Create( 'localhost', 9090); protocol := TBinaryProtocolImpl.Create( transport); client := TCalculator.TClient.Create( protocol); transport.Open; client.ping; WriteLn('ping()'); sum := client.add( 1, 1); WriteLn( Format( '1+1=%d', [sum])); work := TWorkImpl.Create; work.Op := TOperation.DIVIDE; work.Num1 := 1; work.Num2 := 0; try quotient := client.calculate(1, work); WriteLn( 'Whoa we can divide by 0'); WriteLn( Format('1/0=%d',[quotient])); except on io: TInvalidOperation do WriteLn( 'Invalid operation: ' + io.Why); end; work.Op := TOperation.SUBTRACT; work.Num1 := 15; work.Num2 := 10; try diff := client.calculate( 1, work); WriteLn( Format('15-10=%d', [diff])); except on io: TInvalidOperation do WriteLn( 'Invalid operation: ' + io.Why); end; log := client.getStruct(1); WriteLn( Format( 'Check log: %s', [log.Value])); transport.Close(); except on e : Exception do WriteLn( e.ClassName+': '+e.Message); end; end; begin try DelphiTutorialClient.Main; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
28.843478
74
0.625264
83684ad6b93e874c8ec0c11be9fd40ef4455bc3a
2,073
pas
Pascal
Components/cnvcl/Examples/FormMisc/Unit1.pas
98kmir2/98kmir2
46196a161d46cc7a85d168dca683b4aff477a709
[ "BSD-3-Clause" ]
15
2020-02-13T11:59:11.000Z
2021-12-31T14:53:44.000Z
Components/cnvcl/Examples/FormMisc/Unit1.pas
bsjzx8/98
46196a161d46cc7a85d168dca683b4aff477a709
[ "BSD-3-Clause" ]
null
null
null
Components/cnvcl/Examples/FormMisc/Unit1.pas
bsjzx8/98
46196a161d46cc7a85d168dca683b4aff477a709
[ "BSD-3-Clause" ]
13
2020-02-20T07:22:09.000Z
2021-12-31T14:56:09.000Z
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CnFMForm, StdCtrls, ExtCtrls, WinSkinData, Menus; type TForm1 = class(TForm) CnFMForm1: TCnFMForm; CnFMGlassPanel1: TCnFMGlassPanel; CnFMTitleImg1: TCnFMTitleImg; CnFMMenuLabel1: TCnFMMenuLabel; Panel1: TPanel; PopupMenu1: TPopupMenu; New1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; SkinData1: TSkinData; procedure FormCreate(Sender: TObject); procedure CnFMForm1CloseButtonClick(Sender: TObject); procedure CnFMForm1MinButtonClick(Sender: TObject); procedure CnFMForm1MaxButtonClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin CnFMForm1.LoadSkin('Skins\Yellow'); //RaNGlassPanel1.BringToFront; end; procedure TForm1.Button2Click(Sender: TObject); begin CnFMForm1.ResetSkin; end; procedure TForm1.Button3Click(Sender: TObject); begin CnFMForm1.MaxButtonVisible := True; CnFMForm1.SetButtonPosition; end; procedure TForm1.Button4Click(Sender: TObject); begin CnFMForm1.MaxButtonVisible := False; CnFMForm1.SetButtonPosition; end; procedure TForm1.FormCreate(Sender: TObject); begin CnFMForm1.SetSysButtonEnable(True, True, True); end; procedure TForm1.CnFMForm1CloseButtonClick(Sender: TObject); begin Close; end; procedure TForm1.CnFMForm1MaxButtonClick(Sender: TObject); begin if self.WindowState = wsNormal then self.WindowState := wsMaximized else if self.WindowState = wsMaximized then Self.WindowState := wsNormal; end; procedure TForm1.CnFMForm1MinButtonClick(Sender: TObject); begin Application.Minimize; end; end.
22.290323
76
0.755909
83bf76bab48ae53899adced5d5b93dcbe1275c8b
29,328
pas
Pascal
windows/src/ext/jedi/jvcl/tests/archive/jvcl/Archive/JvTypedEdit.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/tests/archive/jvcl/Archive/JvTypedEdit.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/tests/archive/jvcl/Archive/JvTypedEdit.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvTypedEdit.pas, released November 1999. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2001 Anthony Steele. All Rights Reserved. Contributor(s): Last Modified: 2002-05-26 You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.sourceforge.net Known Issues: -----------------------------------------------------------------------------} {$I JVCL.INC} unit JvTypedEdit; {Comments - controls to capture numbers of various kinds (Int, Float, Money) The money edit also does some display formatting Still to do - test some more - The controls do not work well if zero is not within the min/max range What should happen when 0 is not in the range? control should start up with ? min ?max ? 0? displayed User should set the value? Consider only checking the full range on exit. During data capture, extend the range to include 0 - See if a base class is useful for these edit controls - Display formatting for int & float edits? The code in these controls is a bit repetitive, but unfortunately you can't have a base class property with polymorphic type } interface uses Classes, JvEdit; type TCustomIntegerEdit = class(TJvCustomEdit) private FMinValue: Integer; FMaxValue: Integer; FHasMinValue: Boolean; FHasMaxValue: Boolean; protected procedure KeyPress(var Key: Char); override; procedure SetValue(iNewValue: Integer); virtual; function GetValue: Integer; virtual; procedure SetMinValue(iNewValue: Integer); procedure SetMaxValue(iNewValue: Integer); function ChopToRange(iValue: Integer): Integer; function IsInRange(iValue: Integer): Boolean; overload; function IsInRange(sValue: string): Boolean; overload; property MaxValue: Integer read FMaxValue write FMaxValue; property MinValue: Integer read FMinValue write FMinValue; property HasMaxValue: Boolean read FHasMaxValue write FHasMaxValue; property HasMinValue: Boolean read FHasMinValue write FHasMinValue; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; property Value: Integer read GetValue write SetValue; published property AutoSize default True; end; { to capture and display float values } TCustomFloatEdit2 = class(TJvCustomEdit) private FMaxValue: Extended; FMinValue: Extended; FHasMaxValue: Boolean; FHasMinValue: Boolean; FMaxDecimals: Integer; protected procedure KeyPress(var Key: Char); override; procedure SetValue(eNewValue: Extended); function GetValue: Extended; procedure SetMinValue(eNewValue: Extended); procedure SetMaxValue(eNewValue: Extended); procedure SetMaxDecimals(iNewValue: Integer); function ChopToRange(eValue: Extended): Extended; function IsInRange(eValue: Extended): Boolean; overload; function IsInRange(sValue: string): Boolean; overload; property MaxValue: Extended read FMaxValue write FMaxValue; property MinValue: Extended read FMinValue write FMinValue; property MaxDecimals: Integer read FMaxDecimals write SetMaxDecimals; property HasMaxValue: Boolean read FHasMaxValue write FHasMaxValue; property HasMinValue: Boolean read FHasMinValue write FHasMinValue; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; property Value: Extended read GetValue write SetValue; published property AutoSize default True; end; { control to capture a year int edit with automatic 2 digit -> 4 digit expansion in a range controlld by the WindowsillYear which is initialised from the program/system settings } TCustomYearEdit = class(TCustomIntegerEdit) private FWindowsillYear: Integer; protected procedure DoExit; override; procedure SetValue(iNewValue: Integer); override; function GetValue: Integer; override; procedure FixYear; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; property WindowsillYear: Integer read FWindowsillYear write FWindowsillYear; end; { to capture and display Currency values when the control has focus, the number is displayed simply when the control does not have focus, the number is formatted as per control panel Currency settings } TCustomCurrencyEdit = class(TJvCustomEdit) private FMaxValue: Currency; FMinValue: Currency; FHasMaxValue: Boolean; FHasMinValue: Boolean; FOriginalValue: Currency; FOriginalValueOK: Boolean; protected procedure KeyPress(var Key: Char); override; procedure SetValue(const peNewValue: Currency); virtual; function GetValue: Currency; procedure SetMinValue(const peNewValue: Currency); procedure SetMaxValue(const peNewValue: Currency); function ChopToRange(eValue: Currency): Currency; function IsInRange(eValue: Currency): Boolean; overload; function IsInRange(sValue: string): Boolean; overload; property MaxValue: Currency read FMaxValue write FMaxValue; property MinValue: Currency read FMinValue write FMinValue; property HasMaxValue: Boolean read FHasMaxValue write FHasMaxValue; property HasMinValue: Boolean read FHasMinValue write FHasMinValue; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; property Value: Currency read GetValue write SetValue; published property AutoSize default True; end; { another bit of functionality - when the control does not have focus, display a formatted Currency string (as per control panel) - when it has focus, display a raw number string for editing To do - Extend this functionality to int & float edits? I would put code this in as a base class below all the number edits, but unfortunately it uses the Value property which is different per subclass. it could easily be duplicated for int & float edit controls but I don't want to go there until I am convinced that there is no other way - Make the format mask a published property, not a constant? this is more applicable to Int & Float edits } TCustomFormattedCurrencyEdit = class(TCustomCurrencyEdit) private FSupressOnChange: Boolean; FChanging: Boolean; protected procedure UnFormatText; virtual; procedure SetValue(const peNewValue: Currency); override; procedure DoEnter; override; procedure DoExit; override; procedure Change; override; public constructor Create(AOwner: TComponent); override; procedure Loaded; override; procedure FormatText; virtual; end; TJvIntegerEdit = class(TCustomIntegerEdit) published { most properties of TMemo no Text or WordWrap properties } property Align; property Alignment; property Anchors; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; // property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; // property WantReturns; // property WantTabs; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; { new properties } property AutoSelect; property Value; property MaxValue; property MinValue; property HasMaxValue; property HasMinValue; (* ++ RDB ++ *) property ClipBoardCommands; property DisabledTextColor; property DisabledColor; (* -- RDB -- *) end; TJvFloatEdit2 = class(TCustomFloatEdit2) published { most properties of TMemo no Text or WordWrap properties } property Align; property Alignment; property Anchors; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; // property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; // property WantReturns; // property WantTabs; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; { new properties } property AutoSelect; property Value; property MaxValue; property MinValue; property MaxDecimals; property HasMaxValue; property HasMinValue; (* ++ RDB ++ *) property ClipBoardCommands; property DisabledTextColor; property DisabledColor; (* -- RDB -- *) end; TJvYearEdit = class(TCustomYearEdit) published { most properties of TMemo no Text or WordWrap properties } property Align; property Alignment; property Anchors; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; // property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; // property WantReturns; // property WantTabs; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; { new properties } property AutoSelect; property Value; property MaxValue; property MinValue; property HasMaxValue; property HasMinValue; property WindowsillYear; (* ++ RDB ++ *) property ClipBoardCommands; property DisabledTextColor; property DisabledColor; (* -- RDB -- *) end; { surface class } TJvCurrencyEdit = class(TCustomFormattedCurrencyEdit) published { most properties of TMemo no Text or WordWrap properties } property Align; property Alignment; property Anchors; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property OEMConvert; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; // property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; // property WantReturns; // property WantTabs; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; { new properties } property AutoSelect; property Value; property MaxValue; property MinValue; property HasMaxValue; property HasMinValue; (* ++ RDB ++ *) property ClipBoardCommands; property DisabledTextColor; property DisabledColor; (* -- RDB -- *) end; implementation uses SysUtils, JclStrings, JclDateTime, JvFunctions; const MONEY_FORMAT = '%m'; // see help on "format strings" //=== TCustomIntegerEdit ===================================================== constructor TCustomIntegerEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); { default is right aligned } Alignment := taRightJustify; Text := ''; AutoSize := True; { by default no min & max } FMinValue := 0; FMaxValue := 0; FHasMinValue := False; FHasMaxValue := False; end; function TCustomIntegerEdit.ChopToRange(iValue: Integer): Integer; begin Result := iValue; if HasMaxValue and (iValue > MaxValue) then Result := FMaxValue; if HasMinValue and (iValue < MinValue) then Result := FMinValue; end; procedure TCustomIntegerEdit.Assign(Source: TPersistent); var lcSource: TCustomIntegerEdit; begin inherited Assign(Source); if Source is TCustomIntegerEdit then begin lcSource := Source as TCustomIntegerEdit; MinValue := lcSource.MinValue; MaxValue := lcSource.MaxValue; HasMinValue := lcSource.HasMinValue; HasMaxValue := lcSource.HasMaxValue; end; // (rom) why not else inherited Assign? end; function TCustomIntegerEdit.GetValue: Integer; begin if Text = '' then Result := 0 else Result := StrToIntDef(Text, 0); end; function TCustomIntegerEdit.IsInRange(iValue: Integer): Boolean; begin Result := True; if HasMaxValue and (iValue > MaxValue) then Result := False; if HasMinValue and (iValue < MinValue) then Result := False; end; function TCustomIntegerEdit.IsInRange(sValue: string): Boolean; var liValue: Integer; begin if sValue = '' then liValue := 0 else liValue := StrToIntDef(sValue, 0); Result := IsInRange(liValue); end; procedure TCustomIntegerEdit.KeyPress(var Key: Char); var lsNewText: string; begin { not interested in control chars } if Ord(Key) < Ord(' ') then begin if Key = #13 then Key := #0 else inherited KeyPress(Key); Exit; end; { allow only digits and minus sign } if not CharIsDigit(Key) and (Key <> '-') then Key := #0; if Key = '-' then begin { are any neg. numbers in range ? } if HasMinValue and (MinValue >= 0) then Key := #0 { minus sign only as first Char } else if SelStart <> 0 then Key := #0; { only 1 minus sign } if StrLeft(lsNewText, 2) = '--' then Key := #0; end; { no leading zeros } if (SelStart = 0) and (Key = '0') and (StrLeft(lsNewText, 1) = '0') then Key := #0; { no leading '-0' } if (SelStart = 1) and (Key = '0') and (StrLeft(lsNewText, 2) = '-0') then Key := #0; { disallow the keypress if the value would go out of range } lsNewText := GetChangedText(Text, SelStart, SelLength, Key); if not IsInRange(lsNewText) then Key := #0; if Key <> #0 then inherited KeyPress(Key); end; procedure TCustomIntegerEdit.SetMaxValue(iNewValue: Integer); begin FMaxValue := iNewValue; { make min value consistent } if MinValue > MaxValue then FMinValue := MaxValue; end; procedure TCustomIntegerEdit.SetMinValue(iNewValue: Integer); begin FMinValue := iNewValue; { make max value consistent } if MaxValue < MaxValue then FMaxValue := MinValue; end; procedure TCustomIntegerEdit.SetValue(iNewValue: Integer); begin Text := IntToStr(ChopToRange(iNewValue)); end; const { The Extended data type handles up to 20 digits - no point in setting max decimals to more than this } FLOAT_EDIT_MAX_MAX_DECIMALS = 20; { most data capture is more like this - typing in 19 decimal digits usually indicates forehead-on-the-keyboard syndrome } FLOAT_EDIT_DEFAULT_MAX_DECIMALS = 5; //=== TCustomFloatEdit2 ====================================================== constructor TCustomFloatEdit2.Create(AOwner: TComponent); begin inherited Create(AOwner); { default is right aligned } Alignment := taRightJustify; AutoSize := True; Text := ''; { by default no min & max } FMinValue := 0.0; FMaxValue := 0.0; FHasMinValue := False; FHasMaxValue := False; FMaxDecimals := FLOAT_EDIT_DEFAULT_MAX_DECIMALS; end; procedure TCustomFloatEdit2.Assign(Source: TPersistent); var lcSource: TCustomFloatEdit2; begin inherited Assign(Source); if Source is TCustomFloatEdit2 then begin lcSource := Source as TCustomFloatEdit2; MinValue := lcSource.MinValue; MaxValue := lcSource.MaxValue; MaxDecimals := lcSource.MaxDecimals; HasMinValue := lcSource.HasMinValue; HasMaxValue := lcSource.HasMaxValue; end; end; function TCustomFloatEdit2.ChopToRange(eValue: Extended): Extended; begin Result := eValue; if HasMaxValue and (eValue > MaxValue) then Result := MaxValue; if HasMinValue and (eValue < MinValue) then Result := MinValue; end; function TCustomFloatEdit2.GetValue: Extended; begin if Text = '' then Result := 0.0 else Result := StrToFloatDef(Text, 0.0); end; function TCustomFloatEdit2.IsInRange(eValue: Extended): Boolean; begin Result := True; if HasMaxValue and (eValue > MaxValue) then Result := False; if HasMinValue and (eValue < MinValue) then Result := False; end; function TCustomFloatEdit2.IsInRange(sValue: string): Boolean; var leValue: Extended; begin if sValue = '' then leValue := 0.0 else leValue := StrToFloatDef(sValue, 0.0); Result := IsInRange(leValue); end; procedure TCustomFloatEdit2.KeyPress(var Key: Char); var lsNewText: string; iDotPos: Integer; begin { not intersted in control chars } if (Ord(Key)) < Ord(' ') then begin inherited KeyPress(Key); Exit; end; { allow only digits, '.' and minus sign } if not CharIsNumber(Key) then Key := #0; if Key = '-' then begin { are any neg. numbers in range ? } if HasMinValue and (MinValue >= 0) then Key := #0 { minus sign only as first Char } else if SelStart <> 0 then Key := #0; { only 1 minus sign } if StrLeft(lsNewText, 2) = '--' then Key := #0; end; { no leading zeros } if (SelStart = 0) and (Key = '0') and (StrLeft(lsNewText, 1) = '0') then Key := #0; { no leading '-0' } if (SelStart = 1) and (Key = '0') and (StrLeft(lsNewText, 2) = '-0') then Key := #0; iDotPos := Pos('.', Text); if Key = '.' then begin { allow only one dot, but we can overwrite it with another } if (iDotPos > 0) and not ((SelLength > 0) and (SelStart <= iDotPos) and ((SelStart + SelLength) >= iDotPos)) then Key := #0 end; { check number of decimal digits } if (iDotPos > 0) and (SelStart > iDotPos) and ((Length(Text) - iDotPos) >= MaxDecimals) then begin Key := #0; end; { disallow the keypress if the value would go out of range } lsNewText := GetChangedText(Text, SelStart, SelLength, Key); if not IsInRange(lsNewText) then Key := #0; if Key <> #0 then inherited KeyPress(Key); end; procedure TCustomFloatEdit2.SetMaxDecimals(iNewValue: Integer); begin if iNewValue < 0 then iNewValue := 0; if iNewValue > FLOAT_EDIT_MAX_MAX_DECIMALS then iNewValue := FLOAT_EDIT_MAX_MAX_DECIMALS; FMaxDecimals := iNewValue; end; procedure TCustomFloatEdit2.SetMaxValue(eNewValue: Extended); begin FMaxValue := eNewValue; { make min value consistent } if MinValue > MaxValue then FMinValue := MaxValue; end; procedure TCustomFloatEdit2.SetMinValue(eNewValue: Extended); begin FMinValue := eNewValue; { make max value consistent } if MaxValue < MaxValue then FMaxValue := MinValue; end; procedure TCustomFloatEdit2.SetValue(eNewValue: Extended); begin Text := FloatToStr(ChopToRange(eNewValue)); end; //=== TCustomYearEdit ======================================================== constructor TCustomYearEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); { the system var is 'TwoDigitYearCenturyWindow', which by default will have a value of 50 we then want FWindowsillYear to be 1950, if current date is 2020, and TwoDigitYearCenturyWindow is 90, then FWindowsillYear should be 1990 if current date is 2120, and TwoDigitYearCenturyWindow is 90, (this code may last that long?) then FWindowsillYear should be 2090. It helps that FWindowsillYear is assumed to be in the past 100 years } FWindowsillYear := CenturyOfDate(now) + TwoDigitYearCenturyWindow; if FWindowsillYear > YearOfDate(now) then FWindowsillYear := FWindowsillYear - 100; HasMinValue := True; MinValue := 0; HasMaxValue := True; MaxValue := 9999; end; procedure TCustomYearEdit.Assign(Source: TPersistent); var lcSource: TCustomYearEdit; begin inherited Assign(Source); if Source is TCustomYearEdit then begin lcSource := Source as TCustomYearEdit; WindowsillYear := lcSource.WindowsillYear; end; end; procedure TCustomYearEdit.DoExit; begin { allow the user to type & on exit, translate any 2 digit years to 4 digits } FixYear; inherited DoExit; end; procedure TCustomYearEdit.FixYear; begin Value := MakeYear4Digit(Value, WindowsillYear); end; function TCustomYearEdit.GetValue: Integer; var li: Integer; begin li := inherited GetValue; Result := MakeYear4Digit(li, WindowsillYear); end; procedure TCustomYearEdit.SetValue(iNewValue: Integer); var li: Integer; begin li := MakeYear4Digit(iNewValue, WindowsillYear); inherited SetValue(li); end; //=== TCustomCurrencyEdit ==================================================== constructor TCustomCurrencyEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); { default is right aligned } Alignment := taRightJustify; AutoSize := True; Text := ''; { by default no min & max } FMinValue := 0.0; FMaxValue := 0.0; FHasMinValue := False; FHasMaxValue := False; FOriginalValue := 0; FOriginalValueOK := False; end; procedure TCustomCurrencyEdit.Assign(Source: TPersistent); var lcSource: TCustomCurrencyEdit; begin inherited Assign(Source); if Source is TCustomCurrencyEdit then begin lcSource := Source as TCustomCurrencyEdit; MinValue := lcSource.MinValue; MaxValue := lcSource.MaxValue; HasMinValue := lcSource.HasMinValue; HasMaxValue := lcSource.HasMaxValue; end; end; function TCustomCurrencyEdit.ChopToRange(eValue: Currency): Currency; begin Result := eValue; if HasMaxValue and (eValue > MaxValue) then Result := MaxValue; if HasMinValue and (eValue < MinValue) then Result := MinValue; end; function TCustomCurrencyEdit.GetValue: Currency; var lsText: string; begin if FOriginalValueOK then begin Result := FOriginalValue; Exit; end; { Currency string may include a decimal dot (.) so remove it wholesesale } lsText := StrDelete(CurrencyString, Text); lsText := StrStripNonNumberChars(lsText); if lsText = '' then Result := 0.0 else Result := StrToCurrDef(lsText, 0.0); end; function TCustomCurrencyEdit.IsInRange(eValue: Currency): Boolean; begin Result := True; if HasMaxValue and (eValue > MaxValue) then Result := False; if HasMinValue and (eValue < MinValue) then Result := False; end; function TCustomCurrencyEdit.IsInRange(sValue: string): Boolean; var leValue: Extended; begin if sValue = '' then leValue := 0.0 else leValue := StrToCurrDef(sValue, 0.0); Result := IsInRange(leValue); end; procedure TCustomCurrencyEdit.KeyPress(var Key: Char); var lsNewText: string; iDotPos: Integer; begin { not interested in control chars } if (Ord(Key)) < Ord(' ') then begin inherited KeyPress(Key); if Key <> #0 then FOriginalValueOK := False; Exit; end; { allow only digits, '.' and minus sign } if not CharIsNumber(Key) then Key := #0; if Key <> #0 then FOriginalValueOK := False; if Key = '-' then begin { are any neg. numbers in range ? } if HasMinValue and (MinValue >= 0) then Key := #0 { minus sign only as first Char } else if SelStart <> 0 then Key := #0; { only 1 minus sign } if StrLeft(lsNewText, 2) = '--' then Key := #0; end; { no leading zeros } if (SelStart = 0) and (Key = '0') and (StrLeft(lsNewText, 1) = '0') then Key := #0; { no leading '-0' } if (SelStart = 1) and (Key = '0') and (StrLeft(lsNewText, 2) = '-0') then Key := #0; iDotPos := Pos('.', Text); if Key = '.' then begin { allow only one dot, but we can overwrite it with another } if (iDotPos > 0) and not ((SelLength > 0) and (SelStart <= iDotPos) and ((SelStart + SelLength) >= iDotPos)) then Key := #0 end; { check number of decimal digits } if (iDotPos > 0) and (SelStart > iDotPos) and ((Length(Text) - iDotPos) >= CurrencyDecimals) then begin Key := #0; end; { disallow the keypress if the value would go out of range } lsNewText := GetChangedText(Text, SelStart, SelLength, Key); if not IsInRange(lsNewText) then Key := #0; if Key <> #0 then inherited KeyPress(Key); end; procedure TCustomCurrencyEdit.SetMaxValue(const peNewValue: Currency); begin FMaxValue := peNewValue; { make min value consistent } if MinValue > MaxValue then FMinValue := MaxValue; end; procedure TCustomCurrencyEdit.SetMinValue(const peNewValue: Currency); begin FMinValue := peNewValue; { make max value consistent } if MaxValue < MaxValue then FMaxValue := MinValue; end; procedure TCustomCurrencyEdit.SetValue(const peNewValue: Currency); begin FOriginalValue := peNewValue; Text := Format(MONEY_FORMAT, [ChopToRange(peNewValue)]); FOriginalValueOK := True; end; //=== TCustomFormattedCurrencyEdit =========================================== constructor TCustomFormattedCurrencyEdit.Create(AOwner: TComponent); begin FSupressOnChange := True; FChanging := False; inherited Create(AOwner); end; procedure TCustomFormattedCurrencyEdit.Loaded; begin inherited Loaded; FSupressOnChange := False; end; procedure TCustomFormattedCurrencyEdit.Change; begin if not FSupressOnChange then inherited Change; { change after lose focus? o-er! } if not Focused and not FChanging then begin FChanging := True; try FormatText; finally FChanging := False; end; end; end; procedure TCustomFormattedCurrencyEdit.DoEnter; begin FSupressOnChange := True; try UnFormatText; inherited DoEnter; finally FSupressOnChange := False; end; end; procedure TCustomFormattedCurrencyEdit.DoExit; begin FSupressOnChange := True; try inherited DoExit; FormatText; finally FSupressOnChange := False; end; end; procedure TCustomFormattedCurrencyEdit.FormatText; begin Text := Format(MONEY_FORMAT, [Value]); end; procedure TCustomFormattedCurrencyEdit.UnFormatText; var lsText: string; begin lsText := StrDelete(CurrencyString, Text); lsText := StrStripNonNumberChars(lsText); Text := lsText; end; { this sets the text to then non-formatted value, the reads it, then sets it to the formatted value. This could be improved } procedure TCustomFormattedCurrencyEdit.SetValue(const peNewValue: Currency); begin inherited SetValue(peNewValue); FormatText; { what if the control has focus? It won't if this occurs as the result of a button click } FOriginalValueOK := True; end; end.
26.374101
117
0.69732
f141b914b330bf70fef81a19abb0a3f777b39179
1,263
pas
Pascal
windows/src/ext/sentry/test/Sentry.Client.Test.SentryClientTestMain.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
1
2021-03-08T09:31:47.000Z
2021-03-08T09:31:47.000Z
windows/src/ext/sentry/test/Sentry.Client.Test.SentryClientTestMain.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
null
null
null
windows/src/ext/sentry/test/Sentry.Client.Test.SentryClientTestMain.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
null
null
null
unit Sentry.Client.Test.SentryClientTestMain; interface procedure main; implementation uses Sentry.Client, System.SysUtils; procedure DoCrash; forward; procedure DoEvent; forward; procedure main; begin if ParamStr(1) = 'crash' then DoCrash else DoEvent; end; function Init: TSentryClient; var o: TSentryClientOptions; begin o.Debug := False; o.DSN := 'https://92eb58e6005d47daa33c9c9e39458eb7@sentry.keyman.com/5'; //o.DSN := 'https://7b1ff1dae2c8495b84f90dadcf512b84@sentry.io/4853461'; o.Release := 'keyman-14.0.22-alpha-local'; o.HandlerPath := 'c:\Projects\keyman\app\windows\src\ext\sentry\test\Win32\Release\crashpad_handler.exe'; o.DatabasePath := '.\sentry-db'; Result := TSentryClient.Create(o); end; type EFoo = class(Exception); procedure DoCrash; var c: TSentryClient; begin c := Init; try try raise EFoo.Create('This should be captured by TSentryClient'); except on E:Exception do SentryHandleException(E); end; finally c.Free; end; end; procedure DoEvent; var c: TSentryClient; begin c := Init; try // c.ExceptionEvent('fpp'); c.MessageEvent(SENTRY_LEVEL_INFO, 'customer', 'Now testing with TSentryClient'); finally c.Free; end; end; end.
18.042857
107
0.701504
f12854fc4540bf6e77657f78bd09be804791c38d
2,085
dpr
Pascal
PascalCoinWalletLazarus.dpr
nanopool/PascalCoin
f6949c4d16b43b4ffc567c4ed5bc67b48d0ac65c
[ "MIT" ]
8
2017-01-28T10:30:03.000Z
2021-05-11T08:09:33.000Z
PascalCoinWalletLazarus.dpr
nanopool/PascalCoin
f6949c4d16b43b4ffc567c4ed5bc67b48d0ac65c
[ "MIT" ]
null
null
null
PascalCoinWalletLazarus.dpr
nanopool/PascalCoin
f6949c4d16b43b4ffc567c4ed5bc67b48d0ac65c
[ "MIT" ]
4
2017-01-28T22:11:18.000Z
2018-01-08T02:18:59.000Z
program PascalCoinWalletLazarus; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} uses {$IFnDEF FPC} {$ELSE} {$IFDEF LINUX}cthreads,{$ENDIF} Interfaces, {$ENDIF} Forms, UBlockChain in 'Units\PascalCoin\UBlockChain.pas', UCrypto in 'Units\PascalCoin\UCrypto.pas', UTime in 'Units\PascalCoin\UTime.pas', UWalletKeys in 'Units\PascalCoin\UWalletKeys.pas', UOpTransaction in 'Units\PascalCoin\UOpTransaction.pas', UNetProtocol in 'Units\PascalCoin\UNetProtocol.pas', UAccounts in 'Units\PascalCoin\UAccounts.pas', UConst in 'Units\PascalCoin\UConst.pas', UThread in 'Units\PascalCoin\UThread.pas', ULog in 'Units\PascalCoin\ULog.pas', UNode in 'Units\PascalCoin\UNode.pas', UECIES in 'Units\PascalCoin\UECIES.pas', UAES in 'Units\PascalCoin\UAES.pas', UFRMWallet in 'Units\Forms\UFRMWallet.pas' {FRMWallet}, UFileStorage in 'Units\PascalCoin\UFileStorage.pas', UFolderHelper in 'Units\Utils\UFolderHelper.pas', UAppParams in 'Units\Utils\UAppParams.pas', UGridUtils in 'Units\Utils\UGridUtils.pas', UFRMPascalCoinWalletConfig in 'Units\Forms\UFRMPascalCoinWalletConfig.pas' {FRMPascalCoinWalletConfig}, UFRMAbout in 'Units\Forms\UFRMAbout.pas' {FRMAbout}, UFRMOperation in 'Units\Forms\UFRMOperation.pas' {FRMOperation}, UFRMWalletKeys in 'Units\Forms\UFRMWalletKeys.pas' {FRMWalletKeys}, UFRMNewPrivateKeyType in 'Units\Forms\UFRMNewPrivateKeyType.pas' {FRMNewPrivateKeyType}, UFRMPayloadDecoder in 'Units\Forms\UFRMPayloadDecoder.pas' {FRMPayloadDecoder}, UFRMNodesIp in 'Units\Forms\UFRMNodesIp.pas' {FRMNodesIp}, UTCPIP in 'Units\PascalCoin\UTCPIP.pas', UJSONFunctions in 'Units\Utils\UJSONFunctions.pas', URPC in 'Units\PascalCoin\URPC.pas', UPoolMining in 'Units\PascalCoin\UPoolMining.pas', UOpenSSL in 'Units\PascalCoin\UOpenSSL.pas', UOpenSSLdef in 'Units\PascalCoin\UOpenSSLdef.pas'; {.$R *.res} {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.Title := 'Pascal Coin Wallet, Miner & Explorer'; Application.CreateForm(TFRMWallet, FRMWallet); Application.Run; end.
36.578947
105
0.766906
83830b8c2362c93f7ac019e678fd9af24a446ec1
4,169
pas
Pascal
wwwd/crc.pas
koizuka/wwwd
6da94152416656fb54522d42acda3ee4b0b33b92
[ "MIT" ]
null
null
null
wwwd/crc.pas
koizuka/wwwd
6da94152416656fb54522d42acda3ee4b0b33b92
[ "MIT" ]
null
null
null
wwwd/crc.pas
koizuka/wwwd
6da94152416656fb54522d42acda3ee4b0b33b92
[ "MIT" ]
null
null
null
unit crc; (* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-1998 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h *) (* @(#) $Id: crc.pas,v 1.4 2000/05/17 17:39:32 koizuka Exp $ *) interface function crc32_block( crc:Cardinal; buf:Pchar; len: Cardinal): Cardinal; function crc32_byte( crc:Cardinal; b:Byte): Cardinal; implementation var //crc_table_empty: boolean = true; crc_table: array[0..255] of Cardinal; (* Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRC's on data a byte at a time for all combinations of CRC register values and incoming bytes. *) procedure make_crc_table; var c: Cardinal; n, k: integer; poly: Cardinal; (* polynomial exclusive-or pattern *) const (* terms of polynomial defining this crc (except x^32): *) num_p = 14; p: array[0..num_p-1] of byte = (0,1,2,4,5,7,8,10,11,12,16,22,23,26); begin (* make exclusive-or pattern from polynomial (0xedb88320L) *) poly := 0; for n := 0 to num_p-1 do poly := poly or 1 shl (31 - p[n]); for n := 0 to 255 do begin c := n; for k := 0 to 7 do begin if (c and 1) <> 0 then c := poly xor (c shr 1) else c := c shr 1; end; crc_table[n] := c; end; //crc_table_empty := false; end; (* ========================================================================= * This function can be used by asm versions of crc32() *) { const uLongf * ZEXPORT get_crc_table() begin #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif return (const uLongf *)crc_table; end } (* ========================================================================= *) function crc32_block( crc:Cardinal; buf:Pchar; len: Cardinal): Cardinal; begin if (buf = nil) or (len = 0) then begin result := crc; exit; end; //if crc_table_empty then // make_crc_table; crc := not crc; while len >= 8 do begin crc := crc_table[(crc xor byte(buf[0])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[1])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[2])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[3])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[4])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[5])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[6])) and $ff] xor (crc shr 8); crc := crc_table[(crc xor byte(buf[7])) and $ff] xor (crc shr 8); Inc(buf, 8); Dec(len, 8); end; if len <> 0 then begin repeat crc := crc_table[(crc xor byte(buf^)) and $ff] xor (crc shr 8); Inc(buf); Dec(len); until len = 0; end; result := not crc; end; function crc32_byte( crc:Cardinal; b:Byte): Cardinal; begin crc := crc xor $ffffffff; crc := crc_table[(crc xor b) and $ff] xor (crc shr 8); result := crc xor $ffffffff; end; begin make_crc_table; end.
31.11194
79
0.634685
47549d609f0f6e9a198707de6318267abe6eb092
11,657
pas
Pascal
uMisc.pas
agebhar1/sim8008-shared
3f0b4adfe247936489ca97ad9ae778f9cfef71ee
[ "MIT" ]
null
null
null
uMisc.pas
agebhar1/sim8008-shared
3f0b4adfe247936489ca97ad9ae778f9cfef71ee
[ "MIT" ]
null
null
null
uMisc.pas
agebhar1/sim8008-shared
3f0b4adfe247936489ca97ad9ae778f9cfef71ee
[ "MIT" ]
null
null
null
unit uMisc; interface uses Windows, SysUtils, Registry, Classes, Forms; type TRegistryList = class; IRegistry = interface(IInterface) procedure LoadData(RegistryList: TRegistryList); procedure SaveData(RegistryList: TRegistryList); end; TRegistryList = class(TObject) private _List: TInterfaceList; _Registry: TRegistry; public constructor Create; destructor Destroy; override; procedure AddListener(Listener: IRegistry); procedure DelListeners; procedure LoadData; procedure SaveData; procedure LoadFormSettings(Form: TForm; LoadSize: Boolean); procedure SaveFormSettings(Form: TForm; SaveSize: Boolean); property Registry: TRegistry read _Registry write _Registry; end; TWatchType = (wtRAM, wtIPort, wtOPort); TWatchItem = class(TObject) private _Address: Word; _Type: TWatchType; public constructor Create; property Address: Word read _Address write _Address; property WatchType: TWatchType read _Type write _Type; end; TWatchList = class(TObject) private _List: TList; function getItem(Index: Integer): TWatchItem; public constructor Create; destructor Destroy; override; function Add(Address: Word; WatchType: TWatchType): Integer; procedure Delete(Index: Integer); function FindAddress(Address: Word; WatchType: TWatchType): Integer; function AddressExists(Address: Word; WatchType: TWatchType): Boolean; procedure Clear; function Count: Integer; property Item[Index: Integer]: TWatchItem read getItem; end; TBreakpointItem = class(TObject) private _State: Boolean; _Line: Integer; public constructor Create; property Line: Integer read _Line write _Line; property State: Boolean read _State write _State; end; TBreakpointList = class(TObject) private _List: TList; function FindItem(Line: Integer; var found: Boolean): Integer; function getBreakpointState(Line: Integer): Boolean; procedure setBreakpointState(Line: Integer; State: Boolean); function getItem(Index: Integer): TBreakpointItem; public constructor Create; destructor Destroy; override; procedure ClearAllBreakpoints; function Count: Integer; function ToggleBreakpoint(Line: Integer): Boolean; function Breakpoint(Line: Integer): Boolean; property BreakpointState[Line: Integer]: Boolean read GetBreakpointState write SetBreakpointState; property Items[Index: Integer]: TBreakpointItem read getItem; end; const COMPANY_KEY = 'Andreas Gebhardt'; APPLICATION_KEY = 'Sim 8008'; VERSION_KEY = 'V2'; APPLICATION_MAIN_KEY = '\Software\'+COMPANY_KEY+'\'+APPLICATION_KEY+'\'+VERSION_KEY+'\'; implementation { ********* TRegistryList ********* } constructor TRegistryList.Create; begin inherited Create; _List:= TInterfaceList.Create; end; destructor TRegistryList.Destroy; begin DelListeners; _List.Free; inherited Destroy; end; procedure TRegistryList.AddListener(Listener: IRegistry); begin if Assigned(Listener) then _List.Add(Listener); end; procedure TRegistryList.DelListeners; begin _List.Clear; end; procedure TRegistryList.LoadData; var i: Integer; Listener: IRegistry; begin Registry:= TRegistry.Create(KEY_READ); if Assigned(Registry) then begin Registry.RootKey:= HKEY_CURRENT_USER; for i:= 0 to _List.Count-1 do begin Listener:= IRegistry(_List.Items[i]); if Assigned(Listener) then Listener.LoadData(Self); end; Registry.Free; end; end; procedure TRegistryList.SaveData; var i: Integer; Listener: IRegistry; begin Registry:= TRegistry.Create(KEY_WRITE); if Assigned(Registry) then begin Registry.RootKey:= HKEY_CURRENT_USER; for i:= 0 to _List.Count-1 do begin Listener:= IRegistry(_List.Items[i]); if Assigned(Listener) then Listener.SaveData(Self); end; Registry.Free; end; end; procedure TRegistryList.LoadFormSettings(Form: TForm; LoadSize: Boolean); var sScreen: String; begin if Assigned(Form) and Assigned(Registry) then begin if Registry.ValueExists(Form.Name+'_'+'Visible') then if Registry.ReadInteger(Form.Name+'_'+'Visible') = 1 then Form.Show; sScreen:= IntToStr(Screen.Width)+'x'+IntToStr(Screen.Height); if Registry.ValueExists(Form.Name+'_'+sScreen+'_Top') then Form.Top:= Registry.ReadInteger(Form.Name+'_'+sScreen+'_Top'); if Registry.ValueExists(Form.Name+'_'+sScreen+'_Left') then Form.Left:= Registry.ReadInteger(Form.Name+'_'+sScreen+'_Left'); if LoadSize then begin if Registry.ValueExists(Form.Name+'_'+sScreen+'_Width') then Form.Width:= Registry.ReadInteger(Form.Name+'_'+sScreen+'_Width'); if Registry.ValueExists(Form.Name+'_'+sScreen+'_Height') then Form.Height:= Registry.ReadInteger(Form.Name+'_'+sScreen+'_Height'); if Registry.ValueExists(Form.Name+'_'+'WindowState') then case Registry.ReadInteger(Form.Name+'_'+'WindowState') of 0: Form.WindowState:= wsNormal; 1: Form.WindowState:= wsMinimized; 2: Form.WindowState:= wsMaximized; end; end; end; end; procedure TRegistryList.SaveFormSettings(Form: TForm; SaveSize: Boolean); var sScreen: String; begin if Assigned(Form) and Assigned(Registry) then begin if Form.Visible then Registry.WriteInteger(Form.Name+'_'+'Visible',1) else Registry.WriteInteger(Form.Name+'_'+'Visible',0); sScreen:= IntToStr(Screen.Width)+'x'+IntToStr(Screen.Height); Registry.WriteInteger(Form.Name+'_'+sScreen+'_Top',Form.Top); Registry.WriteInteger(Form.Name+'_'+sScreen+'_Left',Form.Left); if SaveSize then begin Registry.WriteInteger(Form.Name+'_'+sScreen+'_Width',Form.Width); Registry.WriteInteger(Form.Name+'_'+sScreen+'_Height',Form.Height); case Form.WindowState of wsNormal : Registry.WriteInteger(Form.Name+'_'+'WindowState',0); wsMinimized : Registry.WriteInteger(Form.Name+'_'+'WindowState',1); wsMaximized : Registry.WriteInteger(Form.Name+'_'+'WindowState',2); end; end; end; end; { ******* TRegistryList ******** } { ********* TWatchItem ********* } constructor TWatchItem.Create; begin _Address:= 0; _Type:= wtRAM; end; { ********* TWatchItem ********* } { ********* TWatchList ********* } function TWatchList.getItem(Index: Integer): TWatchItem; begin if (Index >= 0) and (Index < Count) then result:= _List.Items[Index] else result:= nil; end; constructor TWatchList.Create; begin inherited Create; _List:= TList.Create; end; destructor TWatchList.Destroy; begin Clear; _List.Free; inherited Destroy; end; function TWatchList.Add(Address: Word; WatchType: TWatchType): Integer; var Item: TWatchItem; begin if not AddressExists(Address,WatchType) then begin Item:= TWatchItem.Create; Item.Address:= Address; Item.WatchType:= WatchType; result:= _List.Add(Item) end else result:= -1; end; procedure TWatchList.Delete(Index: Integer); var Item: TWatchItem; begin if (Index >= 0) and (Index < Count) then begin Item:= _List.Items[Index]; if Assigned(Item) then Item.Free; _List.Delete(Index); end; end; function TWatchList.FindAddress(Address: Word; WatchType: TWatchType): Integer; var Item: TWatchItem; i: Integer; found: Boolean; begin found:= false; i:= 0; while not found and (i < _List.Count) do begin Item:= _List.Items[i]; found:= Assigned(Item) and (Item.Address = Address) and (Item.WatchType = WatchType); if not found then Inc(i); end; if found then result:= i else result:= -1; end; function TWatchList.AddressExists(Address: Word; WatchType: TWatchType): Boolean; begin result:= FindAddress(Address,WatchType) >= 0; end; procedure TWatchList.Clear; var Item: TWatchItem; begin while _List.Count > 0 do begin Item:= _List.Items[_List.Count-1]; if Assigned(Item) then Item.Free; _List.Delete(_List.Count-1); end; end; function TWatchList.Count: Integer; begin result:= _List.Count; end; { ********* TWatchList ********* } { ****** TBreakpointItem ******* } constructor TBreakpointItem.Create; begin inherited Create; _Line:= -1; _State:= false; end; { ****** TBreakpointItem ******* } { ****** TBreakpointList ******* } procedure TBreakpointList.ClearAllBreakpoints; var Item: TBreakpointItem; begin while _List.Count > 0 do begin Item:= _List[_List.Count-1]; if Assigned(Item) then Item.Free; _List.Delete(_List.Count-1); end; end; constructor TBreakpointList.Create; begin inherited Create; _List:= TList.Create; end; destructor TBreakpointList.Destroy; begin ClearAllBreakpoints; FreeAndNil(_List); inherited; end; function TBreakpointList.FindItem(Line: Integer; var found: Boolean): Integer; var left, right: Integer; Item: TBreakpointItem; begin found:= false; left:= 0; right:= _List.Count-1; result:= 0; // Binary Search while (not found) and (left <= right) do begin result:= left + (right-left) div 2; Item:= _List[result]; found:= Line = Item.Line; if not found then begin if Line > Item.Line then left:= result + 1 else right:= result - 1; end; end; if not found then result:= right + 1; end; function TBreakpointList.Breakpoint(Line: Integer): Boolean; var Index: Integer; found: Boolean; Item: TBreakpointItem; begin Index:= FindItem(Line, found); if found then begin Item:= _List[Index]; result:= Assigned(Item); end else result:= false; end; function TBreakpointList.ToggleBreakpoint(Line: Integer): Boolean; var Index: Integer; found: Boolean; Item: TBreakpointItem; begin Index:= FindItem(Line, found); if found then begin Item:= _List[Index]; if Assigned(Item) then FreeAndNil(Item); _List.Delete(Index); end else begin Item:= TBreakpointItem.Create; Item.Line:= Line; Item.State:= true; _List.Insert(Index, Item); end; result:= not found; end; function TBreakpointList.getBreakpointState(Line: Integer): Boolean; var Index: Integer; found: Boolean; Item: TBreakpointItem; begin Index:= FindItem(Line, found); if found then begin Item:= _List[Index]; if Assigned(Item) then result:= Item.State else result:= false; end else result:= false; end; procedure TBreakpointList.setBreakpointState(Line: Integer; State: Boolean); var Index: Integer; found: Boolean; Item: TBreakpointItem; begin Index:= FindItem(Line, found); if found then begin Item:= _List[Index]; if Assigned(Item) then Item.State:= State; end; end; function TBreakpointList.Count: Integer; begin result:= _List.Count; end; function TBreakpointList.getItem(Index: Integer): TBreakpointItem; begin if (Index >=0) and (Index < Count) then result:= _List[Index] else result:= nil; end; { ****** TBreakpointList ******* } end.
26.493182
103
0.653084
4732e14d89c66edffcc134e05f575ae3e5b0a043
3,631
dpr
Pascal
04-Internet/ServeurWebBroker/Project1.dpr
DeveloppeurPascal/Des-solutions-de-synchronisations-de-donnees
0c1fba20cc1a2708acc7a7b722be132744c37216
[ "MIT" ]
3
2020-08-06T22:29:58.000Z
2021-06-24T10:01:07.000Z
04-Internet/ServeurWebBroker/Project1.dpr
DeveloppeurPascal/Des-solutions-de-synchronisations-de-donnees
0c1fba20cc1a2708acc7a7b722be132744c37216
[ "MIT" ]
null
null
null
04-Internet/ServeurWebBroker/Project1.dpr
DeveloppeurPascal/Des-solutions-de-synchronisations-de-donnees
0c1fba20cc1a2708acc7a7b722be132744c37216
[ "MIT" ]
2
2020-08-06T22:29:59.000Z
2021-04-05T02:58:43.000Z
program Project1; {$APPTYPE CONSOLE} uses System.SysUtils, System.Types, IPPeerServer, IPPeerAPI, IdHTTPWebBrokerBridge, Web.WebReq, Web.WebBroker, WebModuleUnit1 in 'WebModuleUnit1.pas' {WebModule1: TWebModule}, ServerConst1 in 'ServerConst1.pas'; {$R *.res} function BindPort(APort: Integer): Boolean; var LTestServer: IIPTestServer; begin Result := True; try LTestServer := PeerFactory.CreatePeer('', IIPTestServer) as IIPTestServer; LTestServer.TestOpenPort(APort, nil); except Result := False; end; end; function CheckPort(APort: Integer): Integer; begin if BindPort(APort) then Result := APort else Result := 0; end; procedure SetPort(const AServer: TIdHTTPWebBrokerBridge; APort: String); begin if not AServer.Active then begin APort := APort.Replace(cCommandSetPort, '').Trim; if CheckPort(APort.ToInteger) > 0 then begin AServer.DefaultPort := APort.ToInteger; Writeln(Format(sPortSet, [APort])); end else Writeln(Format(sPortInUse, [APort])); end else Writeln(sServerRunning); Write(cArrow); end; procedure StartServer(const AServer: TIdHTTPWebBrokerBridge); begin if not AServer.Active then begin if CheckPort(AServer.DefaultPort) > 0 then begin Writeln(Format(sStartingServer, [AServer.DefaultPort])); AServer.Bindings.Clear; AServer.Active := True; end else Writeln(Format(sPortInUse, [AServer.DefaultPort.ToString])); end else Writeln(sServerRunning); Write(cArrow); end; procedure StopServer(const AServer: TIdHTTPWebBrokerBridge); begin if AServer.Active then begin Writeln(sStoppingServer); AServer.Active := False; AServer.Bindings.Clear; Writeln(sServerStopped); end else Writeln(sServerNotRunning); Write(cArrow); end; procedure WriteCommands; begin Writeln(sCommands); Write(cArrow); end; procedure WriteStatus(const AServer: TIdHTTPWebBrokerBridge); begin Writeln(sIndyVersion + AServer.SessionList.Version); Writeln(sActive + AServer.Active.ToString(TUseBoolStrs.True)); Writeln(sPort + AServer.DefaultPort.ToString); Writeln(sSessionID + AServer.SessionIDCookieName); Write(cArrow); end; procedure RunServer(APort: Integer); var LServer: TIdHTTPWebBrokerBridge; LResponse: string; begin WriteCommands; LServer := TIdHTTPWebBrokerBridge.Create(nil); try LServer.DefaultPort := APort; while True do begin Readln(LResponse); LResponse := LowerCase(LResponse); if LResponse.StartsWith(cCommandSetPort) then SetPort(LServer, LResponse) else if sametext(LResponse, cCommandStart) then StartServer(LServer) else if sametext(LResponse, cCommandStatus) then WriteStatus(LServer) else if sametext(LResponse, cCommandStop) then StopServer(LServer) else if sametext(LResponse, cCommandHelp) then WriteCommands else if sametext(LResponse, cCommandExit) then if LServer.Active then begin StopServer(LServer); break end else break else begin Writeln(sInvalidCommand); Write(cArrow); end; end; finally LServer.Free; end; end; begin try if WebRequestHandler <> nil then WebRequestHandler.WebModuleClass := WebModuleClass; RunServer(8080); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end end.
23.425806
79
0.667034
f1b7fc60e32964caf865791c505f7f5c47c4e17a
4,792
pas
Pascal
EventEngine/src/Event.Engine.Utils.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
3
2020-11-06T15:46:18.000Z
2021-06-24T09:23:29.000Z
EventEngine/src/Event.Engine.Utils.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
null
null
null
EventEngine/src/Event.Engine.Utils.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
3
2020-10-31T00:46:34.000Z
2021-06-23T15:23:27.000Z
unit Event.Engine.Utils; interface uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} System.SysUtils, Spring, Event.Engine.Interfaces; type Utils = record private class var Reference: TStopwatch; class constructor CreateIni; public class function CreateEvent<T>: IEvent<T>; static; {$IFDEF MSWINDOWS} class procedure IdeDebugMsg(const AMsg: String); static; {$ENDIF} class function iif<T>(const ACondition: Boolean; AResult_True, AResult_False: T): T; overload; static; class function iif<T>(const ACondition: Boolean; AResult_True, AResult_False: TFunc<T>): T; overload; static; class function StringToCaseSelect(const Selector: string; const CaseList: array of string): integer; static; class function InterfaceToCaseSelect(Selector: IInterface; const CaseList: array of TGUID): integer; static; class function IsMainThreadUI: Boolean; static; class procedure DelegateExecution(AProc: TProc; AExecutionMode: EDelegatedExecutionMode); overload; static; class procedure DelegateExecution<T>(AData: T; AProc: TProc<T>; AExecutionMode: EDelegatedExecutionMode); overload; static; class function ElapsedMiliseconds: Int64; static; class function ElapsedTicks: Int64; static; class function GetTimeStamp: Int64; static; class function Elapsed: TTimeSpan; static; class function GetReferenceTime: Double; static; end; implementation uses System.Classes, System.Threading; { Utils } class function Utils.CreateEvent<T>: IEvent<T>; var E: Event<T>; begin Result := E; end; class constructor Utils.CreateIni; begin Reference := TStopwatch.Create; Reference.Start; end; class procedure Utils.DelegateExecution(AProc: TProc; AExecutionMode: EDelegatedExecutionMode); begin case AExecutionMode of medQueue: begin TThread.Queue(TThread.CurrentThread, procedure begin AProc; end); end; medSynchronize: begin TThread.Synchronize(TThread.CurrentThread, procedure begin AProc end); end; medNewTask: begin TTask.Create( procedure begin AProc end).Start; end; medNormal: begin AProc; end; end; end; class procedure Utils.DelegateExecution<T>(AData: T; AProc: TProc<T>; AExecutionMode: EDelegatedExecutionMode); begin case AExecutionMode of medQueue: begin TThread.Queue(TThread.CurrentThread, procedure begin AProc(AData); end); end; medSynchronize: begin TThread.Synchronize(TThread.CurrentThread, procedure begin AProc(AData) end); end; medNewTask: begin TTask.Create( procedure begin AProc(AData) end).Start; end; medNormal: begin AProc(AData); end; end; end; class function Utils.Elapsed: TTimeSpan; begin Result := Reference.Elapsed; end; class function Utils.ElapsedMiliseconds: Int64; begin Result := Reference.ElapsedMilliseconds; end; class function Utils.ElapsedTicks: Int64; begin Result := Reference.ElapsedTicks; end; class function Utils.GetReferenceTime: Double; begin Result := TStopwatch.GetTimeStamp / TStopwatch.Frequency; end; class function Utils.GetTimeStamp: Int64; begin Result := Reference.GetTimeStamp end; {$IFDEF MSWINDOWS} class procedure Utils.IdeDebugMsg(const AMsg: String); begin OutputDebugString(PChar(FormatDateTime('hhnnss.zzz', Now) + AMsg)); end; {$ENDIF} class function Utils.iif<T>(const ACondition: Boolean; AResult_True, AResult_False: TFunc<T>): T; begin if ACondition then Result := AResult_True else Result := AResult_False; end; class function Utils.iif<T>(const ACondition: Boolean; AResult_True, AResult_False: T): T; begin if ACondition then Result := AResult_True else Result := AResult_False; end; class function Utils.InterfaceToCaseSelect(Selector: IInterface; const CaseList: array of TGUID): integer; var LCnt: integer; begin Result := -1; for LCnt := 0 to Length(CaseList) - 1 do begin if Supports(Selector, CaseList[LCnt]) then begin Result := LCnt; break; end; end; end; class function Utils.IsMainThreadUI: Boolean; begin Result := TThread.Current.ThreadID = MainThreadID; end; class function Utils.StringToCaseSelect(const Selector: string; const CaseList: array of string): integer; var LCnt: integer; begin Result := -1; for LCnt := 0 to Length(CaseList) - 1 do begin if CompareText(Selector, CaseList[LCnt]) = 0 then begin Result := LCnt; break; end; end; end; end.
22.288372
127
0.680301
47505a952f96ed0e0e4e8916c916fbf1ef7c5af9
664
pas
Pascal
1. Konsep Pemilihan/CharsTester.pas
belajarstatistik/Algoritma-Pemrograman
4f33b359254db167b6107757d35d50d391d836e2
[ "MIT" ]
null
null
null
1. Konsep Pemilihan/CharsTester.pas
belajarstatistik/Algoritma-Pemrograman
4f33b359254db167b6107757d35d50d391d836e2
[ "MIT" ]
null
null
null
1. Konsep Pemilihan/CharsTester.pas
belajarstatistik/Algoritma-Pemrograman
4f33b359254db167b6107757d35d50d391d836e2
[ "MIT" ]
null
null
null
program CharsTester; label 1000, 2000; {deklarasi label} var InputChar:char; begin 1000: write('Please enter a letter (or 0 to quit): ');readln(InputChar ); if InputChar = '0' then {kondisi untuk keluar} goto 2000 else if (ORD(InputChar ) > 64) and (InputChar) < 91) then writeln('This is an upper case letter.') else if (ORD(InputChar ) > 96) and ( InputChar ) < 123) then writeln('This is a lower case letter.') else if (ORD(InputChar ) > 47) and ( InputChar ) < 58) then writeln('Hey, this is a number!') else writeln('Sorry, this is not a letter.'); GOTO 1000; {mengulang program} 2000: {keluar program} end.
33.2
69
0.650602
473fed2613639aefe09ae54489114b13d87cbe97
1,993
pas
Pascal
MemDBF.pas
atkins126/Utils
a4fc52727b5019b598a8cdec4b45039dc1fdf00b
[ "MIT" ]
6
2020-08-01T01:17:33.000Z
2021-05-16T01:18:00.000Z
MemDBF.pas
atkins126/Utils
a4fc52727b5019b598a8cdec4b45039dc1fdf00b
[ "MIT" ]
null
null
null
MemDBF.pas
atkins126/Utils
a4fc52727b5019b598a8cdec4b45039dc1fdf00b
[ "MIT" ]
3
2019-12-31T01:29:21.000Z
2020-09-09T02:42:56.000Z
unit MemDBF; //////////////////////////////////////////////////////////////////////////////// // // Author: Jaap Baak // https://github.com/transportmodelling/Utils // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// Uses SysUtils,Data.DB,FireDac.Comp.Client,DBF; Type TDBFMemDataSet = record Class Procedure Read(const DBFFileName: String; const MemDataSet: TFDMemTable); static; end; //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// Class Procedure TDBFMemDataSet.Read(const DBFFileName: String; const MemDataSet: TFDMemTable); begin var DBFReader := TDBFReader.Create(DBFFileName); try // Read fields MemDataSet.FieldDefs.Clear; for var Field := 0 to DBFReader.FieldCount-1 do case DBFReader.FieldTypes[Field] of 'C': MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftString,DBFReader.FieldLength[Field]); 'D': MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftDate); 'L': MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftBoolean); 'F','N': if DBFReader.DecimalCount[Field] = 0 then MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftInteger) else MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftFloat) end; MemDataSet.CreateDataSet; // Read data for var Rec := 0 to DBFReader.RecordCount-1 do if DBFReader.NextRecord then begin MemDataSet.Append; for var Field := 0 to DBFReader.FieldCount-1 do MemDataSet.Fields[Field].Value := DBFReader[Field]; end else raise exception.Create('Error reading DBF-file'); MemDataSet.First; finally DBFReader.Free; end; end; end.
33.779661
105
0.53437
4738a38c5c08985133e664c13389108f3a49673d
84,747
dpr
Pascal
dll/oimenuapi.dpr
oimenu/oimenu-delphi
a4099af2aaf2d7aedda88f5bd7d30779f6d926ef
[ "MIT" ]
1
2019-04-25T14:50:37.000Z
2019-04-25T14:50:37.000Z
dll/oimenuapi.dpr
oimenu/oimenu-delphi
a4099af2aaf2d7aedda88f5bd7d30779f6d926ef
[ "MIT" ]
null
null
null
dll/oimenuapi.dpr
oimenu/oimenu-delphi
a4099af2aaf2d7aedda88f5bd7d30779f6d926ef
[ "MIT" ]
null
null
null
library oimenuapi; { Important note about DLL memory management: ShareMem must be the first unit in your library's USES clause AND your project's (select Project-View Source) USES clause if your DLL exports any procedures or functions that pass strings as parameters or function results. This applies to all strings passed to and from your DLL--even those that are nested in records and classes. ShareMem is the interface unit to the BORLNDMM.DLL shared memory manager, which must be deployed along with your DLL. To avoid using BORLNDMM.DLL, pass string information using PChar or ShortString parameters. } uses SysUtils, Classes, IdHTTP, Contnrs, uJSON in 'uJSON.pas'; {$R *.res} //PARAM type TRequestParam = class token : PChar; customUrl : PChar; end; //SIMPLE RESULT type TSimpleResult = class success : Boolean; message : PChar; responseCode : Integer; data : PChar; count : Integer; end; //ORDER type TOrderProduct = class code : PChar; name : PChar; quantity : Integer; price : Double; end; type TOrderItemOption = class id : PChar; optionId : PChar; code : PChar; name : PChar; quantity : Integer; price : Double; notes : TStringList; extraFields : PChar; constructor Create; Destructor Destroy; end; type TListOrderItemOption = Class( TObjectList ) private function GetItems(Index: Integer): TOrderItemOption; procedure SetItems(Index: Integer; const Value: TOrderItemOption); public function Add(AObject: TOrderItemOption): Integer; property Items[Index: Integer]: TOrderItemOption read GetItems write SetItems; default; End; type TOrderItem = class id : PChar; code : PChar; name : PChar; quantity : Integer; price : Double; options : TListOrderItemOption; notes : TStringList; extraFields : PChar; constructor Create; Destructor Destroy; end; type TListOrderItem = Class( TObjectList ) private function GetItems(Index: Integer): TOrderItem; procedure SetItems(Index: Integer; const Value: TOrderItem); public function Add(AObject: TOrderItem): Integer; property Items[Index: Integer]: TOrderItem read GetItems write SetItems; default; End; type TOrder = class id : PChar; date : PChar; table : Integer; card : Integer; waiter : PChar; items : TListOrderItem; constructor Create; Destructor Destroy; end; type TListOrder = Class( TObjectList ) private function GetItems(Index: Integer): TOrder; procedure SetItems(Index: Integer; const Value: TOrder); public function Add(AObject: TOrder): Integer; property Items[Index: Integer]: TOrder read GetItems write SetItems; default; End; type TOrderResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListOrder; count : Integer; constructor Create; Destructor Destroy; end; Constructor TOrderItemOption.Create; begin notes := TStringList.Create; end; Destructor TOrderItemOption.Destroy; begin FreeAndNil(notes); end; Constructor TOrderItem.Create; begin options := TListOrderItemOption.Create; notes := TStringList.Create; end; Destructor TOrderItem.Destroy; begin FreeAndNil(options); FreeAndNil(notes); end; Constructor TOrder.Create; begin items := TListOrderItem.Create; end; Destructor TOrder.Destroy; begin FreeAndNil(items); end; Constructor TOrderResult.Create; begin data := TListOrder.Create; end; Destructor TOrderResult.Destroy; begin FreeAndNil(data); end; function TListOrderItemOption.GetItems(Index: Integer): TOrderItemOption; begin Result := TOrderItemOption(inherited Items[Index]); end; procedure TListOrderItemOption.SetItems(Index: Integer; const Value: TOrderItemOption); begin inherited Items[Index] := Value; end; function TListOrderItemOption.Add(AObject: TOrderItemOption): Integer; begin Result := inherited Add(AObject); end; function TListOrderItem.GetItems(Index: Integer): TOrderItem; begin Result := TOrderItem(inherited Items[Index]); end; procedure TListOrderItem.SetItems(Index: Integer; const Value: TOrderItem); begin inherited Items[Index] := Value; end; function TListOrderItem.Add(AObject: TOrderItem): Integer; begin Result := inherited Add(AObject); end; function TListOrder.GetItems(Index: Integer): TOrder; begin Result := TOrder(inherited Items[Index]); end; procedure TListOrder.SetItems(Index: Integer; const Value: TOrder); begin inherited Items[Index] := Value; end; function TListOrder.Add(AObject: TOrder): Integer; begin Result := inherited Add(AObject); end; //BILL type TBillItem = class total : Double; items : TListOrderItem; constructor Create; Destructor Destroy; end; type TBillResult = class success : Boolean; message : PChar; responseCode : Integer; data : TBillItem; count : Integer; constructor Create; Destructor Destroy; end; Constructor TBillResult.Create; begin data := TBillItem.Create; end; Destructor TBillResult.Destroy; begin FreeAndNil(data); end; Constructor TBillItem.Create; begin items := TListOrderItem.Create; end; Destructor TBillItem.Destroy; begin FreeAndNil(items); end; //EVENT type TEventTheCheck = class table : PChar; card : PChar; waiter : PChar; document : PChar; splitWith : PChar; end; type TEventCallWaiter = class table : PChar; waiter : PChar; options : TStringList; constructor Create; Destructor Destroy; end; type TEvent = class id : PChar; date : PChar; eventType : PChar; data : TObject; end; type TListEvent = Class( TObjectList ) private function GetItems(Index: Integer): TEvent; procedure SetItems(Index: Integer; const Value: TEvent); public function Add(AObject: TEvent): Integer; property Items[Index: Integer]: TEvent read GetItems write SetItems; default; End; type TEventResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListEvent; count : Integer; constructor Create; Destructor Destroy; end; Constructor TEventResult.Create; begin data := TListEvent.Create; end; Destructor TEventResult.Destroy; begin FreeAndNil(data); end; function TListEvent.GetItems(Index: Integer): TEvent; begin Result := TEvent(inherited Items[Index]); end; procedure TListEvent.SetItems(Index: Integer; const Value: TEvent); begin inherited Items[Index] := Value; end; function TListEvent.Add(AObject: TEvent): Integer; begin Result := inherited Add(AObject); end; Constructor TEventCallWaiter.Create; begin options := TStringList.Create; end; Destructor TEventCallWaiter.Destroy; begin FreeAndNil(options); end; //PRODUCT type TProduct = class code : PChar; name : PChar; price : Double; extraFields : PChar; end; type TListProduct = Class( TObjectList ) private function GetItems(Index: Integer): TProduct; procedure SetItems(Index: Integer; const Value: TProduct); public function Add(AObject: TProduct): Integer; property Items[Index: Integer]: TProduct read GetItems write SetItems; default; End; type TProductResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListProduct; count : Integer; constructor Create; Destructor Destroy; end; Constructor TProductResult.Create; begin data := TListProduct.Create; end; Destructor TProductResult.Destroy; begin FreeAndNil(data); end; function TListProduct.GetItems(Index: Integer): TProduct; begin Result := TProduct(inherited Items[Index]); end; procedure TListProduct.SetItems(Index: Integer; const Value: TProduct); begin inherited Items[Index] := Value; end; function TListProduct.Add(AObject: TProduct): Integer; begin Result := inherited Add(AObject); end; //TABLE type TTable = class code : Integer; name : PChar; servicePercentage : Double; end; type TListTable = Class( TObjectList ) private function GetItems(Index: Integer): TTable; procedure SetItems(Index: Integer; const Value: TTable); public function Add(AObject: TTable): Integer; property Items[Index: Integer]: TTable read GetItems write SetItems; default; End; type TTableResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListTable; count : Integer; constructor Create; Destructor Destroy; end; Constructor TTableResult.Create; begin data := TListTable.Create; end; Destructor TTableResult.Destroy; begin FreeAndNil(data); end; function TListTable.GetItems(Index: Integer): TTable; begin Result := TTable(inherited Items[Index]); end; procedure TListTable.SetItems(Index: Integer; const Value: TTable); begin inherited Items[Index] := Value; end; function TListTable.Add(AObject: TTable): Integer; begin Result := inherited Add(AObject); end; //CARD type TCard = class code : Integer; qrCode : PChar; servicePercentage : Double; end; type TListCard = Class( TObjectList ) private function GetItems(Index: Integer): TCard; procedure SetItems(Index: Integer; const Value: TCard); public function Add(AObject: TCard): Integer; property Items[Index: Integer]: TCard read GetItems write SetItems; default; End; type TCardResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListCard; count : Integer; constructor Create; Destructor Destroy; end; Constructor TCardResult.Create; begin data := TListCard.Create; end; Destructor TCardResult.Destroy; begin FreeAndNil(data); end; function TListCard.GetItems(Index: Integer): TCard; begin Result := TCard(inherited Items[Index]); end; procedure TListCard.SetItems(Index: Integer; const Value: TCard); begin inherited Items[Index] := Value; end; function TListCard.Add(AObject: TCard): Integer; begin Result := inherited Add(AObject); end; //USER type TUser = class code : Integer; name : PChar; active : Boolean; end; type TListUser = Class( TObjectList ) private function GetItems(Index: Integer): TUser; procedure SetItems(Index: Integer; const Value: TUser); public function Add(AObject: TUser): Integer; property Items[Index: Integer]: TUser read GetItems write SetItems; default; End; type TUserResult = class success : Boolean; message : PChar; responseCode : Integer; data : TListUser; count : Integer; constructor Create; Destructor Destroy; end; Constructor TUserResult.Create; begin data := TListUser.Create; end; Destructor TUserResult.Destroy; begin FreeAndNil(data); end; function TListUser.GetItems(Index: Integer): TUser; begin Result := TUser(inherited Items[Index]); end; procedure TListUser.SetItems(Index: Integer; const Value: TUser); begin inherited Items[Index] := Value; end; function TListUser.Add(AObject: TUser): Integer; begin Result := inherited Add(AObject); end; //ITEM type TItemResult = class success : Boolean; message : PChar; responseCode : Integer; data : TOrderItem; count : Integer; end; const apiUrl : String = 'https://developers.oimenu.com.br'; apiVersion : String = 'v1'; function getJson(param: TRequestParam; method: String; api: String; postJson: String):TJSONObject; var url, requestResult : String; PostDataStream : TStringStream; IdHTTP: TIdHTTP; jsonToSend: TStringStream; jsonObj: TJSONObject; begin requestResult := ''; IdHTTP := TIdHTTP.Create(nil); IdHTTP.Request.UserAgent := 'Mozilla/5.0'; IdHTTP.Request.CustomHeaders.Add('Authorization:Bearer ' + param.token); IdHTTP.Request.ContentType := 'application/json'; IdHTTP.Request.CharSet := 'utf-8'; if (Length(param.customUrl) > 0) then url := param.customUrl + '/' + api else url := apiUrl + '/api/' + apiVersion + '/' + api; try try if (method = 'POST') then begin jsonToSend := TStringStream.Create(Utf8Encode(postJson)); requestResult := UTF8Decode(IdHTTP.Post(url, jsonToSend)); end else if (method = 'PUT') then begin if (postJson <> '') then jsonToSend := TStringStream.Create(Utf8Encode(postJson)) else jsonToSend := nil; requestResult := UTF8Decode(IdHTTP.Put(url, jsonToSend)); end else if (method = 'DELETE') then begin PostDataStream := TStringStream.Create(''); IdHTTP.Delete(url, PostDataStream); requestResult := UTF8Decode(PostDataStream.DataString); end else if (method = 'GET') then begin PostDataStream := TStringStream.Create(''); IdHTTP.Get(url, PostDataStream); requestResult := UTF8Decode(PostDataStream.DataString); end; except on E: EIdHTTPProtocolException do begin requestResult := StringReplace(E.ErrorMessage,#13#10, ' ', [rfReplaceAll, rfIgnoreCase]); end; on E: Exception do requestResult := '{"success":"false","message":"'+StringReplace(E.Message,#13#10, ' ', [rfReplaceAll, rfIgnoreCase])+'","code":"501"}'; end; finally IdHTTP.Disconnect; jsonObj := TJSONObject.create(requestResult); if (jsonObj.has('success') = false) then jsonObj.put('success', 'false'); if (jsonObj.has('code') = false) then jsonObj.put('code', 200); if (jsonObj.has('message') = false) then jsonObj.put('message', ''); Result := jsonObj; end; end; //PRODUCT function createProduct(param: TRequestParam; product: TProduct): TProductResult;stdcall; var productResult: TProductResult; jsonObj: TJSONObject; list: TListProduct; begin jsonObj := TJSONObject.create; jsonObj.put('code', product.code); jsonObj.put('name', product.name); jsonObj.put('price', product.price); jsonObj.put('extra_fields', product.extraFields); jsonObj := getJson(param, 'POST', 'product', jsonObj.toString); productResult := TProductResult.Create; productResult.success := jsonObj.getBoolean('success'); productResult.message := PChar(jsonObj.getString('message')); productResult.responseCode := jsonObj.getInt('code'); if (productResult.success) then begin productResult.count := 1; product := TProduct.Create; product.code := PChar(jsonObj.getJSONObject('data').getString('code')); product.name := PChar(jsonObj.getJSONObject('data').getString('name')); product.price := jsonObj.getJSONObject('data').getDouble('price'); product.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); list := TListProduct.Create; list.Add(product); productResult.data := list; end else begin productResult.count := 0; end; Result := productResult; end; function batchProducts(param: TRequestParam; products: TListProduct): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; jsonArray: TJSONArray; count: Integer; begin jsonArray := TJSONArray.create; for count := 0 to products.Count-1 do begin jsonObj := TJSONObject.create; jsonObj.put('code', products.Items[count].code); jsonObj.put('name', products.Items[count].name); jsonObj.put('price', products.Items[count].price); jsonObj.put('extra_fields', products.Items[count].extraFields); jsonArray.put(jsonObj); end; jsonObj := getJson(param, 'POST', 'products', jsonArray.toString); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function updateProduct(param: TRequestParam; product: TProduct): TProductResult;stdcall; var productResult: TProductResult; jsonObj: TJSONObject; list: TListProduct; begin jsonObj := TJSONObject.create; jsonObj.put('code', product.code); jsonObj.put('name', product.name); jsonObj.put('price', product.price); jsonObj.put('extra_fields', product.extraFields); jsonObj := getJson(param, 'PUT', 'product/' + product.code, jsonObj.toString); productResult := TProductResult.Create; productResult.success := jsonObj.getBoolean('success'); productResult.message := PChar(jsonObj.getString('message')); productResult.responseCode := jsonObj.getInt('code'); if (productResult.success) then begin productResult.count := 1; product := TProduct.Create; product.code := PChar(jsonObj.getJSONObject('data').getString('code')); product.name := PChar(jsonObj.getJSONObject('data').getString('name')); product.price := jsonObj.getJSONObject('data').getDouble('price'); product.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); list := TListProduct.Create; list.Add(product); productResult.data := list; end else begin productResult.count := 0; end; Result := productResult; end; function deleteProduct(param: TRequestParam; id: PChar): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'DELETE', 'product/' + id, ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; //ORDER function getAllOrders(param: TRequestParam): TOrderResult;stdcall; var orderResult: TOrderResult; jsonObj: TJSONObject; x, y, z, w: Integer; order: TOrder; orderItem: TOrderItem; orderItemOption: TOrderItemOption; begin jsonObj := getJson(param, 'GET', 'orders', ''); orderResult := TOrderResult.Create; orderResult.success := jsonObj.getBoolean('success'); orderResult.message := PChar(jsonObj.getString('message')); orderResult.responseCode := jsonObj.getInt('code'); if (orderResult.success) then begin orderResult.count := jsonObj.getJSONArray('data').length; for x := 0 to jsonObj.getJSONArray('data').length-1 do begin order := TOrder.Create; order.id := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('id')); order.date := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('date')); order.table := jsonObj.getJSONArray('data').getJSONObject(x).getInt('table'); if (jsonObj.getJSONArray('data').getJSONObject(x).has('card')) then if (jsonObj.getJSONArray('data').getJSONObject(x).isNull('card') = false) then order.card := jsonObj.getJSONArray('data').getJSONObject(x).getInt('card'); for y := 0 to jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').length-1 do begin orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getString('id')); orderItem.code := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getString('code')); orderItem.name := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getString('name')); orderItem.quantity := jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getInt('quantity'); orderItem.price := jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getDouble('price'); for z := 0 to jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('notes').getString(z)); orderItem.extraFields := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getString('extra_fields')); for z := 0 to jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('name')); orderItemOption.quantity := jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getInt('quantity'); orderItemOption.price := jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getDouble('price'); for w := 0 to jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getJSONArray('notes').getString(w)); orderItemOption.extraFields := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; order.items.Add(orderItem); end; orderResult.data.Add(order); end; end else begin orderResult.count := 0; end; Result := orderResult; end; function setOrderAsReceived(param: TRequestParam; id: String): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'order/' + id + '/received', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; //EVENT function getAllEvents(param: TRequestParam): TEventResult;stdcall; var eventResult: TEventResult; jsonObj: TJSONObject; x, y: Integer; event: TEvent; eventCallWaiter: TEventCallWaiter; eventTheCheck: TEventTheCheck; begin jsonObj := getJson(param, 'GET', 'events', ''); eventResult := TEventResult.Create; eventResult.success := jsonObj.getBoolean('success'); eventResult.message := PChar(jsonObj.getString('message')); eventResult.responseCode := jsonObj.getInt('code'); if (eventResult.success) then begin eventResult.count := jsonObj.getJSONArray('data').length; for x := 0 to jsonObj.getJSONArray('data').length-1 do begin event := TEvent.Create; event.id := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('id')); event.date := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('date')); event.eventType := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('type')); if (event.eventType = 'the-check') then begin eventTheCheck := TEventTheCheck.create; eventTheCheck.table := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('table')); if (jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').has('card')) then if (jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').isNull('card') = false) then eventTheCheck.card := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('card')); eventTheCheck.waiter := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('waiter')); eventTheCheck.document := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('document')); eventTheCheck.splitWith := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('split_with')); event.data := eventTheCheck; end else if (event.eventType = 'call-waiter') then begin eventCallWaiter := TEventCallWaiter.Create; eventCallWaiter.table := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('table')); eventCallWaiter.waiter := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getString('waiter')); for y := 0 to jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getJSONArray('options').length-1 do eventCallWaiter.options.Add(jsonObj.getJSONArray('data').getJSONObject(x).getJSONObject('data').getJSONArray('options').getString(y)); event.data := eventCallWaiter; end; eventResult.data.Add(event); end; end else begin eventResult.count := 0; end; Result := eventResult; end; function setEventAsReceived(param: TRequestParam; id: String): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'event/' + id + '/received', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; //TABLE ACTION function closeTable(param: TRequestParam; code: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(code) + '/close', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function transferTable(param: TRequestParam; code: Integer; codeNew: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(code) + '/transfer', '{"new_table":'+IntToStr(codeNew)+'}'); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function cancelTable(param: TRequestParam; code: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(code) + '/cancel', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function reopenTable(param: TRequestParam; code: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(code) + '/reopen', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function createTableItem(param: TRequestParam; codeTable: Integer; product: TOrderProduct): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('code', product.code); jsonObj.put('name', product.name); jsonObj.put('price', product.price); jsonObj.put('quantity', product.quantity); jsonObj := getJson(param, 'POST', 'table/' + IntToStr(codeTable) + '/item', jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function updateTableItem(param: TRequestParam; codeTable: Integer; idItem: String; quantity: Integer; price: Double ): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('quantity', quantity); jsonObj.put('price', price); jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(codeTable) + '/item/' + idItem, jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function transferTableItem(param: TRequestParam; codeTable: Integer; codeTableNew: Integer; idItem: String): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('new_table', codeTableNew); jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(codeTable) + '/item/' + idItem + '/transfer', jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); Result := itemResult; end; function transferTableItemQtd(param: TRequestParam; codeTable: Integer; codeTableNew: Integer; idItem: String; quantity: Integer): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('new_table', codeTableNew); jsonObj.put('quantity', quantity); jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(codeTable) + '/item/' + idItem + '/transfer', jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getJSONObject('new_item').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getJSONObject('new_item').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function cancelTableItem(param: TRequestParam; code: Integer; idItem: String ): TItemResult; stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(code) + '/item/' + idItem + '/cancel', ''); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function cancelTableItemQtd(param: TRequestParam; code: Integer; idItem: String; quantity: Integer ): TItemResult; stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(code) + '/item/' + idItem + '/cancel', '{"quantity":'+IntToStr(quantity)+'}'); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function getBill(param: TRequestParam; url: String): TBillResult; var billResult: TBillResult; jsonObj: TJSONObject; x, y, z, w: Integer; orderItem: TOrderItem; orderItemOption: TOrderItemOption; begin jsonObj := getJson(param, 'GET', url, ''); billResult := TBillResult.Create; billResult.success := jsonObj.getBoolean('success'); billResult.message := PChar(jsonObj.getString('message')); billResult.responseCode := jsonObj.getInt('code'); if (billResult.success) then begin billResult.count := 1; billResult.data.total := jsonObj.getJSONObject('data').getDouble('total'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('items').length-1 do begin orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getDouble('price'); for z := 0 to jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('notes').getString(z)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getString('extra_fields')); for z := 0 to jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getDouble('price'); for w := 0 to jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getJSONArray('notes').getString(w)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('items').getJSONObject(y).getJSONArray('options').getJSONObject(z).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; billResult.data.items.Add(orderItem); end; end else begin billResult.count := 0; end; Result := billResult; end; function getTableBill(param: TRequestParam; code: Integer): TBillResult;stdcall; begin Result := getBill(param, 'table/' + IntToStr(code) + '/bill'); end; function getCardBill(param: TRequestParam; code: Integer): TBillResult;stdcall; begin Result := getBill(param, 'card/' + IntToStr(code) + '/bill'); end; //CARD ACTION function closeCard(param: TRequestParam; code: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(code) + '/close', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function transferCard(param: TRequestParam; code: Integer; codeNew: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(code) + '/transfer', '{"new_card":'+IntToStr(codeNew)+'}'); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function cancelCard(param: TRequestParam; code: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(code) + '/cancel', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function reopenCard(param: TRequestParam; code: Integer ): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(code) + '/reopen', ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function createCardItem(param: TRequestParam; codeCard: Integer; product: TOrderProduct): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('code', product.code); jsonObj.put('name', product.name); jsonObj.put('price', product.price); jsonObj.put('quantity', product.quantity); jsonObj := getJson(param, 'POST', 'card/' + IntToStr(codeCard) + '/item', jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function updateCardItem(param: TRequestParam; codeCard: Integer; idItem: String; quantity: Integer; price: Double ): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('quantity', quantity); jsonObj.put('price', price); jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(codeCard) + '/item/' + idItem, jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function transferCardItem(param: TRequestParam; codeCard: Integer; codeCardNew: Integer; idItem: String): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('new_table', codeCardNew); jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(codeCard) + '/item/' + idItem + '/transfer', jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); Result := itemResult; end; function transferCardItemQtd(param: TRequestParam; codeCard: Integer; codeCardNew: Integer; idItem: String; quantity: Integer): TItemResult;stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := TJSONObject.create; jsonObj.put('new_table', codeCardNew); jsonObj.put('quantity', quantity); jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(codeCard) + '/item/' + idItem + '/transfer', jsonObj.toString); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getJSONObject('new_item').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getJSONObject('new_item').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONObject('new_item').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; itemResult.data := orderItem; end else begin itemResult.count := 0; end; Result := itemResult; end; function cancelCardItem(param: TRequestParam; code: Integer; idItem: String ): TItemResult; stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(code) + '/item/' + idItem + '/cancel', ''); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; end else begin itemResult.count := 0; end; Result := itemResult; end; function cancelCardItemQtd(param: TRequestParam; code: Integer; idItem: String; quantity: Integer ): TItemResult; stdcall; var itemResult: TItemResult; jsonObj: TJSONObject; orderItem: TOrderItem; orderItemOption: TOrderItemOption; x, y: Integer; begin jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(code) + '/item/' + idItem + '/cancel', '{"quantity":'+IntToStr(quantity)+'}'); itemResult := TItemResult.Create; itemResult.success := jsonObj.getBoolean('success'); itemResult.message := PChar(jsonObj.getString('message')); itemResult.responseCode := jsonObj.getInt('code'); if (itemResult.success) then begin itemResult.count := 1; orderItem := TOrderItem.Create; orderItem.id := PChar(jsonObj.getJSONObject('data').getString('id')); orderItem.code := PChar(jsonObj.getJSONObject('data').getString('code')); orderItem.name := PChar(jsonObj.getJSONObject('data').getString('name')); orderItem.quantity := jsonObj.getJSONObject('data').getInt('quantity'); orderItem.price := jsonObj.getJSONObject('data').getDouble('price'); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('notes').getString(x)); orderItem.extraFields := PChar(jsonObj.getJSONObject('data').getString('extra_fields')); for x := 0 to jsonObj.getJSONObject('data').getJSONArray('options').length-1 do begin orderItemOption := TOrderItemOption.Create; orderItemOption.id := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('id')); orderItemOption.optionId := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('option_id')); orderItemOption.code := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('code')); orderItemOption.name := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('name')); orderItemOption.quantity := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getInt('quantity'); orderItemOption.price := jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getDouble('price'); for y := 0 to jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').length-1 do orderItem.notes.Add(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getJSONArray('notes').getString(y)); orderItemOption.extraFields := PChar(jsonObj.getJSONObject('data').getJSONArray('options').getJSONObject(x).getString('extra_fields')); orderItem.options.Add(orderItemOption); end; end else begin itemResult.count := 0; end; Result := itemResult; end; //TABLE function getAllTables(param: TRequestParam): TTableResult;stdcall; var tableResult: TTableResult; jsonObj: TJSONObject; table: TTable; x: Integer; begin jsonObj := getJson(param, 'GET', 'tables', ''); tableResult := TTableResult.Create; tableResult.success := jsonObj.getBoolean('success'); tableResult.message := PChar(jsonObj.getString('message')); tableResult.responseCode := jsonObj.getInt('code'); if (tableResult.success) then begin tableResult.count := jsonObj.getJSONArray('data').length; for x := 0 to jsonObj.getJSONArray('data').length-1 do begin table := TTable.Create; table.code := jsonObj.getJSONArray('data').getJSONObject(x).getInt('code'); table.name := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('name')); table.servicePercentage := jsonObj.getJSONArray('data').getJSONObject(x).getDouble('service_percentage'); tableResult.data.Add(table); end; end else begin tableResult.count := 0; end; Result := tableResult; end; function createTable(param: TRequestParam; table: TTable): TTableResult;stdcall; var tableResult: TTableResult; jsonObj: TJSONObject; list: TListTable; begin jsonObj := TJSONObject.create; jsonObj.put('code', table.code); jsonObj.put('name', table.name); jsonObj.put('service_percentage', table.servicePercentage); jsonObj := getJson(param, 'POST', 'table', jsonObj.toString); tableResult := TTableResult.Create; tableResult.success := jsonObj.getBoolean('success'); tableResult.message := PChar(jsonObj.getString('message')); tableResult.responseCode := jsonObj.getInt('code'); if (tableResult.success) then begin tableResult.count := 1; table := TTable.Create; table.code := jsonObj.getJSONObject('data').getInt('code'); table.name := PChar(jsonObj.getJSONObject('data').getString('name')); table.servicePercentage := jsonObj.getJSONObject('data').getDouble('service_percentage'); list := TListTable.Create; list.Add(table); tableResult.data := list; end else begin tableResult.count := 0; end; Result := tableResult; end; function batchTables(param: TRequestParam; tables: TListTable): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; jsonArray: TJSONArray; count: Integer; begin jsonArray := TJSONArray.create; for count := 0 to tables.Count-1 do begin jsonObj := TJSONObject.create; jsonObj.put('code', tables.Items[count].code); jsonObj.put('name', tables.Items[count].name); jsonObj.put('service_percentage', tables.Items[count].servicePercentage); jsonArray.put(jsonObj); end; jsonObj := getJson(param, 'POST', 'tables', jsonArray.toString); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function updateTable(param: TRequestParam; table: TTable): TTableResult;stdcall; var tableResult: TTableResult; jsonObj: TJSONObject; list: TListTable; begin jsonObj := TJSONObject.create; jsonObj.put('code', table.code); jsonObj.put('name', table.name); jsonObj.put('service_percentage', table.servicePercentage); jsonObj := getJson(param, 'PUT', 'table/' + IntToStr(table.code), jsonObj.toString); tableResult := TTableResult.Create; tableResult.success := jsonObj.getBoolean('success'); tableResult.message := PChar(jsonObj.getString('message')); tableResult.responseCode := jsonObj.getInt('code'); if (tableResult.success) then begin tableResult.count := 1; table := TTable.Create; table.code := jsonObj.getJSONObject('data').getInt('code'); table.name := PChar(jsonObj.getJSONObject('data').getString('name')); table.servicePercentage := jsonObj.getJSONObject('data').getDouble('service_percentage'); list := TListTable.Create; list.Add(table); tableResult.data := list; end else begin tableResult.count := 0; end; Result := tableResult; end; function deleteTable(param: TRequestParam; id: Integer): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'DELETE', 'table/' + IntToStr(id), ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; //CARD function getAllCards(param: TRequestParam): TCardResult;stdcall; var cardResult: TCardResult; jsonObj: TJSONObject; card: TCard; x: Integer; begin jsonObj := getJson(param, 'GET', 'cards', ''); cardResult := TCardResult.Create; cardResult.success := jsonObj.getBoolean('success'); cardResult.message := PChar(jsonObj.getString('message')); cardResult.responseCode := jsonObj.getInt('code'); if (cardResult.success) then begin cardResult.count := jsonObj.getJSONArray('data').length; for x := 0 to jsonObj.getJSONArray('data').length-1 do begin card := TCard.Create; card.code := jsonObj.getJSONArray('data').getJSONObject(x).getInt('code'); card.qrCode := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('qr_code')); card.servicePercentage := jsonObj.getJSONArray('data').getJSONObject(x).getDouble('service_percentage'); cardResult.data.Add(card); end; end else begin cardResult.count := 0; end; Result := cardResult; end; function createCard(param: TRequestParam; card: TCard): TCardResult;stdcall; var cardResult: TCardResult; jsonObj: TJSONObject; list: TListCard; begin jsonObj := TJSONObject.create; jsonObj.put('code', card.code); jsonObj.put('qr_code', card.qrCode); jsonObj.put('service_percentage', card.servicePercentage); jsonObj := getJson(param, 'POST', 'card', jsonObj.toString); cardResult := TCardResult.Create; cardResult.success := jsonObj.getBoolean('success'); cardResult.message := PChar(jsonObj.getString('message')); cardResult.responseCode := jsonObj.getInt('code'); if (cardResult.success) then begin cardResult.count := 1; card := TCard.Create; card.code := jsonObj.getJSONObject('data').getInt('code'); card.qrCode := PChar(jsonObj.getJSONObject('data').getString('qr_code')); card.servicePercentage := jsonObj.getJSONObject('data').getDouble('service_percentage'); list := TListCard.Create; list.Add(card); cardResult.data := list; end else begin cardResult.count := 0; end; Result := cardResult; end; function batchCards(param: TRequestParam; cards: TListCard): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; jsonArray: TJSONArray; count: Integer; begin jsonArray := TJSONArray.create; for count := 0 to cards.Count-1 do begin jsonObj := TJSONObject.create; jsonObj.put('code', cards.Items[count].code); jsonObj.put('qr_code', cards.Items[count].qrCode); jsonObj.put('service_percentage', cards.Items[count].servicePercentage); jsonArray.put(jsonObj); end; jsonObj := getJson(param, 'POST', 'cards', jsonArray.toString); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function updateCard(param: TRequestParam; card: TCard): TCardResult;stdcall; var cardResult: TCardResult; jsonObj: TJSONObject; list: TListCard; begin jsonObj := TJSONObject.create; jsonObj.put('code', card.code); jsonObj.put('qr_code', card.qrCode); jsonObj.put('service_percentage', card.servicePercentage); jsonObj := getJson(param, 'PUT', 'card/' + IntToStr(card.code), jsonObj.toString); cardResult := TCardResult.Create; cardResult.success := jsonObj.getBoolean('success'); cardResult.message := PChar(jsonObj.getString('message')); cardResult.responseCode := jsonObj.getInt('code'); if (cardResult.success) then begin cardResult.count := 1; card := TCard.Create; card.code := jsonObj.getJSONObject('data').getInt('code'); card.qrCode := PChar(jsonObj.getJSONObject('data').getString('qr_code')); card.servicePercentage := jsonObj.getJSONObject('data').getDouble('service_percentage'); list := TListCard.Create; list.Add(card); cardResult.data := list; end else begin cardResult.count := 0; end; Result := cardResult; end; function deleteCard(param: TRequestParam; id: Integer): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'DELETE', 'card/' + IntToStr(id), ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; //USER function getAllUsers(param: TRequestParam): TUserResult;stdcall; var userResult: TUserResult; jsonObj: TJSONObject; user: TUser; x: Integer; begin jsonObj := getJson(param, 'GET', 'users', ''); userResult := TUserResult.Create; userResult.success := jsonObj.getBoolean('success'); userResult.message := PChar(jsonObj.getString('message')); userResult.responseCode := jsonObj.getInt('code'); if (userResult.success) then begin userResult.count := jsonObj.getJSONArray('data').length; for x := 0 to jsonObj.getJSONArray('data').length-1 do begin user := TUser.Create; user.code := jsonObj.getJSONArray('data').getJSONObject(x).getInt('code'); user.name := PChar(jsonObj.getJSONArray('data').getJSONObject(x).getString('name')); user.active := (jsonObj.getJSONArray('data').getJSONObject(x).getInt('active') = 1); userResult.data.Add(user); end; end else begin userResult.count := 0; end; Result := userResult; end; function createUser(param: TRequestParam; user: TUser): TUserResult;stdcall; var userResult: TUserResult; jsonObj: TJSONObject; list: TListUser; begin jsonObj := TJSONObject.create; jsonObj.put('code', user.code); jsonObj.put('name', user.name); if (user.active) then jsonObj.put('active', 1) else jsonObj.put('active', 0); jsonObj := getJson(param, 'POST', 'user', jsonObj.toString); userResult := TUserResult.Create; userResult.success := jsonObj.getBoolean('success'); userResult.message := PChar(jsonObj.getString('message')); userResult.responseCode := jsonObj.getInt('code'); if (userResult.success) then begin userResult.count := 1; user := TUser.Create; user.code := jsonObj.getJSONObject('data').getInt('code'); user.name := PChar(jsonObj.getJSONObject('data').getString('name')); user.active := (jsonObj.getJSONObject('data').getInt('active') = 1); list := TListUser.Create; list.Add(user); userResult.data := list; end else begin userResult.count := 0; end; Result := userResult; end; function batchUsers(param: TRequestParam; users: TListUser): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; jsonArray: TJSONArray; count: Integer; begin jsonArray := TJSONArray.create; for count := 0 to users.Count-1 do begin jsonObj := TJSONObject.create; jsonObj.put('code', users.Items[count].code); jsonObj.put('name', users.Items[count].name); if (users.Items[count].active) then jsonObj.put('active', 1) else jsonObj.put('active', 0); jsonArray.put(jsonObj); end; jsonObj := getJson(param, 'POST', 'users', jsonArray.toString); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; function updateUser(param: TRequestParam; user: TUser): TUserResult;stdcall; var userResult: TUserResult; jsonObj: TJSONObject; list: TListUser; begin jsonObj := TJSONObject.create; jsonObj.put('code', user.code); jsonObj.put('name', user.name); if (user.active) then jsonObj.put('active', 1) else jsonObj.put('active', 1); jsonObj := getJson(param, 'PUT', 'user/' + IntToStr(user.code), jsonObj.toString); userResult := TUserResult.Create; userResult.success := jsonObj.getBoolean('success'); userResult.message := PChar(jsonObj.getString('message')); userResult.responseCode := jsonObj.getInt('code'); if (userResult.success) then begin userResult.count := 1; user := TUser.Create; user.code := jsonObj.getJSONObject('data').getInt('code'); user.name := PChar(jsonObj.getJSONObject('data').getString('name')); user.active := (jsonObj.getJSONObject('data').getInt('active') = 1); list := TListUser.Create; list.Add(user); userResult.data := list; end else begin userResult.count := 0; end; Result := userResult; end; function deleteUser(param: TRequestParam; id: Integer): TSimpleResult;stdcall; var simpleResult: TSimpleResult; jsonObj: TJSONObject; begin jsonObj := getJson(param, 'DELETE', 'user/' + IntToStr(id), ''); simpleResult := TSimpleResult.Create; simpleResult.success := jsonObj.getBoolean('success'); simpleResult.message := PChar(jsonObj.getString('message')); simpleResult.responseCode := jsonObj.getInt('code'); simpleResult.count := 0; Result := simpleResult; end; exports createProduct, batchProducts, updateProduct, deleteProduct, getAllOrders, setOrderAsReceived, getAllEvents, setEventAsReceived, closeTable, transferTable, cancelTable, reopenTable, createTableItem, updateTableItem, transferTableItem, transferTableItemQtd, cancelTableItem, cancelTableItemQtd, getTableBill, getCardBill, closeCard, transferCard, cancelCard, reopenCard, createCardItem, updateCardItem, transferCardItem, transferCardItemQtd, cancelCardItem, cancelCardItemQtd, getAllTables, createTable, batchTables, updateTable, deleteTable, getAllCards, createCard, batchCards, updateCard, deleteCard, getAllUsers, createUser, batchUsers, updateUser, deleteUser; begin end.
35.548238
202
0.675458
8394f8fde0835acc2af54c07890a5f9ff0e774a1
14,270
pas
Pascal
mothershipwebserver.pas
randydom/commonx
2315f1acf41167bd77ba4d040b3f5b15a5c5b81a
[ "MIT" ]
1
2020-08-25T00:02:54.000Z
2020-08-25T00:02:54.000Z
mothershipwebserver.pas
wkfff/commonx
787b9a4a1e7c02f55d81d2236b0cc9f332b38f53
[ "MIT" ]
null
null
null
mothershipwebserver.pas
wkfff/commonx
787b9a4a1e7c02f55d81d2236b0cc9f332b38f53
[ "MIT" ]
1
2020-08-25T00:02:55.000Z
2020-08-25T00:02:55.000Z
unit MothershipWebserver; //Contains the TMotherShipWebServer class and related classes. interface uses WebConfig, WebStats, DataObjectServices, sysutils, windows, REquestManager, classes, sharedobject, webdispatch, RequestInfo, backgroundthreads, versioninfo, systemx, simplewinsock, stringx, stringx.ansi, helplookup, dir, dirfile; type Tmothershipwebserver = class;//forward TMothershipStartupRoutine = procedure (sender: TMothershipWebServer); TMothershipShutdownRoutine = procedure (sender: TMothershipWebServer); TMothershipWebServerState = ( wssInit, //The Web Server is initializing resources. wssReady, //The Web Server is Ready for a command. wssStarting, //The web server is starting. wssRunning, //The Web server is running, Listening. wssStopping, //The Web Server is in the process of stopping. wssStopped, //The Web Server is stopped, not listening. wssDestroy //The Web Server object is being destroyed. ); TMothershipWebServerOptions = set of (pwsNoDOS, pwsNoHelp, pwsNoINI, pwsNoPlugins); TMothershipWebServer = class (TSharedObject) //TMothershipWebServer represents the abstracted web server in PWLN. It is essentially //the ENGINE, encapsulating all the parts required to dispatch and produce web pages. //It is important to note that it DOES NOT: //<li>Establish a listening socket</li> //<li>Parse HTTP Request Headers</li> //<li>Build HTTP Response Headers (directly)</li> //The key word here is "ABSTRACTED". Requests come to TMothershipWebServer after //the outer abstraction layer converts them to an abstract format that TMothershipWebServer can work with. //<H2>PWLN Functional Layering</H2> //<TABLE border="1"> //<TR><TD colspan="1">Web Server (IIS)</TD><TD colspan="1">Web Server (native listener/other)</TD><TR> //<TR><TD colspan="1">Web Server Access Later (IIS)</TD><TD colspan="1">Web Server Access Layer(other)</TD><TR> //<TR><TD colspan="1">Web Server Adapter [TPWLN]</TD><TD colspan="1">WebS erver Adapter [TWebThread]</TD><TR> //<TR><TD colspan="2">Web Server Dispatcher</TD><TR> //<TR><TD colspan="2">Web Request (Individual dispatched page)</TD><TR> //<TR><TD colspan="2">Middle Tier to Data-Tier Interface [MTDTInterface]</TD><TR> //<TR><TD colspan="2">Data Object Services/Caching</TD><TR> //<TR><TD colspan="2">Server Interface Layer</TD><TR> //<TR><TD colspan="2">Network Language Layer [TPacket]</TD><TR> //<TR><TD colspan="2">Transport Layer [TTransport]</TD><TR> //<TR><TD colspan="2">Communication Layer [TSimpleAbstractConnection]</TD><TR> //</TABLE> private FHits, FHitAccepts: int64; FState: TMothershipWebServerState; FStopListening, FStartListening: TNotifyEvent; FHelp: THelpLookup; Foptions: TMothershipWebServerOptions; FStartupRoutines: TList; FShutdownRoutines: Tlist; function GetState: TMothershipWebServerState; procedure SetState(const Value: TMothershipWebServerState); function GetStateString: ansistring; function GetHitCount: int64; function GEtShutdownRoutine(idx: integer): TMothershipShutdownRoutine; function GetStartupRoutine(idx: integer): TMothershipStartupRoutine; function GetHitAcceptCount: int64; public constructor create;override; procedure Configure(sPublicKeyName: ansistring; options: TMothershipWebServerOptions);reintroduce; destructor Destroy; override; procedure Start; procedure Stop; function DispatchWebRequest(rqInfo: TRequestInfo): boolean; property State: TMothershipWebServerState read GetState write SetState; //Reports the state of the server. Running, Stopped, etc. See TMothershipWebServerState. property StateString: ansistring read GetStateString; //Returns a displayable ansistring representation of the server's state. May also return diagnostic information about error states. property OnStartListening: TNotifyEvent read FStartListening write FStartListening; //Hookable event property. Implement a hook to be notified when the server starts listening. property OnStopListening: TNotifyEvent read FStopListening write FStopListening; //Hookable event property. Implement a hook to be notified when the server stops listening. //Points to TPluginVersions object for getting information about the download of plugins from this server. //Points to the background thread object for timing out user sessions. property HitCount: int64 read GetHitCount; procedure Hit(rqInfo: TrequestInfo); procedure HitAccept; property HitAcceptCount: int64 read GetHitAcceptCount; procedure ClearHits; property Help: THelpLookup read FHelp; property StartupRoutines[idx: integer]: TMothershipStartupRoutine read GetStartupRoutine; property ShutdownRoutines[idx: integer]: TMothershipShutdownRoutine read GEtShutdownRoutine; procedure AddStartupRoutine(proc: TMothershipStartupRoutine); procedure AddShutdownRoutine(proc: TMothershipShutdownRoutine); function StartupRoutineCount: integer; function ShutdownRoutineCount: integer; procedure RunStartupRoutines; procedure RunShutdownRoutines; end; var WebServer : TMothershipWebServer; implementation { TMothershipWebServer } //------------------------------------------------------------------------------ procedure TMothershipWebServer.AddShutdownRoutine( proc: TMothershipShutdownRoutine); var p: pointer; begin p := @proc; FShutdownRoutines.Add(p); end; procedure TMothershipWebServer.AddStartupRoutine(proc: TMothershipStartupRoutine); var p: pointer; begin p := @proc; FStartupRoutines.add(p); end; procedure TMothershipWebServer.ClearHits; begin lock; try FHits:= 0; FHitAccepts := 0; finally unlock; end; end; procedure TMothershipWebServer.Configure(sPublicKeyName: ansistring; options: TMothershipWebServerOptions); //a: Jason Nelson //Constructor: Creates aggregate objects and initializes internal state. var t: integer; dest: TNetConnection; begin inherited create; FOptions := options; //create the configuration handler WebServerconfig.free; WebServerconfig := nil; WebServerConfig := TWebConfig.create(sPublicKeyName); if not (pwsNoHelp in options) then try Help.FileName := slash(WebServerConfig.ExternalResourcePath)+'helpfiles.txt'; except end; DOSVpool.clear; //create all the data-tier communications handlers if not (pwsNoDOS in options) then for t:= 0 to WebServerconfig.ConnectionCount-1 do begin dest := WebServerConfig.DestByIndex[t]; if lowercase(copy(dest.name, 1, 8)) = 'datatier' then begin DOSVPool.Add(dest.name, dest.host, dest.endpoint, dest.Context, WebServerConfig.DataCenterID); end; end; //update server state state := wssReady; end; constructor TMothershipWebServer.create; //a: Jason Nelson //Constructor: Creates aggregate objects and initializes internal state. var t: integer; dest: TNetConnection; begin inherited create; FHelp := THelpLookup.create; FHits:=0; FState := wssInit; FStartListening := nil; FStopListening := nil; FStartupRoutines := TList.create; FShutdownRoutines := TList.create; WebServerStats := TWebStats.create; //update server state state := wssReady; end; //------------------------------------------------------------------------------ destructor TMothershipWebServer.Destroy; //a: Jason Nelson //Shutsdown the server if not already shut down, then frees aggregate resoureces. begin if state = wssRunning then stop; //set state state := wssDestroy; // DOSV.free; WebServerStats.free; WebServerConfig.free; rqMan.Shutdown; {$IFDEF BEEP} // beeper.beep(100,100); {$ENDIF} Fhelp.free; FStartupRoutines.free; FShutdownRoutines.free; inherited; end; //------------------------------------------------------------------------------ function TMothershipWebServer.DispatchWebRequest(rqInfo: TRequestInfo): boolean; //a: Jason Nelson //This is the key function in the object. Pass this function a TRequestInfo class and it will //be sent thorugh the entire dispatching process, including database, template conversionm etc. //Typically you want to have the TRequestInfo.Request property pre-filled out BEFORE you call this function. The long dispatching process will then //respond by filling out the TRequestInfo.Response portion. //<BR> //It is rare that a typical PWLN programmer will have to call this function. The only //situations where this would be necessary would be if the programmer were writing an interface //to a new WebServer. For example, if we decided to run as an ISAPI filter instead of //an ISAPI servlet, or decided to run on Apache, or as a stand-alone service process (been done). //In the layer ABOVE this call, the program would be required to interface with the 3rd Party //web server and extract the HTTP request Information in whatever way available, fill out the //TRequestInfo.Request property and THEN pass the entire TRequestInfo object to THIS function. //Once this function returns, the TRequestInfo.Response property is read and the information is pushed back out to the client. begin {$IFDEF Serialize} //Lock; {$ENDIF} try result := WebDispatch.DispatchWebRequest(rqInfo); finally {$IFDEF Serialize} //UnLock; {$ENDIF} end; if rqINfo.request.hasparam('User-Agent') and (lowercase(rqInfo.request['User-Agent']) = 'monitor') then begin end else self.Hit(rqInfo); end; //------------------------------------------------------------------------------ function TMothershipWebServer.GetHitAcceptCount: int64; begin Lock; try result := FHitAccepts; finally Unlock; end; end; function TMothershipWebServer.GetHitCount: int64; begin Lock; try result := FHits; finally Unlock; end; end; function TMothershipWebServer.GEtShutdownRoutine(idx: integer): TMothershipShutdownRoutine; begin result := TMothershipShutdownRoutine(FStartupRoutines[idx]); end; function TMothershipWebServer.GetStartupRoutine(idx: integer): TMothershipStartupRoutine; begin result := TMothershipStartupRoutine(FStartupRoutines[idx]); end; function TMothershipWebServer.GetState: TMothershipWebServerState; //a: Jason Nelson //Getter for the State property. begin Lock; try result := FState; finally Unlock; end; end; //------------------------------------------------------------------------------ function TMothershipWebServer.GetStateString: ansistring; //a: Jason Nelson //Getter for the StateString Property. begin Lock; try Case FState of wssInit: result := MakeThreadSafe('Initializing'); wssReady: result := MakeThreadSafe('Ready'); wssStarting: result := MakeThreadSafe('Starting'); wssRunning: result := MakeThreadSafe('Running'); wssStopping: result := MakeThreadSafe('Stopping'); wssStopped: result := MakeThreadSafe('Stopped'); wssDestroy: result := MakeThreadSafe('Destroying'); end; finally UnLock; end; end; //------------------------------------------------------------------------------ procedure TMothershipWebServer.Hit(rqInfo: TrequestInfo); begin Lock; try if not rqInfo.NoHit then inc(FHits); if FHits>2000000000 then FHits := 0; finally Unlock; end; end; procedure TMothershipWebServer.HitAccept; begin Lock; try inc(FHitAccepts); finally Unlock; end; end; procedure TMothershipWebServer.RunShutdownRoutines; var t: integer; begin for t:= 0 to self.ShutdownRoutineCount-1 do begin shutdownroutines[t](self); end; end; procedure TMothershipWebServer.RunStartupRoutines; var t: integer; begin for t:= 0 to self.StartupRoutineCount-1 do begin startuproutines[t](self); end; end; procedure TMothershipWebServer.SetState(const Value: TMothershipWebServerState); //a: Jason Nelson //Setter for the State property. begin Lock; try FState := value; finally Unlock; end; end; function TMothershipWebServer.ShutdownRoutineCount: integer; begin result := FShutdownroutines.count; end; //------------------------------------------------------------------------------ procedure TMothershipWebServer.Start; //a: Jason Nelson //Starts the WebServer. Enables dormant background threads, and enables listening if it applies to the access layer. var dir: Tdirectory; t: integer; begin if state = wssRunning then exit; // AuditLog('The Web Service is starting'); dir := nil; try dir := TDirectory.create(slash(WebServerconfig.ExternalResourcePath)+'firmware\', '*.longhex', 0,0,true); //ReviveSockets; //set state state := wssStarting; if Assigned(FStartListening) then FStartListening(self); //set state state := wssRunning; rqMan.Start; try for t:= 0 to dir.filecount-1 do begin try DeleteFile(PChar(dir.files[t].FullName)); {$IFDEF BEEP} // beeper.Beep(100,100); {$ENDIF} except end; end; finally dir.free; end; except end; RunStartupRoutines; {$IFDEF BEEP} // beeper.beep(800,50); {$ENDIF} // AuditLog('The Web Service is started'); end; function TMothershipWebServer.StartupRoutineCount: integer; begin result := FStartupRoutines.count; end; //------------------------------------------------------------------------------ procedure TMothershipWebServer.Stop; //a: Jason Nelson //Stops the WebServer. Disables background threads, and disables listening if it applies to the access layer. begin // SayNatural('The Web Service is stopping.'); // AuditLog('The Web Service is stopping'); {$IFDEF BEEP} // beeper.beep(800,50); {$ENDIF} // KillSockets; RunShutdownRoutines; //set state state := wssStopping; if Assigned(FStopListening) then FStopListening(self); backgroundthreads.BackgroundThreadMan.TerminateAllThreads; backgroundthreads.BackgroundThreadMan.WaitForThreads; rqMan.shutdown; //set state state := wssStopped; // SayNatural('Stopped successfully.'); // AuditLog('Stopped successfully.'); end; initialization webserver := TMothershipWebServer.create; end.
29.544513
231
0.703574
f1d0a30f3cb963255e9186cc495a09000b93983a
7,220
pas
Pascal
Source/dwsEncoding.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
12
2015-01-02T08:27:25.000Z
2021-07-16T16:59:01.000Z
Source/dwsEncoding.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
1
2018-04-02T21:31:37.000Z
2018-04-02T21:31:37.000Z
Source/dwsEncoding.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
6
2015-01-02T08:27:13.000Z
2020-06-08T07:03:33.000Z
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsEncoding; {$I dws.inc} {$R-} interface uses SysUtils; function Base58Encode(const data : RawByteString) : String; function Base58Decode(const data : String) : RawByteString; // RFC 4648 without padding function Base32Encode(data : Pointer; len : Integer) : String; overload; function Base32Encode(const data : RawByteString) : String; overload; function Base32Decode(const data : String) : RawByteString; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ const cBase58 : String = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; function DivBy58(var v : Integer) : Integer; const cMagic : Cardinal = 2369637129; {$ifdef WIN32_ASM} asm mov ecx, eax mov eax, dword ptr [eax] mul eax, cMagic mov eax, edx shr eax, 5 mov edx, eax imul edx, 58 sub dword ptr [ecx], edx {$else} begin Result := UInt64(cMagic)*v shr 37; v := v - Result*58; {$endif} end; function Base58Encode(const data : RawByteString) : String; var i, j, carry, nextCarry, n : Integer; digits : array of Integer; begin if data = '' then exit; Result := ''; n := -1; for j := 1 to Length(data) do begin if data[j] = #0 then Result := Result + cBase58[1] else begin SetLength(digits, 1); digits[0] := 0; n := 0; break; end; end; for i := Length(Result)+1 to Length(data) do begin digits[0] := (digits[0] shl 8) + Ord(data[i]); carry := DivBy58(digits[0]); for j := 1 to n do begin digits[j] := (digits[j] shl 8) + carry; carry := DivBy58(digits[j]); end; while carry > 0 do begin Inc(n); SetLength(digits, n+1); nextCarry := carry div 58; digits[n] := carry - nextCarry*58; carry := nextCarry; end; end; for j := n downto 0 do Result := Result + cBase58[digits[j]+1]; end; function Base58Decode(const data : String) : RawByteString; var i, j, carry, n, d : Integer; bytes : array of Integer; begin if data = '' then exit; Result := ''; n := -1; for j := 1 to Length(data) do begin if data[j] = '1' then Result := Result + #0 else begin SetLength(bytes, 1); bytes[0] := 0; n := 0; break; end; end; for i := Length(Result)+1 to Length(data) do begin d := Pos(data[i], cBase58)-1; if d<0 then raise Exception.Create('Non-base58 character'); for j := 0 to n do bytes[j] := bytes[j]*58; bytes[0] := bytes[0]+d; carry := 0; for j := 0 to n do begin bytes[j] := bytes[j] + carry; carry := bytes[j] shr 8; bytes[j] := bytes[j] and $FF; end; while carry > 0 do begin Inc(n); SetLength(bytes, n+1); bytes[n] := carry and $FF; carry := carry shr 8; end; end; for j := n downto 0 do Result := Result + AnsiChar(bytes[j]); end; const cBase32 : array [0..31] of Char = ( 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','2','3','4','5','6','7' ); function Base32Encode(data : Pointer; len : Integer) : String; var i, n, c, b : Integer; pIn : PByteArray; pOut : PChar; begin if (len = 0) or (data = nil) then Exit(''); n := len; SetLength(Result, ((n div 5)+1)*8); c := 0; b := 0; pIn := data; pOut := Pointer(Result); for i := 0 to n-1 do begin c := (c shl 8) or pIn[i]; Inc(b, 8); while b >= 5 do begin Dec(b, 5); pOut^ := cBase32[(c shr b) and $1F]; Inc(pOut); end; end; if b > 0 then begin pOut^ := cBase32[(c shl (5-b)) and $1F]; Inc(pOut); end; n := (NativeUInt(pOut)-NativeUInt(Pointer(Result))) div SizeOf(Char); SetLength(Result, n); end; // Base32Encode // function Base32Encode(const data : RawByteString) : String; begin Result:=Base32Encode(Pointer(data), Length(data)); end; // Base32Decode // var vBase32DecodeTable : array [#0..'z'] of Byte; function Base32Decode(const data : String) : RawByteString; procedure PrepareTable; var c : Char; begin for c := #0 to High(vBase32DecodeTable) do begin case c of 'A'..'Z' : vBase32DecodeTable[c] := Ord(c)-Ord('A'); 'a'..'z' : vBase32DecodeTable[c] := Ord(c)-Ord('a'); '2'..'7' : vBase32DecodeTable[c] := Ord(c)+(26-Ord('2')); '0' : vBase32DecodeTable[c] := Ord('O')-Ord('A'); else vBase32DecodeTable[c] := 255; end; end; end; var c, b, i, n, d : Integer; pIn : PChar; pOut : PByte; begin if data = '' then Exit(''); if vBase32DecodeTable['z']=0 then PrepareTable; n := Length(data); SetLength(Result, ((n div 8)+1)*5); pIn := Pointer(data); pOut := Pointer(Result); c := 0; b := 0; for i := 0 to n-1 do begin d := vBase32DecodeTable[pIn[i]]; if d = 255 then begin if pIn[i] = '=' then break; raise Exception.CreateFmt('Invalid character (#%d) in Base32', [Ord(pIn[i])]); end; c := (c shl 5) or d; Inc(b, 5); if b >= 8 then begin Dec(b, 8); pOut^ := c shr b; Inc(pOut); end; end; n := NativeUInt(pOut)-NativeUInt(Pointer(Result)); SetLength(Result, n); end; end.
28.203125
88
0.461496
47173867f1245f7ef6c84cbf79b7306450953cda
2,253
pas
Pascal
egavga/0183.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
egavga/0183.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
egavga/0183.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ David Proper posted a cross-fade routine here, some days ago. This is an update on that one. It now fades all texts. Quite a pain to figure this out, realy. Put it in the SWAG if you want, Kerry - Done!. } program xfade; { made by Bas van Gaalen, Holland, PD, fido 2:285/213.8, internet bas.van.gaalen@schotman.nl } uses crt; const vseg=$a000; fseg=$f000; fofs=$fa6e; lines=13; creds:array[0..lines-1] of string[20]=( {.........|.........|} 'This cross-fade', 'routine was made by', 'Bas van Gaalen', 'Code and idea', 'inspired by', 'David Proper', 'This routine was', 'enhanced a bit', 'in comparison with', 'David''s one...', 'cu later', 'alligator!', ''); procedure setpal(c,r,g,b:byte); assembler; asm mov dx,3c8h; mov al,[c]; out dx,al; inc dx; mov al,[r] out dx,al; mov al,[g]; out dx,al; mov al,[b]; out dx,al; end; procedure retrace; assembler; asm mov dx,3dah; @vert1: in al,dx; test al,8; jz @vert1 @vert2: in al,dx; test al,8; jnz @vert2; end; procedure cleartxt(col,new:byte); var x,y,vofs:word; begin for x:=0 to 319 do for y:=100 to 107 do begin vofs:=y*320+x; if mem[vseg:vofs]=col then mem[vseg:vofs]:=0 else if mem[vseg:vofs]<>0 then mem[vseg:vofs]:=new; end; end; procedure writetxt(col,cur:byte; txt:string); var x,y,vofs:word; i,j,k:byte; begin x:=(320-8*length(txt)) div 2; y:=100; for i:=1 to length(txt) do for j:=0 to 7 do for k:=0 to 7 do if ((mem[fseg:fofs+ord(txt[i])*8+j] shl k) and 128) <> 0 then begin vofs:=(y+j)*320+(i*8)+x+k; if mem[vseg:vofs]=cur then mem[vseg:vofs]:=col+cur else mem[vseg:vofs]:=col; end; end; var txtidx,curcol,i:byte; begin asm mov ax,13h; int 10h; end; setpal(1,0,0,0); setpal(2,0,0,0); setpal(3,63 div 2,63,63 div 2); curcol:=1; txtidx:=0; repeat cleartxt(curcol,3-curcol); writetxt(curcol,3-curcol,creds[txtidx]); for i:=0 to 63 do begin retrace; setpal(curcol,i div 2,i,i div 2); setpal(3-curcol,(63-i) div 2,63-i,(63-i) div 2); end; delay(500); curcol:=1+(curcol mod 2); txtidx:=(1+txtidx) mod lines; until keypressed; textmode(lastmode); end. 
29.644737
80
0.600089
61ba6711153d04bea2075397fc56707338856f10
991
dfm
Pascal
efx/frmText.dfm
apfeltee/lysee
35461c660a49b852888ed379748bbbc0f4683cb8
[ "BSD-3-Clause" ]
null
null
null
efx/frmText.dfm
apfeltee/lysee
35461c660a49b852888ed379748bbbc0f4683cb8
[ "BSD-3-Clause" ]
null
null
null
efx/frmText.dfm
apfeltee/lysee
35461c660a49b852888ed379748bbbc0f4683cb8
[ "BSD-3-Clause" ]
null
null
null
object TextForm: TTextForm Left = 400 Top = 198 BorderStyle = bsDialog BorderWidth = 12 Caption = #32534#36753#21333#20803#26684#25991#26412 ClientHeight = 280 ClientWidth = 443 Color = clBtnFace Font.Charset = GB2312_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = #23435#20307 Font.Style = [] OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 12 object mText: TMemo Left = 0 Top = 0 Width = 360 Height = 280 Lines.Strings = ( 'mText') ScrollBars = ssBoth TabOrder = 0 WordWrap = False end object bOK: TButton Left = 368 Top = 0 Width = 75 Height = 25 Caption = #30830#23450 ModalResult = 1 TabOrder = 1 end object bCancel: TButton Left = 368 Top = 32 Width = 75 Height = 25 Cancel = True Caption = #21462#28040 ModalResult = 2 TabOrder = 2 end end
19.82
55
0.596367
832bfb8f3d3a7e6b1b039b84a17d46a744ef6762
12,603
pas
Pascal
lazutils/ttcmap.pas
coolchyni/jcf-cli
69fd71b962fd1c1386ec4939e94dab70568bf7e6
[ "MIT" ]
22
2018-05-31T23:01:15.000Z
2021-11-16T11:25:36.000Z
iscbase/lazutils/ttcmap.pas
isyscore/isc-fpbase
ce2469c977eba901005982dc7f89fee2d0718f76
[ "MIT" ]
1
2018-08-14T21:15:51.000Z
2018-08-15T12:42:58.000Z
iscbase/lazutils/ttcmap.pas
isyscore/isc-fpbase
ce2469c977eba901005982dc7f89fee2d0718f76
[ "MIT" ]
6
2018-05-31T06:31:55.000Z
2022-02-19T03:04:14.000Z
(******************************************************************* * * ttcmap.pas 1.0 * * Character Mappings unit. * * Copyright 1996, 1997 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used * modified and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify or distribute * this file you indicate that you have read the license and * understand and accept it fully. * ******************************************************************) unit TTCMap; interface {$R-} // TODO: Fix out-of-bounds accesses. uses TTTypes; type (********************************************************************) (* *) (* CHARACTER MAPPINGS SUBTABLES *) (* *) (********************************************************************) (* FORMAT 0 *) (* Apple standard character to glyph index mapping table *) (* the glyphIdArray for this format has 256 entries *) TCMap0 = record glyphIdArray : PUShort; end; (* FORMAT 2 *) (* the format 2 table contains a variable-length array of subHeaders *) (* (at most 256 entries) whose size must be determined algorithmically *) TCMap2SubHeader = record firstCode : UShort; (* first valid low byte *) entryCount : UShort; (* number of valid low bytes *) idDelta : Short; (* delta value to glyphIndex *) idRangeOffset : UShort; (* offset fr. here to 1stCode *) end; TCMap2SubHeaders = array[0..100] of TCMap2SubHeader; PCMap2SubHeaders = ^TCMap2SubHeaders; (* Format 2 is used for mixed 8/16bit encodings (usually CJK fonts) *) TCMap2 = record subHeaderKeys : PUShort; (* high byte mapping table *) (* value = subHeader index * 8 *) subHeaders : PCMap2SubHeaders; glyphIdArray : PUShort; numGlyphId : Int; end; (* FORMAT 4 *) (*The format 4 table contains segCount segments *) TCMap4Segment = record endCount : UShort; startCount : UShort; idDelta : UShort; idRangeOffset : UShort; end; TCMap4Segments = array[0..100] of TCMap4Segment; PCMap4Segments = ^TCMap4Segments; (* Microsoft standard character to glyph index mapping table *) TCMap4 = record segCountX2 : UShort; (* segments number * 2 *) searchRange : UShort; (* these parameters can be used *) entrySelector : UShort; (* for a binary search *) rangeShift : UShort; segments : PCMap4Segments; glyphIdArray : PUShort; numGlyphId : Int; end; (* FORMAT 6 *) (* trimmed table mapping (for representing one subrange) *) TCMap6 = record firstCode : UShort; (* first character code of subrange *) entryCount : UShort; (* num. of character codes in subrange *) glyphIdArray : PUShort; end; (* CHARMAP TABLE *) PCMapTable = ^TCMapTable; TCMapTable = record platformID : UShort; platformEncodingID : UShort; Format : word; Length : word; Version : word; Loaded : Boolean; CannotLoad: Boolean; StreamPtr: ^TT_Stream; Offset : Long; case Byte of 0 : ( cmap0 : TCMap0 ); 2 : ( cmap2 : TCMap2 ); 4 : ( cmap4 : TCMap4 ); 6 : ( cmap6 : TCMap6 ); end; TCMapTables = array[0..9] of TCMapTable; PCMapTables = ^TCMapTables; function CharMap_Load( var cmap : TCMapTable ) : TError; procedure CharMap_Free( var cmap : TCMapTable ); function CharMap_Index( var cmap : TCMapTable; charCode : Long ) : UShort; implementation uses TTError, TTMemory, TTFile; function CharMap_Load( var cmap : TCMapTable ) : TError; var num_SH, u : UShort; i : Int; num_segs : Int; ftstream: TFreeTypeStream; label Fail, SimpleExit; begin CharMap_Load := Failure; if cmap.loaded then begin CharMap_Load := Success; exit; end; if TT_Use_Stream(cmap.StreamPtr^, ftstream) then exit; if ftstream.SeekFile( cmap.offset ) then goto SimpleExit; case cmap.format of 0: with cmap.cmap0 do if Alloc( glyphIdArray, 256 ) or ftstream.ReadFile( glyphIdArray^, 256 ) then goto Fail; 2: begin num_SH := 0; with cmap.cmap2 do begin if Alloc( subHeaderKeys, 256*sizeof(UShort) ) or ftstream.AccessFrame( 512 ) then goto Fail; for i := 0 to 255 do begin u := ftstream.GET_UShort shr 3; subHeaderKeys^[i] := u; if num_SH < u then num_SH := u; end; ftstream.ForgetFrame; (* now load sub headers *) numGlyphId := ((cmap.length - 2*(256+3) - num_SH*8) and $FFFF) div 2; if Alloc( subHeaders, (num_SH+1)*sizeof(TCMap2SubHeader) ) or ftstream.AccessFrame( (num_SH+1)*8 ) then goto Fail; for i := 0 to num_SH do with subHeaders^[i] do begin firstCode := ftstream.GET_UShort; entryCount := ftstream.GET_UShort; idDelta := ftstream.GET_UShort; (* we apply the location offset immediately *) idRangeOffset := ftstream.GET_UShort - (num_SH-i)*8 - 2; end; ftstream.ForgetFrame; (* load glyph ids *) if Alloc( glyphIdArray, numGlyphId*sizeof(UShort) ) or ftstream.AccessFrame( numGlyphId*2 ) then goto Fail; for i := 0 to numGlyphId-1 do glyphIdArray^[i] := ftstream.GET_UShort; ftstream.ForgetFrame; end; end; 4: with cmap.cmap4 do begin if ftstream.AccessFrame(8) then goto Fail; segCountX2 := ftstream.Get_UShort; searchRange := ftstream.Get_UShort; entrySelector := ftstream.Get_UShort; rangeShift := ftstream.Get_UShort; num_segs := segCountX2 shr 1; ftstream.ForgetFrame; (* load segments *) if Alloc( segments, num_segs*sizeof(TCMap4Segment) ) or ftstream.AccessFrame( (num_segs*4+1)*2 ) then goto Fail; for i := 0 to num_segs-1 do segments^[i].endCount := ftstream.Get_UShort; ftstream.Get_UShort; for i := 0 to num_segs-1 do segments^[i].startCount := ftstream.Get_UShort; for i := 0 to num_segs-1 do segments^[i].idDelta := ftstream.GET_Short; for i := 0 to num_segs-1 do segments^[i].idRangeOffset := ftstream.GET_UShort; ftstream.ForgetFrame; numGlyphId := (( cmap.length - (16+8*num_segs) ) and $FFFF) div 2; (* load glyph ids *) if Alloc( glyphIdArray, numGlyphId*sizeof(UShort) ) or ftstream.AccessFrame( numGlyphId*2 ) then goto Fail; for i := 0 to numGlyphId-1 do glyphIdArray^[i] := ftstream.Get_UShort; ftstream.ForgetFrame; end; 6: with cmap.cmap6 do begin if ftstream.AccessFrame(4) then goto Fail; firstCode := ftstream.GET_UShort; entryCount := ftstream.GET_UShort; ftstream.ForgetFrame; if Alloc( glyphIdArray, entryCount*sizeof(Short) ) or ftstream.AccessFrame( entryCount*2 ) then goto Fail; for i := 0 to entryCount-1 do glyphIdArray^[i] := ftstream.GET_UShort; ftstream.ForgetFrame; end; else error := TT_Err_Invalid_Charmap_Format; goto SimpleExit; end; CharMap_Load := success; cmap.Loaded := True; goto SimpleExit; Fail: CharMap_Free( cmap ); exit; SimpleExit: TT_Done_Stream(cmap.StreamPtr^); end; procedure CharMap_Free( var cmap : TCMapTable ); begin with cmap do case format of 0 : begin Free( cmap.cmap0.glyphIdArray ); end; 2 : begin Free( cmap.cmap2.glyphIdArray ); Free( cmap.cmap2.subHeaders ); Free( cmap.cmap2.glyphIdArray ); end; 4 : begin Free( cmap.cmap4.segments ); Free( cmap.cmap4.glyphIdArray ); cmap.cmap4.segCountX2 := 0; end; 6 : begin Free( cmap.cmap6.glyphIdArray ); cmap.cmap6.entryCount := 0; end; end; cmap.loaded := False; cmap.format := 0; cmap.length := 0; cmap.version := 0; cmap.StreamPtr := nil; end; function code_to_index0( charCode : UShort; var cmap0 : TCMap0 ) : UShort; begin code_to_index0 := 0; if charCode < 256 then code_to_index0 := cmap0.glyphIdArray^[charCode] end; function code_to_index2( charCode : UShort; var cmap2 : TCMap2 ) : UShort; var index1, idx, offset : UShort; begin code_to_index2 := 0; if charCode < 256 then idx := charCode else idx := charCode shr 8; index1 := cmap2.subHeaderKeys^[idx]; if index1 = 0 then begin if charCode < 256 then code_to_index2 := cmap2.glyphIdArray^[charCode]; (* 8Bit charcode *) end else begin if charCode < 256 then exit; idx := charCode and 255; with cmap2.subHeaders^[index1] do begin if ( idx < firstCode ) or ( idx >= firstCode + entryCount ) then exit; offset := idRangeOffset div 2 + idx - firstCode; if offset >= cmap2.numGlyphId then exit; idx := cmap2.glyphIdArray^[offset]; if idx <> 0 then code_to_index2 := (idx + idDelta) and $FFFF; end end; end; function code_to_index4( charCode : UShort; var cmap4 : TCMap4 ) : UShort; var i, index1, num_segs, rangeStart : Int; label Found; begin code_to_index4 := 0; num_segs := cmap4.segCountX2 div 2; i := 0; while ( i < num_segs ) do with cmap4.segments^[i] do begin if charCode <= endCount then goto Found; inc(i); end; exit; Found: with cmap4.segments^[i] do begin if charCode < startCount then exit; if idRangeOffset = 0 then code_to_index4 := (charCode + idDelta) and $FFFF else begin //the offset in glyphIdArray is given in bytes from the //position after idRangeOffset value itself rangeStart := idRangeOffset div 2 - (num_segs-i); index1 := rangeStart + (charCode - startCount); if ( index1 < cmap4.numGlyphId ) and ( cmap4.glyphIdArray^[index1] <> 0 ) then code_to_index4 := (cmap4.glyphIdArray^[index1] + idDelta) and $FFFF; end; end; end; function code_to_index6( charCode : UShort; var cmap6 : TCMap6 ) : UShort; begin code_to_index6 := 0; with cmap6 do begin if ( charCode < firstCode ) or ( charCode >= firstCode + entryCount ) then exit; code_to_index6 := glyphIdArray^[charCode-firstCode]; end end; function CharMap_Index( var cmap : TCMapTable; charCode : Long ) : UShort; begin CharMap_Index := 0; if not cmap.Loaded then if cmap.CannotLoad then exit else if CharMap_Load( cmap ) then begin cmap.CannotLoad:= true; exit; end; case cmap.format of 0: CharMap_Index := code_to_index0( charCode, cmap.cmap0 ); 2: CharMap_Index := code_to_index2( charCode, cmap.cmap2 ); 4: CharMap_Index := code_to_index4( charCode, cmap.cmap4 ); 6: CharMap_Index := code_to_index6( charCode, cmap.cmap6 ); end; end; end.
27.698901
78
0.534317
47312b74aecd775e98db64d9c0e6898840535df3
394
lpr
Pascal
Samples/Lazarus/Samples.lpr
viniciussanchez/delphi-jose-jwt
800efddd20fbbfae2a0711a1603c0882a15ca7d1
[ "Apache-2.0" ]
2
2021-04-26T05:58:55.000Z
2021-09-24T11:58:02.000Z
Samples/Lazarus/Samples.lpr
viniciussanchez/delphi-jose-jwt
800efddd20fbbfae2a0711a1603c0882a15ca7d1
[ "Apache-2.0" ]
null
null
null
Samples/Lazarus/Samples.lpr
viniciussanchez/delphi-jose-jwt
800efddd20fbbfae2a0711a1603c0882a15ca7d1
[ "Apache-2.0" ]
null
null
null
program Samples; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Interfaces, // this includes the LCL widgetset Forms, indylaz, Main { you can add units after this }; {$R *.res} begin RequireDerivedFormResource:=True; Application.Scaled:=True; Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.
17.130435
48
0.705584
851e31442fbd2b5547baf5d61689459c63cd9cbb
2,493
dfm
Pascal
SelfParametersUnit.dfm
naumovda/d-client
4fa4be0d97962ad6166243fdd9b92b2269909151
[ "Apache-2.0" ]
null
null
null
SelfParametersUnit.dfm
naumovda/d-client
4fa4be0d97962ad6166243fdd9b92b2269909151
[ "Apache-2.0" ]
null
null
null
SelfParametersUnit.dfm
naumovda/d-client
4fa4be0d97962ad6166243fdd9b92b2269909151
[ "Apache-2.0" ]
null
null
null
inherited SelfParameters: TSelfParameters Left = 265 Top = 277 Width = 941 Caption = #1055#1072#1088#1072#1084#1077#1090#1088#1099' '#1086#1088#1075#1072#1085#1080#1079#1072#1094#1080#1080 OldCreateOrder = True PixelsPerInch = 96 TextHeight = 13 inherited Grid: TcxGrid Width = 617 inherited tvMain: TcxGridDBTableView object tvMainRowNumber: TcxGridDBColumn Caption = #8470 DataBinding.FieldName = 'RowNumber' end object tvMainObjectCode: TcxGridDBColumn Caption = #1050#1086#1076 DataBinding.FieldName = 'ObjectCode' Width = 68 end object tvMainObjectName: TcxGridDBColumn Caption = #1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 DataBinding.FieldName = 'ObjectName' Width = 168 end object tvMainObjectValue: TcxGridDBColumn Caption = #1047#1085#1072#1095#1077#1085#1080#1077 DataBinding.FieldName = 'ObjectValue' Width = 232 end end end inherited dxLeft: TdxLayoutControl inherited cxSearch: TcxButton Top = 67 TabOrder = 1 end inherited cxClear: TcxButton Top = 67 TabOrder = 2 end object cxValue: TcxTextEdit [2] Left = 112 Top = 28 Style.HotTrack = False TabOrder = 0 Text = 'cxValue' Width = 121 end inherited dxLeftGroup_Root: TdxLayoutGroup inherited dxLeftGroup: TdxLayoutGroup object dxLeftItem1: TdxLayoutItem CaptionOptions.Text = #1055#1086#1080#1089#1082' '#1079#1085#1072#1095#1077#1085#1080#1103':' Control = cxValue ControlOptions.ShowBorder = False end end end end inherited DS: TDataSource DataSet = dmPublic.tSelfParameters Left = 96 Top = 114 end inherited ImageList: TImageList Left = 64 Top = 114 end inherited Actions: TActionList Left = 31 Top = 114 inherited acSearch: TAction OnExecute = acSearchExecute end end inherited cxStyleRepository: TcxStyleRepository Left = 134 Top = 114 end inherited dxBarManager: TdxBarManager Categories.ItemsVisibles = ( 2) Categories.Visibles = ( True) Left = 171 Top = 113 DockControlHeights = ( 0 0 26 0) end inherited dxComponentPrinter: TdxComponentPrinter Left = 208 Top = 112 end inherited OpenDialog: TOpenDialog Left = 248 Top = 112 end end
24.441176
115
0.645006
f18012e1754f2dcbbae699726ab655de60595504
1,042
pas
Pascal
Login.pas
PaulohSouza/Notesc-4.0
a0d03f216b8a5cb2b77c470b4739c67667523740
[ "MIT" ]
null
null
null
Login.pas
PaulohSouza/Notesc-4.0
a0d03f216b8a5cb2b77c470b4739c67667523740
[ "MIT" ]
1
2020-04-03T23:06:38.000Z
2020-04-03T23:06:38.000Z
Sistema/Imagens/Images/Buttons/Login.pas
PaulohSouza/Notesc-4.0
a0d03f216b8a5cb2b77c470b4739c67667523740
[ "MIT" ]
null
null
null
unit Login; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, jpeg, Buttons; type TFrmLogin = class(TForm) GrpBxLogin: TGroupBox; Label2: TLabel; Label3: TLabel; BtnOk: TBitBtn; BitBtn2: TBitBtn; StatusBar1: TStatusBar; Timer1: TTimer; Edit1: TEdit; Edit2: TEdit; Label4: TLabel; Image1: TImage; Image2: TImage; procedure Timer1Timer(Sender: TObject); procedure BitBtn2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmLogin: TFrmLogin; implementation uses controledenotas, Unit1, secretaria, Administrador, aviso, Unit10; {$R *.dfm} procedure TFrmLogin.Timer1Timer(Sender: TObject); begin StatusBar1.Panels[0].Text :='' + FormatDateTime('hh:nn:ss',now); StatusBar1.Panels[1].Text :='' + FormatDateTime('dddd","dd" de "mmmm" de "yyyy',now); end; procedure TFrmLogin.BitBtn2Click(Sender: TObject); begin Close; end; end.
19.660377
87
0.698656
6174b9a9956604aae863a7a8ab0621a8f12ce2a1
3,907
pas
Pascal
processlist.pas
gguimp/submodule-01
bc3f56be95bf4bb71e6904020e405a40fcf7f855
[ "MIT" ]
null
null
null
processlist.pas
gguimp/submodule-01
bc3f56be95bf4bb71e6904020e405a40fcf7f855
[ "MIT" ]
null
null
null
processlist.pas
gguimp/submodule-01
bc3f56be95bf4bb71e6904020e405a40fcf7f855
[ "MIT" ]
null
null
null
{ *************************************************************************** * * * This source 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 code 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. * * * * A copy of the GNU General Public License is available on the World * * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also * * obtain it by writing to the Free Software Foundation, * * Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. * * * *************************************************************************** } unit ProcessList; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LCLProc, UTF8Process; type { The TProcessList is used by the IDE to store all running programs and external tools, that are not watched. From time to time the IDE checks, if the processes has terminated and will free them cleanly to avoid zombies. } TProcessList = class private FItems: TList; // list of TProcessUTF8 FFreeing: Boolean; // set wehn freeing stopped processes function GetCount: integer; function GetItems(Index: integer): TProcessUTF8; public constructor Create; destructor Destroy; override; function Add(NewProcess: TProcessUTF8): integer; procedure Clear; procedure FreeStoppedProcesses; public property Count: integer read GetCount; property Items[Index: integer]: TProcessUTF8 read GetItems; default; end; function GetDefaultProcessList: TProcessList; implementation var DefaultProcessList: TProcessList; function GetDefaultProcessList: TProcessList; begin if DefaultProcessList=nil then DefaultProcessList:=TProcessList.Create; Result:=DefaultProcessList; end; { TProcessList } function TProcessList.GetCount: integer; begin Result:=FItems.Count; end; function TProcessList.GetItems(Index: integer): TProcessUTF8; begin Result:=TProcessUTF8(FItems[Index]); end; constructor TProcessList.Create; begin FItems:=TList.Create; end; destructor TProcessList.Destroy; begin FreeStoppedProcesses; Clear; FItems.Free; inherited Destroy; end; function TProcessList.Add(NewProcess: TProcessUTF8): integer; begin Result:=FItems.Add(NewProcess); end; procedure TProcessList.Clear; var i: Integer; begin for i:=0 to FItems.Count-1 do Items[i].Free; FItems.Clear; end; procedure TProcessList.FreeStoppedProcesses; var AProcess: TProcessUTF8; i: Integer; begin // waitonexit or free may trigger another idle if FFreeing then Exit; FFreeing := True; try for i:=FItems.Count-1 downto 0 do begin AProcess:=Items[i]; if AProcess.Running then continue; try try AProcess.WaitOnExit; AProcess.Free; finally FItems.Delete(i); end; except on E: Exception do begin DebugLn('Error freeing stopped process: ',E.Message); end; end; end; finally FFreeing := False; end; end; initialization DefaultProcessList:=nil; finalization DefaultProcessList.Free; DefaultProcessList:=nil; end.
27.321678
76
0.610699
f1a3c7e4859837085084e4d415d33783575a5bc1
60
pas
Pascal
test/pascal_ISO7185/test/no/ExprErr1.pas
tanhleno/pegparser
1d4b7bffd5860a4b54d021bfcf7e93ab82aa6582
[ "MIT" ]
8
2019-05-13T16:11:24.000Z
2022-02-23T12:35:36.000Z
test/pascal_ISO7185/test/no/ExprErr1.pas
tanhleno/pegparser
1d4b7bffd5860a4b54d021bfcf7e93ab82aa6582
[ "MIT" ]
null
null
null
test/pascal_ISO7185/test/no/ExprErr1.pas
tanhleno/pegparser
1d4b7bffd5860a4b54d021bfcf7e93ab82aa6582
[ "MIT" ]
1
2021-01-27T00:51:52.000Z
2021-01-27T00:51:52.000Z
program ExprErr1; begin a := .5; b := 0.4; c := 0.6 end.
8.571429
17
0.516667
83dcc0826577be025781657922bca99a1bb24e77
3,279
pas
Pascal
Testes Dunit/TestUfProdutos.pas
PCVCPAULO/Projeto-Areco
98080e6c176372d7395df57a7ef7ea22b1b227e6
[ "MIT" ]
1
2020-08-24T05:32:10.000Z
2020-08-24T05:32:10.000Z
Testes Dunit/TestUfProdutos.pas
BoscoBecker/Projeto-Areco
98080e6c176372d7395df57a7ef7ea22b1b227e6
[ "MIT" ]
null
null
null
Testes Dunit/TestUfProdutos.pas
BoscoBecker/Projeto-Areco
98080e6c176372d7395df57a7ef7ea22b1b227e6
[ "MIT" ]
1
2020-04-13T13:32:17.000Z
2020-04-13T13:32:17.000Z
unit TestUfProdutos; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Vcl.Grids, ppParameter, ppCtrls, ppPrnabl, ppBands, System.SysUtils, UfProdutos, Vcl.Graphics, System.Classes, Ucontrole, Data.Win.ADODB, Winapi.Messages, ppReport, Uproduto, ppDB, Vcl.Controls, Vcl.Imaging.pngimage, Vcl.Dialogs, ppDBPipe, Data.DB, ppProd, ppComm, ppDesignLayer, System.Variants, ppCache, ppClass, ppRelatv, ppDBBDE, Vcl.ExtCtrls, Winapi.Windows, Vcl.DBGrids, Vcl.Forms, Vcl.StdCtrls, ppVar; type // Test methods for class TFrmProduto TestTFrmProduto = class(TTestCase) strict private FFrmProduto: TFrmProduto; public procedure SetUp; override; procedure TearDown; override; published procedure TestbtnFecharClick; procedure TestbtnAtualizaGridClick; procedure TestbtnNovoClick; procedure TestbtnAlterarClick; procedure TestbtnDeletarClick; procedure TestbtnSalvarClick; procedure TestFormShow; procedure TestFormCreate; procedure TestbtnImprimirClick; end; implementation procedure TestTFrmProduto.SetUp; begin FFrmProduto := TFrmProduto.Create; end; procedure TestTFrmProduto.TearDown; begin FFrmProduto.Free; FFrmProduto := nil; end; procedure TestTFrmProduto.TestbtnFecharClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnFecharClick(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestbtnAtualizaGridClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnAtualizaGridClick(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestbtnNovoClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnNovoClick(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestbtnAlterarClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnAlterarClick(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestbtnDeletarClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnDeletarClick(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestbtnSalvarClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnSalvarClick(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestFormShow; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.FormShow(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestFormCreate; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.FormCreate(Sender); // TODO: Validate method results end; procedure TestTFrmProduto.TestbtnImprimirClick; var Sender: TObject; begin // TODO: Setup method call parameters FFrmProduto.btnImprimirClick(Sender); // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestTFrmProduto.Suite); end.
23.255319
87
0.769137
f1c854ed55699116447d587a90bb598c428880a8
1,113
pas
Pascal
windows/src/ext/jedi/jvcl/jvcl/examples/JvAppDDECmd/AppDdeCmdModal.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/jvcl/examples/JvAppDDECmd/AppDdeCmdModal.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/jvcl/examples/JvAppDDECmd/AppDdeCmdModal.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
{****************************************************************** JEDI-VCL Demo Copyright (C) 2002 Project JEDI Original author: You may retrieve the latest version of this file at the JEDI-JVCL home page, located at http://jvcl.delphi-jedi.org The contents of this file are used with permission, subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1_1Final.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. ******************************************************************} unit AppDdeCmdModal; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm2 = class(TForm) Button1: TButton; private public end; var Form2: TForm2; implementation {$R *.dfm} end.
23.680851
75
0.646002
614d5cf952d8b1b82438685d09110ee00c3e8c8b
2,885
pas
Pascal
Gestion_Interventions/u_feuille_style.pas
MaxHwK/Gestion_Interventions
e2f5b7e8d2a8e7b14ea37008c91aaa2afd47a892
[ "MIT" ]
null
null
null
Gestion_Interventions/u_feuille_style.pas
MaxHwK/Gestion_Interventions
e2f5b7e8d2a8e7b14ea37008c91aaa2afd47a892
[ "MIT" ]
null
null
null
Gestion_Interventions/u_feuille_style.pas
MaxHwK/Gestion_Interventions
e2f5b7e8d2a8e7b14ea37008c91aaa2afd47a892
[ "MIT" ]
null
null
null
unit u_feuille_style; {$mode objfpc}{$H+} interface uses Classes, SysUtils,Controls, ExtCtrls , Grids, StdCtrls, Graphics; type Tfeuille_style = CLASS procedure fonte_defaut (ctrl : TControl); procedure panel_defaut (pnl : TPanel); procedure panel_selection (pnl : TPanel); procedure panel_travail (pnl : TPanel); procedure panel_bouton (pnl : TPanel); procedure grille (grid : TStringGrid); procedure label_titre (lbl : TLabel); procedure label_erreur (lbl : TLabel); procedure combo (cbo : TComboBox); procedure memo_info (mmo : TMemo); END; var style : Tfeuille_style; implementation // fonte par défaut procedure Tfeuille_style.fonte_defaut (ctrl : TControl); begin ctrl.Font.Name := 'Calibri'; ctrl.Font.Size := 11; ctrl.Font.Color := $00000000; end; procedure Tfeuille_style.panel_defaut (pnl : TPanel); begin pnl.Color := $00EBEBEB; pnl.BorderStyle := bsNone; pnl.BevelOuter := bvNone; pnl.Alignment := taLeftJustify; fonte_defaut(pnl); end; procedure Tfeuille_style.panel_selection (pnl : TPanel); begin panel_defaut(pnl); pnl.Color := $00505050; pnl.Font.Color := $00FFFFFF; end; // panel zone de travail procedure Tfeuille_style.panel_travail (pnl : TPanel); begin panel_defaut(pnl); pnl.Color := $00FFFFFF; end; // panel aspect bouton et comportement bouton procedure Tfeuille_style.panel_bouton (pnl : TPanel); begin panel_defaut(pnl); pnl.BorderStyle:= bsSingle; end; procedure Tfeuille_style.grille (grid : TStringGrid); begin fonte_defaut (grid); grid.Options := [goFixedHorzLine, goRowSelect, goColSizing, goSmoothScroll]; grid.Flat := true; grid.BorderStyle := bsnone; grid.FixedColor := $00EBEBEB; grid.AlternateColor := $00EBEBEB; grid.SelectedColor := $00505050; grid.RowCount := 1; grid.ColumnClickSorts := true; end; procedure Tfeuille_style.label_titre (lbl : TLabel); begin fonte_defaut (lbl); lbl.color := $005B5B5B; lbl.font.color := $00FFFFFF; lbl.font.style := [fsBold]; end; procedure Tfeuille_style.label_erreur (lbl : TLabel); begin fonte_defaut (lbl); lbl.font.size := lbl.font.size -1; lbl.transparent := true; lbl.font.color := $000000FF; lbl.font.style := [fsItalic]; end; procedure Tfeuille_style.combo (cbo : TComboBox); begin fonte_defaut (cbo); cbo.color := $00FFFFFF; cbo.Style := csOwnerDrawFixed; cbo.sorted := true; cbo.AutoComplete := true; end; procedure Tfeuille_style.memo_info (mmo : TMemo); begin fonte_defaut (mmo); mmo.BorderStyle := bsNone; mmo.ReadOnly := True; mmo.TabStop := False; end; end.
24.041667
81
0.641594
f1a2ee6a40a325ddc68ebbe931aa5a4f2c9566a3
1,175
pas
Pascal
src/Mvc/Views/Parsers/Factories/BaseTemplateParserFactoryImpl.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
78
2019-01-31T13:40:48.000Z
2022-03-22T17:26:54.000Z
src/Mvc/Views/Parsers/Factories/BaseTemplateParserFactoryImpl.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
24
2020-01-04T11:50:53.000Z
2022-02-17T09:55:23.000Z
src/Mvc/Views/Parsers/Factories/BaseTemplateParserFactoryImpl.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
9
2018-11-05T03:43:24.000Z
2022-01-21T17:23:30.000Z
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 - 2021 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit BaseTemplateParserFactoryImpl; interface {$MODE OBJFPC} {$H+} uses DependencyIntf, DependencyContainerIntf, FactoryImpl; type (*!------------------------------------------------ * base abstract class that can create template parser * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-------------------------------------------------*) TBaseTemplateParserFactory = class(TFactory, IDependencyFactory) protected openTag : string; closeTag : string; public constructor create( const openTagStr : string = '{{'; const closeTagStr : string = '}}' ); end; implementation constructor TBaseTemplateParserFactory.create( const openTagStr : string = '{{'; const closeTagStr : string = '}}' ); begin openTag := openTagStr; closeTag := closeTagStr; end; end.
22.596154
77
0.574468
6a633ae2d2c18ef2e74383851855bd8df88acf45
213
pas
Pascal
Pascal/test/cohadar/pascal/programs/functions/test02.pas
cohadar/parapascal
863bc9b8d7f813dd3bbf8f6e7df36d70de8f5242
[ "MIT" ]
null
null
null
Pascal/test/cohadar/pascal/programs/functions/test02.pas
cohadar/parapascal
863bc9b8d7f813dd3bbf8f6e7df36d70de8f5242
[ "MIT" ]
null
null
null
Pascal/test/cohadar/pascal/programs/functions/test02.pas
cohadar/parapascal
863bc9b8d7f813dd3bbf8f6e7df36d70de8f5242
[ "MIT" ]
null
null
null
{* test arguments *} program test02; var a, b : integer; c: real; procedure njak(x, y: integer; z:real); begin a := x; b := y; c := z; end; begin njak(111, 222, 33.3); debug(a, b, c); end.
12.529412
39
0.530516
f11f6242400478124fcc474316dfd887468b0ca8
34,479
pas
Pascal
library/ftx/ftx_loinc_publisher.pas
rhausam/fhirserver
d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3
[ "BSD-3-Clause" ]
132
2015-02-02T00:22:40.000Z
2021-08-11T12:08:08.000Z
library/ftx/ftx_loinc_publisher.pas
rhausam/fhirserver
d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3
[ "BSD-3-Clause" ]
113
2015-03-20T01:55:20.000Z
2021-10-08T16:15:28.000Z
library/ftx/ftx_loinc_publisher.pas
rhausam/fhirserver
d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3
[ "BSD-3-Clause" ]
49
2015-04-11T14:59:43.000Z
2021-03-30T10:29:18.000Z
unit ftx_loinc_publisher; { Copyright (c) 2001+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {$I fhir.inc} Interface Uses SysUtils, Classes, Math, fsl_threads, fsl_base, fsl_collections, fsl_http, fsl_htmlgen, ftx_loinc_services; Const MAX_ROWS = 50; Type TloincPublisher = class (TFslObject) Private Lock : TFslLock; FSearchCache : TStringList; FLoinc : TLOINCServices; FFHIRPath : String; langs : TLangArray; function useLang(lang : byte) : boolean; function GetConceptDesc(iConcept : cardinal):String; function makeParentsLists(parents : Cardinal) : TCardinalArrayArray; procedure loincFooter(html : THTMLPublisher); Procedure PublishCode(Const sPrefix, sCode : String; html : THTMLPublisher); Procedure PublishCodes(Const sPrefix : String; iStart : Integer; html : THTMLPublisher); Procedure PublishConcept(bRoot : Boolean; Const sPrefix, sId : String; iStart : Integer; html : THTMLPublisher); Procedure PublishHome(Const sPrefix : String; html : THTMLPublisher); Procedure PublishSearch(Const sPrefix, sText : String; iStart: Integer; all : boolean; html : THTMLPublisher); Procedure PublishHeirarchyRoot(Const sPrefix : String; html : THTMLPublisher); Procedure PublishHeirarchyEntry(sCode : String; iStart : Integer; Const sPrefix : String; html : THTMLPublisher); Procedure ProcessMap(Const sPath : String; oMap : TFslStringMatch); Procedure PublishDictInternal(oMap : TFslStringMatch; Const sPrefix : String; html : THTMLPublisher); function descLength(i: cardinal): String; protected function sizeInBytesV(magic : integer) : cardinal; override; Public constructor Create(oLoinc : TLoincServices; FHIRPathEngine : String; const lang : THTTPLanguages); destructor Destroy; Override; Procedure PublishDict(Const sPath, sPrefix : String; html : THTMLPublisher); Overload; Virtual; Procedure PublishDict(oMap : TFslStringMatch; Const sPrefix : String; html : THTMLPublisher); Overload; Virtual; End; Implementation Uses fsl_utilities; function StringToBoolDef(s : String; def : boolean):boolean; begin s := lowercase(s); if s = 'true' then result := true else if s = '1' then result := true else if s = 'yes' then result := true else if s = 'y' then result := true else if s = 'false' then result := false else if s = '0' then result := false else if s = 'no' then result := false else if s = 'n' then result := false else result := def; end; Procedure TloincPublisher.PublishDictInternal(oMap : TFslStringMatch; Const sPrefix : String; html : THTMLPublisher); Var sURL : String; sId : String; Begin sURL := sPrefix +'?type=loinc&'; sId := oMap.Matches['id']; If sId <> '' Then PublishConcept(false, sURL, sId, StrToIntDef(oMap.Matches['start'], 0), html) else if oMap.ExistsByKey('srch') then if FLoinc.IsCode(oMap.Matches['srch']) then PublishCode(sURL, oMap.Matches['srch'], html) else if FLoinc.IsMACode(oMap.Matches['srch']) then PublishHeirarchyEntry(oMap.Matches['srch'], StrToIntDef(oMap.Matches['start'], 0), sURL, html) else PublishSearch(sURL, oMap.Matches['srch'], StrToIntDef(oMap.Matches['start'], 0), StringToBoolDef(oMap.matches['all'], false), html) else if oMap.ExistsByKey('macode') then PublishHeirarchyEntry(oMap.Matches['macode'], StrToIntDef(oMap.Matches['start'], 0), sURL, html) else Begin sId := oMap.Matches['code']; If sId = '' Then PublishHome(sURL, html) else If sId = '*' Then PublishCodes(sURL, StrToIntDef(oMap.Matches['start'], 0), html) else PublishCode(sURL, sId, html); End; End; Procedure TloincPublisher.ProcessMap(Const sPath : String; oMap : TFslStringMatch); Var sLeft, sRight : String; sName, sValue : String; Begin if sPath.Contains('?') then Stringsplit(sPath, '?', sLeft, sRight) else sRight := sPath; oMap.Forced := True; While sRight <> '' Do Begin StringSplit(sRight, '&', sLeft, sRight); StringSplit(sLeft, '=', sName, sValue); oMap.Matches[sName] := sValue; End; End; Procedure TloincPublisher.PublishDict(Const sPath, sPrefix : String; html : THTMLPublisher); Var oMap : TFslStringMatch; Begin oMap := TFslStringMatch.Create; Try ProcessMap(sPath, oMap); PublishDict(oMap, sPrefix, html); Finally oMap.Free; End; End; procedure TloincPublisher.PublishDict(oMap: TFslStringMatch; const sPrefix: String; html: THTMLPublisher); begin Try PublishDictInternal(oMap, sPrefix, html); Except On e:Exception Do Begin html.AddParagraph(e.Message); End; End; end; function TloincPublisher.descLength(i : cardinal) : String; begin if i = 0 then result := '0' else result := IntToStr(Length(FLoinc.Refs.GetRefs(i))); end; function TloincPublisher.makeParentsLists(parents : Cardinal) : TCardinalArrayArray; begin SetLength(result, 0); end; procedure TloincPublisher.PublishHeirarchyEntry(sCode: String; iStart : Integer; const sPrefix: String; html: THTMLPublisher); procedure AddParentPath(index : Cardinal; plist : TCardinalArray); var p : Cardinal; code, text, parents, children, concepts, descendentConcepts, stems : Cardinal; lang : byte; begin FLoinc.Entries.GetEntry(index, code, text, parents, children, concepts, descendentConcepts, stems); html.URL(FLoinc.Desc.GetEntry(text, lang), sPrefix+'macode='+FLoinc.Desc.GetEntry(code, lang)); for p in plist do begin FLoinc.Entries.GetEntry(p, code, text, parents, children, concepts, descendentConcepts, stems); html.AddTextPlain(' / '); html.URL(FLoinc.Desc.GetEntry(text, lang), sPrefix+'macode='+FLoinc.Desc.GetEntry(code, lang)); end; end; procedure addParentsLists(index : Cardinal; parents : cardinal); var pll : TCardinalArrayArray; pl : TCardinalArray; begin if (parents <> 0) then begin pll := makeParentsLists(parents); if length(pll) = 1 then begin html.StartParagraph; html.addTextPlain('Heirarchy: '); addParentPath(index, pll[0]); html.EndParagraph; end else begin html.AddParagraph('Heirarchy: '); html.StartList(); for pl in pll do begin html.StartListItem(); addParentPath(index, pl); html.EndListItem; end; html.EndList; end; end; end; var index, code, text, parents, children, concepts, descendentConcepts, stems, iCategories : Cardinal; stext : string; arr : TCardinalArray; i, iTotal : integer; b : boolean; iDescription, iOtherNames, iStems : Cardinal; iEntries : Cardinal; sCode1 : String; iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass : Cardinal; iFlags : Byte; lang : byte; begin index := FLoinc.findMAConcept(sCode); if index = 0 then raise ETerminologyError.create('Unknown Malti-axial code '+sCode); FLoinc.Entries.GetEntry(index, code, text, parents, children, concepts, descendentConcepts, stems); stext := FLoinc.Desc.GetEntry(text, lang); arr := FLoinc.Refs.GetRefs(children); if (length(arr) = 0) then begin html.Heading(1, 'LOINC Part Concept '+sText+' ('+scode+')'); addParentsLists(index, parents); end else begin html.Heading(1, 'Categories in LOINC Part Concept '+sText+' ('+scode+')'); addParentsLists(index, parents); html.StartParagraph; html.AddText('', true, false); html.EndParagraph; html.StartTable(true); html.StartTableRow; html.AddTableCell('Code', true); html.AddTableCell('Description', true); html.AddTableCell('Children', true); html.AddTableCell('Concepts', true); if FFHIRPath <> '' then html.AddTableCell('Tools', true); html.EndTableRow; for I := 0 to Length(arr) - 1 do begin FLoinc.Entries.GetEntry(arr[i], code, text, parents, children, concepts, descendentConcepts, stems); html.StartTableRow; html.AddTableCellURL(FLoinc.Desc.GetEntry(code, lang),sPrefix+'macode='+FLoinc.Desc.GetEntry(code, lang)); html.AddTableCell(FLoinc.Desc.GetEntry(text, lang)); html.AddTableCell(descLength(children)); html.AddTableCell(descLength(descendentConcepts)); if FFHIRPath <> '' then html.AddTableCellURL('Expanded Value Set', FFHIRPath+'ValueSet?_query=expand&identifier=http://loinc.org/vs/'+FLoinc.Desc.GetEntry(code, lang)); html.EndTableRow; end; html.EndTable; end; // reset descendentConcepts: FLoinc.Entries.GetEntry(index, code, text, parents, children, concepts, descendentConcepts, stems); arr := FLoinc.Refs.GetRefs(descendentConcepts); if (length(arr) > 0) then begin html.StartParagraph; html.AddText('LOINC Codes in Category "'+sText+'"', true, false); if FFHIRPath <> '' then begin html.AddTextPlain('. Get this as an '); html.URL('Expanded Value Set', FFHIRPath+'ValueSet?_query=expand&identifier=http://loinc.org/vs/'+scode); end; html.EndParagraph; b := false; html.StartTable(false); html.StartTableRow; html.StartTableCell; html.AddParagraph(' '); html.EndTableCell; html.StartTableCell; html.StartList; iTotal := length(arr)-1; For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do Begin if not b And ((i - iStart) / Min(MAX_ROWS, iTotal) >= 0.5) Then Begin html.EndList; html.EndTableCell; html.StartTableCell; html.StartList; b := true; End; FLoinc.CodeList.GetInformation(arr[i], nil, sCode1, iDescription, iOtherNames, iStems, iEntries, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iFlags); html.StartListItem; html.URL(sCode1, sPrefix + 'code='+sCode1); html.AddTextPlain(': '+FLoinc.Desc.GetEntry(iDescription, lang)); html.EndListItem; End; html.EndList; html.EndTableCell; html.EndTableRow; html.EndTable; if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then Begin html.StartParagraph; if iStart > 0 Then Begin html.URL('Start', sPrefix+'macode='+sCode); html.AddTextPlain(' '); End; if iStart > MAX_ROWS Then Begin html.URL('Previous', sPrefix+'macode='+sCode+'&start='+inttostr(iStart - MAX_ROWS)); html.AddTextPlain(' '); End; html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false); if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then Begin html.AddTextPlain(' '); html.URL('Next', sPrefix+'macode='+sCode+'&start='+inttostr(iStart + MAX_ROWS)); End; if (iStart+MAX_ROWS < iTotal) Then Begin html.AddTextPlain(' '); html.URL('End', sPrefix+'macode='+sCode+'&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS))); End; html.EndParagraph; End; end; html.line; html.ParaURL('LOINC Home', sPrefix); loincFooter(html); html.Done; end; procedure TloincPublisher.PublishHeirarchyRoot(const sPrefix: String; html: THTMLPublisher); var i : integer; code, text, parents, children, concepts, descendentConcepts, stems: Cardinal; lang : byte; begin html.StartTable(true); html.StartTableRow; html.AddTableCell('Code', true); html.AddTableCell('Description', true); html.AddTableCell('Children', true); html.AddTableCell('Concepts', true); html.EndTableRow; for I := 0 to Length(FLoinc.HeirarchyRoots) - 1 do begin FLoinc.Entries.GetEntry(FLoinc.HeirarchyRoots[i], code, text, parents, children, concepts, descendentConcepts, stems); html.StartTableRow; html.AddTableCellURL(FLoinc.Desc.GetEntry(code, lang),sPrefix+'macode='+FLoinc.Desc.GetEntry(code, lang)); html.AddTableCell(FLoinc.Desc.GetEntry(text, lang)); html.AddTableCell(descLength(children)); html.AddTableCell(descLength(descendentConcepts)); html.EndTableRow; end; html.EndTable; end; procedure TloincPublisher.PublishHome(const sPrefix: String; html: THTMLPublisher); var i : Integer; Begin html.Heading(1, 'LOINC Definitions'); if not FLOINC.Loaded then Begin html.StartParagraph; html.AddText('LOINC is not loaded', true, false); html.EndParagraph; End Else Begin html.StartForm('GET', sPrefix); html.StartParagraph; html.AddTextPlain('Search LOINC: '); html.textInput('srch'); html.submit('Go'); html.AddTextPlain(' '); html.checkbox('all', false, 'Tight'); html.endForm; html.Line; html.ParaURL('Browse All Codes', sPrefix+'code=*'); html.StartParagraph; html.AddText('LOINC Axes', true, false); html.EndParagraph; PublishConcept(true, sPrefix, inttostr(FLoinc.root), 0, html); html.AddParagraph; html.AddText('LOINC Heirarchy', true, false); html.EndParagraph; PublishHeirarchyRoot(sPrefix, html); html.AddParagraph; html.Line; Lock.Lock; Try if FSearchCache.Count <> 0 Then Begin html.AddParagraph('Past Searches:'); html.StartList; For i := 0 to FSearchCache.Count - 1 Do begin html.StartListItem; html.URL('Search for "'+FSearchCache[i]+'"', sPrefix+'srch='+FSearchCache[i]+'&caption=Search LOINC Codes&prompt=Text'); html.EndListItem; end; html.EndList; End; Finally Lock.UnLock; End; End; loincFooter(html); html.Done; End; function TloincPublisher.GetConceptDesc(iConcept : cardinal):String; var iName : Cardinal; iChildren : Cardinal; iCodes : Cardinal; lang : byte; Begin if iConcept = 0 then result := '' Else Begin FLoinc.Concepts.GetConcept(iConcept, langs, iName, iChildren, iCodes); result := FLoinc.Desc.GetEntry(iname, lang); End; End; procedure TloincPublisher.loincFooter(html: THTMLPublisher); begin html.StartParagraph; html.AddTextPlain('LOINC Version: '); html.AddTextPlain(FLoinc.version(nil)); html.EndParagraph; end; procedure TloincPublisher.PublishCode(const sPrefix, sCode: String; html: THTMLPublisher); var iIndex : Cardinal; iDescription, iOtherNames, iStems, iCategories : Cardinal; sCode1, s, se : String; iEntries : Cardinal; iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, parents, children, concepts, descendentConcepts, stems, iCode, iText : Cardinal; iFlags : Byte; iRefs : TCardinalArray; i, j : integer; lang : byte; found, match : boolean; begin iRefs := nil; if FLoinc.CodeList.FindCode(sCode, iIndex) Then Begin FLoinc.CodeList.GetInformation(iIndex, langs, sCode1, iDescription, iOtherNames, iEntries, iStems, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iFlags); assert(sCode = sCode1); html.Heading(1, 'LOINC Code '+sCode+' : '+FLoinc.Desc.GetEntry(iDescription, lang)); html.StartTable(true); if iComponent <> 0 Then Begin html.StartRow(); html.AddTableCell('Component'); html.AddTableCell(GetConceptDesc(iComponent)); html.EndTableRow; End; if iProperty <> 0 Then Begin html.StartRow(); html.AddTableCell('Property'); html.AddTableCell(GetConceptDesc(iProperty)); html.EndTableRow; End; if iTimeAspect <> 0 Then Begin html.StartRow(); html.AddTableCell('Time Aspect'); html.AddTableCell(GetConceptDesc(iTimeAspect)); html.EndTableRow; End; if iSystem <> 0 Then Begin html.StartRow(); html.AddTableCell('System'); html.AddTableCell(GetConceptDesc(iSystem)); html.EndTableRow; End; if iScale <> 0 Then Begin html.StartRow(); html.AddTableCell('Scale'); html.AddTableCell(GetConceptDesc(iScale)); html.EndTableRow; End; if iMethod <> 0 Then Begin html.StartRow(); html.AddTableCell('Method'); html.AddTableCell(GetConceptDesc(iMethod)); html.EndTableRow; End; if iClass <> 0 Then Begin html.StartRow(); html.AddTableCell('Class'); html.AddTableCell(GetConceptDesc(iClass)); html.EndTableRow; End; html.StartRow(); html.AddTableCell('Type'); if iFlags and FLAGS_CLIN > 0 Then html.AddTableCell('Clinical') Else if iFlags and FLAGS_ATT > 0 Then html.AddTableCell('Attachment') Else if iFlags and FLAGS_SURV > 0 Then html.AddTableCell('Survey') Else html.AddTableCell('Lab'); html.EndTableRow; html.StartRow(); html.AddTableCell('Status'); if iFlags and FLAGS_HOLD > 0 Then html.AddTableCell('Not yet final') Else html.AddTableCell('Final'); html.EndTableRow; if iFlags and FLAGS_ROOT > 0 Then Begin html.StartRow(); html.AddTableCell('Root'); html.AddTableCell('This is a root of a set'); html.EndTableRow; End; if iFlags and FLAGS_UNITS > 0 Then Begin html.StartRow(); html.AddTableCell('Units'); html.AddTableCell('Units are required'); html.EndTableRow; End; html.StartRow(); html.AddTableCell('Order/Obs Status'); if (iFlags and FLAGS_ORDER> 0 ) and (iFlags and FLAGS_OBS> 0 ) Then html.AddTableCell('Both') Else if iFlags and FLAGS_ORDER > 0 Then html.AddTableCell('Order') Else if iFlags and FLAGS_OBS > 0 Then html.AddTableCell('Observation') Else html.AddTableCell(''); html.EndTableRow; html.EndTable; html.AddParagraph(''); if iOtherNames <> 0 Then Begin html.StartParagraph; html.AddText('Other Names', true, false); html.EndParagraph; iRefs := FLoinc.Refs.GetRefs(iOtherNames); html.StartTable(true); for i := Low(iRefs) To High(iRefs) Do if iRefs[i] <> 0 Then begin s := FLoinc.desc.GetEntry(iRefs[i], lang); if useLang(lang) then begin html.StartRow(); html.AddTableCell(s); html.EndTableRow; end; End; html.EndTable; End; found := false; for i := 0 to FLoinc.Entries.Count - 1 do begin FLoinc.Entries.GetEntry(i, iCode, iText, parents, children, concepts, descendentConcepts, stems); se := FLoinc.Desc.GetEntry(iCode, lang); iRefs := FLoinc.Refs.GetRefs(descendentConcepts); match := false; for j := 0 to length(iRefs) - 1 do if iRefs[j] = iIndex then begin match := true; break; end; if match then begin if not found then begin html.StartParagraph; html.AddText('Categories', true, false); html.EndParagraph; html.StartTable(true); found := true; end; html.StartRow(); html.AddTableCell(se); html.AddTableCell(FLoinc.Desc.GetEntry(iText, lang)); html.EndTableRow; end; end; if found then html.EndTable; End Else html.AddParagraph('Unable to find code '+sCode); html.line; html.ParaURL('LOINC Home', sPrefix); loincFooter(html); html.done; end; procedure TloincPublisher.PublishConcept(bRoot : Boolean; const sPrefix, sId: String; iStart : Integer; html: THTMLPublisher); var aChildren : TCardinalArray; aCodes : TCardinalArray; iName : Cardinal; iChildren : Cardinal; iCodes : Cardinal; i : Integer; iDummy : Cardinal; b : Boolean; iDescription, iOtherNames, iStems, iCategories : Cardinal; sCode1 : String; iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass : Cardinal; iFlags, lang : Byte; iEntries : Cardinal; begin aChildren := nil; aCodes := nil; FLoinc.Concepts.GetConcept(StrToInt(sId), langs, iName, iChildren, iCodes); if Not bRoot then html.Heading(1, 'LOINC Concept '+FLoinc.Desc.GetEntry(iName, lang)); b := false; if iChildren <> 0 Then begin aChildren := FLoinc.Refs.GetRefs(iChildren); html.StartTable(false, 'bare'); html.StartTableRow; html.StartTableCell; html.AddParagraph(' '); html.EndTableCell; html.StartTableCell; html.StartList; For i := iStart to Min(iStart+MAX_ROWS, High(aChildren)) Do Begin if not b And (Length(aChildren) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aChildren)) >= 0.5) Then Begin html.EndList; html.EndTableCell; html.StartTableCell; html.StartList; b := true; End; FLoinc.Concepts.GetConcept(aChildren[i], langs, iName, iChildren, iDummy); html.StartListItem; html.URL(FLoinc.Desc.GetEntry(iName, lang), sPrefix + 'id='+inttostr(aChildren[i])); html.EndListItem; End; html.EndList; html.EndTableCell; html.EndTableRow; html.EndTable; if (iStart > 0) or (iStart+MAX_ROWS < High(aChildren)) Then Begin html.StartParagraph; if iStart > 0 Then Begin html.URL('Start', sPrefix+'id='+sId); html.AddTextPlain(' '); End; if iStart > MAX_ROWS Then Begin html.URL('Previous', sPrefix+'id='+sId+'&start='+inttostr(iStart - MAX_ROWS)); html.AddTextPlain(' '); End; html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(High(aChildren) div MAX_ROWS + 1), true, false); if (iStart+MAX_ROWS < High(aChildren)) And (iStart + MAX_ROWS < MAX_ROWS * (High(aChildren) div MAX_ROWS)) Then Begin html.AddTextPlain(' '); html.URL('Next', sPrefix+'id='+sId+'&start='+inttostr(iStart + MAX_ROWS)); End; if (iStart+MAX_ROWS < High(aChildren)) Then Begin html.AddTextPlain(' '); html.URL('End', sPrefix+'id='+sId+'&start='+inttostr(MAX_ROWS * (High(aChildren) div MAX_ROWS))); End; html.EndParagraph; End; End; b := false; if iCodes <> 0 Then begin aCodes := FLoinc.Refs.GetRefs(iCodes); html.StartTable(false); html.StartTableRow; html.StartTableCell; html.AddParagraph(' '); html.EndTableCell; html.StartTableCell; For i := iStart to Min(iStart+MAX_ROWS, High(aCodes)) Do Begin if not b And (Length(aCodes) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aCodes)) >= 0.5) Then Begin html.EndTableCell; html.StartTableCell; b := true; End; FLoinc.CodeList.GetInformation(aCodes[i], nil, sCode1, iDescription, iOtherNames, iEntries, iStems, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iFlags); html.StartParagraph; html.URL(sCode1, sPrefix + 'code='+sCode1); html.AddTextPlain(': '+FLoinc.Desc.GetEntry(iDescription, lang)); html.EndParagraph; End; html.EndTableCell; html.EndTableRow; html.EndTable; if (iStart > 0) or (iStart+MAX_ROWS < High(aCodes)) Then Begin html.StartParagraph; if iStart > 0 Then Begin html.URL('Start', sPrefix+'id='+sId); html.AddTextPlain(' '); End; if iStart > MAX_ROWS Then Begin html.URL('Previous', sPrefix+'id='+sId+'&start='+inttostr(iStart - MAX_ROWS)); html.AddTextPlain(' '); End; html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(High(aCodes) div MAX_ROWS + 1), true, false); if (iStart+MAX_ROWS < High(aCodes)) And (iStart + MAX_ROWS < MAX_ROWS * (High(aCodes) div MAX_ROWS)) Then Begin html.AddTextPlain(' '); html.URL('Next', sPrefix+'id='+sId+'&start='+inttostr(iStart + MAX_ROWS)); End; if (iStart+MAX_ROWS < High(aCodes)) Then Begin html.AddTextPlain(' '); html.URL('End', sPrefix+'id='+sId+'&start='+inttostr(MAX_ROWS * (High(aCodes) div MAX_ROWS))); End; html.EndParagraph; End; End; if not bRoot then begin html.line; html.ParaURL('LOINC Home', sPrefix); loincFooter(html); html.done; end; end; procedure TloincPublisher.PublishCodes(const sPrefix: String; iStart: Integer; html: THTMLPublisher); var i : Integer; iTotal : Integer; b : Boolean; iDescription, iOtherNames, iStems, iCategories : Cardinal; iEntries : Cardinal; sCode1 : String; iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass : Cardinal; iFlags, lang : Byte; begin b := false; if iStart = 0 then html.Heading(1, 'All Loinc Codes') else html.Heading(1, 'All Loinc Codes (offset = '+inttostr(iStart)+')'); html.StartTable(false); html.StartTableRow; html.StartTableCell; html.AddParagraph(' '); html.EndTableCell; html.StartTableCell; html.StartList; iTotal := FLoinc.CodeList.Count; For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do Begin if not b And ((i - iStart) / Min(MAX_ROWS, iTotal) >= 0.5) Then Begin html.EndList; html.EndTableCell; html.StartTableCell; html.StartList; b := true; End; FLoinc.CodeList.GetInformation(i, langs, sCode1, iDescription, iOtherNames, iStems, iEntries, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iFlags); html.StartListItem; html.URL(sCode1, sPrefix + 'code='+sCode1); html.AddTextPlain(': '+FLoinc.Desc.GetEntry(iDescription, lang)); html.EndListItem; End; html.EndList; html.EndTableCell; html.EndTableRow; html.EndTable; if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then Begin html.StartParagraph; if iStart > 0 Then Begin html.URL('Start', sPrefix+'code=*'); html.AddTextPlain(' '); End; if iStart > MAX_ROWS Then Begin html.URL('Previous', sPrefix+'code=*&start='+inttostr(iStart - MAX_ROWS)); html.AddTextPlain(' '); End; html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false); if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then Begin html.AddTextPlain(' '); html.URL('Next', sPrefix+'code=*&start='+inttostr(iStart + MAX_ROWS)); End; if (iStart+MAX_ROWS < iTotal) Then Begin html.AddTextPlain(' '); html.URL('End', sPrefix+'code=*&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS))); End; html.EndParagraph; End; html.line; html.ParaURL('LOINC Home', sPrefix); end; constructor TloincPublisher.Create(oLoinc : TLoincServices; FHIRPathEngine : String; const lang : THTTPLanguages); begin inherited Create; Lock := TFslLock.Create('LOINC publisher'); FSearchCache := TStringList.Create; FSearchCache.Sorted := true; FLoinc := oLoinc.Link; FFHIRPath := FHIRPathEngine; langs := FLoinc.langsForLang(lang); end; destructor TloincPublisher.Destroy; var i : integer; begin For i := 0 to FSearchCache.Count - 1 do FSearchCache.Objects[i].Free; FSearchCache.Free; Lock.Free; FLoinc.Free; inherited; end; Type TSearchCache = class (TObject) public a : TMatchArray; End; procedure TloincPublisher.PublishSearch(const sPrefix, sText: String; iStart: Integer; all : boolean; html: THTMLPublisher); //procedure AddParent(p : Cardinal); //var // code, text, parent, children, concepts, descendentConcepts, stems, iCategories : Cardinal; // lang : byte; //begin // FLoinc.Entries.GetEntryH(p, code, text, parent, children, concepts, descendentConcepts, stems); // if (parent <> NO_PARENT) then // begin // AddParent(parent); // html.AddTextPlain(' / '); // end; // html.URL(FLoinc.Desc.GetEntry(text, lang), sPrefix+'macode='+FLoinc.Desc.GetEntry(code, lang)); //end; var a : TMatchArray; i : integer; o : TSearchCache; iTotal : Integer; // iDummy : Cardinal; iDescription, iOtherNames, iStems, iCategories : Cardinal; iEntries : Cardinal; sCode1 : String; iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass : Cardinal; iFlags, ilang : Byte; code, text, parents, children, concepts, descendentConcepts, stems: Cardinal; begin Lock.Lock; Try if FSearchCache.Find(sText, i) Then a := TSearchCache(FSearchCache.Objects[i]).a else Begin a := FLoinc.Search(sText, all); o := TSearchCache.Create; o.a := a; FSearchCache.AddObject(sText, o); End; Finally Lock.Unlock; End; html.Heading(1, 'Search LOINC for '+sText); html.StartTable(false); html.StartTableRow; html.AddTableCell('Code'); html.AddTableCell('Description'); html.AddTableCell('Component'); html.AddTableCell('Property'); html.AddTableCell('Time Aspect'); html.AddTableCell('System'); html.AddTableCell('Scale'); html.AddTableCell('Method'); html.AddTableCell('Class'); html.AddTableCell('Rating'); html.EndTableRow; iTotal := Length(a)-1; For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do Begin html.StartTableRow; if a[i].iscode then begin FLoinc.CodeList.GetInformation(a[i].index, nil, sCode1, iDescription, iOtherNames, iEntries, iStems, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iFlags); html.AddTableCellURL(sCode1, sPrefix + 'code='+sCode1); html.AddTableCell(FLoinc.Desc.GetEntry(iDescription, ilang)); html.AddTableCell(GetConceptDesc(iComponent)); html.AddTableCell(GetConceptDesc(iProperty)); html.AddTableCell(GetConceptDesc(iTimeAspect)); html.AddTableCell(GetConceptDesc(iSystem)); html.AddTableCell(GetConceptDesc(iScale)); html.AddTableCell(GetConceptDesc(iMethod)); html.AddTableCell(GetConceptDesc(iClass)); html.AddTableCell(RealToString(a[i].Priority)); end else begin FLoinc.Entries.GetEntry(a[i].index, code, text, parents, children, concepts, descendentConcepts, stems); sCode1 := FLoinc.Desc.GetEntry(code, ilang); html.AddTableCellURL(sCode1, sPrefix + 'macode='+sCode1); html.AddTableCell(FLoinc.Desc.GetEntry(text, ilang)); html.StartTableCell(7); //html.AddTextPlain('Heirarchy: '); //if (parent = NO_PARENT) then // html.AddTextPlain('(root)') //else // AddParent(parent); html.EndTableCell; html.AddTableCell(RealToString(a[i].Priority - 1000000)); end; html.EndTableRow; End; html.EndTable; if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then Begin html.StartParagraph; if iStart > 0 Then Begin html.URL('Start', sPrefix+'srch='+sText); html.AddTextPlain(' '); End; if iStart > MAX_ROWS Then Begin html.URL('Previous', sPrefix+'srch='+sText+'&start='+inttostr(iStart - MAX_ROWS)); html.AddTextPlain(' '); End; html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false); if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then Begin html.AddTextPlain(' '); html.URL('Next', sPrefix+'srch='+sText+'&start='+inttostr(iStart + MAX_ROWS)); End; if (iStart+MAX_ROWS < iTotal) Then Begin html.AddTextPlain(' '); html.URL('End', sPrefix+'srch='+sText+'&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS))); End; html.EndParagraph; End; html.line; html.ParaURL('LOINC Home', sPrefix); loincFooter(html); html.done; end; function TloincPublisher.useLang(lang: byte): boolean; var b: byte; begin result := false; for b in langs do if b = lang then exit(true); end; function TloincPublisher.sizeInBytesV(magic : integer) : cardinal; begin result := inherited sizeInBytesV(magic); inc(result, FSearchCache.sizeInBytes(magic)); inc(result, FLoinc.sizeInBytes(magic)); inc(result, (FFHIRPath.length * sizeof(char)) + 12); end; End.
32.103352
186
0.644044
83c5197723f3eda8457014f2d906e1e0e409031c
751
pas
Pascal
CustomProgressBar.pas
delphi-pascal-archive/thread_file_checksums
247a008b8f634adbaaed99e05a2be22bc7b1992d
[ "Unlicense" ]
1
2021-11-06T23:51:00.000Z
2021-11-06T23:51:00.000Z
CustomProgressBar.pas
delphi-pascal-archive/thread_file_checksums
247a008b8f634adbaaed99e05a2be22bc7b1992d
[ "Unlicense" ]
null
null
null
CustomProgressBar.pas
delphi-pascal-archive/thread_file_checksums
247a008b8f634adbaaed99e05a2be22bc7b1992d
[ "Unlicense" ]
1
2021-11-06T23:51:02.000Z
2021-11-06T23:51:02.000Z
unit CustomProgressBar; interface uses Classes, Graphics, Controls, Gauges; type TCustomProgressBar = class(TGauge) private protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property Text; end; implementation { TCustomProgressBar } constructor TCustomProgressBar.Create(AOwner: TComponent); begin inherited; height := 16; forecolor := clBlue; Text := ''; align := alTop; showtext := false; end; procedure TCustomProgressBar.Paint; begin inherited; with canvas do begin Brush.Style := bsClear; pen.color := clBlack; TextOut((Width div 2) - (TextWidth(text) div 2),1,text); end; end; end.
16.688889
61
0.661784
837ac1f654c93b8f1f5c6d1400700b8565776070
9,965
pas
Pascal
SH02/SH/SH.InputHandlerBase.pas
federgraph/SudokuHelper
331e9069232350cd5454b2fb01b82f17382e1d36
[ "CC0-1.0" ]
null
null
null
SH02/SH/SH.InputHandlerBase.pas
federgraph/SudokuHelper
331e9069232350cd5454b2fb01b82f17382e1d36
[ "CC0-1.0" ]
null
null
null
SH02/SH/SH.InputHandlerBase.pas
federgraph/SudokuHelper
331e9069232350cd5454b2fb01b82f17382e1d36
[ "CC0-1.0" ]
null
null
null
{! <summary> This unit implements the base class for Sudoku input handlers. </summary> <author>Dr. Peter Below</author> <history> Version 1.0 created 2021-10-27<p> Last modified by PB 2021-10-27<p> Last modified by GS 2022-01-xx<p> </history> <copyright>Copyright 2021 by Dr. Peter Below</copyright> <licence> The code in this unit is released to the public domain without restrictions for use or redistribution. Just leave the copyright note above intact. The code carries no warranties whatsoever, use at your own risk!</licence> <remarks> The input handler processes mouse and keyboard input coming from the user working on the main form, at least the part intended to change the content of the Sudoku's cells. The user can * Set the value of a Sudoku cell (0 clears the cell) * via keyboard by just typing a number. It will go into the currently selected cell of the display grid. * via mouse/touch by first selecting the value from a group of speedbuttons and then clicking on the cell the value is intended for. * Set or clear candidate values for a cell * via keyboard by typing the value while holding down Ctrl to clear a candidate and Shift to set it for the currently selected cell of the display grid.. * via mouse/touch by first selecting the value from a group of speedbuttons, the action to perform (set/unset) from a second set of speedbuttons, and then clicking on the target cell. Setting values or candidates that would require two keystrokes is a bit of a problem. To make this a bit easier we accept heptadecimal input for values above 9, with a=10, b=11 etc. and g=16 to allow input with a single keystroke. </remarks> } unit SH.InputHandlerBase; interface uses System.SysUtils, System.Classes, System.Types, SH.Interfaces; type {! <summary> Base class for all Sudoku input handlers.</summary> <remarks> The class implements all functionality needed for a Sudoku to react to user input via mouse or keyboard. Descendants have to override the virtual methods CharToValue, IsAllowedValue, SetButtonSymbol and perhaps GetButtonSize if the defaults implement here do not fit their needs. The defaults should serve for Sudokus that display decimal numbers for values. The input handler will be created by the Sudoku helper and has to be initialized by the UI before it can do its work. During initialization the class will create the speedbuttons needed to select the values to input via mouse. Method comments are in the implementation section. Properties are intended for the use of descendants only. </remarks> } TBaseSudokuInputHandler = class abstract(TInterfacedObject, ISudokuInputHandler) strict private FDataStorage: ISudokuData; FHost: ISudokuHostForm; strict protected function CharToValue(aChar: Char; var aValue: TSudokuValue): Boolean; virtual; procedure HandleCellClick(aCol, aRow: Integer; aClickAction: TClickAction = TClickAction.SetFocus); procedure HandleCharacter(aCol, aRow: Integer; aChar: Char); procedure HandleLeftClick(const aCol, aRow: TSudokuCellIndex); procedure HandleRightClick(const aCol, aRow: TSudokuCellIndex); procedure HandleValueOrCandidate(const LCell: ISudokuCell; aChar: Char); virtual; procedure Initialize(aHost: ISudokuHostForm); function IsAllowedValue(aChar: Char): Boolean; virtual; property Data: ISudokuData read FDataStorage; property Host: ISudokuHostForm read FHost; public constructor Create(const ADataStorage: ISudokuData); virtual; end; implementation uses SH.Exceptions, System.Math, System.Character; constructor TBaseSudokuInputHandler.Create(const ADataStorage: ISudokuData); begin inherited Create; FDataStorage := ADataStorage; end; {! <summary> Deduce a Sudoku value from character input </summary> <returns> true if a value could be determined and is valid for the Sudoku, false if not.</returns> <param name="aChar">is the character entered</param> <param name="aValue">returns the value</param> <remarks> If the method returns false aValue should not be used by the caller.</remarks> } function TBaseSudokuInputHandler.CharToValue(aChar: Char; var aValue: TSudokuValue): Boolean; begin Result := true; case aChar of '1'..'9': aValue := StrToInt(aChar); 'a'..'g': aValue := Ord(aChar) - Ord('a') + 10; else Result := false; end; Result := Result and InRange(aValue, 1, Data.Bounds.MaxValue); end; {! <summary> Implements ISudokuInputHandler.HandleCellClick </summary> <param name="aCol">is the grid column of the clicked cell</param> <param name="aRow">is the grid row of the clicked cell</param> <param name="aRightClick">false indicates a click with the left mouse button, true a click with the right one.</param> <remarks> Clicks with the left button set a cell's value, clicks with the right button set or unset candidates, if the cell is empty, or toggle the Gosu state of a cell. Which right-click action is taken depends on the state of some buttons on the main form. The value is also defined by a set of speed buttons on that form. </remarks> } procedure TBaseSudokuInputHandler.HandleCellClick(aCol, aRow: Integer; aClickAction: TClickAction = TClickAction.SetFocus); begin { Convert grid to Sudoku cell index first } Inc(aCol); Inc(aRow); if aClickAction <> TClickAction.SetValue then HandleRightClick(aCol, aRow) else HandleLeftClick(aCol, aRow); end; {! <summary> Implements ISudokuInputHandler.HandleCharacter <param name="aCol">is the grid column of the active cell</param> <param name="aRow">is the grid row of the active cell</param> <param name="aChar">is the character entered</param> <remarks> A character not valid for our purpose is ignored. The method will * set the cell value if aChar represents one of the valid Sudoku values (1..MaxValue) and neither Alt nor Ctrl are held down. If aChar is '1' and MaxValue is 10 or higher a delay mechanism is used to allow a second call to complete a two character sequence. Alternatively letters a to g can be used to input the values 10 to 16. * clear the cell if aChar is '0'. * set a candidate if the cell is empty and Shift is down. * remove a candidate if the cell is empty and Ctrl is down. * toggle the Gosu state of the cell if aChar is a space. </remarks> } procedure TBaseSudokuInputHandler.HandleCharacter(aCol, aRow: Integer; aChar: Char); var LCell: ISudokuCell; begin { Convert grid to Sudoku cell index first } Inc(aCol); Inc(aRow); LCell := Data.Cell[aCol, aRow]; case aChar of ' ': if Data.IsGosu then LCell.ToggleEvenOnly; '0': LCell.Clear; else if IsAllowedValue(aChar) then HandleValueOrCandidate(LCell, aChar); end; end; {! <summary> Handle a left mouse click on a Sudoku cell </summary> <param name="aCol">is the column index of the cell</param> <param name="aRow">is the row index of the cell</param> <remarks> A left click sets a cell's value, which is obtained from the host form. Setting a cell to the value it already contains clears the cell. </remarks> } procedure TBaseSudokuInputHandler.HandleLeftClick(const aCol, aRow: TSudokuCellIndex); var LValue: TSudokuValue; LCell : ISudokuCell; begin LCell := Data.Cell[aCol, aRow]; LValue := Host.CurrentValue; if (LValue = 0) or (LValue = LCell.Value) then LCell.Clear else LCell.Value := LValue; end; {! <summary> Handle a right mouse click on a Sudoku cell </summary> <param name="aCol">is the column index of the cell</param> <param name="aRow">is the row index of the cell</param> <remarks> A right click is used to set or unset a candidate or toggle the Gosu state of a cell. The kind of action to take is obtained from the host form, where the user can select it via a group of speedbuttons. Note that trying to set or unset a candidate only does something if the cell is empty. </remarks> } procedure TBaseSudokuInputHandler.HandleRightClick(const aCol, aRow: TSudokuCellIndex); var LAction: TClickAction; LValue: TSudokuValue; LCell: ISudokuCell; begin LCell := Data.Cell[aCol, aRow]; LValue := Host.CurrentCandidate; LAction := Host.ClickAction; if (LValue = 0) and (LAction <> TClickAction.ToggleGosu) then Exit; // 0 is not a valid candidate value! case LAction of TClickAction.SetFocus: LCell.Select; TClickAction.SetCandidate: LCell.AddCandidate(LValue); TClickAction.UnsetCandidate: LCell.RemoveCandidate(LValue); TClickAction.ToggleGosu: LCell.ToggleEvenOnly; end; end; procedure TBaseSudokuInputHandler.HandleValueOrCandidate(const LCell: ISudokuCell; aChar: Char); var LModifierKeys: TShiftstate; LValue: TSudokuValue; begin LValue := 0; if CharToValue(aChar, LValue) then begin LModifierKeys := Host.Modifierkeys; if ssShift in LModifierKeys then LCell.AddCandidate(LValue) else if ssCtrl in LModifierKeys then LCell.RemoveCandidate(LValue) else LCell.Value := LValue end; end; {! <summary>Implements ISudokuInputHandler.Initialize. </summary> <param name="aHost">represents the main form, required</param> <exception cref="EParameterCannotBeNil">is raised if aHost is nil </exception> } procedure TBaseSudokuInputHandler.Initialize(aHost: ISudokuHostForm); begin if not Assigned(aHost) then raise EParameterCannotBeNil.Create(Classname + '.Initialize', 'aHost'); FHost := aHost; end; {! <summary> Check wheather the passed character is valid as input for a value of the current Sudoku.</summary> <returns> true if the character is OK, false if not</returns> <param name="aChar">is the character to check</param> <remarks> Descendants can override this method to allow more characters as input.</remarks> } function TBaseSudokuInputHandler.IsAllowedValue(aChar: Char): Boolean; begin Result := CharInSet(aChar, ['0'..'9']); end; end.
33.327759
123
0.744104
4754bb3fbdabc07724b9156e2892e7b18454a8e2
17,714
pas
Pascal
source/IWBSCustomRegion.pas
kattunga/IW-Bootstrap-Framework
f2b3bd2ff817626b3f4c400a1aa59367a80201dc
[ "MIT" ]
106
2015-08-27T22:31:26.000Z
2021-12-23T16:56:09.000Z
source/IWBSCustomRegion.pas
kattunga/IW-Bootstrap-Framework
f2b3bd2ff817626b3f4c400a1aa59367a80201dc
[ "MIT" ]
37
2015-08-27T22:07:30.000Z
2019-06-26T02:03:24.000Z
source/IWBSCustomRegion.pas
kattunga/IW-Bootstrap-Framework
f2b3bd2ff817626b3f4c400a1aa59367a80201dc
[ "MIT" ]
43
2015-10-02T23:27:04.000Z
2021-09-30T01:09:41.000Z
unit IWBSCustomRegion; interface {$Include IWBootstrap.inc} uses SysUtils, Classes, Controls, Forms, StrUtils, IWApplication, IWBaseRenderContext, IWContainer, IWControl, IWHTMLContainer, IWHTML40Container, IWRegion, IWBaseHTMLControl, IWRenderContext, IWHTMLTag, IWBaseInterfaces, IWXMLTag, IWBSCommon, IWBSCommonInterfaces, IWBSLayoutMgr, IWScriptEvents, IWBSCustomEvents; type TIWBSCustomRegion = class(TIWCustomRegion, IIWBSComponent, IIWBSContainer) private FOldCss: string; FOldStyle: string; FOldVisible: boolean; FAsyncRefreshControl: boolean; FRendered: boolean; FCustomAsyncEvents: TIWBSCustomAsyncEvents; FCustomRestEvents: TIWBSCustomRestEvents; FCss: string; FGridOptions: TIWBSGridOptions; FScript: TStringList; FScriptInsideTag: boolean; FScriptParams: TIWBSScriptParams; FStyle: TStringList; FReleased: boolean; FText: string; FCollapseVisible: boolean; FCollapse: boolean; FRawText: boolean; FOnAfterRender: TNotifyEvent; FOnAfterAsyncChange: TNotifyEvent; function HTMLControlImplementation: TIWHTMLControlImplementation; function RegionDiv: TIWHTMLTag; function RenderText: string; procedure OnScriptChange(ASender : TObject); procedure OnStyleChange(ASender : TObject); function GetCustomAsyncEvents: TIWBSCustomAsyncEvents; procedure SetCustomAsyncEvents(const Value: TIWBSCustomAsyncEvents); function GetCustomRestEvents: TIWBSCustomRestEvents; procedure SetCustomRestEvents(const Value: TIWBSCustomRestEvents); procedure SetGridOptions(const AValue: TIWBSGridOptions); function GetScript: TStringList; procedure SetScript(const AValue: TStringList); function GetScriptParams: TIWBSScriptParams; procedure SetScriptParams(const AValue: TIWBSScriptParams); function GetStyle: TStringList; procedure SetStyle(const AValue: TStringList); function GetScriptInsideTag: boolean; procedure SetScriptInsideTag(const Value: boolean); function GetAfterRender: TNotifyEvent; procedure SetAfterRender(const Value: TNotifyEvent); procedure SetCollapse(const Value: boolean); procedure SetCollapseVisible(const Value: boolean); procedure SetRawText(const Value: boolean); procedure SetText(const Value: string); procedure SetCss(const Value: string); {$IFNDEF IW_14_1_0_UP} function IsScriptEventsStored: Boolean; virtual; function get_ScriptEvents: TIWScriptEvents; procedure set_ScriptEvents(const Value: TIWScriptEvents); {$ENDIF} protected FMainID: string; FRegionDiv: TIWHTMLTag; FTagName: string; {$hints off} function get_Visible: Boolean; override; procedure set_Visible(Value: Boolean); override; procedure SetParent(AParent: TWinControl); override; {$hints on} function ContainerPrefix: string; override; function InitContainerContext(AWebApplication: TIWApplication): TIWContainerContext; override; procedure InternalRenderCss(var ACss: string); virtual; procedure InternalRenderScript(AContext: TIWCompContext; const AHTMLName: string; AScript: TStringList); virtual; procedure InternalRenderStyle(AStyle: TStringList); virtual; property Released: boolean read FReleased; function RenderAsync(AContext: TIWCompContext): TIWXMLTag; override; procedure RenderComponents(AContainerContext: TIWContainerContext; APageContext: TIWBasePageContext); override; function RenderCSSClass(AComponentContext: TIWCompContext): string; override; function RenderHTML(AContext: TIWCompContext): TIWHTMLTag; override; procedure RenderScripts(AComponentContext: TIWCompContext); override; function RenderStyle(AContext: TIWCompContext): string; override; function SupportsInput: Boolean; procedure IWComponentsChanged(AComponent: TComponent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Let you destroy the region inside a self event handler procedure Release; procedure AsyncRefreshControl; procedure ResetAsyncRefreshControl; procedure AsyncRemoveControl; procedure ApplyAsyncChanges; function GetCssString: string; function GetRoleString: string; virtual; function IsStoredCustomAsyncEvents: Boolean; function IsStoredCustomRestEvents: Boolean; function JQSelector: string; procedure SetFocus; override; property TagType: string read FTagName; published property Align; property BSGridOptions: TIWBSGridOptions read FGridOptions write SetGridOptions; property ClipRegion default False; property CustomAsyncEvents: TIWBSCustomAsyncEvents read GetCustomAsyncEvents write SetCustomAsyncEvents stored IsStoredCustomAsyncEvents; property CustomRestEvents: TIWBSCustomRestEvents read GetCustomRestEvents write SetCustomRestEvents stored IsStoredCustomRestEvents; property Css: string read FCss write SetCss; property Collapse: boolean read FCollapse write SetCollapse default False; property CollapseVisible: boolean read FCollapseVisible write SetCollapseVisible default False; property ExtraTagParams; property LayoutMgr; property RawText: boolean read FRawText write SetRawText default False; property RenderInvisibleControls default True; property ScriptEvents {$IFNDEF IW_14_1_0_UP}: TIWScriptEvents read get_ScriptEvents write set_ScriptEvents stored IsScriptEventsStored {$ENDIF}; property Script: TStringList read GetScript write SetScript; property ScriptInsideTag: boolean read GetScriptInsideTag write SetScriptInsideTag default True; property ScriptParams: TIWBSScriptParams read GetScriptParams write SetScriptParams; property Style: TStringList read GetStyle write SetStyle; property Text: string read FText write SetText; property ZIndex default 0; // Occurs after component is rendered. property OnAfterRender: TNotifyEvent read GetAfterRender write SetAfterRender; // Occurs after component is changed on an Asyn call, it doesn't occurs if the control is fully rendered property OnAfterAsyncChange: TNotifyEvent read FOnAfterAsyncChange write FOnAfterAsyncChange; property OnHTMLTag; end; implementation uses IWBSUtils, IWBSScriptEvents, IWBSGlobal; type TIWContainerHack = class(TIWContainer); constructor TIWBSCustomRegion.Create(AOwner: TComponent); begin inherited; FAsyncRefreshControl := False; FRendered := False; FReleased := False; FCustomAsyncEvents := nil; FCustomRestEvents := nil; FCss := ''; FGridOptions := TIWBSGridOptions.Create(Self); FMainID := ''; FScript := TStringList.Create; FScript.OnChange := OnScriptChange; FScriptInsideTag := True; FScriptParams := TIWBSScriptParams.Create; FScriptParams.OnChange := OnScriptChange; FStyle := TStringList.Create; FStyle.OnChange := OnStyleChange; FStyle.NameValueSeparator := ':'; FTagName := 'div'; ClipRegion := False; RenderInvisibleControls := True; ZIndex := 0; if name = '' then name := IWBSGetUniqueComponentName(Owner, Copy(ClassName,2,MaxInt)); end; destructor TIWBSCustomRegion.Destroy; begin FreeAndNil(FCustomAsyncEvents); FreeAndNil(FCustomRestEvents); FreeAndNil(FGridOptions); FreeAndNil(FScript); FreeAndNil(FScriptParams); FreeAndNil(FStyle); inherited; end; {$IFNDEF IW_14_1_0_UP} function TIWBSCustomRegion.get_ScriptEvents: TIWScriptEvents; begin Result := inherited get_ScriptEvents; end; procedure TIWBSCustomRegion.set_ScriptEvents(const Value: TIWScriptEvents); begin inherited set_ScriptEvents(Value); end; function TIWBSCustomRegion.IsScriptEventsStored: Boolean; begin Result := ScriptEvents.Count > 0; end; {$ENDIF} function TIWBSCustomRegion.get_Visible: Boolean; begin if (Parent is TFrame) and (Name = 'IWFrameRegion') then Result := Parent.Visible else Result := inherited; end; procedure TIWBSCustomRegion.set_Visible(Value: Boolean); begin inherited; if (Parent is TFrame) and (Name = 'IWFrameRegion') and (Parent.Visible <> Value) then Parent.Visible := Value; end; procedure TIWBSCustomRegion.SetParent(AParent: TWinControl); begin inherited; if (Parent is TFrame) and (Name <> 'IWFrameRegion') and (Parent.FindComponent('IWFrameRegion') = nil) then Name := 'IWFrameRegion'; end; procedure TIWBSCustomRegion.SetRawText(const Value: boolean); begin FRawText := Value; AsyncRefreshControl; end; function TIWBSCustomRegion.JQSelector: string; begin Result := '$("#'+HTMLName+'")'; end; procedure TIWBSCustomRegion.AsyncRefreshControl; begin FAsyncRefreshControl := True; Invalidate; end; procedure TIWBSCustomRegion.ResetAsyncRefreshControl; begin FAsyncRefreshControl := False; end; procedure TIWBSCustomRegion.ApplyAsyncChanges; begin if FAsyncRefreshControl or not FRendered then raise Exception.Create('Cannot apply changes now, control should be full refreshed'); RenderAsync(nil); DoRefreshControl := False; end; procedure TIWBSCustomRegion.AsyncRemoveControl; begin TIWBSCommon.AsyncRemoveControl(FMainID); FAsyncRefreshControl := False; FRendered := False; end; procedure TIWBSCustomRegion.Release; var LWebApplication: TIWApplication; begin if Released then Exit; FReleased := True; Hide; LWebApplication := GGetWebApplicationThreadVar; if LWebApplication <> nil then if Parent is TFrame then LWebApplication.ReleaseForm(Parent) else LWebApplication.ReleaseForm(Self); end; procedure TIWBSCustomRegion.SetFocus; begin IWBSExecuteAsyncJScript(JQSelector+'.focus()'); end; function TIWBSCustomRegion.GetRoleString: string; begin result := ''; end; procedure TIWBSCustomRegion.SetGridOptions(const AValue: TIWBSGridOptions); begin FGridOptions.Assign(AValue); Invalidate; end; procedure TIWBSCustomRegion.OnScriptChange( ASender : TObject ); begin AsyncRefreshControl; end; procedure TIWBSCustomRegion.OnStyleChange( ASender : TObject ); begin Invalidate; end; function TIWBSCustomRegion.GetAfterRender: TNotifyEvent; begin Result := FOnAfterRender; end; function TIWBSCustomRegion.GetCssString: string; begin Result := RenderCSSClass(nil); end; function TIWBSCustomRegion.GetCustomAsyncEvents: TIWBSCustomAsyncEvents; begin if FCustomAsyncEvents = nil then FCustomAsyncEvents := TIWBSCustomAsyncEvents.Create(Self); Result := FCustomAsyncEvents; end; function TIWBSCustomRegion.GetCustomRestEvents: TIWBSCustomRestEvents; begin if FCustomRestEvents = nil then FCustomRestEvents := TIWBSCustomRestEvents.Create(Self); Result := FCustomRestEvents; end; procedure TIWBSCustomRegion.SetAfterRender(const Value: TNotifyEvent); begin FOnAfterRender := Value; end; procedure TIWBSCustomRegion.SetCollapse(const Value: boolean); begin FCollapse := Value; Invalidate; end; procedure TIWBSCustomRegion.SetCollapseVisible(const Value: boolean); begin FCollapseVisible := Value; Invalidate; end; procedure TIWBSCustomRegion.SetCss(const Value: string); begin FCss := Value; Invalidate; end; procedure TIWBSCustomRegion.SetCustomAsyncEvents(const Value: TIWBSCustomAsyncEvents); begin FCustomAsyncEvents.Assign(Value); end; procedure TIWBSCustomRegion.SetCustomRestEvents(const Value: TIWBSCustomRestEvents); begin FCustomRestEvents.Assign(Value); end; function TIWBSCustomRegion.IsStoredCustomAsyncEvents: boolean; begin Result := (FCustomAsyncEvents <> nil) and (FCustomAsyncEvents.Count > 0); end; function TIWBSCustomRegion.IsStoredCustomRestEvents: boolean; begin Result := (FCustomRestEvents <> nil) and (FCustomRestEvents.Count > 0); end; procedure TIWBSCustomRegion.SetScript(const AValue: TStringList); begin FScript.Assign(AValue); end; procedure TIWBSCustomRegion.SetScriptInsideTag(const Value: boolean); begin FScriptInsideTag := Value; end; procedure TIWBSCustomRegion.SetScriptParams(const AValue: TIWBSScriptParams); begin FScriptParams.Assign(AValue); end; function TIWBSCustomRegion.GetScript: TStringList; begin Result := FScript; end; function TIWBSCustomRegion.GetScriptInsideTag: boolean; begin Result := FScriptInsideTag; end; function TIWBSCustomRegion.GetScriptParams: TIWBSScriptParams; begin Result := FScriptParams; end; function TIWBSCustomRegion.GetStyle: TStringList; begin Result := FStyle; end; procedure TIWBSCustomRegion.SetStyle(const AValue: TStringList); begin FStyle.Assign(AValue); end; procedure TIWBSCustomRegion.SetText(const Value: string); begin FText := TrimRight(Value); AsyncRefreshControl; end; function TIWBSCustomRegion.ContainerPrefix: string; begin if Owner is TFrame then Result := UpperCase(TFrame(Owner).Name) else if isBaseContainer(Parent) then Result := BaseContainerInterface(Parent).ContainerPrefix else Result := UpperCase(Name); end; function TIWBSCustomRegion.HTMLControlImplementation: TIWHTMLControlImplementation; begin Result := ControlImplementation; end; function TIWBSCustomRegion.RegionDiv: TIWHTMLTag; begin Result := FRegionDiv; end; function TIWBSCustomRegion.InitContainerContext(AWebApplication: TIWApplication): TIWContainerContext; begin if not (Self.LayoutMgr is TIWBSLayoutMgr) then Self.LayoutMgr := TIWBSLayoutMgr.Create(Self); Result := inherited; end; function TIWBSCustomRegion.SupportsInput: Boolean; begin Result := False; end; procedure TIWBSCustomRegion.IWComponentsChanged(AComponent: TComponent); procedure NotifyParentContainer(AParent: TWinControl); begin if (AParent is TIWContainer) then TIWContainerHack(AParent).IWComponentsChanged(AComponent) else if AParent.Parent <> nil then NotifyParentContainer(AParent.Parent); end; begin if not (csDestroying in ComponentState) and Assigned(Parent) then NotifyParentContainer(Parent); end; procedure TIWBSCustomRegion.InternalRenderCss(var ACss: string); begin if FCollapse then begin TIWBSCommon.AddCssClass(ACss, 'collapse'); if FCollapseVisible then TIWBSCommon.AddCssClass(ACss, 'in'); end; end; procedure TIWBSCustomRegion.InternalRenderScript(AContext: TIWCompContext; const AHTMLName: string; AScript: TStringList); begin // end; procedure TIWBSCustomRegion.InternalRenderStyle(AStyle: TStringList); begin // end; function TIWBSCustomRegion.RenderAsync(AContext: TIWCompContext): TIWXMLTag; var xHTMLName: string; xApplication: TIWApplication; begin Result := nil; xHTMLName := HTMLName; if FAsyncRefreshControl or not FRendered then begin TIWBSRegionCommon.CancelChildAsyncRender(Self); TIWBSCommon.RenderAsync(xHTMLName, Self, AContext); end else begin if AContext = nil then xApplication := GGetWebApplicationThreadVar else xApplication := AContext.WebApplication; TIWBSCommon.SetAsyncClass(xApplication, xHTMLName, RenderCSSClass(nil), FOldCss); TIWBSCommon.SetAsyncStyle(xApplication, xHTMLName, RenderStyle(nil), FOldStyle); TIWBSCommon.SetAsyncVisible(xApplication, FMainID, Visible, FOldVisible); if Assigned(FOnAfterAsyncChange) then FOnAfterAsyncChange(Self); if Assigned(gIWBSOnAfterAsyncChange) then gIWBSOnAfterAsyncChange(Self, xHTMLName); end; end; procedure TIWBSCustomRegion.RenderComponents(AContainerContext: TIWContainerContext; APageContext: TIWBasePageContext); begin TIWBSRegionCommon.RenderComponents(Self, AContainerContext, APageContext); end; function TIWBSCustomRegion.RenderCSSClass(AComponentContext: TIWCompContext): string; begin Result := FGridOptions.GetClassString; if FCss <> '' then begin if Result <> '' then Result := Result + ' '; Result := Result + FCss; end; InternalRenderCss(Result); end; function TIWBSCustomRegion.RenderHTML(AContext: TIWCompContext): TIWHTMLTag; begin FOldCss := RenderCSSClass(AContext); FOldStyle := RenderStyle(AContext); FOldVisible := Visible; FRegionDiv := TIWHTMLTag.CreateTag(FTagName); FRegionDiv.AddStringParam('id',HTMLName); FRegionDiv.AddClassParam(FOldCss); FRegionDiv.AddStringParam('role',GetRoleString); FRegionDiv.AddStringParam('style',RenderStyle(AContext)); if FText <> '' then FRegionDiv.Contents.AddText(RenderText); IWBSRenderScript(Self, AContext, FRegionDiv); FMainID := FRegionDiv.Params.Values['id']; if gIWBSAttributeCmpName <> '' then FRegionDiv.Params.Values[gIWBSAttributeCmpName] := name; Result := FRegionDiv; FAsyncRefreshControl := False; FRendered := True; end; procedure TIWBSCustomRegion.RenderScripts(AComponentContext: TIWCompContext); begin // end; function TIWBSCustomRegion.RenderStyle(AContext: TIWCompContext): string; begin Result := TIWBSCommon.RenderStyle(Self); end; function TIWBSCustomRegion.RenderText: string; var i: integer; LLines: TStringList; lHTMLName: string; begin if RawText then begin lHTMLName := HTMLName; LLines := TStringList.Create; try LLines.Text := FText; // replace params before custom events LLines.Text := TIWBSCommon.ReplaceParams(Self, LLines.Text); // replace inner events calls if IsStoredCustomAsyncEvents then for i := 0 to CustomAsyncEvents.Count-1 do TIWBSCustomAsyncEvent(CustomAsyncEvents.Items[i]).ParseParam(lHTMLName, LLines); // replace inner events calls if IsStoredCustomRestEvents then for i := 0 to CustomRestEvents.Count-1 do TIWBSCustomRestEvent(CustomRestEvents.Items[i]).ParseParam(LLines); Result := LLines.Text; finally LLines.Free; end; end else Result := TIWBaseHTMLControl.TextToHTML(FText); end; end.
28.944444
148
0.773004
470883518a0f2b8101dcbc51bc2c73aa80ac873e
56,764
pas
Pascal
SFTP/lib/uMySFTPClient.pas
minias/delphi_tip
6544bd545852b303c5e9543c6a4b028f8a873d9e
[ "MIT" ]
null
null
null
SFTP/lib/uMySFTPClient.pas
minias/delphi_tip
6544bd545852b303c5e9543c6a4b028f8a873d9e
[ "MIT" ]
null
null
null
SFTP/lib/uMySFTPClient.pas
minias/delphi_tip
6544bd545852b303c5e9543c6a4b028f8a873d9e
[ "MIT" ]
null
null
null
{ ** * Copyright (c) 2010, Zeljko Marjanovic <savethem4ever@gmail.com> * This code is licensed under MPL 1.1 * For details, see http://www.mozilla.org/MPL/MPL-1.1.html * } { ** * Delphi/Pascal Wrapper around the library "libssh2" * Base repository: * https://bitbucket.org/ZeljkoMarjanovic/libssh2-delphi * Contributors: * https://bitbucket.org/jeroenp/libssh2-delphi * https://bitbucket.org/VadimLV/libssh2_delphi * https://github.com/pult/libssh2_delphi/ * } unit uMySFTPClient; {$i libssh2.inc} interface uses {$IFDEF allow_hvdll} HVDll, // alternative for: external ?dll_name name '?function_name' delayed; {$ENDIF} {$IFDEF WIN32} Windows, {$ELSE} Wintypes, WinProcs, {$ENDIF} Classes, SysUtils, WinSock, libssh2, libssh2_sftp; const AF_INET6 = 23; SFTPCLIENT_VERSION = '0.5'; type TSFTPItemType = (sitUnknown, sitDirectory, sitFile, sitSymbolicLink, sitSymbolicLinkDir, sitBlockDev, sitCharDev, sitFIFO, sitSocket); TIPVersion = (IPvUNSPEC = 0, IPv4 = AF_INET, IPv6 = AF_INET6); TAuthMode = (amTryAll, amPassword, amPublicKey, amKeyboardInteractive, amPublicKeyViaAgent); TAuthModes = set of TAuthMode; TFingerprintState = (fsNew, fsChanged); TConnectHashAction = (chaCancel, chaIgnore, chaSave); TFingerprintEvent = procedure(ASender: TObject; const AState: TFingerprintState; var AAction: TConnectHashAction) of object; TKeybInteractiveEvent = procedure(ASender: TObject; var Password: string) of object; TTransferProgress = procedure(ASender: TObject; const AFileName: WideString; ATransfered, ATotal: UInt64) of object; TContinueEvent = procedure(ASender: TObject; var ACountinue: Boolean) of object; EWorkThreadException = class(Exception); ESSH2Exception = class(Exception); PAddrInfo = ^addrinfo; addrinfo = record ai_flags: Integer; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST ai_family: Integer; // PF_xxx ai_socktype: Integer; // SOCK_xxx ai_protocol: Integer; // 0 or IPPROTO_xxx for IPv4 and IPv6 ai_addrlen: ULONG; // Length of ai_addr ai_canonname: PAnsiChar; // Canonical name for nodename ai_addr: PSockAddr; // Binary address ai_next: PAddrInfo; // Next structure in linked list end; TStructStat = struct_stat; PStructStat = ^TStructStat; TWorkThread = class(TThread) private FInterval: Cardinal; FNEvent: TNotifyEvent; FSender: TObject; FCanceled: Boolean; FEvent: THandle; FInEvent: THandle; FSyncExecute: Boolean; FEnabled: Boolean; FData: Pointer; protected procedure Execute; override; procedure Trigger; public constructor Create(const CreateSuspended: Boolean); destructor Destroy; override; procedure Terminate; overload; procedure Start; procedure Stop; property Interval: Cardinal Read FInterval Write FInterval; property Event: TNotifyEvent Read FNEvent Write FNEvent; property ThreadSender: TObject Read FSender Write FSender; property Data: Pointer read FData write FData; property SyncExecute: Boolean read FSyncExecute write FSyncExecute; end; TSFTPStatData = class(TCollectionItem) private FFileSize: UInt64; FUid: UInt; FGid: UInt; FPerms: Cardinal; FAtime: TDateTime; FMtime: TDateTime; protected published property FileSize: UInt64 read FFileSize write FFileSize; property UID: UInt read FUid write FUid; property GID: UInt read FGid write FGid; property Permissions: Cardinal read FPerms write FPerms; property LastAccessTime: TDateTime read FAtime write FAtime; property LastModificationTime: TDateTime read FMtime write FMtime; end; TSFTPItem = class(TSFTPStatData) private FFileName: WideString; FLinkPath: WideString; FItemType: TSFTPItemType; FLinkSize: UInt64; FHidden: Boolean; FGIDStr: WideString; FUIDStr: WideString; function GetPermsOct: string; procedure SetPermsOct(const Value: string); protected published procedure Assign(ASource: TPersistent); override; property FileName: WideString read FFileName write FFileName; property LinkPath: WideString read FLinkPath write FLinkPath; property LinkSize: UInt64 read FLinkSize write FLinkSize; property Hidden: Boolean read FHidden write FHidden; property UIDStr: WideString read FUIDStr write FUIDStr; property GIDStr: WideString read FGIDStr write FGIDStr; property PermsOctal: string read GetPermsOct write SetPermsOct; property ItemType: TSFTPItemType read FItemType write FItemType; end; TSFTPItems = class(TCollection) private FOwner: TComponent; FPath: WideString; function GetItems(const AIndex: Integer): TSFTPItem; procedure SetItems(const AIndex: Integer; const Value: TSFTPItem); protected function GetOwner: TPersistent; override; public constructor Create(AOwner: TComponent); function Add: TSFTPItem; function IndexOf(const AItem: TSFTPItem): Integer; procedure ParseEntryBuffers(ABuffer, ALongEntry: PAnsiChar; const AAttributes: LIBSSH2_SFTP_ATTRIBUTES; ACodePage: Word = CP_UTF8); procedure SortDefault; property Path: WideString read FPath write FPath; property Items[const AIndex: Integer]: TSFTPItem read GetItems write SetItems; default; end; THashMode = (hmMD5, hmSHA1); IHashManager = interface ['{296711A3-DE46-4674-9160-382A6F7D87A0}'] function GetFingerprint(const AHost: string; APort: Word): Pointer; overload; function StoreFingerprint(const AHost: string; APort: Word; const AHash: Pointer): Boolean; function RemoveFingerprint(const AHost: string; APort: Word; const AHash: Pointer): Boolean; function CompareFingerprints(const F1, F2: Pointer): Boolean; function GetHashMode: THashMode; end; TSSH2Client = class(TComponent) private FPrivKeyPass: string; FPrivKeyPath: TFileName; FAuthModes: TAuthModes; FPubKeyPath: TFileName; FPort: Word; FPassword: string; FHost: string; FUserName: string; FIPVersion: TIPVersion; FClientBanner: string; FConnected: Boolean; FCanceled: Boolean; FLastErrStr: string; FKeepAlive: Boolean; {+} FTimeOut: Integer; // keepalive timeout interval in seconds {+.} FSockBufLen: Integer; FHashMgr: IHashManager; FSocket: Integer; FSession: PLIBSSH2_SESSION; FOnFingerprint: TFingerprintEvent; FOnKeybInt: TKeybInteractiveEvent; FOnAuthFail: TContinueEvent; FOnConnect: TNotifyEvent; FCodePage: Word; FCompression: Boolean; function GetConnected: Boolean; procedure SetConnected(const Value: Boolean); procedure SetAuthModes(const Value: TAuthModes); procedure DoOnFingerprint(const AState: TFingerprintState; var AAction: TConnectHashAction); function GetVersion: string; function GetLibString: string; protected function GetSessionPtr: PLIBSSH2_SESSION; function GetSocketHandle: Integer; function CreateSocket: Integer; virtual; function ConnectSocket(var S: Integer): Boolean; virtual; procedure RaiseSSHError(const AMsg: string = ''; E: Integer = 0); virtual; function MyEncode(const WS: WideString): AnsiString; virtual; function MyDecode(const S: AnsiString): WideString; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; virtual; procedure Disconnect; virtual; function GetLastSSHError(E: Integer = 0): string; virtual; procedure Cancel(ADisconnect: Boolean = True); virtual; function GetSessionMethodsStr: string; property Host: string read FHost write FHost; property Port: Word read FPort write FPort default 22; property IPVersion: TIPVersion read FIPVersion write FIPVersion; property KeepAlive: Boolean read FKeepAlive write FKeepAlive; {+} property TimeOut: Integer read FTimeOut write FTimeOut; {+.} property SockSndRcvBufLen: Integer read FSockBufLen write FSockBufLen; property AuthModes: TAuthModes read FAuthModes write SetAuthModes default[amTryAll]; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property PublicKeyPath: TFileName read FPubKeyPath write FPubKeyPath; property PrivateKeyPath: TFileName read FPrivKeyPath write FPrivKeyPath; property PrivKeyPassPhrase: string read FPrivKeyPass write FPrivKeyPass; property ClientBanner: string read FClientBanner write FClientBanner; property HashManager: IHashManager read FHashMgr write FHashMgr; property Connected: Boolean read GetConnected write SetConnected; property LibraryVersion: string read GetLibString; property Compression: Boolean read FCompression write FCompression; property CodePage: Word read FCodePage write FCodePage default CP_UTF8; property OnFingerprint: TFingerprintEvent read FOnFingerprint write FOnFingerprint; property OnKeybdInteractive: TKeybInteractiveEvent read FOnKeybInt write FOnKeybInt; property OnConnected: TNotifyEvent read FOnConnect write FOnConnect; property OnAuthFailed: TContinueEvent read FOnAuthFail write FOnAuthFail; property Version: string read GetVersion; end; TSFTPClient = class(TSSH2Client) private FCurrentDir: string; FItems: TSFTPItems; FCanceled: Boolean; FSFtp: PLIBSSH2_SFTP; FLastDirChangedOK: Boolean; FOnTProgress: TTransferProgress; FOnNoStartDir: TContinueEvent; FReadBufLen: Cardinal; FWriteBufLen: Cardinal; procedure SetCurrentDir(const Value: string); procedure DoMakeDir(const LDir: WideString; AMode: Integer = 0; ARecurse: Boolean = False); protected procedure RaiseSSHError(const AMsg: string = ''; E: Integer = 0); override; function ChangeDir(const APath: WideString): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect(const ARemoteDir: WideString = '.'); reintroduce; procedure Disconnect; override; function GetLastSSHError(E: Integer = 0): string; override; procedure Cancel(ADisconnect: Boolean = True); override; procedure List(const AStartPath: WideString = ''); procedure DeleteFile(const AFileName: WideString); procedure DeleteDir(const ADirName: WideString); procedure MakeDir(const ADirName: WideString; AMode: Integer = 0; ARecurse: Boolean = False); {+} function OpenDir(const APath: WideString; AutoMake: Boolean = False; MakeMode: Integer = 0): Boolean; function Exists(const ASourceFileName: WideString): Boolean; {+.} procedure Get(const ASourceFileName: WideString; const ADest: TStream; AResume: Boolean); procedure Put(const ASource: TStream; const ADestFileName: WideString; AOverwrite: Boolean = False); // TODO: AResume: Boolean; procedure Rename(const AOldName, ANewName: WideString); procedure MakeSymLink(const AOrigin, ADest: WideString); function ResolveSymLink(const AOrigin: WideString; var AAtributes: LIBSSH2_SFTP_ATTRIBUTES; ARealPath: Boolean = False): string; procedure SetAttributes(const APath: WideString; AAtribs: LIBSSH2_SFTP_ATTRIBUTES); procedure SetPermissions(const APath: WideString; APerms: Cardinal); overload; procedure SetPermissions(const APath: WideString; const AOctalPerms: string); overload; function ExpandCurrentDirPath: WideString; property ReadBufferLen: Cardinal read FReadBufLen write FReadBufLen; property WriteBufferLen: Cardinal read FWriteBufLen write FWriteBufLen; property DirectoryItems: TSFTPItems read FItems; property CurrentDirectory: string read FCurrentDir write SetCurrentDir; property OnCantChangeStartDir: TContinueEvent read FOnNoStartDir write FOnNoStartDir; property OnTransferProgress: TTransferProgress read FOnTProgress write FOnTProgress; end; TSCPClient = class(TSSH2Client) private FCanceled: Boolean; FOnTProgress: TTransferProgress; protected public procedure Cancel(ADisconnect: Boolean = True); override; procedure Get(const ASourceFileName: WideString; const ADest: TStream; var AStat: TStructStat); procedure Put(const ASource: TStream; const ADestFileName: WideString; AFileSize: UInt64; ATime, MTime: TDateTime; AMode: Integer = 0); property OnTransferProgress: TTransferProgress read FOnTProgress write FOnTProgress; end; function ToOctal(X: Cardinal; const Len: Integer = 4): string; function FromOctal(const S: string): Cardinal; function EncodeStr(const WS: WideString; ACodePage: Word = CP_UTF8): AnsiString; function DecodeStr(const S: AnsiString; ACodePage: Word = CP_UTF8): WideString; implementation uses DateUtils, Forms, WideStrUtils; var GSSH2Init: Integer; const dll_ws2_32_name = 'ws2_32.dll'; {$if declared(uHVDll)} var connect2 : function(S: TSocket; name: Pointer; namelen: Integer): Integer; stdcall; // external dll_ws2_32_name name 'connect'; getaddrinfo : function(pNodeName, pServiceName: PAnsiChar; const pHints: PAddrInfo; var ppResult: PAddrInfo): Integer; stdcall; // external dll_ws2_32_name name 'getaddrinfo'; freeaddrinfo : procedure(ai: PAddrInfo); stdcall; // external dll_ws2_32_name name 'freeaddrinfo'; dll_ws2_32 : TDll; dll_ws2_32_entires : array[0..2] of HVDll.TEntry = ( (Proc: @@connect2; Name: 'connect'), (Proc: @@getaddrinfo; Name: 'getaddrinfo'), (Proc: @@freeaddrinfo; Name: 'freeaddrinfo') ); {$else !declared(uHVDll)} function connect2(S: TSocket; name: Pointer; namelen: Integer): Integer; stdcall; external dll_ws2_32_name name 'connect'{$ifdef allow_delayed} delayed{$endif}; function getaddrinfo(pNodeName, pServiceName: PAnsiChar; const pHints: PAddrInfo; var ppResult: PAddrInfo): Integer; stdcall; external dll_ws2_32_name name 'getaddrinfo' {$ifdef allow_delayed} delayed{$endif}; procedure freeaddrinfo(ai: PAddrInfo); stdcall; external dll_ws2_32_name name 'freeaddrinfo' {$ifdef allow_delayed} delayed{$endif}; {$ifend !declared(uHVDll)} function TestBit(const ABits, AVal: Cardinal): Boolean; inline; begin Result := ABits and AVal { = AVal } <> 0; end; procedure ProcessMsgs; begin Application.ProcessMessages; end; function FromOctal(const S: string): Cardinal; var I: Cardinal; begin Result := 0; for I := 1 to Length(S) do Result := Result * 8 + Cardinal(StrToIntDef(Copy(S, I, 1), 0)); end; function ToOctal(X: Cardinal; const Len: Integer): string; var M: Integer; begin if X = 0 then begin Result := '0'; Exit; end; Result := ''; while X <> 0 do begin M := X mod 8; X := X div 8; Result := IntToStr(M) + Result; end; if Len > 0 then // Result := Format('%.'+IntToStr(Len)+'d', [StrToIntDef(Result, 0)]); Result := Copy(Result, Length(Result) - Len + 1, Len); end; function EncodeStr(const WS: WideString; ACodePage: Word): AnsiString; var L: Integer; Flags: Cardinal; begin if ACodePage = CP_UTF8 then begin Result := UTF8Encode(WS); Exit; end; Result := ''; Flags := 0; // WC_COMPOSITECHECK; L := WideCharToMultiByte(ACodePage, Flags, @WS[1], -1, nil, 0, nil, nil); if L > 1 then begin SetLength(Result, L - 1); WideCharToMultiByte(ACodePage, Flags, @WS[1], -1, @Result[1], L - 1, nil, nil) end; end; function DecodeStr(const S: AnsiString; ACodePage: Word): WideString; var L: Integer; Flags: Cardinal; begin if ACodePage = CP_UTF8 then begin {$IFDEF UNICODE} // TODO: FPC Check Result := UTF8ToWideString(S); {$ELSE} Result := UTF8Decode(S); {$ENDIF} Exit; end; Result := ''; Flags := MB_PRECOMPOSED; L := MultiByteToWideChar(ACodePage, Flags, PAnsiChar(@S[1]), -1, nil, 0); if L > 1 then begin SetLength(Result, L - 1); MultiByteToWideChar(ACodePage, Flags, PAnsiChar(@S[1]), -1, PWideChar(@Result[1]), L - 1); end; end; { TSFTPItem } procedure TSFTPItem.Assign(ASource: TPersistent); var X: TSFTPItem; begin if ASource is TSFTPItem then begin X := TSFTPItem(ASource); Self.FFileName := X.FFileName; Self.FLinkPath := X.FLinkPath; Self.FItemType := X.FItemType; Self.FLinkSize := X.FLinkSize; Self.FHidden := X.FHidden; Self.FGIDStr := X.FGIDStr; Self.FUIDStr := X.FUIDStr; Self.FPerms := X.FPerms; Self.FAtime := X.FAtime; Self.FMtime := X.FMtime; Self.FFileSize := X.FFileSize; Self.FUid := X.FUid; Self.FGid := X.FGid; end else inherited Assign(ASource); end; function TSFTPItem.GetPermsOct: string; begin Result := ToOctal(Permissions) end; procedure TSFTPItem.SetPermsOct(const Value: string); begin Permissions := FromOctal(Value) end; { TWorkThread } constructor TWorkThread.Create(const CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FEnabled := not CreateSuspended; FreeOnTerminate := False; FInterval := INFINITE; FNEvent := nil; FSender := nil; FCanceled := False; FSyncExecute := True; FEvent := CreateEvent(nil, True, False, nil); FInEvent := CreateEvent(nil, True, False, nil); if (FEvent = 0) or (FInEvent = 0) then raise EWorkThreadException.Create('Could not create events.'); end; destructor TWorkThread.Destroy; begin SetEvent(FEvent); FCanceled := True; CloseHandle(FEvent); CloseHandle(FInEvent); inherited; end; procedure TWorkThread.Execute; begin try while not Terminated and not FCanceled and Assigned(Self.FSender) do begin if WaitForSingleObject(FInEvent, INFINITE) = WAIT_OBJECT_0 then begin if FSyncExecute then Synchronize(Trigger) else Trigger; end; if WaitForSingleObject(FEvent, FInterval) = WAIT_OBJECT_0 then Exit; end; except end; end; procedure TWorkThread.Start; begin if not FEnabled then begin {$warnings off} if Suspended then Resume; {$warnings on} SetEvent(FInEvent); FEnabled := True; end; end; procedure TWorkThread.Stop; begin if FEnabled then begin FEnabled := False; ResetEvent(FInEvent); SetEvent(FEvent); end; end; procedure TWorkThread.Terminate; begin SetEvent(FEvent); SetEvent(FInEvent); FCanceled := True; inherited Terminate; end; procedure TWorkThread.Trigger; begin if Assigned(FNEvent) and not FCanceled and not Terminated then FNEvent(FSender); end; { TMySFTPItems } function TSFTPItems.Add: TSFTPItem; begin Result := TSFTPItem( inherited Add); end; constructor TSFTPItems.Create(AOwner: TComponent); begin inherited Create(TSFTPItem); FOwner := AOwner; end; function TSFTPItems.GetItems(const AIndex: Integer): TSFTPItem; begin Result := TSFTPItem( inherited Items[AIndex]); end; function TSFTPItems.GetOwner: TPersistent; begin Result := FOwner; end; function TSFTPItems.IndexOf(const AItem: TSFTPItem): Integer; var I: Integer; begin Result := -1; for I := 0 to Count - 1 do if AItem = Items[I] then begin Result := I; Exit; end; end; procedure TSFTPItems.ParseEntryBuffers(ABuffer, ALongEntry: PAnsiChar; const AAttributes: LIBSSH2_SFTP_ATTRIBUTES; ACodePage: Word); const UID_POS = 3; GID_POS = 4; // surf the string to extract uid/gid name values // this was only tested on openssh server listing // hence the above constants for pos, // dunno if this is standardized or not function ExtractEntryData(ALongEntry: PAnsiChar; const APosition: Integer): string; inline; var I, J, L, K: Integer; S: string; P: PAnsiChar; begin Result := ''; if ALongEntry = nil then Exit; J := APosition - 1; if J < 0 then J := 0; L := Length(ALongEntry); S := ''; P := ALongEntry; K := 0; for I := 0 to L - 1 do begin if (P^ in [#9, #13, #32]) and ((P + sizeof(P^))^ <> #32) then begin Inc(P); Inc(K); Dec(J); if J = 0 then begin Inc(ALongEntry, I + K); K := I; for J := I to L - 1 do begin if P^ in [#0, #9, #13, #32] then begin K := J; break; end; Inc(P); end; SetString(S, ALongEntry, K - I); break; end end; Inc(P); if P^ = #0 then break; end; Result := S; end; var Item: TSFTPItem; LinkAttrs: LIBSSH2_SFTP_ATTRIBUTES; Client: TSFTPClient; begin if (ABuffer = nil) or (ABuffer = '.') or (ABuffer = '..') then Exit; Item := Add; Item.FileName := DecodeStr(ABuffer, ACodePage); if TestBit(AAttributes.Flags, LIBSSH2_SFTP_ATTR_PERMISSIONS) then begin case AAttributes.Permissions and LIBSSH2_SFTP_S_IFMT of LIBSSH2_SFTP_S_IFDIR: Item.ItemType := sitDirectory; LIBSSH2_SFTP_S_IFBLK: Item.ItemType := sitBlockDev; LIBSSH2_SFTP_S_IFIFO: Item.ItemType := sitFIFO; LIBSSH2_SFTP_S_IFCHR: Item.ItemType := sitCharDev; LIBSSH2_SFTP_S_IFSOCK: Item.ItemType := sitSocket; LIBSSH2_SFTP_S_IFLNK: begin if not(Owner is TSSH2Client) then Exit; Client := TSFTPClient(Owner); FillChar(LinkAttrs, sizeof(LinkAttrs), 0); try Item.LinkPath := Client.ResolveSymLink(Client.CurrentDirectory + '/' + Item.FFileName, LinkAttrs, True); if TestBit(LinkAttrs.Flags, LIBSSH2_SFTP_ATTR_PERMISSIONS) and (LinkAttrs.Permissions and LIBSSH2_SFTP_S_IFMT = LIBSSH2_SFTP_S_IFDIR) then Item.ItemType := sitSymbolicLinkDir else Item.ItemType := sitSymbolicLink; if TestBit(LinkAttrs.Flags, LIBSSH2_SFTP_ATTR_SIZE) then Item.LinkSize := LinkAttrs.FileSize else Item.LinkSize := 0; except on E: ESSH2Exception do begin Item.LinkPath := ''; Item.LinkSize := 0; Item.ItemType := sitSymbolicLink; end; end; end; LIBSSH2_SFTP_S_IFREG: Item.ItemType := sitFile; end; Item.Permissions := AAttributes.Permissions; end else begin Item.ItemType := sitUnknown; Item.Permissions := 0; end; if TestBit(AAttributes.Flags, LIBSSH2_SFTP_ATTR_SIZE) then Item.FileSize := AAttributes.FileSize else Item.FileSize := 0; Item.Hidden := ABuffer[0] = '.'; if TestBit(AAttributes.Flags, LIBSSH2_SFTP_ATTR_UIDGID) then begin Item.UID := AAttributes.UID; Item.GID := AAttributes.GID; Item.UIDStr := ExtractEntryData(ALongEntry, UID_POS); Item.GIDStr := ExtractEntryData(ALongEntry, GID_POS); end else begin Item.UID := 0; Item.GID := 0; Item.UIDStr := ''; Item.GIDStr := ''; end; if TestBit(AAttributes.Flags, LIBSSH2_SFTP_ATTR_ACMODTIME) then begin Item.LastAccessTime := UnixToDateTime(AAttributes.ATime); Item.LastModificationTime := UnixToDateTime(AAttributes.MTime); end else begin Item.LastAccessTime := 0; Item.LastModificationTime := 0; end; end; procedure TSFTPItems.SetItems(const AIndex: Integer; const Value: TSFTPItem); begin inherited Items[AIndex] := Value; end; function StrCmpLogicalW(psz1, psz2: PWideChar): integer; stdcall; external 'shlwapi.dll' name 'StrCmpLogicalW'; procedure TSFTPItems.SortDefault; var T: TSFTPItem; function MyCmpWStr(const W1, W2: WideString): Integer; inline; begin //Result := WideCompareStr(W1, W2) //CompareStringW(LOCALE_INVARIANT, 0, PWideChar(W1), -1, PWideChar(W2), -1); if W1 > W2 then Result := 1 else if W1 < W2 then Result := -1 else Result := 0; end; procedure QuickSort(AItems: TSFTPItems; L, R: Integer); var I, J: Integer; P: TSFTPItem; begin repeat I := L; J := R; P := AItems[(L + R) shr 1]; // AItems[L + Trunc(Random(R - L + 1))]; repeat repeat Inc(I); until not(MyCmpWStr(AItems[I - 1].FFileName, P.FFileName) < 0); Dec(I); repeat Dec(J); until not(MyCmpWStr(P.FFileName, AItems[J + 1].FFileName) < 0); Inc(J); if I > J then break; T.Assign(AItems[I]); AItems[I].Assign(AItems[J]); AItems[J].Assign(T); if P = AItems[I] then P := AItems[J] else if P = AItems[J] then P := AItems[I]; Inc(I); Dec(J); until I > J; if L < J then QuickSort(AItems, L, J); L := I; until I >= R; end; var Dirs, Files: TSFTPItems; I, K, L: Integer; Item, SItem: TSFTPItem; begin // Dirs := TSFTPItems.Create(nil); Files := TSFTPItems.Create(nil); try for I := 0 to Count - 1 do begin Item := Items[I]; if Item.ItemType in [sitDirectory, sitSymbolicLinkDir] then begin SItem := Dirs.Add; SItem.Assign(Item); end else begin SItem := Files.Add; SItem.Assign(Item); end; end; K := Dirs.Count; L := Files.Count; T := TSFTPItem.Create(nil); try if K > 1 then QuickSort(Dirs, 0, K - 1); if L > 1 then QuickSort(Files, 0, L - 1); finally T.Free; end; for I := 0 to K - 1 do Items[I].Assign(Dirs[I]); for I := 0 to L - 1 do Items[I + K].Assign(Files[I]); finally Dirs.Free; Files.Free; end; end; { TSSH2Client } procedure TSSH2Client.Cancel(ADisconnect: Boolean); begin // FCanceled := True; Sleep(500); try if ADisconnect then Disconnect; except end; end; procedure TSSH2Client.Connect; type PAbstractData = ^TAbstractData; TAbstractData = record SelfPtr: Pointer; Extra: Pointer; end; function HandleFingerprint(const AState: TFingerprintState; const F: Pointer): Boolean; var HashAction: TConnectHashAction; begin Result := False; HashAction := chaIgnore; DoOnFingerprint(AState, HashAction); case HashAction of chaIgnore: ; chaCancel: Result := True; chaSave: FHashMgr.StoreFingerprint(FHost, FPort, F); end; end; function ParseAuthList(const AList: PAnsiChar): TAuthModes; var Modes: TAuthModes; S: string; begin S := string(AList); if amTryAll in FAuthModes then begin Result := [amTryAll]; Exit; end; Modes := []; if Pos('password', S) > 0 then Modes := Modes + [amPassword]; if Pos('publickey', S) > 0 then begin if amPublicKeyViaAgent in FAuthModes then Modes := Modes + [amPublicKeyViaAgent]; if amPublicKey in FAuthModes then Modes := Modes + [amPublicKey]; end; if Pos('keyboard-interactive', S) > 0 then Modes := Modes + [amKeyboardInteractive]; Result := FAuthModes * Modes; if Result = [] then RaiseSSHError('Server does not support requested auth mode(s)'); end; function UserAuthPassword: Boolean; var Returned: Integer; begin Returned := libssh2_userauth_password(FSession, PAnsiChar(AnsiString(FUserName)), PAnsiChar(AnsiString(FPassword))); Result := Returned = 0; end; procedure KbdInteractiveCallback(const Name: PAnsiChar; name_len: Integer; const instruction: PAnsiChar; instruction_len: Integer; num_prompts: Integer; const prompts: PLIBSSH2_USERAUTH_KBDINT_PROMPT; var responses: LIBSSH2_USERAUTH_KBDINT_RESPONSE; _abstract: Pointer); cdecl; var Pass: string; Data: PAbstractData; SSH2Client: TSSH2Client; begin if num_prompts = 1 then begin // zato sto je abstract->void** Data := PAbstractData(Pointer(_abstract)^); SSH2Client := TSSH2Client(Data.SelfPtr); Pass := SSH2Client.Password; // TODO -o##jpluimers -cGeneral : if Password is assigned, then firs try that at least once before asking if Assigned(SSH2Client.FOnKeybInt) then SSH2Client.FOnKeybInt(Data.SelfPtr, Pass); if (Pass <> '') and (Pos('password', LowerCase(string(prompts.Text))) > 0) then begin responses.text := PAnsiChar(AnsiString(Pass)); responses.length := Length(Pass); end; end; end; function UserAuthKeyboardInteractive: Boolean; var Returned: Integer; begin Returned := libssh2_userauth_keyboard_interactive(FSession, PAnsiChar(AnsiString(FUserName)), @KbdInteractiveCallback); Result := Returned = 0; end; function UserAuthPKey: Boolean; var Returned: Integer; begin Returned := libssh2_userauth_publickey_fromfile(FSession, PAnsiChar(AnsiString(FUserName)), PAnsiChar(AnsiString(FPubKeyPath)), PAnsiChar(AnsiString(FPrivKeyPath)), PAnsiChar(AnsiString(FPrivKeyPass))); Result := Returned = 0; end; function UserAuthPKeyViaAgent: Boolean; var Agent: PLIBSSH2_AGENT; Identity, PrevIdentity: PLIBSSH2_AGENT_PUBLICKEY; begin Result := False; Agent := libssh2_agent_init(FSession); if Agent <> nil then begin try if libssh2_agent_connect(Agent) = 0 then begin if libssh2_agent_list_identities(Agent) = 0 then begin PrevIdentity := nil; while True do begin if libssh2_agent_get_identity(Agent, Identity, PrevIdentity) <> 0 then break; if libssh2_agent_userauth(Agent, PAnsiChar(AnsiString(FUserName)), Identity) = 0 then begin Result := True; break; end; PrevIdentity := Identity; end; end; libssh2_agent_disconnect(Agent); end; finally libssh2_agent_free(Agent); end; end; end; function UserAuthTryAll: Boolean; begin Result := UserAuthPassword or UserAuthKeyboardInteractive or UserAuthPKey or UserAuthPKeyViaAgent; end; label auth; var Sock: Integer; Fingerprint, StoredFingerprint: array of Byte; Abstract: TAbstractData; Aborted: Boolean; UserAuthList: PAnsiChar; AuthMode: TAuthModes; AuthOK: Boolean; B: Boolean; Prefs: AnsiString; begin if Connected then Exit; FCanceled := False; Sock := CreateSocket; if Sock = INVALID_SOCKET then Exit; if not ConnectSocket(Sock) then RaiseSSHError(FLastErrStr); FSocket := Sock; if FSession <> nil then libssh2_session_free(FSession); Abstract.SelfPtr := Self; Abstract.Extra := nil; FSession := libssh2_session_init_ex(nil, nil, nil, @Abstract); if FSession = nil then RaiseSSHError; libssh2_banner_set(FSession, PAnsiChar(MyEncode(FClientBanner))); if FCompression then begin libssh2_session_flag(FSession, LIBSSH2_FLAG_COMPRESS, 1); Prefs := 'zlib,none'; if libssh2_session_method_pref(FSession, LIBSSH2_METHOD_COMP_CS, PAnsiChar(AnsiString(Prefs))) <> 0 then OutputDebugStringW(PWChar(WideString('Error setting comp_cs: ' + GetLastSSHError))); if libssh2_session_method_pref(FSession, LIBSSH2_METHOD_COMP_SC, PAnsiChar(AnsiString(Prefs))) <> 0 then OutputDebugStringW(PWChar(WideString('Error setting comp_sc: ' + GetLastSSHError))); end; if libssh2_session_startup(FSession, FSocket) = 0 then begin if FHashMgr <> nil then begin case FHashMgr.GetHashMode of hmMD5: begin SetLength(Fingerprint, MD5_DIGEST_LENGTH); Pointer(Fingerprint) := libssh2_hostkey_hash(FSession, LIBSSH2_HOSTKEY_HASH_MD5); end; hmSHA1: begin SetLength(Fingerprint, SHA_DIGEST_LENGTH); Pointer(Fingerprint) := libssh2_hostkey_hash(FSession, LIBSSH2_HOSTKEY_HASH_SHA1); end; end; Aborted := False; Pointer(StoredFingerprint) := FHashMgr.GetFingerprint(FHost, FPort); if StoredFingerprint = nil then Aborted := HandleFingerprint(fsNew, Fingerprint) else if not FHashMgr.CompareFingerprints(Fingerprint, StoredFingerprint) then Aborted := HandleFingerprint(fsChanged, Fingerprint); if Aborted then begin Disconnect; Exit; end; end; libssh2_session_set_blocking(FSession, 1); {+} if (FTimeOut > 0) and (FTimeOut<10) then FTimeOut := 10; if FKeepAlive then libssh2_keepalive_config(FSession, Integer(FKeepAlive), FTimeOut); // FTimeOut - number of seconds {+.} UserAuthList := libssh2_userauth_list(FSession, PAnsiChar(AnsiString(FUserName)), Length(AnsiString(FUserName))); if UserAuthList = nil then begin Disconnect; RaiseSSHError('Could not get user auth list.'); end; auth : AuthOK := False; AuthMode := ParseAuthList(UserAuthList); if amTryAll in AuthMode then AuthOK := UserAuthTryAll else begin if amPassword in AuthMode then AuthOK := UserAuthPassword; if not AuthOK and (amKeyboardInteractive in AuthMode) then AuthOK := UserAuthKeyboardInteractive; if not AuthOK and (amPublicKey in AuthMode) then AuthOK := UserAuthPKey; if not AuthOK and (amPublicKeyViaAgent in AuthMode) then AuthOK := UserAuthPKeyViaAgent; end; if not(AuthOK and (libssh2_userauth_authenticated(FSession) > 0)) then begin B := True; if Assigned(FOnAuthFail) then FOnAuthFail(Self, B); if not B then begin Disconnect; Exit; end else goto auth; end; FConnected := True; if Assigned(FOnConnect) then FOnConnect(Self); end else RaiseSSHError; end; function TSSH2Client.ConnectSocket(var S: Integer): Boolean; type PConectData = ^TConectData; TConectData = record S: Integer; ConnectRes: Integer; LastErr: string; ResAddrInfo: PAddrInfo; HaveRes: Boolean; end; procedure TryConnect(ASender: TObject); var PData: PConectData; P: PAddrInfo; begin // PData := PConectData(TWorkThread(ASender).Data); P := PData.ResAddrInfo; while P <> nil do begin PData.ConnectRes := connect2(PData.S, P^.ai_addr, P^.ai_addrlen); PData.LastErr := SysErrorMessage(WSAGetLastError); if PData.ConnectRes <> -1 then break; P := P^.ai_next; end; if PData.ConnectRes = -1 then WSACleanup; PData.HaveRes := True; end; var Worker: TWorkThread; Data: TConectData; Hints: addrinfo; IpFamily: Integer; E: TMethod; begin Result := False; if S <> INVALID_SOCKET then begin Data.HaveRes := False; Data.ConnectRes := -1; Data.S := S; IpFamily := Ord(FIPVersion); if IpFamily <> AF_UNSPEC then begin IpFamily := Ord(FIPVersion); end; FillChar(Hints, sizeof(Hints), 0); Hints.ai_family := IpFamily; Hints.ai_socktype := SOCK_STREAM; Hints.ai_protocol := IPPROTO_TCP; if getaddrinfo(PAnsiChar(AnsiString(FHost)), PAnsiChar(AnsiString(IntToStr(FPort))), @Hints, Data.ResAddrInfo) <> 0 then RaiseSSHError(SysErrorMessage(WSAGetLastError)); Worker := TWorkThread.Create(True); try Worker.SyncExecute := False; Worker.ThreadSender := Worker; E.Code := @TryConnect; E.Data := Worker; Worker.Event := TNotifyEvent(E); Worker.Data := @Data; Worker.Start; while not(Data.HaveRes or FCanceled or Application.Terminated) do begin ProcessMsgs; Sleep(1); end; Worker.Stop; FLastErrStr := Data.LastErr; if not Worker.Terminated then begin Worker.Terminate; if FCanceled then TerminateThread(Worker.Handle, 0); // hiyoooo!! end; finally Worker.Free; freeaddrinfo(Data.ResAddrInfo); end; if not FCanceled then Result := Data.ConnectRes <> -1; end; end; constructor TSSH2Client.Create(AOwner: TComponent); begin inherited; FHost := ''; FPort := 22; FUserName := ''; FPassword := ''; FIPVersion := IPvUNSPEC; FAuthModes := [amTryAll]; FClientBanner := LIBSSH2_SSH_BANNER; FConnected := False; FCanceled := False; FKeepAlive := False; {+} FTimeOut := 10; {+.} FSockBufLen := 8 * 1024; FSocket := INVALID_SOCKET; FCodePage := CP_UTF8; FCompression := False; if InterlockedIncrement(GSSH2Init) = 1 then if libssh2_init(0) <> 0 then RaiseSSHError('Error initializing libssh2.'); end; function TSSH2Client.CreateSocket: Integer; var WSData: TWSAData; begin Result := INVALID_SOCKET; if WSAStartup(MakeWord(2, 2), WSData) <> 0 then begin RaiseSSHError('Invalid winsock version!'); Exit; end; Result := socket(Ord(FIPVersion), SOCK_STREAM, IPPROTO_TCP); if Result = INVALID_SOCKET then begin RaiseSSHError(SysErrorMessage(WSAGetLastError)); Exit; end; setsockopt(Result, SOL_SOCKET, SO_SNDBUF, @FSockBufLen, sizeof(FSockBufLen)); setsockopt(Result, SOL_SOCKET, SO_RCVBUF, @FSockBufLen, sizeof(FSockBufLen)); setsockopt(Result, SOL_SOCKET, SO_KEEPALIVE, @FKeepAlive, sizeof(FKeepAlive)); end; destructor TSSH2Client.Destroy; begin if Connected then Disconnect; if InterlockedDecrement(GSSH2Init) < 1 then libssh2_exit; inherited; end; procedure TSSH2Client.Disconnect; begin try if FSession <> nil then begin libssh2_session_disconnect(FSession, PAnsiChar(AnsiString(FClientBanner + ': ' + GetVersion + ' going to shutdown. Bye.'))); libssh2_session_free(FSession); end; finally closesocket(FSocket); FSocket := INVALID_SOCKET; FSession := nil; WSACleanup; FConnected := False; end; end; procedure TSSH2Client.DoOnFingerprint(const AState: TFingerprintState; var AAction: TConnectHashAction); begin if Assigned(FOnFingerprint) then FOnFingerprint(Self, AState, AAction); end; function TSSH2Client.GetConnected: Boolean; { var Buf: Pointer; } begin Result := False; if (FSession = nil) or { (FSFtp = nil) or } (FSocket = INVALID_SOCKET) then Exit; { if WinSock.send(FSocket, Buf, 0, 0) = SOCKET_ERROR then Exit; } Result := FConnected; end; function TSSH2Client.GetLastSSHError(E: Integer): string; var I: Integer; P: PAnsiChar; begin if E = 0 then Result := SysErrorMessage(WSAGetLastError) else Result := 'No error'; I := 0; P := PAnsiChar(AnsiString(Result)); if FSession <> nil then libssh2_session_last_error(FSession, P, I, 0); Result := string(P); end; function TSSH2Client.GetLibString: string; begin Result := string(libssh2_version(0)); end; function TSSH2Client.GetSessionMethodsStr: string; begin Result := ''; if FSession <> nil then Result := Format('KEX: %s, CRYPT: %s, MAC: %s, COMP: %s, LANG: %s', [libssh2_session_methods(FSession, LIBSSH2_METHOD_KEX), libssh2_session_methods(FSession, LIBSSH2_METHOD_CRYPT_CS), libssh2_session_methods(FSession, LIBSSH2_METHOD_MAC_CS), libssh2_session_methods(FSession, LIBSSH2_METHOD_COMP_CS) + ' ' + libssh2_session_methods(FSession, LIBSSH2_METHOD_COMP_SC), libssh2_session_methods(FSession, LIBSSH2_METHOD_LANG_CS)]); end; function TSSH2Client.GetSessionPtr: PLIBSSH2_SESSION; begin Result := FSession; end; function TSSH2Client.GetSocketHandle: Integer; begin Result := FSocket; end; function TSSH2Client.GetVersion: string; begin Result := ClassName + ' v' + SFTPCLIENT_VERSION; end; function TSSH2Client.MyDecode(const S: AnsiString): WideString; begin Result := DecodeStr(S, FCodePage); end; function TSSH2Client.MyEncode(const WS: WideString): AnsiString; begin Result := EncodeStr(WS, FCodePage); end; procedure TSSH2Client.RaiseSSHError(const AMsg: string; E: Integer); begin // if AMsg <> '' then raise ESSH2Exception.Create(AMsg) else raise ESSH2Exception.Create(GetLastSSHError(E)); end; procedure TSSH2Client.SetAuthModes(const Value: TAuthModes); begin if FAuthModes <> Value then begin if Value = [] then Exit; if amTryAll in Value then begin FAuthModes := [amTryAll]; Exit; end; FAuthModes := Value; end; end; procedure TSSH2Client.SetConnected(const Value: Boolean); begin if FConnected <> Value then begin FConnected := Value; if Value then Connect else Disconnect; end; end; { TSFTPClient } procedure TSFTPClient.Cancel(ADisconnect: Boolean); begin // FCanceled := True; inherited; end; function TSFTPClient.ChangeDir(const APath: WideString): Boolean; var DirHandle: PLIBSSH2_SFTP_HANDLE; begin Result := False; if FSFtp <> nil then begin DirHandle := libssh2_sftp_opendir(FSFtp, PAnsiChar(MyEncode(APath))); if DirHandle <> nil then begin libssh2_sftp_closedir(DirHandle); Result := True; end; end; FLastDirChangedOK := Result; end; function TSFTPClient.OpenDir(const APath: WideString; AutoMake: Boolean = False; MakeMode: Integer = 0): Boolean; begin Result := FCurrentDir = APath; if not Result then begin Result := ChangeDir(APath); if not Result and AutoMake then begin MakeDir(APath, MakeMode, {Recurse:}True); Result := ChangeDir(APath); end; if Result then begin FCurrentDir := APath; FItems.Path := APath; end; end; end; procedure TSFTPClient.Connect(const ARemoteDir: WideString); var Dir: WideString; B: Boolean; begin inherited Connect; if not Connected then Exit; FSFtp := libssh2_sftp_init(GetSessionPtr); if FSFtp = nil then begin Disconnect; RaiseSSHError; end; Dir := ExpandCurrentDirPath; if Dir = '' then begin B := True; if Assigned(FOnNoStartDir) then FOnNoStartDir(Self, B); if not B then begin Disconnect; Exit; end; end; if ARemoteDir <> '.' then if ARemoteDir <> Dir then begin if ChangeDir(ARemoteDir) then Dir := ARemoteDir else begin B := True; if Assigned(FOnNoStartDir) then FOnNoStartDir(Self, B); if not B then begin Disconnect; Exit; end; end; end; {+} //CurrentDirectory := Dir; FCurrentDir := Dir; {+.} end; constructor TSFTPClient.Create(AOwner: TComponent); begin inherited; FCurrentDir := '.'; FItems := TSFTPItems.Create(Self); FItems.Path := ''; FLastDirChangedOK := False; FReadBufLen := 32 * 1024; FWriteBufLen := 32 * 1024 - 1; end; procedure TSFTPClient.DeleteDir(const ADirName: WideString); begin FCanceled := False; if libssh2_sftp_rmdir(FSFtp, PAnsiChar(MyEncode(ADirName))) <> 0 then RaiseSSHError; end; procedure TSFTPClient.DeleteFile(const AFileName: WideString); begin FCanceled := False; if libssh2_sftp_unlink(FSFtp, PAnsiChar(MyEncode(AFileName))) <> 0 then RaiseSSHError; end; destructor TSFTPClient.Destroy; begin FItems.Free; if Connected then Disconnect; inherited; end; procedure TSFTPClient.Disconnect; begin try if FSFtp <> nil then libssh2_sftp_shutdown(FSFtp); inherited; finally FSFtp := nil; end; end; function TSFTPClient.ExpandCurrentDirPath: WideString; const BUF_LEN = 4 * 1024; var DirHandle: PLIBSSH2_SFTP_HANDLE; Buf: PAnsiChar; begin Result := ''; DirHandle := libssh2_sftp_opendir(FSFtp, '.'); if DirHandle <> nil then begin GetMem(Buf, BUF_LEN); try libssh2_sftp_realpath(FSFtp, nil, Buf, BUF_LEN); libssh2_sftp_close(DirHandle); Result := MyDecode(Buf); finally FreeMem(Buf); end; end else RaiseSSHError; end; {+} function TSFTPClient.Exists(const ASourceFileName: WideString): Boolean; var Attribs: LIBSSH2_SFTP_ATTRIBUTES; FHandle: PLIBSSH2_SFTP_HANDLE; begin Result := False; if libssh2_sftp_stat(FSFtp, PAnsiChar(MyEncode(ASourceFileName)), Attribs) = 0 then begin if not TestBit(Attribs.Flags, LIBSSH2_SFTP_ATTR_SIZE) then OutputDebugStringW(PWChar('TSFTPClient::Get >> No size attrib:' + ASourceFileName)); FHandle := libssh2_sftp_open(FSFtp, PAnsiChar(MyEncode(ASourceFileName)), LIBSSH2_FXF_READ, 0); if FHandle = nil then Exit; libssh2_sftp_close(FHandle); Result := True; end; end; {+.} procedure TSFTPClient.Get(const ASourceFileName: WideString; const ADest: TStream; AResume: Boolean); var Attribs: LIBSSH2_SFTP_ATTRIBUTES; Transfered, Total: UInt64; FHandle: PLIBSSH2_SFTP_HANDLE; Buf: PAnsiChar; R, N: Integer; begin // FCanceled := False; if libssh2_sftp_stat(FSFtp, PAnsiChar(MyEncode(ASourceFileName)), Attribs) = 0 then begin if not TestBit(Attribs.Flags, LIBSSH2_SFTP_ATTR_SIZE) then OutputDebugStringW(PWChar('TSFTPClient::Get >> No size attrib:' + ASourceFileName)); FHandle := libssh2_sftp_open(FSFtp, PAnsiChar(MyEncode(ASourceFileName)), LIBSSH2_FXF_READ, 0); if FHandle = nil then RaiseSSHError; if AResume then begin Total := UInt64(Attribs.FileSize) - UInt64(ADest.Position); libssh2_sftp_seek64(FHandle, ADest.Position); end else Total := Attribs.FileSize; Transfered := 0; GetMem(Buf, FReadBufLen); try repeat R := libssh2_sftp_read(FHandle, Buf, FReadBufLen); if R > 0 then begin N := ADest.Write(Buf^, R); if N > 0 then begin Inc(Transfered, N); if Assigned(FOnTProgress) then FOnTProgress(Self, ASourceFileName, Transfered, Total); end; end else if R < 0 then RaiseSSHError; until (R = 0) or FCanceled; finally FreeMem(Buf); libssh2_sftp_close(FHandle); end; end else RaiseSSHError; end; function TSFTPClient.GetLastSSHError(E: Integer): string; var S: string; C: Integer; begin S := ''; if FSFtp <> nil then begin S := 'SFTP: '; if E = 0 then begin C := libssh2_sftp_last_error(FSFtp); if C = 0 then begin Result := SysErrorMessage(WSAGetLastError); Exit; end; end else C := E; case C of LIBSSH2_FX_OK: S := S + 'No error'; LIBSSH2_FX_EOF: S := S + 'End of file'; LIBSSH2_FX_NO_SUCH_FILE: S := S + 'No such file'; LIBSSH2_FX_PERMISSION_DENIED: S := S + 'Permission denied'; LIBSSH2_FX_FAILURE: S := S + 'Failure'; LIBSSH2_FX_BAD_MESSAGE: S := S + 'Bad messagge'; LIBSSH2_FX_NO_CONNECTION: S := S + 'No connection'; LIBSSH2_FX_CONNECTION_LOST: S := S + 'Connection lost'; LIBSSH2_FX_OP_UNSUPPORTED: S := S + 'Operation unsupported'; LIBSSH2_FX_INVALID_HANDLE: S := S + 'Invalid handle'; LIBSSH2_FX_NO_SUCH_PATH: S := S + 'No such path'; LIBSSH2_FX_FILE_ALREADY_EXISTS: S := S + 'File exists'; LIBSSH2_FX_WRITE_PROTECT: S := S + 'Write protect'; LIBSSH2_FX_NO_MEDIA: S := S + 'No media'; LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: S := S + 'No space on filesystem'; LIBSSH2_FX_QUOTA_EXCEEDED: S := S + 'Quota exceeded'; LIBSSH2_FX_UNKNOWN_PRINCIPAL: S := S + 'Unknown principal'; LIBSSH2_FX_LOCK_CONFlICT: S := S + 'Lock conflict'; LIBSSH2_FX_DIR_NOT_EMPTY: S := S + 'Directory not empty'; LIBSSH2_FX_NOT_A_DIRECTORY: S := S + 'Not a directory'; LIBSSH2_FX_INVALID_FILENAME: S := S + 'Invalid filename'; LIBSSH2_FX_LINK_LOOP: S := S + 'Link loop' else S := S + 'Unknown error'; end; end else S := inherited GetLastSSHError(E); Result := S; end; procedure TSFTPClient.List(const AStartPath: WideString); const BUF_LEN = 4 * 1024; var EntryBuffer: array [0 .. BUF_LEN - 1] of AnsiChar; LongEntry: array [0 .. BUF_LEN - 1] of AnsiChar; Attribs: LIBSSH2_SFTP_ATTRIBUTES; R: Integer; DirHandle: PLIBSSH2_SFTP_HANDLE; begin if not Connected then Exit; FCanceled := False; if AStartPath <> '' then if AStartPath <> FCurrentDir then if not ChangeDir(AStartPath) then RaiseSSHError('Could not change to dir: ' + AStartPath + ' :: ' + GetLastSSHError) else FCurrentDir := AStartPath; DirHandle := libssh2_sftp_opendir(FSFtp, PAnsiChar(MyEncode(CurrentDirectory))); if DirHandle = nil then RaiseSSHError('Could not open dir: ' + GetLastSSHError); FItems.Clear; FItems.BeginUpdate; try repeat R := libssh2_sftp_readdir_ex(DirHandle, EntryBuffer, BUF_LEN, LongEntry, BUF_LEN, @Attribs); if (R <= 0) or FCanceled then break; FItems.ParseEntryBuffers(EntryBuffer, LongEntry, Attribs, FCodePage); until not True; finally FItems.EndUpdate; libssh2_sftp_closedir(DirHandle); FItems.Path := FCurrentDir; end; end; procedure TSFTPClient.MakeDir(const ADirName: WideString; AMode: Integer; ARecurse: Boolean); var Dir: WideString; begin FCanceled := False; Dir := ADirName; if (Dir = '') or (Dir = '.') or (Dir = '/') then Exit; Dir := WideStringReplace(Dir, '/', '\', [rfReplaceAll]); Dir := WideStringReplace(Dir, '\\', '\', [rfReplaceAll]); if (Dir = '\') or (Dir = '.\') then Exit; if Dir[Length(Dir)] = '\' then SetLength(Dir, Length(Dir)-1); DoMakeDir(Dir, AMode, ARecurse); end; procedure TSFTPClient.DoMakeDir(const LDir: WideString; AMode: Integer; ARecurse: Boolean); var // LDir - direcrory delimiter ( PathDelim ) ( windows '\' ) SDir: WideString; // sub dir RDir: WideString; // direcrory delimiter '/' ( sftp ) Mode: Integer; begin FCanceled := False; if (LDir = '') or (LDir = PathDelim) then Exit; if ARecurse then begin SDir := ExtractFileDir(LDir); if (SDir <> '') and (SDir <> '.') then begin if PathDelim <> '/' then RDir := WideStringReplace(SDir, PathDelim, '/', [rfReplaceAll]) else RDir := SDir; if not ChangeDir( RDir ) then DoMakeDir(SDir, AMode, ARecurse); end; end; if AMode <> 0 then Mode := AMode else // mkdir with standard perms 0755 Mode := LIBSSH2_SFTP_S_IRWXU or LIBSSH2_SFTP_S_IRGRP or LIBSSH2_SFTP_S_IXGRP or LIBSSH2_SFTP_S_IROTH or LIBSSH2_SFTP_S_IXOTH; if PathDelim <> '/' then RDir := WideStringReplace(LDir, PathDelim, '/', [rfReplaceAll]) else RDir := LDir; if libssh2_sftp_mkdir(FSFtp, PAnsiChar(MyEncode(RDir)), Mode) <> 0 then RaiseSSHError; end; procedure TSFTPClient.MakeSymLink(const AOrigin, ADest: WideString); begin FCanceled := False; if libssh2_sftp_symlink(FSFtp, PAnsiChar(MyEncode(ADest)), PAnsiChar(MyEncode(AOrigin))) <> 0 then RaiseSSHError; end; procedure TSFTPClient.Put(const ASource: TStream; const ADestFileName: WideString; AOverwrite: Boolean); var R, N, K: Integer; Mode: Integer; FHandle: PLIBSSH2_SFTP_HANDLE; Buf, StartBuf: PAnsiChar; Transfered, Total: UInt64; begin FCanceled := False; Mode := LIBSSH2_FXF_WRITE or LIBSSH2_FXF_CREAT; if AOverwrite then Mode := Mode or LIBSSH2_FXF_TRUNC else Mode := Mode or LIBSSH2_FXF_EXCL; // ensure call fails if file exists FHandle := libssh2_sftp_open(FSFtp, PAnsiChar(MyEncode(ADestFileName)), Mode, LIBSSH2_SFTP_S_IRUSR or LIBSSH2_SFTP_S_IWUSR or LIBSSH2_SFTP_S_IRGRP or LIBSSH2_SFTP_S_IROTH); if FHandle = nil then RaiseSSHError; GetMem(Buf, FWriteBufLen); StartBuf := Buf; Transfered := 0; Total := ASource.Size - ASource.Position; try repeat N := ASource.Read(Buf^, FWriteBufLen); if N > 0 then begin K := N; repeat R := libssh2_sftp_write(FHandle, Buf, K); if R < 0 then RaiseSSHError; Inc(Transfered, R); Inc(Buf, R); Dec(K, R); if Assigned(FOnTProgress) then FOnTProgress(Self, ADestFileName, Transfered, Total); until (K <= 0) or FCanceled; Buf := StartBuf; end; until (N <= 0) or FCanceled; finally FreeMem(StartBuf); libssh2_sftp_close(FHandle); end; end; procedure TSFTPClient.RaiseSSHError(const AMsg: string; E: Integer); begin inherited; // end; procedure TSFTPClient.Rename(const AOldName, ANewName: WideString); begin FCanceled := False; if libssh2_sftp_rename(FSFtp, PAnsiChar(MyEncode(AOldName)), PAnsiChar(MyEncode(ANewName))) <> 0 then RaiseSSHError; end; function TSFTPClient.ResolveSymLink(const AOrigin: WideString; var AAtributes: LIBSSH2_SFTP_ATTRIBUTES; ARealPath: Boolean): string; const BUF_LEN = 4 * 1024; var Target: array [0 .. BUF_LEN - 1] of AnsiChar; R: Integer; begin FCanceled := False; Result := ''; if not ARealPath then R := libssh2_sftp_readlink(FSFtp, PAnsiChar(MyEncode(AOrigin)), PAnsiChar(@Target), BUF_LEN) else R := libssh2_sftp_realpath(FSFtp, PAnsiChar(MyEncode(AOrigin)), PAnsiChar(@Target), BUF_LEN); if R > 0 then begin Result := MyDecode(Target); libssh2_sftp_stat(FSFtp, PAnsiChar(@Target), AAtributes); end else RaiseSSHError; end; procedure TSFTPClient.SetAttributes(const APath: WideString; AAtribs: LIBSSH2_SFTP_ATTRIBUTES); begin FCanceled := False; if libssh2_sftp_setstat(FSFtp, PAnsiChar(MyEncode(APath)), AAtribs) <> 0 then RaiseSSHError; end; procedure TSFTPClient.SetCurrentDir(const Value: string); begin if FCurrentDir <> Value then if ChangeDir(Value) then begin FCurrentDir := Value; FItems.Path := Value; end; end; procedure TSFTPClient.SetPermissions(const APath: WideString; const AOctalPerms: string); begin SetPermissions(APath, FromOctal(AOctalPerms)); end; procedure TSFTPClient.SetPermissions(const APath: WideString; APerms: Cardinal); var Attribs: LIBSSH2_SFTP_ATTRIBUTES; begin FillChar(Attribs, sizeof(Attribs), 0); Attribs.Flags := LIBSSH2_SFTP_ATTR_PERMISSIONS; Attribs.Permissions := APerms; SetAttributes(APath, Attribs); end; { TSCPClient } procedure TSCPClient.Cancel(ADisconnect: Boolean); begin FCanceled := True; inherited; end; procedure TSCPClient.Get(const ASourceFileName: WideString; const ADest: TStream; var AStat: TStructStat); const BUF_LEN = 24 * 1024 - 1; var Channel: PLIBSSH2_CHANNEL; N, R, K: Integer; Buf: array [0 .. BUF_LEN - 1] of AnsiChar; begin // FCanceled := False; Channel := libssh2_scp_recv(GetSessionPtr, PAnsiChar(MyEncode(ASourceFileName)), AStat); if Channel = nil then RaiseSSHError; try N := 0; K := BUF_LEN; while (N < AStat.st_size) and not FCanceled do begin if AStat.st_size - N < K then K := AStat.st_size - N; R := libssh2_channel_read(Channel, Buf, K); if K = R then begin ADest.Write(Buf, K); if Assigned(FOnTProgress) then FOnTProgress(Self, ASourceFileName, N, AStat.st_size); end else RaiseSSHError; Inc(N, R); end; finally libssh2_channel_free(Channel); end; end; procedure TSCPClient.Put(const ASource: TStream; const ADestFileName: WideString; AFileSize: UInt64; ATime, MTime: TDateTime; AMode: Integer); const BUF_LEN = 8 * 1024 - 1; var Channel: PLIBSSH2_CHANNEL; Mode: Integer; Buf, StartBuf: PAnsiChar; N, K, R: Integer; Transfered: UInt64; begin // FCanceled := False; if AMode <> 0 then Mode := AMode else Mode := LIBSSH2_SFTP_S_IRUSR or LIBSSH2_SFTP_S_IWUSR or LIBSSH2_SFTP_S_IRGRP or LIBSSH2_SFTP_S_IROTH; Channel := libssh2_scp_send64(GetSessionPtr, PAnsiChar(MyEncode(ADestFileName)), Mode, AFileSize, DateTimeToUnix(ATime), DateTimeToUnix(MTime)); if Channel = nil then RaiseSSHError; GetMem(Buf, BUF_LEN); StartBuf := Buf; Transfered := 0; try repeat N := ASource.Read(Buf^, BUF_LEN); if N > 0 then begin K := N; repeat R := libssh2_channel_write(Channel, Buf, K); if R < 0 then RaiseSSHError; Inc(Transfered, R); Inc(Buf, R); Dec(K, R); if Assigned(FOnTProgress) then FOnTProgress(Self, ADestFileName, Transfered, AFileSize); until (K <= 0) or FCanceled; Buf := StartBuf; end; until (N <= 0) or FCanceled; libssh2_channel_send_eof(Channel); libssh2_channel_wait_eof(Channel); libssh2_channel_wait_closed(Channel); finally FreeMem(Buf); libssh2_channel_free(Channel); end; end; initialization GSSH2Init := 0; {$if declared(uHVDll)} dll_ws2_32 := TDll.Create(dll_ws2_32_name, dll_ws2_32_entires); //dll_ws2_32.Load(); // @dbg {$ifend} finalization {$if declared(uHVDll)} dll_ws2_32.Unload; {$ifend} end.
26.979087
115
0.673666
f12270ff55ea5db006e3c866e4588a66084ab674
1,506
pas
Pascal
windows/src/developer/TIKE/child/UfrmInternalDebug.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/developer/TIKE/child/UfrmInternalDebug.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/developer/TIKE/child/UfrmInternalDebug.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
(* Name: UfrmInternalDebug Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 14 Sep 2006 Modified Date: 14 Sep 2006 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 14 Sep 2006 - mcdurdin - Initial version *) unit UfrmInternalDebug; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, UfrmTike; type TfrmInternalDebug = class(TTIKEForm) PageControl1: TPageControl; TabSheet4: TTabSheet; lbDEBUG: TListBox; private public procedure AddDEBUG(s: string); end; var frmInternalDebug: TfrmInternalDebug; implementation {$R *.dfm} { if (di.Flags and QID_FLAG_NOMATCH) = QID_FLAG_NOMATCH then s := ' NoMatch in Group' else s := ''; s := Format('RULEMATCH %s%s', [qid[di.ItemType], s]); //Context:%s Output:%s, HexString(di.Context), HexString(di.Output), if Assigned(di.Rule) then begin s := s + Format(' Line:%d', [di.Rule.Line]); end; AddDEBUG(s); } procedure TfrmInternalDebug.AddDEBUG(s: string); begin // lbDEBUG.Clear; if panDebug.Visible then begin lbDEBUG.Items.Add(s); if (lbDEBUG.Items.Count - lbDEBUG.TopIndex) * lbDEBUG.ItemHeight >= lbDEBUG.ClientHeight then lbDEBUG.TopIndex := lbDEBUG.Items.Count - (lbDEBUG.ClientHeight div lbDEBUG.ItemHeight); end; end; end.
22.477612
99
0.653386
47511d90c21e406afab6f48ccf386419c26620f1
1,168
dpr
Pascal
TestSelf/SameOfArraies.dpr
Oreder/DelphiPro01
5cd0c6b79b2c4bdf17f5fe66d9498fe81ba749ca
[ "MIT" ]
1
2017-06-27T23:47:30.000Z
2017-06-27T23:47:30.000Z
TestSelf/SameOfArraies.dpr
Oreder/DelphiPro01
5cd0c6b79b2c4bdf17f5fe66d9498fe81ba749ca
[ "MIT" ]
null
null
null
TestSelf/SameOfArraies.dpr
Oreder/DelphiPro01
5cd0c6b79b2c4bdf17f5fe66d9498fe81ba749ca
[ "MIT" ]
1
2021-02-26T11:23:29.000Z
2021-02-26T11:23:29.000Z
program SameOfArraies; {$APPTYPE CONSOLE} uses SysUtils; const NA = 1000; type Arr = array[1..NA] of Integer; procedure OP(Z: Arr; N,S: Integer); var I: Integer; begin Write('Out[',S,']: '); for I := 1 to N do Write(Z[I]:3); WriteLn; WriteLn; end; var X,Y,Z: Arr; M,N,P: Integer; I,J,K: Integer; Re: Boolean; begin Write('Input number elements of 3 arraies: '); ReadLn(M,N,P); WriteLn; X[1] := Random(5); for I := 2 to M do X[I] := X[I-1] + Random(5); Y[1] := Random(5); for J := 2 to N do Y[J] := Y[J-1] + Random(5); Z[1] := Random(5); for I := 2 to P do Z[I] := Z[I-1] + Random(5); OP(X,M,1); OP(Y,N,2); OP(Z,P,3); (* -------- main -------- *) I := 1; J := 1; K := 1; Re := False; while not ((I>M) or (J>N) or (K>P)) do begin if X[I] < Y[J] then Inc(I) else if X[I] > Y[J] then Inc(J) else begin if Z[K] < X[I] then Inc(K) else if Z[K] = X[I] then begin Re := True; break; end else begin Inc(I); Inc(J); end; end; end; if Re then Write(' FOUND: ',Z[K]) else Write(' NOT Found!'); ReadLn; end.
18.25
72
0.486301
85a9231d7b09b7e813942f4367fcd57403dde482
3,534
pas
Pascal
units/urtpol4.pas
BishopWolf/DelphiMath
bc03e918f2cbe6aad91e8153f5c7ae35abef75e2
[ "Apache-2.0" ]
1
2019-11-20T02:18:47.000Z
2019-11-20T02:18:47.000Z
units/urtpol4.pas
BishopWolf/DelphiMath
bc03e918f2cbe6aad91e8153f5c7ae35abef75e2
[ "Apache-2.0" ]
null
null
null
units/urtpol4.pas
BishopWolf/DelphiMath
bc03e918f2cbe6aad91e8153f5c7ae35abef75e2
[ "Apache-2.0" ]
2
2017-05-14T03:56:55.000Z
2019-11-20T02:18:48.000Z
{ ****************************************************************** Quartic equation ****************************************************************** } unit urtpol4; interface uses utypes, urtpol2, urtpol3; function RootPol4(Coef: TVector; out Z: TCompVector): Integer; { ------------------------------------------------------------------ Solves the quartic equation: Coef[1] + Coef[2] * X + Coef[3] * X^2 + Coef[4] * X^3 + Coef[5] * X^4 = 0 ------------------------------------------------------------------ } implementation uses uConstants; function RootPol4(Coef: TVector; out Z: TCompVector): Integer; var A, AA, B, C, D: Float; Q, R, S: Float; K, KK, L, M: Float; N1, N2: Integer; Cf: TVector; Z1, Z2: TCompVector; function HighestRealRoot(Deg: Integer; Z: TCompVector): Float; { Find the highest real root among the roots of a polynomial } var I: Integer; R: Float; begin R := -MaxNum; for I := 1 to Deg do if (Z[I].Imaginary = 0.0) and (Z[I].Real > R) then R := Z[I].Real; HighestRealRoot := R; end; begin DimVector(Z, 4, 0); { for I := 1 to 4 do //not need begin Z[I].Real := 0.0; Z[I].Imaginary := 0.0; end; } if Coef[5] = 0 then begin RootPol4 := RootPol3(Coef, Z); Exit; end; DimVector(Cf, 4); if Coef[1] = 0.0 then begin { 0 is root. Equation becomes cubic } Cf[1] := Coef[2]; Cf[2] := Coef[3]; Cf[3] := Coef[4]; Cf[4] := Coef[5]; { Solve cubic equation } RootPol4 := RootPol3(Cf, Z) + 1; DelVector(Cf); Exit; end; if Coef[5] = 1.0 then begin A := Coef[4] * 0.25; B := Coef[3]; C := Coef[2]; D := Coef[1]; end else begin A := Coef[4] / Coef[5] * 0.25; B := Coef[3] / Coef[5]; C := Coef[2] / Coef[5]; D := Coef[1] / Coef[5]; end; AA := A * A; Q := B - 6.0 * AA; R := C + A * (8.0 * AA - 2.0 * B); S := D - A * C + AA * (B - 3.0 * AA); { Compute coefficients of cubic equation } Cf[4] := 1.0; Cf[3] := 0.5 * Q; Cf[2] := 0.25 * (Sqr(Cf[1]) - S); { Solve cubic equation and set KK = highest real root } if (R = 0.0) and (Cf[1] < 0.0) then begin { Eq. becomes quadratic with 2 real roots } Cf[1] := Cf[2]; Cf[2] := Cf[3]; Cf[3] := 1.0; { N1 := not needed } RootPol2(Cf, Z); KK := HighestRealRoot(2, Z); end else begin Cf[1] := -0.015625 * Sqr(R); { N1 := not needed } RootPol3(Cf, Z); KK := HighestRealRoot(3, Z); end; K := Sqrt(KK); if K = 0.0 then R := Sqrt(Sqr(Q) - 4.0 * S) else begin Q := Q + 4.0 * KK; R := 0.5 * R / K; end; L := 0.5 * (Q - R); M := 0.5 * (Q + R); { Solve quadratic equation: Y^2 + 2KY + L = 0 } DimVector(Z1, 2, 0); Cf[1] := L; Cf[2] := 2.0 * K; Cf[3] := 1.0; N1 := RootPol2(Cf, Z1); { Solve quadratic equation: Z^2 - 2KZ + M = 0 } DimVector(Z2, 2, 0); Cf[1] := M; Cf[2] := -Cf[2]; N2 := RootPol2(Cf, Z2); { Transfer roots into vectors Xr and Xi } Z[1].Real := Z1[1].Real - A; Z[1].Imaginary := Z1[1].Imaginary; Z[2].Real := Z1[2].Real - A; Z[2].Imaginary := Z1[2].Imaginary; Z[3].Real := Z2[1].Real - A; Z[3].Imaginary := Z2[1].Imaginary; Z[4].Real := Z2[2].Real - A; Z[4].Imaginary := Z2[2].Imaginary; RootPol4 := N1 + N2; DelVector(Cf); DelVector(Z1); DelVector(Z2); end; end.
21.814815
71
0.453594
f1240c70022d0b15c04acbe4b5ff255ac06580d2
1,188
pas
Pascal
77-Signature/Unit1.pas
FMXExpress/Cross-Platform-Samples
d6b761b81a6521652db814b0c1e65263dff4f694
[ "BSD-3-Clause" ]
140
2019-08-07T23:22:44.000Z
2022-02-23T18:27:51.000Z
77-Signature/Unit1.pas
azrael11/Cross-Platform-Samples
f2c16ae3ae23d1ecca00110af1571313eb4e4c51
[ "BSD-3-Clause" ]
1
2020-06-08T11:23:04.000Z
2020-06-08T11:23:04.000Z
77-Signature/Unit1.pas
azrael11/Cross-Platform-Samples
f2c16ae3ae23d1ecca00110af1571313eb4e4c51
[ "BSD-3-Clause" ]
54
2019-08-09T21:37:51.000Z
2022-03-13T12:13:16.000Z
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects, FMX.StdCtrls, FMX.Controls.Presentation, MyPaintBox, FMX.Objects, FMX.Layouts; type TForm1 = class(TForm) MaterialOxfordBlueSB: TStyleBook; ToolBar1: TToolBar; Label1: TLabel; ShadowEffect4: TShadowEffect; Layout1: TLayout; Line1: TLine; Label2: TLabel; Button1: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FSignBox: TMyPaintBox; public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses System.IOUtils; procedure TForm1.Button1Click(Sender: TObject); begin FSignBox.SaveToFile(TPath.Combine(TPath.GetDocumentsPath,'signature.png')); end; procedure TForm1.FormCreate(Sender: TObject); begin FSignBox := TMyPaintBox.Create(Self); FSignBox.Parent := Self; FSignBox.SendToBack; end; procedure TForm1.FormDestroy(Sender: TObject); begin FSignBox.DisposeOf; end; end.
20.135593
81
0.734007
83d1994837760444a7ae36149791d92f572ab279
1,625
pas
Pascal
sources/chHash.CRC.CRC16.CDMA2000.pas
vampirsoft/CryptoHash
bd8eb1fc2f8c8b63c3cb52b47908b7fbadab4be4
[ "MIT" ]
null
null
null
sources/chHash.CRC.CRC16.CDMA2000.pas
vampirsoft/CryptoHash
bd8eb1fc2f8c8b63c3cb52b47908b7fbadab4be4
[ "MIT" ]
null
null
null
sources/chHash.CRC.CRC16.CDMA2000.pas
vampirsoft/CryptoHash
bd8eb1fc2f8c8b63c3cb52b47908b7fbadab4be4
[ "MIT" ]
2
2020-08-30T18:22:38.000Z
2021-06-08T19:52:56.000Z
///////////////////////////////////////////////////////////////////////////////// //*****************************************************************************// //* Project : CryptoHash *// //* Latest Source: https://github.com/vampirsoft/CryptoHash *// //* Unit Name : CryptoHash.inc *// //* Author : Сергей (LordVampir) Дворников *// //* Copyright 2021 LordVampir (https://github.com/vampirsoft) *// //* Licensed under MIT *// //*****************************************************************************// ///////////////////////////////////////////////////////////////////////////////// unit chHash.CRC.CRC16.CDMA2000; {$INCLUDE CryptoHash.inc} interface uses {$IF DEFINED(SUPPORTS_INTERFACES)} chHash.CRC.CRC16.Impl; {$ELSE ~ NOT SUPPORTS_INTERFACES} chHash.CRC.CRC16; {$ENDIF ~ SUPPORTS_INTERFACES} type { TchCrc16CDMA2000 } TchCrc16CDMA2000 = class({$IF DEFINED(SUPPORTS_INTERFACES)}chHash.CRC.CRC16.Impl{$ELSE}chHash.CRC.CRC16{$ENDIF}.TchCrc16) public constructor Create; reintroduce; end; implementation uses {$IF DEFINED(USE_JEDI_CORE_LIBRARY)} JclLogic; {$ELSE ~ NOT USE_JEDI_CORE_LIBRARY} chHash.Core.Bits; {$ENDIF ~ USE_JEDI_CORE_LIBRARY} { TchCrc16CDMA2000 } constructor TchCrc16CDMA2000.Create; begin inherited Create('CRC-16/CDMA2000', $C867, WordMask, $0000, $4C06, False, False); end; end.
31.25
107
0.457846
f1ff88c748477e770e807eda8c3c1c832607bf9f
531
pas
Pascal
.LHP/.Lop10/Minh333/DSTH/BT10.pas
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop10/Minh333/DSTH/BT10.pas
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop10/Minh333/DSTH/BT10.pas
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
// maxn = 62 uses math; const fi='bt10.inp'; fo='bt10.out'; var n: longint; a: array [0..1] of qword; f: text; procedure nhap; begin assign(f,fi); reset(f); read(f,n); close(f); end; function fibo(n: longint): int64; begin fibo:= trunc(((1/sqrt(5))*((1+sqrt(5))/2)**n) - ((1/sqrt(5))*((1-sqrt(5))/2)**n)); end; procedure xl; var p: byte; i: longint; begin assign(f,fo); rewrite(f); p:=1; a[0]:=0; a[1]:=1; write(f,2**n - fibo(n) - fibo(n+1)); close(f); end; begin nhap; xl; end.
12.642857
84
0.536723
47665a5fc9ffd8404f1870df47e96ded4eef1242
18,492
pas
Pascal
library/fhir/fhir_htmlgen.pas
danka74/fhirserver
1fc53b6fba67a54be6bee39159d3db28d42eb8e2
[ "BSD-3-Clause" ]
null
null
null
library/fhir/fhir_htmlgen.pas
danka74/fhirserver
1fc53b6fba67a54be6bee39159d3db28d42eb8e2
[ "BSD-3-Clause" ]
null
null
null
library/fhir/fhir_htmlgen.pas
danka74/fhirserver
1fc53b6fba67a54be6bee39159d3db28d42eb8e2
[ "BSD-3-Clause" ]
null
null
null
unit fhir_htmlgen; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {$I fhir.inc} interface uses SysUtils, fsl_base, fsl_utilities, fsl_stream, fhir_objects, fhir_xhtml, fhir_factory, fsl_http, fhir_parser; Type THtmlPublisher = class (TFslObject) private FBuilder : TFslStringBuilder; FFactory : TFHIRFactory; FBaseURL: String; FLang: THTTPLanguages; FVersion: String; FLogId: String; function Footer(base : String; const lang : THTTPLanguages; logId: String; tail: boolean = true): string; function HeaderX(base : String; const lang : THTTPLanguages; version: String): String; public constructor Create(factory : TFHIRFactory); destructor Destroy; Override; procedure Header(s : String); procedure Done; procedure Line; procedure StartPre; procedure endPre; procedure Heading(level : integer; text : String); procedure StartParagraph; procedure EndParagraph; procedure AddParagraph(text : String = ''); procedure AddTextPlain(text : String); procedure AddTitle(text : String); procedure AddText(text : String; bold, italics : boolean); procedure URL(text, url : String; hint : string = ''); procedure ParaURL(text, url : String); procedure StartTable(borders : boolean; clss : String = ''); procedure StartTableRow; procedure StartRow(bgcolor : string = ''); procedure StartTableCell(span : integer = 1); procedure EndTableCell; procedure EndTableRow; procedure EndTable; procedure AddTableCellURL(text, url : String; hint : String = ''); procedure AddTableCell(text : String; bold : boolean = false); procedure AddTableCellHint(text, hint : String); procedure StartList(ordered : boolean = false); procedure EndList(ordered : boolean = false); procedure StartListItem; procedure EndListItem; procedure StartBlockQuote; procedure EndBlockQuote; procedure startDiv; procedure endDiv; procedure StartForm(method, action : String); procedure TextInput(name : String; length : integer = 20); overload; procedure TextInput(name, value : String; length : integer = 20); overload; procedure TextInput(name, value, text : String; length : integer = 20); overload; procedure Memo(name, value, text : String); overload; procedure checkbox(name : String; value : boolean; text : String); procedure hiddenInput(name, value : String); procedure Submit(name : String); procedure EndForm; procedure writeXhtml(node : TFhirXHtmlNode); procedure Spacer; function output : String; Property BaseURL : String read FBaseURL write FBaseURL; Property Lang : THTTPLanguages read FLang write FLang; Property Version : String read FVersion write FVersion; Property LogId : String read FLogId write FLogid; end; implementation { THtmlPublisher } procedure THtmlPublisher.AddParagraph(text: String); begin StartParagraph; AddTextPlain(text); EndParagraph; end; procedure THtmlPublisher.AddTableCell(text: String; bold: boolean); begin StartTableCell; addtext(text, bold, false); EndTableCell; end; procedure THtmlPublisher.AddTableCellHint(text, hint: String); begin StartTableCell; FBuilder.Append('<span title="'+FormatTextToXML(hint, xmlAttribute)+'">'); addtext(text, false, false); FBuilder.Append('</span>'); EndTableCell; end; procedure THtmlPublisher.AddTableCellURL(text, url: String; hint : String = ''); begin StartTableCell; self.URL(text, url, hint); EndTableCell; end; procedure THtmlPublisher.AddText(text: String; bold, italics: boolean); begin if bold then FBuilder.Append('<b>'); if italics then FBuilder.Append('<i>'); AddTextPlain(text); if italics then FBuilder.Append('</i>'); if bold then FBuilder.Append('</b>'); end; procedure THtmlPublisher.AddTextPlain(text: String); begin FBuilder.Append(FormatTextToXml(text, xmlText)); end; procedure THtmlPublisher.AddTitle(text: String); begin AddText(text, true, false); end; procedure THtmlPublisher.checkbox(name : String; value : boolean; text : String); begin if value then FBuilder.Append('<input type="checkbox" name="'+name+'" checked value="1"/> '+text) else FBuilder.Append('<input type="checkbox" name="'+name+'" value="1"/> '+text); end; procedure THtmlPublisher.endDiv; begin FBuilder.Append('</div>') end; constructor THtmlPublisher.Create(factory : TFHIRFactory); begin inherited Create; FBuilder := TFslStringBuilder.create; FFactory := factory; end; destructor THtmlPublisher.Destroy; begin FBuilder.Free; FFactory.Free; inherited; end; function THtmlPublisher.Footer(base : String; const lang : THTTPLanguages; logId : String; tail : boolean = true): string; begin result := '</div>'+#13#10+ ''+#13#10+ ''+#13#10+ ' </div> <!-- /inner-wrapper -->'+#13#10+ ' </div> <!-- /row -->'+#13#10+ ' </div> <!-- /container -->'+#13#10+ ' </div> <!-- /segment-content -->'+#13#10+ ''+#13#10+ ''+#13#10+ ' <div id="segment-footer" class="segment"> <!-- segment-footer -->'+#13#10+ ' <div class="container"> <!-- container -->'+#13#10+ ' <div class="inner-wrapper">'+#13#10+ ' <p>'+#13#10+ ' <a href="'+base+'" style="color: gold">'+GetFhirMessage('SERVER_HOME', lang)+'</a>.&nbsp;|&nbsp;FHIR &copy; HL7.org 2011+. &nbsp;|&nbsp; FHIR '+GetFhirMessage('NAME_VERSION', lang)+' <a href="'+Ffactory.specUrl+'" style="color: gold">'+FFactory.versionString+'</a>'+#13#10+ ' | Request-id: '+logId+ ' </span>'+#13#10+ ' </p>'+#13#10+ ' </div> <!-- /inner-wrapper -->'+#13#10+ ' </div> <!-- /container -->'+#13#10+ ' </div> <!-- /segment-footer -->'+#13#10+ ''+#13#10+ ''+#13#10+ ' <div id="segment-post-footer" class="segment hidden"> <!-- segment-post-footer -->'+#13#10+ ' <div class="container"> <!-- container -->'+#13#10+ ' </div> <!-- /container -->'+#13#10+ ' </div> <!-- /segment-post-footer -->'+#13#10+ ''+#13#10+ ''+#13#10+ ''+#13#10+ ''+#13#10+ ''+#13#10+ ' <!-- JS and analytics only. -->'+#13#10+ ' <!-- Bootstrap core JavaScript'+#13#10+ '================================================== -->'+#13#10+ ' <!-- Placed at the end of the document so the pages load faster -->'+#13#10+ '<script src="/assets/js/jquery.js"/>'+#13#10+ '<script src="/dist/js/bootstrap.min.js"/>'+#13#10+ '<script src="/assets/js/respond.min.js"/>'+#13#10+ ''+#13#10+ '<script src="/assets/js/fhir.js"/>'+#13#10+ ''+#13#10+ ' <!-- Analytics Below'+#13#10+ '================================================== -->'+#13#10+ ''+#13#10+ ''+#13#10+ ''+#13#10; if tail then result := result + '</body>'+#13#10+ '</html>'+#13#10; end; procedure THtmlPublisher.Done; begin FBuilder.Append(footer(BaseURL, lang, logid)); end; procedure THtmlPublisher.EndBlockQuote; begin FBuilder.Append('</blockquote>'#13#10); end; procedure THtmlPublisher.EndForm; begin FBuilder.Append('</form>'#13#10); end; procedure THtmlPublisher.EndList(ordered: boolean); begin if ordered then FBuilder.Append('</ol>'#13#10) else FBuilder.Append('</ul>'#13#10); end; procedure THtmlPublisher.EndListItem; begin FBuilder.Append('</li>'#13#10); end; procedure THtmlPublisher.EndParagraph; begin FBuilder.Append('<p>'#13#10); end; procedure THtmlPublisher.endPre; begin FBuilder.Append('<pre>'#13#10); end; procedure THtmlPublisher.EndTable; begin FBuilder.Append('</table>'#13#10); end; procedure THtmlPublisher.EndTableCell; begin FBuilder.Append('</td>'#13#10); end; procedure THtmlPublisher.EndTableRow; begin FBuilder.Append('</tr>'#13#10); end; function THtmlPublisher.HeaderX(base : String; const lang : THTTPLanguages; version: String): String; begin result := ' <div id="segment-navbar" class="segment"> <!-- segment-breadcrumb -->'+#13#10+ ' <div id="stripe"> </div>'+#13#10+ ' <div class="container"> <!-- container -->'+#13#10+ ' <div style="background-color: #ad1f2f; padding: 6px; color: white;"> <!-- container -->'+#13#10; result := result + ' <a href="http://www.hl7.org/fhir" style="color: gold" title="'+GetFhirMessage('MSG_HOME_PAGE_TITLE', lang)+'"><img border="0" src="/icon-fhir-16.png" style="vertical-align: text-bottom"/> <b>FHIR</b></a>'#13#10+ ''#13#10+ ' &copy; HL7.org'#13#10+ ' &nbsp;|&nbsp;'#13#10+ ' <a href="/" style="color: gold">'+GetFhirMessage('SERVER_HOME', lang)+'</a> '+ ' &nbsp;|&nbsp;'#13#10+ ' <a href="http://www.healthintersections.com.au" style="color: gold">Health Intersections</a> '+GetFhirMessage('NAME_SERVER', lang)+' v'+version+#13#10+ ' &nbsp;|&nbsp;'#13#10+ ' <a href="'+Ffactory.specUrl+'" style="color: gold">FHIR '+GetFhirMessage('NAME_VERSION', lang)+' '+FFactory.versionString+'</a>'#13#10; result := result + ' &nbsp;'#13#10+ ' </div> <!-- /container -->'+#13#10+ ' </div> <!-- /container -->'+#13#10+ '</div>'#13#10+ ''#13#10; // if FFacebookLike and (FOauthUrl <> '') then // result := result + '<iframe src="https://www.facebook.com/plugins/like.php?href='+FOauthUrl+'" scrolling="no" frameborder="0" style="border:none; width:450px; height:30px"></iframe>'#13#10; result := result + ' <!-- /segment-breadcrumb -->'+#13#10+ ''+#13#10+ ' <div id="segment-content" class="segment"> <!-- segment-content -->'+#13#10+ ' <div class="container"> <!-- container -->'+#13#10+ ' <div class="row">'+#13#10+ ' <div class="inner-wrapper">'+#13#10+ ' <div id="div-cnt" class="col-9">'+#13#10+ ''+#13#10+ ''+#13#10; end; function PageLinks: String; begin result := ' <meta charset="utf-8"/>'+#13#10+ ' <meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=edge" />'+#13#10+ ' <meta content="width=device-width, initial-scale=1.0" name="viewport"/>'+#13#10+ ' <meta content="http://hl7.org/fhir" name="author"/>'+#13#10+ ''+#13#10+ ' <link rel="stylesheet" href="/fhir.css"/>'+#13#10+ ''+#13#10+ ''+#13#10+ ' <!-- Bootstrap core CSS -->'+#13#10+ ' <link rel="stylesheet" href="/dist/css/bootstrap.css"/>'+#13#10+ ' <link rel="stylesheet" href="/assets/css/bootstrap-fhir.css"/>'+#13#10+ ''+#13#10+ ' <!-- Project extras -->'+#13#10+ ' <link rel="stylesheet" href="/assets/css/project.css"/>'+#13#10+ ' <link rel="stylesheet" href="/assets/css/pygments-manni.css"/>'+#13#10+ ''+#13#10+ ' <!-- FHIR Server stuff -->'+#13#10+ ' <link rel="stylesheet" href="/css/tags.css"/>'+#13#10+ ''+#13#10+ ' <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->'+#13#10+ ' <!-- [if lt IE 9]>'+#13#10+ ' <script src="/assets/js/html5shiv.js"></script>'+#13#10+ ' <script src="/assets/js/respond.min.js"></script>'+#13#10+ ' <![endif] -->'+#13#10+ ''+#13#10+ ' <!-- Favicons -->'+#13#10+ ' <link sizes="144x144" rel="apple-touch-icon-precomposed" href="/assets/ico/apple-touch-icon-144-precomposed.png"/>'+#13#10+ ' <link sizes="114x114" rel="apple-touch-icon-precomposed" href="/assets/ico/apple-touch-icon-114-precomposed.png"/>'+#13#10+ ' <link sizes="72x72" rel="apple-touch-icon-precomposed" href="/assets/ico/apple-touch-icon-72-precomposed.png"/>'+#13#10+ ' <link rel="apple-touch-icon-precomposed" href="/assets/ico/apple-touch-icon-57-precomposed.png"/>'+#13#10+ ' <link rel="shortcut icon" href="/assets/ico/favicon.png"/>'+#13#10; end; procedure THtmlPublisher.Header(s: String); begin FBuilder.Append( '<?xml version="1.0" encoding="UTF-8"?>'#13#10+ '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'#13#10+ ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'#13#10+ ''#13#10+ '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'#13#10+ '<head>'#13#10+ ' <title>'+s+'FHIR Server</title>'#13#10+ pagelinks+ FHIR_JS+ '</head>'#13#10+ ''#13#10+ '<body>'#13#10+ HeaderX(BaseURL, FLang, Version)+ '<h1>'+s+'</h1>'#13#10); end; procedure THtmlPublisher.Heading(level: integer; text: String); begin FBuilder.Append('<h'+inttostr(level)+'>'); AddTextPlain(text); FBuilder.Append('</h'+inttostr(level)+'>'); end; procedure THtmlPublisher.hiddenInput(name, value: String); begin FBuilder.Append('<input type="hidden" name="'+name+'" value="'+value+'"/>'); end; procedure THtmlPublisher.Line; begin FBuilder.Append('<hr/>'#13#10); end; procedure THtmlPublisher.Memo(name, value, text: String); begin FBuilder.Append(text+'<textArea name="'+name+'">'#13#10+value+'</textArea>'); end; function THtmlPublisher.output: String; begin result := FBuilder.ToString; end; procedure THtmlPublisher.ParaURL(text, url: String); begin StartParagraph; self.URL(text, url); EndParagraph; end; procedure THtmlPublisher.Spacer; begin FBuilder.Append('&nbsp;'); end; procedure THtmlPublisher.StartBlockQuote; begin FBuilder.Append('<blockquote>'); end; procedure THtmlPublisher.startDiv; begin FBuilder.Append('<div>') end; procedure THtmlPublisher.StartForm(method, action: String); begin FBuilder.Append('<form method="'+method+'" action="'+action+'">'#13#10); end; procedure THtmlPublisher.StartList(ordered: boolean); begin if ordered then FBuilder.Append('<ol>') else FBuilder.Append('<ul>'); end; procedure THtmlPublisher.StartListItem; begin FBuilder.Append('<li>'); end; procedure THtmlPublisher.StartParagraph; begin FBuilder.Append('<p>'); end; procedure THtmlPublisher.StartPre; begin FBuilder.Append('<pre>'#13#10); end; procedure THtmlPublisher.StartRow(bgcolor : string = ''); begin if (bgcolor <> '') then FBuilder.Append('<tr style="background-color: '+bgcolor+'">') else FBuilder.Append('<tr>') end; procedure THtmlPublisher.StartTable(borders: boolean; clss : String); begin if clss <> '' then clss := ' class="'+clss+'"'; if borders then FBuilder.Append('<table border="1"'+clss+'>') else FBuilder.Append('<table border="0"'+clss+'>'); end; procedure THtmlPublisher.StartTableCell; begin if (span <> 1) then FBuilder.Append('<td colspan="'+inttostr(span)+'">') else FBuilder.Append('<td>') end; procedure THtmlPublisher.StartTableRow; begin FBuilder.Append('<tr>') end; procedure THtmlPublisher.Submit(name: String); begin FBuilder.Append('<input type="submit" value="'+name+'"/>'); end; procedure THtmlPublisher.TextInput(name, value: String; length: integer); begin FBuilder.Append('<input type="text" name="'+name+'" value="'+value+'" size="'+inttostr(length)+'"/>'); end; procedure THtmlPublisher.TextInput(name: String; length: integer); begin FBuilder.Append('<input type="text" name="'+name+'" size="'+inttostr(length)+'"/>'); end; procedure THtmlPublisher.URL(text, url, hint: String); begin if (hint <> '') then FBuilder.Append('<a href="'+url+'" title="'+FormatTextToXml(hint, xmlAttribute)+'">') else FBuilder.Append('<a href="'+url+'">'); AddTextPlain(text); FBuilder.Append('</a>'); end; procedure THtmlPublisher.writeXhtml(node: TFhirXHtmlNode); var i : integer; begin case node.NodeType of fhntElement, fhntDocument: begin FBuilder.Append('<'+node.Name); if node.HasAttributes then for i := 0 to node.Attributes.Count - 1 do FBuilder.Append(' '+node.Attributes[i].Name+'="'+FormatTextToXml(node.Attributes[i].value, xmlAttribute)+'"'); if node.ChildNodes.Count = 0 then FBuilder.Append('/>') else begin FBuilder.Append('>'); for i := 0 to node.ChildNodes.Count - 1 do writeXhtml(node.ChildNodes[i]); FBuilder.Append('</'+node.Name+'>'); end; end; fhntText: AddTextPlain(node.Content); fhntComment: FBuilder.Append('<!-- '+FormatTextToXml(node.Content, xmlText)+' -->'); end; end; procedure THtmlPublisher.TextInput(name, value, text: String; length: integer); begin FBuilder.Append('<input type="text" name="'+name+'" value="'+value+'" size="'+inttostr(length)+'"/> '+text); end; end.
32.104167
287
0.626055
f1f3829401db5e0fe9bb2ce477679d99146a1989
28,382
pas
Pascal
Delphi/ThirdParty/JCL/JclSecurity.pas
atkins126/ets-ddui
842e2238a9f64cf69b9eed57c11ad05488a9f444
[ "MIT" ]
132
2015-02-02T00:22:40.000Z
2021-08-11T12:08:08.000Z
Delphi/ThirdParty/JCL/JclSecurity.pas
atkins126/ets-ddui
842e2238a9f64cf69b9eed57c11ad05488a9f444
[ "MIT" ]
113
2015-03-20T01:55:20.000Z
2021-10-08T16:15:28.000Z
Delphi/ThirdParty/JCL/JclSecurity.pas
atkins126/ets-ddui
842e2238a9f64cf69b9eed57c11ad05488a9f444
[ "MIT" ]
49
2015-04-11T14:59:43.000Z
2021-03-30T10:29:18.000Z
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); } { you may not use this file except in compliance with the License. You may obtain a copy of the } { License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is JclSecurity.pas. } { } { The Initial Developer of the Original Code is Marcel van Brakel. } { Portions created by Marcel van Brakel are Copyright (C) Marcel van Brakel. All Rights Reserved. } { } { Contributor(s): } { Marcel van Brakel } { Peter Friese } { Robert Marquardt (marquardt) } { John C Molyneux } { Robert Rossmair (rrossmair) } { Matthias Thoma (mthoma) } { Petr Vones (pvones) } { Christoph Lindeman } { } {**************************************************************************************************} { } { Various NT security related routines to perform commen asks such as enabling and disabling } { privileges. } { } {**************************************************************************************************} { } { Last modified: $Date:: $ } { Revision: $Rev:: $ } { Author: $Author:: $ } { } {**************************************************************************************************} unit JclSecurity; {$I jcl.inc} {$I windowsonly.inc} {$HPPEMIT '#define TTokenInformationClass TOKEN_INFORMATION_CLASS'} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} {$IFDEF HAS_UNITSCOPE} Winapi.Windows, System.SysUtils, {$ELSE ~HAS_UNITSCOPE} Windows, SysUtils, {$ENDIF ~HAS_UNITSCOPE} JclBase; type EJclSecurityError = class(EJclError); // Access Control function CreateNullDacl(out Sa: TSecurityAttributes; const Inheritable: Boolean): PSecurityAttributes; function CreateInheritable(out Sa: TSecurityAttributes): PSecurityAttributes; // Privileges function IsGroupMember(RelativeGroupID: DWORD): Boolean; function IsAdministrator: Boolean; function IsUser: Boolean; function IsGuest: Boolean; function IsPowerUser: Boolean; function IsAccountOperator: Boolean; function IsSystemOperator: Boolean; function IsPrintOperator: Boolean; function IsBackupOperator: Boolean; function IsReplicator: Boolean; function IsRASServer: Boolean; function IsPreWin2000CompAccess: Boolean; function IsRemoteDesktopUser: Boolean; function IsNetworkConfigurationOperator: Boolean; function IsIncomingForestTrustBuilder: Boolean; function IsMonitoringUser: Boolean; function IsLoggingUser: Boolean; function IsAuthorizationAccess: Boolean; function IsTSLicenseServer: Boolean; function EnableProcessPrivilege(const Enable: Boolean; const Privilege: string): Boolean; function EnableThreadPrivilege(const Enable: Boolean; const Privilege: string): Boolean; function IsPrivilegeEnabled(const Privilege: string): Boolean; function GetPrivilegeDisplayName(const PrivilegeName: string): string; function SetUserObjectFullAccess(hUserObject: THandle): Boolean; function GetUserObjectName(hUserObject: THandle): string; // Account Information procedure LookupAccountBySid(Sid: PSID; out Name, Domain: AnsiString; Silent: Boolean = False); overload; procedure LookupAccountBySid(Sid: PSID; out Name, Domain: WideString; Silent: Boolean = False); overload; procedure QueryTokenInformation(Token: THandle; InformationClass: TTokenInformationClass; var Buffer: Pointer); procedure FreeTokenInformation(var Buffer: Pointer); function GetInteractiveUserName: string; // SID utilities function SIDToString(ASID: PSID): string; procedure StringToSID(const SIDString: String; SID: PSID; cbSID: DWORD); // Computer Information function GetComputerSID(SID: PSID; cbSID: DWORD): Boolean; // Windows Vista/Server 2008 UAC (User Account Control) function IsUACEnabled: Boolean; function IsElevated: Boolean; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL$'; Revision: '$Revision$'; Date: '$Date$'; LogPath: 'JCL\source\windows'; Extra: ''; Data: nil ); {$ENDIF UNITVERSIONING} implementation uses {$IFDEF HAS_UNITSCOPE} System.Classes, {$IFDEF BORLAND} Winapi.AccCtrl, {$ENDIF BORLAND} {$ELSE ~HAS_UNITSCOPE} Classes, {$IFDEF BORLAND} AccCtrl, {$ENDIF BORLAND} {$ENDIF ~HAS_UNITSCOPE} JclRegistry, JclResources, JclStrings, JclSysInfo, JclWin32; //=== Access Control ========================================================= function CreateNullDacl(out Sa: TSecurityAttributes; const Inheritable: Boolean): PSecurityAttributes; begin if IsWinNT then begin Sa.lpSecurityDescriptor := AllocMem(SizeOf(TSecurityDescriptor)); try Sa.nLength := SizeOf(Sa); Sa.bInheritHandle := Inheritable; Win32Check(InitializeSecurityDescriptor(Sa.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION)); Win32Check(SetSecurityDescriptorDacl(Sa.lpSecurityDescriptor, True, nil, False)); Result := @Sa; except FreeMem(Sa.lpSecurityDescriptor); Sa.lpSecurityDescriptor := nil; raise; end; end else begin Sa.lpSecurityDescriptor := nil; Result := nil; end; end; function CreateInheritable(out Sa: TSecurityAttributes): PSecurityAttributes; begin Sa.nLength := SizeOf(Sa); Sa.lpSecurityDescriptor := nil; Sa.bInheritHandle := True; if IsWinNT then Result := @Sa else Result := nil; end; //=== Privileges ============================================================= function IsGroupMember(RelativeGroupID: DWORD): Boolean; var psidAdmin: Pointer; Token: THandle; Count: DWORD; TokenInfo: PTokenGroups; HaveToken: Boolean; I: Integer; const SE_GROUP_USE_FOR_DENY_ONLY = $00000010; begin Result := not IsWinNT; if Result then // Win9x and ME don't have user groups Exit; psidAdmin := nil; TokenInfo := nil; HaveToken := False; try Token := 0; HaveToken := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, Token); if (not HaveToken) and (GetLastError = ERROR_NO_TOKEN) then HaveToken := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token); if HaveToken then begin {$IFDEF FPC} Win32Check(AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, RelativeGroupID, 0, 0, 0, 0, 0, 0, psidAdmin)); if GetTokenInformation(Token, TokenGroups, nil, 0, @Count) or (GetLastError <> ERROR_INSUFFICIENT_BUFFER) then RaiseLastOSError; TokenInfo := PTokenGroups(AllocMem(Count)); Win32Check(GetTokenInformation(Token, TokenGroups, TokenInfo, Count, @Count)); {$ELSE FPC} Win32Check(AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, RelativeGroupID, 0, 0, 0, 0, 0, 0, psidAdmin)); if GetTokenInformation(Token, TokenGroups, nil, 0, Count) or (GetLastError <> ERROR_INSUFFICIENT_BUFFER) then RaiseLastOSError; TokenInfo := PTokenGroups(AllocMem(Count)); Win32Check(GetTokenInformation(Token, TokenGroups, TokenInfo, Count, Count)); {$ENDIF FPC} for I := 0 to TokenInfo^.GroupCount - 1 do begin {$RANGECHECKS OFF} // Groups is an array [0..0] of TSIDAndAttributes, ignore ERangeError Result := EqualSid(psidAdmin, TokenInfo^.Groups[I].Sid); if Result then begin //consider denied ACE with Administrator SID Result := TokenInfo^.Groups[I].Attributes and SE_GROUP_USE_FOR_DENY_ONLY <> SE_GROUP_USE_FOR_DENY_ONLY; Break; end; {$IFDEF RANGECHECKS_ON} {$RANGECHECKS ON} {$ENDIF RANGECHECKS_ON} end; end; finally if TokenInfo <> nil then FreeMem(TokenInfo); if HaveToken then CloseHandle(Token); if psidAdmin <> nil then FreeSid(psidAdmin); end; end; function IsAdministrator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_ADMINS); end; function IsUser: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_USERS); end; function IsGuest: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_GUESTS); end; function IsPowerUser: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_POWER_USERS); end; function IsAccountOperator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_ACCOUNT_OPS); end; function IsSystemOperator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_SYSTEM_OPS); end; function IsPrintOperator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_PRINT_OPS); end; function IsBackupOperator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_BACKUP_OPS); end; function IsReplicator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_REPLICATOR); end; function IsRASServer: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_RAS_SERVERS); end; function IsPreWin2000CompAccess: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_PREW2KCOMPACCESS); end; function IsRemoteDesktopUser: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS); end; function IsNetworkConfigurationOperator: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS); end; function IsIncomingForestTrustBuilder: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS); end; function IsMonitoringUser: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_MONITORING_USERS); end; function IsLoggingUser: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_LOGGING_USERS); end; function IsAuthorizationAccess: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS); end; function IsTSLicenseServer: Boolean; begin Result := IsGroupMember(DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS); end; function EnableProcessPrivilege(const Enable: Boolean; const Privilege: string): Boolean; const PrivAttrs: array [Boolean] of DWORD = (0, SE_PRIVILEGE_ENABLED); var Token: THandle; TokenPriv: TTokenPrivileges; begin Result := not IsWinNT; if Result then // if Win9x, then function return True Exit; Token := 0; if OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, Token) then begin TokenPriv.PrivilegeCount := 1; LookupPrivilegeValue(nil, PChar(Privilege), TokenPriv.Privileges[0].Luid); TokenPriv.Privileges[0].Attributes := PrivAttrs[Enable]; JclWin32.AdjustTokenPrivileges(Token, False, TokenPriv, SizeOf(TokenPriv), nil, nil); Result := GetLastError = ERROR_SUCCESS; CloseHandle(Token); end; end; function EnableThreadPrivilege(const Enable: Boolean; const Privilege: string): Boolean; const PrivAttrs: array [Boolean] of DWORD = (0, SE_PRIVILEGE_ENABLED); var Token: THandle; TokenPriv: TTokenPrivileges; HaveToken: Boolean; begin Result := not IsWinNT; if Result then // Win9x/ME Exit; Token := 0; HaveToken := OpenThreadToken(GetCurrentThread, TOKEN_ADJUST_PRIVILEGES, False, Token); if (not HaveToken) and (GetLastError = ERROR_NO_TOKEN) then HaveToken := OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, Token); if HaveToken then begin TokenPriv.PrivilegeCount := 1; LookupPrivilegeValue(nil, PChar(Privilege), TokenPriv.Privileges[0].Luid); TokenPriv.Privileges[0].Attributes := PrivAttrs[Enable]; JclWin32.AdjustTokenPrivileges(Token, False, TokenPriv, SizeOf(TokenPriv), nil, nil); Result := GetLastError = ERROR_SUCCESS; CloseHandle(Token); end; end; function IsPrivilegeEnabled(const Privilege: string): Boolean; var Token: THandle; TokenPriv: TPrivilegeSet; Res: LongBool; HaveToken: Boolean; begin Result := not IsWinNT; if Result then // Win9x/ME Exit; Token := 0; HaveToken := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, False, Token); if (not HaveToken) and (GetLastError = ERROR_NO_TOKEN) then HaveToken := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token); if HaveToken then begin TokenPriv.PrivilegeCount := 1; TokenPriv.Control := 0; LookupPrivilegeValue(nil, PChar(Privilege), TokenPriv.Privilege[0].Luid); Res := False; Result := PrivilegeCheck(Token, TokenPriv, Res) and Res; CloseHandle(Token); end; end; function GetPrivilegeDisplayName(const PrivilegeName: string): string; var Count: DWORD; LangID: DWORD; begin if IsWinNT then begin Count := 0; LangID := LANG_USER_DEFAULT; // have the the API function determine the required string length Result := ''; if not LookupPrivilegeDisplayName(nil, PChar(PrivilegeName), PChar(Result), Count, LangID) then Count := 256; SetLength(Result, Count + 1); if LookupPrivilegeDisplayName(nil, PChar(PrivilegeName), PChar(Result), Count, LangID) then StrResetLength(Result) else Result := ''; end else Result := ''; // Win9x/ME end; function SetUserObjectFullAccess(hUserObject: THandle): Boolean; var Sd: PSecurity_Descriptor; Si: Security_Information; begin Result := not IsWinNT; if Result then // Win9x/ME Exit; { TODO : Check the success of called functions } Sd := PSecurity_Descriptor(LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH)); InitializeSecurityDescriptor(Sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(Sd, True, nil, False); Si := DACL_SECURITY_INFORMATION; Result := SetUserObjectSecurity(hUserObject, Si, Sd); LocalFree(HLOCAL(Sd)); end; function GetUserObjectName(hUserObject: THandle): string; var Count: DWORD; begin if IsWinNT then begin // have the API function determine the required string length Count := 0; Result := ''; GetUserObjectInformation(hUserObject, UOI_NAME, PChar(Result), 0, Count); SetLength(Result, Count + 1); if GetUserObjectInformation(hUserObject, UOI_NAME, PChar(Result), Count, Count) then StrResetLength(Result) else Result := ''; end else Result := ''; end; //=== Account Information ==================================================== procedure LookupAccountBySid(Sid: PSID; out Name, Domain: AnsiString; Silent: Boolean); var NameSize, DomainSize: DWORD; Use: SID_NAME_USE; Success: Boolean; begin if IsWinNT then begin NameSize := 0; DomainSize := 0; Use := SidTypeUnknown; LookupAccountSidA(nil, Sid, nil, NameSize, nil, DomainSize, Use); if NameSize > 0 then SetLength(Name, NameSize - 1); if DomainSize > 0 then SetLength(Domain, DomainSize - 1); Success := LookupAccountSidA(nil, Sid, PAnsiChar(Name), NameSize, PAnsiChar(Domain), DomainSize, Use); if Silent and not Success then begin Name := AnsiString(SIDToString(Sid)); Domain := ''; end else Win32Check(Success); end else begin // if Win9x, then function return '' Name := ''; Domain := ''; end; end; procedure LookupAccountBySid(Sid: PSID; out Name, Domain: WideString; Silent: Boolean); var NameSize, DomainSize: DWORD; Use: SID_NAME_USE; Success: Boolean; begin if IsWinNT then begin NameSize := 0; DomainSize := 0; Use := SidTypeUnknown; LookupAccountSidW(nil, Sid, nil, NameSize, nil, DomainSize, Use); if NameSize > 0 then SetLength(Name, NameSize - 1); if DomainSize > 0 then SetLength(Domain, DomainSize - 1); Success := LookupAccountSidW(nil, Sid, PWideChar(Name), NameSize, PWideChar(Domain), DomainSize, Use); if Silent and not Success then begin Name := WideString(SIDToString(Sid)); Domain := ''; end else Win32Check(Success); end else begin Name := ''; Domain := ''; end; end; procedure QueryTokenInformation(Token: THandle; InformationClass: TTokenInformationClass; var Buffer: Pointer); var Ret: BOOL; Length, LastError: DWORD; begin Buffer := nil; if not IsWinNT then // Win9x/ME Exit; Length := 0; {$IFDEF FPC} Ret := GetTokenInformation(Token, InformationClass, Buffer, Length, @Length); {$ELSE ~FPC} Ret := GetTokenInformation(Token, InformationClass, Buffer, Length, Length); {$ENDIF ~FPC} if (not Ret) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then begin GetMem(Buffer, Length); {$IFDEF FPC} Ret := GetTokenInformation(Token, InformationClass, Buffer, Length, @Length); {$ELSE ~FPC} Ret := GetTokenInformation(Token, InformationClass, Buffer, Length, Length); {$ENDIF ~FPC} if not Ret then begin LastError := GetLastError; FreeTokenInformation(Buffer); SetLastError(LastError); end; end; end; procedure FreeTokenInformation(var Buffer: Pointer); begin if Buffer <> nil then FreeMem(Buffer); Buffer := nil; end; function GetInteractiveUserName: string; var Handle: THandle; Token: THandle; User: PTokenUser; {$IFDEF SUPPORTS_UNICODE} Name, Domain: WideString; {$ELSE ~SUPPORTS_UNICODE} Name, Domain: AnsiString; {$ENDIF ~SUPPORTS_UNICODE} begin Result := ''; if not IsWinNT then // if Win9x, then function return '' Exit; Handle := GetShellProcessHandle; try Token := 0; Win32Check(OpenProcessToken(Handle, TOKEN_QUERY, Token)); try User := nil; QueryTokenInformation(Token, TokenUser, Pointer(User)); try LookupAccountBySid(User.User.Sid, Name, Domain); Result := Domain + '\' + Name; finally FreeMem(User); end; finally CloseHandle(Token); end; finally CloseHandle(Handle); end; end; //=== SID utilities ========================================================== function SIDToString(ASID: PSID): string; var SidIdAuthority: PSIDIdentifierAuthority; SubAuthorities, SidRev, SidSize: DWORD; Counter: Integer; begin SidRev := SID_REVISION; // Validate the binary SID. if not IsValidSid(ASid) then Raise EJclSecurityError.CreateRes(@RsInvalidSID); // Get the identifier authority value from the SID. SidIdAuthority := GetSidIdentifierAuthority(ASid); // Get the number of subauthorities in the SID. SubAuthorities := GetSidSubAuthorityCount(ASid)^; //Compute the buffer length. // S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL SidSize := (15 + 12 + (12 * SubAuthorities) + 1) * SizeOf(CHAR); SetLength(Result, SidSize+1); // Add 'S' prefix and revision number to the string. Result := Format('S-%u-',[SidRev]); // Add SID identifier authority to the string. if (SidIdAuthority^.Value[0] <> 0) or (SidIdAuthority^.Value[1] <> 0) then Result := Result + AnsiLowerCase(Format('0x%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x', [USHORT(SidIdAuthority^.Value[0]), USHORT(SidIdAuthority^.Value[1]), USHORT(SidIdAuthority^.Value[2]), USHORT(SidIdAuthority^.Value[3]), USHORT(SidIdAuthority^.Value[4]), USHORT(SidIdAuthority^.Value[5])])) else Result := Result + Format('%u', [ULONG(SidIdAuthority^.Value[5])+ ULONG(SidIdAuthority^.Value[4] shl 8)+ ULONG(SidIdAuthority^.Value[3] shl 16)+ ULONG(SidIdAuthority^.Value[2] shl 24)]); // Add SID subauthorities to the string. for Counter := 0 to SubAuthorities-1 do Result := Result + Format('-%u',[GetSidSubAuthority(ASid, Counter)^]); end; procedure StringToSID(const SIDString: String; SID: PSID; cbSID: DWORD); var {$IFDEF FPC} ASID: PSID; {$ELSE} ASID : ^_SID; {$ENDIF} CurrentPos, TempPos: Integer; AuthorityValue, RequiredSize: DWORD; Authority: string; begin if (Length (SIDString) <= 3) or (SIDString [1] <> 'S') or (SIDString [2] <> '-') then raise EJclSecurityError.CreateRes(@RsInvalidSID); RequiredSize := SizeOf(_SID) - SizeOf(DWORD); // _SID.Revision + _SID.SubAuthorityCount + _SID.IdentifierAuthority if cbSID < RequiredSize then raise EJclSecurityError.CreateRes(@RsSIDBufferTooSmall); ASID := SID; // typecast from opaque structure CurrentPos := StrFind('-', SIDString, 3); if CurrentPos <= 0 then raise EJclSecurityError.CreateRes(@RsInvalidSID); ASID^.Revision := StrToInt(Copy(SIDString, 3, CurrentPos - 3)); Inc(CurrentPos); TempPos := StrFind('-', SIDString, CurrentPos); if TempPos = 0 then Authority := Copy(SIDString, CurrentPos, Length(SIDString) - CurrentPos + 1) else Authority := Copy(SIDString, CurrentPos, TempPos - CurrentPos); if Length(Authority) < 1 then raise EJclSecurityError.CreateRes(@RsInvalidSID); if (Length(Authority) = 14) and (Authority[1] = '0') and (Authority[2] = 'x') then begin ASID^.IdentifierAuthority.Value[0] := StrToInt(HexPrefix + Authority[3] + Authority[4]); ASID^.IdentifierAuthority.Value[1] := StrToInt(HexPrefix + Authority[5] + Authority[6]); ASID^.IdentifierAuthority.Value[2] := StrToInt(HexPrefix + Authority[7] + Authority[8]); ASID^.IdentifierAuthority.Value[3] := StrToInt(HexPrefix + Authority[9] + Authority[10]); ASID^.IdentifierAuthority.Value[4] := StrToInt(HexPrefix + Authority[11] + Authority[12]); ASID^.IdentifierAuthority.Value[5] := StrToInt(HexPrefix + Authority[13] + Authority[14]); end else begin ASID^.IdentifierAuthority.Value[0] := 0; ASID^.IdentifierAuthority.Value[1] := 0; AuthorityValue := StrToInt(Authority); ASID^.IdentifierAuthority.Value[2] := (AuthorityValue and $FF000000) shr 24; ASID^.IdentifierAuthority.Value[3] := (AuthorityValue and $00FF0000) shr 16; ASID^.IdentifierAuthority.Value[4] := (AuthorityValue and $0000FF00) shr 8; ASID^.IdentifierAuthority.Value[5] := AuthorityValue and $000000FF; end; CurrentPos := TempPos + 1; ASID^.SubAuthorityCount := 0; while CurrentPos > 1 do begin TempPos := StrFind('-', SIDString, CurrentPos); Inc(RequiredSize, SizeOf(DWORD)); // _SID.SubAuthority[x] if cbSID < RequiredSize then raise EJclSecurityError.CreateRes(@RsSIDBufferTooSmall); if TempPos = 0 then Authority := Copy(SIDString, CurrentPos, Length(SIDString) - CurrentPos + 1) else Authority := Copy(SIDString, CurrentPos, TempPos - CurrentPos); {$RANGECHECKS OFF} ASID^.SubAuthority[ASID^.SubAuthorityCount] := StrToInt64(Authority); {$IFDEF RANGECHECKS_ON} {$RANGECHECKS ON} {$ENDIF RANGECHECKS_ON} Inc(ASID^.SubAuthorityCount); CurrentPos := TempPos + 1; end; end; //=== Computer Information =================================================== function LsaNTCheck(NTResult: Cardinal) : Cardinal; var WinError: Cardinal; begin Result := NTResult; if ($C0000000 and Cardinal(NTResult)) = $C0000000 then begin WinError := LsaNtStatusToWinError(NTResult); if WinError <> ERROR_SUCCESS then raise EJclSecurityError.CreateResFmt(@RsLsaError, [NTResult, SysErrorMessage(WinError)]); end; end; function GetComputerSID(SID: PSID; cbSID: DWORD): Boolean; var ObjectAttributes: TLsaObjectAttributes; PolicyHandle: TLsaHandle; Info: PPolicyAccountDomainInfo; begin if IsWinNT then begin ZeroMemory(@ObjectAttributes,SizeOf(ObjectAttributes)); {$IFDEF FPC} PolicyHandle := 0; {$ENDIF FPC} LsaNTCheck(LsaOpenPolicy(nil, // Use local system ObjectAttributes, //Object attributes. POLICY_VIEW_LOCAL_INFORMATION, // We're just looking PolicyHandle)); //Receives the policy handle. try Info := nil; LsaNTCheck(LsaQueryInformationPolicy(PolicyHandle, PolicyAccountDomainInformation, Pointer(Info))); try Result := CopySid(cbSID,SID,Info^.DomainSid); finally LsaFreeMemory(Info); end; finally LsaClose(PolicyHandle); end; end else Result := False; // Win9x end; //=== Windows Vista/Server 2008 UAC (User Account Control) =================== function IsUACEnabled: Boolean; begin Result := JclCheckWinVersion(6, 0) and RegReadBoolDef(HKLM, '\Software\Microsoft\Windows\CurrentVersion\Policies\System', 'EnableLUA', False); end; // source: Vista elevator from the Code Project function IsElevated: Boolean; const TokenElevation = TTokenInformationClass(20); type TOKEN_ELEVATION = record TokenIsElevated: DWORD; end; var TokenHandle: THandle; ResultLength: Cardinal; ATokenElevation: TOKEN_ELEVATION; begin if JclCheckWinVersion(6, 0) then begin TokenHandle := 0; if OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle) then begin try ResultLength := 0; if GetTokenInformation(TokenHandle, TokenElevation, @ATokenElevation, SizeOf(ATokenElevation), ResultLength) then Result := ATokenElevation.TokenIsElevated <> 0 else Result := False; finally CloseHandle(TokenHandle); end; end else Result := False; end else Result := IsAdministrator; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
33.46934
122
0.616341
836ebebc13bdc05afa4b4cf89887d18605dbf0b4
4,054
dfm
Pascal
windows/src/ext/jedi/jvcl/jvcl/examples/JvBackground/MDIForm/MDIBkgndDemoSettings.dfm
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/jvcl/examples/JvBackground/MDIForm/MDIBkgndDemoSettings.dfm
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/jvcl/examples/JvBackground/MDIForm/MDIBkgndDemoSettings.dfm
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
object BkgndImageSettings: TBkgndImageSettings Left = 485 Top = 265 ClientWidth = 283 ClientHeight = 228 Caption = 'Background Image Properties' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] FormStyle = fsMDIChild OldCreateOrder = True Position = poDefaultPosOnly Visible = True OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 16 Top = 42 Width = 21 Height = 13 Caption = '&Shift' FocusControl = ScrollBar1 end object Label2: TLabel Left = 16 Top = 10 Width = 27 Height = 13 Caption = '&Mode' FocusControl = Mode end object ScrollBar1: TScrollBar Left = 56 Top = 42 Width = 213 Height = 13 LargeChange = 8 Max = 200 PageSize = 0 TabOrder = 2 OnChange = ScrollBar1Change end object ShiftMode: TRadioGroup Left = 8 Top = 64 Width = 113 Height = 69 Caption = 'ShiftMode' ItemIndex = 1 Items.Strings = ( 'sm&Rows' 'sm&Columns') TabOrder = 3 OnClick = ShiftModeClick end object Mode: TComboBox Left = 56 Top = 8 Width = 93 Height = 21 Style = csDropDownList ItemHeight = 13 TabOrder = 0 OnChange = ModeChange Items.Strings = ( 'bmTile' 'bmCenter' 'bmTopLeft' 'bmTop' 'bmTopRight' 'bmLeft' 'bmBottomLeft' 'bmRight' 'bmBottom' 'bmBottomRight' 'bmStretch') end object TranspColor: TButton Left = 156 Top = 8 Width = 113 Height = 25 Caption = 'TransparentCo&lor...' TabOrder = 1 OnClick = TranspColorClick end object GroupBox1: TGroupBox Left = 128 Top = 64 Width = 145 Height = 69 Caption = 'Tile' TabOrder = 4 object Label3: TLabel Left = 16 Top = 16 Width = 28 Height = 13 Caption = '&Width' FocusControl = TileWidth end object Label4: TLabel Left = 16 Top = 44 Width = 31 Height = 13 Caption = '&Height' FocusControl = TileHeight end object TileWidth: TSpinEdit Left = 72 Top = 12 Width = 57 Height = 22 MaxValue = 1000 MinValue = 16 TabOrder = 0 Value = 16 OnChange = TileWidthChange end object TileHeight: TSpinEdit Left = 72 Top = 40 Width = 57 Height = 22 MaxValue = 1000 MinValue = 16 TabOrder = 1 Value = 16 OnChange = TileHeightChange end end object GroupBox2: TGroupBox Left = 8 Top = 134 Width = 265 Height = 83 TabOrder = 5 object ZigZag: TCheckBox Left = 152 Top = 56 Width = 89 Height = 17 Caption = '&ZigZag' Checked = True State = cbChecked TabOrder = 5 OnClick = ZigZagClick end object Transparent: TCheckBox Left = 12 Top = 56 Width = 89 Height = 17 Caption = '&Transparent' TabOrder = 2 OnClick = TransparentClick end object Enabled: TCheckBox Left = 12 Top = 16 Width = 89 Height = 17 Caption = '&Enabled' Checked = True State = cbChecked TabOrder = 0 OnClick = EnabledClick end object GrayMapped: TCheckBox Left = 12 Top = 36 Width = 130 Height = 17 Caption = '&GrayMapped' Enabled = False TabOrder = 1 OnClick = GrayMappedClick end object AutoSizeTile: TCheckBox Left = 152 Top = 36 Width = 97 Height = 17 Caption = '&AutoSizeTile' TabOrder = 4 OnClick = AutoSizeTileClick end object FitPictureSize: TCheckBox Left = 152 Top = 16 Width = 97 Height = 17 Caption = '&FitPictureSize' TabOrder = 3 OnClick = FitPictureSizeClick end end object ColorDialog: TColorDialog Ctl3D = True end end
19.584541
46
0.571041
f1fbcf8ce564d969be4180a710e7ebc4893a813f
5,994
pas
Pascal
Base/extra/IMixEx.pas
Cooler2/ApusGameEngine
6250348a4be29c7d1afff35c99e4e7eba9ce8c2c
[ "BSD-3-Clause" ]
124
2020-03-05T07:57:43.000Z
2022-03-28T07:59:26.000Z
Base/extra/IMixEx.pas
Cooler2/ApusGameEngine
6250348a4be29c7d1afff35c99e4e7eba9ce8c2c
[ "BSD-3-Clause" ]
null
null
null
Base/extra/IMixEx.pas
Cooler2/ApusGameEngine
6250348a4be29c7d1afff35c99e4e7eba9ce8c2c
[ "BSD-3-Clause" ]
20
2020-03-07T21:42:14.000Z
2022-03-31T00:33:25.000Z
// IMixerPro Sound System by Igor Lobanchikov: http://apus-software.com/imixer/ // Installer (dll + lib + documentation): http://apus-software.com/imixer/bin/IMixerPro.exe // Don't confuse IMix* (IMixer) and IMX* (IMixerPro) - they are different things. unit IMixEx; interface uses windows; type HSample=DWORD; HChannel=DWORD; HStream=DWORD; HMod=DWORD; HSYNC=DWORD; // Sync callback SyncProc=procedure(handle:HSync;channel:HChannel;data,user:DWORD); stdcall; PIMX3DVector=^IMX3DVECTOR; IMX3DVECTOR=record x,y,z:single; end; const IMX_OK = 0; // IMXInit flags IMX_INIT_8BIT = 1; IMX_INIT_MONO = 2; // IMXModulePlay flags IMX_MODULE_LOOP = 1; IMX_MODULE_POSRESET = 2; // IMXStreamPlay flags IMX_STREAM_LOOP = 1; IMX_STREAM_3D = 4; IMX_STREAM_FORCERIGHT = $10; IMX_STREAM_FORCELEFT = $20; IMX_STREAM_FORCEMONO = $30; // IMXSampleLoad flags IMX_SAMPLE_LOOP = 1; IMX_SAMPLE_3D = 4; // IMXSampleSet3DParameters // IMXChannelSet3DParameters IMX_3DMODE_NORMAL = 0; IMX_3DMODE_HEADRELATIVE = 1; IMX_3DMODE_DISABLE = 2; // IMXChannelSetSync type IMX_SYNC_END = 1; IMX_SYNC_POS = 2; IMX_SYNC_EVMASK = $0FFFFFF; IMX_SYNC_MIXTIME = $4000000; // 3D Algorythms IMX_3DALG_DEFAULT = 0; IMX_3DALG_OFF = 1; IMX_3DALG_FULL = 2; IMX_3DALG_LIGHT = 3; // Initialization done function IMXInit(hwnd:HWnd;freq,flags:DWORD;reserved:integer=-1):boolean; cdecl; external 'IMxEx.dll' delayed; function IMXUninit:longbool; cdecl; external 'IMxEx.dll' delayed; function IMXStart:longbool; cdecl; external 'IMxEx.dll' delayed; function IMXStop:longbool; cdecl; external 'IMxEx.dll' delayed; function IMXPause(Pause:longbool):longbool; cdecl; external 'IMxEx.dll' delayed; // Control mixer function IMXSetGlobalVolumes(modvol,smpvol,streamvol:integer):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXGetGlobalVolumes(var modvol,smpvol,streamvol:integer):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXSetBlockSize(sec:double):double; cdecl; external 'IMxEx.dll' delayed; function IMXGetVersion:cardinal; cdecl; external 'IMxEx.dll' delayed; // 3D functions function IMXCommit3D:longbool; cdecl; external 'IMxEx.dll' delayed; function IMXSetListnerPosition(Pos:PIMX3DVector=nil;vel:PIMX3DVector=nil; front:PIMX3DVector=nil;top:PIMX3DVector=nil):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXSetEnvironmentFactors(distance:single=-1;rolloff:single=-1;doppler:single=-1):longbool; cdecl; external 'IMxEx.dll' delayed; procedure IMXSet3DAlgorithm(Algorithm:cardinal=IMX_3DALG_DEFAULT); cdecl; external 'IMxEx.dll' delayed; // Sample function IMXSampleLoad(FromMem:longbool;FileName:PAnsiChar;Offset:DWORD=0; Length:DWord=0;res2:DWORD=0;Flags:DWORD=0):HSample; cdecl; external 'IMxEx.dll' delayed; function IMXSamplePlay(hsmp:HSAMPLE;vol:integer=100;pan:integer=0; freq:DWORD=0;start:DWORD=0):HChannel; cdecl; external 'IMxEx.dll' delayed; function IMXSamplePlay3D(hsmp:HSAMPLE;pos:PIMX3DVector=nil;orient:PIMX3DVector=nil; vel:PIMX3DVector=nil;vol:integer=100;freq:cardinal=0;start:cardinal=0):HChannel; cdecl; external 'IMxEx.dll' delayed; function IMXSampleSet3DParameters(hsmp:HSAMPLE;IAngle:integer=-1;OAngle:integer=-1;outVol:integer=-1; MinDist:single=-1;MaxDist:single=-1;Mode:integer=-1):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXSampleUnload(hsmp:HSample):longbool; cdecl; external 'IMxEx.dll' delayed; // Module function IMXModuleLoad(FromMem:longbool;FileName:PAnsiChar;Offset:DWORD=0; Length:DWORD=0;res2:DWORD=0):HMod; cdecl; external 'IMxEx.dll' delayed; function IMXModulePlay(hmod:HMod;flags:integer=-1):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXModuleUnload(hmod:HMod):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXModuleAttachInstruments(targethmod,sourcehmod:HMod):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXModuleAdjustBPM(hmod:HMod;bpm:double=1):longbool; cdecl; external 'IMxEx.dll' delayed; // Stream function IMXStreamOpenFile(fromMem:longbool;filename:PAnsiChar;offset:DWORD=0; length:DWORD=0;flags:DWORD=0):HStream; cdecl; external 'IMxEx.dll' delayed; function IMXStreamPlay(hstream:HStream;flags:integer=-1):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXStreamClose(hstream:HStream):longbool; cdecl; external 'IMxEx.dll' delayed; // Channel function IMXChannelStop(hchan:HChannel):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXChannelSetAttributes(hchan:HChannel;vol:integer=-1;pan:integer=-101; freq:integer=-1):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXChannelSetSync(hchan:HChannel;sType,param:DWORD;proc:SyncProc; User:DWORD):HSync; cdecl; external 'IMxEx.dll' delayed; function IMXChannelSlide(hchan:HChannel;vol:integer=-1;pan:integer=-101;freq:DWORD=0; time:integer=100):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXChannelSetPosition(hchan:HChannel;pos:DWORD):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXChannelRemoveSync(hchan:HChannel;sync:HSync):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXChannelSet3DParameters(hchan:HChannel;IAngle:integer=-1;OAngle:integer=-1; outVol:integer=-1;MinDist:single=-1;MaxDist:single=-1; Mode:integer=-1):longbool; cdecl; external 'IMxEx.dll' delayed; function IMXChannelSet3DPosition(hchan:HChannel;pos:PIMX3DVector=nil;orient:PIMX3DVector=nil; vel:PIMX3DVector=nil):longbool; cdecl; external 'IMxEx.dll' delayed; implementation end.
47.19685
138
0.716717
f1dbf66abbd3f830ffe1c76a961096ee7fdde632
1,463
dpr
Pascal
SimOptic.dpr
reymillenium/simoptic
0b0a5e51e178e3422c58d510d01dde7f549bf9b7
[ "FSFAP" ]
null
null
null
SimOptic.dpr
reymillenium/simoptic
0b0a5e51e178e3422c58d510d01dde7f549bf9b7
[ "FSFAP" ]
null
null
null
SimOptic.dpr
reymillenium/simoptic
0b0a5e51e178e3422c58d510d01dde7f549bf9b7
[ "FSFAP" ]
null
null
null
program SimOptic; uses UIApp in 'uiapp.pas', Forms, UfrmPrincipal in 'UfrmPrincipal.pas' {frmPrincipal}, UfrmAcercaDe in 'UfrmAcercaDe.pas' {frmAcercaDe}, UfrmPresentacion in 'UfrmPresentacion.pas' {frmPresentacion}, UPantalla in 'UPantalla.pas', UFicheroIdioma in 'UFicheroIdioma.pas', UFicheroAlineacionVisores in 'UFicheroAlineacionVisores.pas', UFicheroTipoVisores in 'UFicheroTipoVisores.pas', USimuladorOptico in 'USimuladorOptico.pas', UFicheroZoomImagen in 'UFicheroZoomImagen.pas', UFicheroComentarios in 'UFicheroComentarios.pas', UfrmPreviewReporteSimulacionImagenes in 'UfrmPreviewReporteSimulacionImagenes.pas' {frmPreviewReporteSimulacionImagenes}, UfrmQRReporteSimulacionImagenes in 'UfrmQRReporteSimulacionImagenes.pas' {QuickReportSimulacionImagenes: TQuickRep}, UfrmRegistro in 'UfrmRegistro.pas' {frmRegistro}; {$R *.res} begin Application.Initialize; Application.Title := 'SimOptic 2008'; Application.HelpFile := 'HelpFiles\HELP.HLP'; Application.CreateForm(TfrmPrincipal, frmPrincipal); Application.CreateForm(TfrmAcercaDe, frmAcercaDe); Application.CreateForm(TfrmPresentacion, frmPresentacion); Application.CreateForm(TfrmPreviewReporteSimulacionImagenes, frmPreviewReporteSimulacionImagenes); Application.CreateForm(TfrmRegistro, frmRegistro); Application.CreateForm(TQuickReportSimulacionImagenes, QuickReportSimulacionImagenes); Application.Run; end.
43.029412
124
0.802461
f1f163008e305c124376f11833b656db8d990f1b
1,781
dpr
Pascal
windows/src/test/unit-tests/ui-language-manager/UILanguageManagerTest.dpr
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/test/unit-tests/ui-language-manager/UILanguageManagerTest.dpr
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/test/unit-tests/ui-language-manager/UILanguageManagerTest.dpr
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
program UILanguageManagerTest; {$IFNDEF TESTINSIGHT} {$APPTYPE CONSOLE} {$ENDIF}{$STRONGLINKTYPES ON} uses System.SysUtils, {$IFDEF TESTINSIGHT} TestInsight.DUnitX, {$ENDIF } DUnitX.Loggers.Console, DUnitX.Loggers.Xml.NUnit, DUnitX.TestFramework, Keyman.System.UILanguageManager in '..\..\..\global\delphi\general\Keyman.System.UILanguageManager.pas', Keyman.System.Test.UILanguageManagerTest in 'Keyman.System.Test.UILanguageManagerTest.pas'; {$R *.res} var runner : ITestRunner; results : IRunResults; logger : ITestLogger; nunitLogger : ITestLogger; begin {$IFDEF TESTINSIGHT} TestInsight.DUnitX.RunRegisteredTests; exit; {$ENDIF} try //Check command line options, will exit if invalid TDUnitX.CheckCommandLine; //Create the test runner runner := TDUnitX.CreateRunner; //Tell the runner to use RTTI to find Fixtures runner.UseRTTI := True; //tell the runner how we will log things //Log to the console window logger := TDUnitXConsoleLogger.Create(true); runner.AddLogger(logger); //Generate an NUnit compatible XML File nunitLogger := TDUnitXXMLNUnitFileLogger.Create(TDUnitX.Options.XMLOutputFile); runner.AddLogger(nunitLogger); runner.FailsOnNoAsserts := False; //When true, Assertions must be made during tests; //Run tests results := runner.Execute; if not results.AllPassed then System.ExitCode := EXIT_ERRORS; {$IFNDEF CI} //We don't want this happening when running under CI. if TDUnitX.Options.ExitBehavior = TDUnitXExitBehavior.Pause then begin System.Write('Done.. press <Enter> key to quit.'); System.Readln; end; {$ENDIF} except on E: Exception do System.Writeln(E.ClassName, ': ', E.Message); end; end.
28.269841
106
0.71196
6ac1cf9735a609b27d51c6b2d42069bb5ea5c183
1,297
pas
Pascal
Capitulo8/3.2.ObjetosEListas/Client/ClientModuleUnit1.pas
diondcm/exemplos-delphi
16b4d195981e5f3161d0a2c62f778bec5ba9f3d4
[ "MIT" ]
10
2017-08-02T00:44:41.000Z
2021-10-13T21:11:28.000Z
Capitulo8/3.2.ObjetosEListas/Client/ClientModuleUnit1.pas
diondcm/exemplos-delphi
16b4d195981e5f3161d0a2c62f778bec5ba9f3d4
[ "MIT" ]
10
2019-12-30T04:09:37.000Z
2022-03-02T06:06:19.000Z
Capitulo8/3.2.ObjetosEListas/Client/ClientModuleUnit1.pas
diondcm/exemplos-delphi
16b4d195981e5f3161d0a2c62f778bec5ba9f3d4
[ "MIT" ]
9
2017-04-29T16:12:21.000Z
2020-11-11T22:16:32.000Z
unit ClientModuleUnit1; interface uses System.SysUtils, System.Classes, ClientClassesUnit1, Datasnap.DSClientRest; type TClientModule1 = class(TDataModule) DSRestConnection1: TDSRestConnection; private FInstanceOwner: Boolean; FServerMethodsGeralClient: TServerMethodsGeralClient; function GetServerMethodsGeralClient: TServerMethodsGeralClient; { Private declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property InstanceOwner: Boolean read FInstanceOwner write FInstanceOwner; property ServerMethodsGeralClient: TServerMethodsGeralClient read GetServerMethodsGeralClient write FServerMethodsGeralClient; end; var ClientModule1: TClientModule1; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} constructor TClientModule1.Create(AOwner: TComponent); begin inherited; FInstanceOwner := True; end; destructor TClientModule1.Destroy; begin FServerMethodsGeralClient.Free; inherited; end; function TClientModule1.GetServerMethodsGeralClient: TServerMethodsGeralClient; begin if FServerMethodsGeralClient = nil then FServerMethodsGeralClient:= TServerMethodsGeralClient.Create(DSRestConnection1, FInstanceOwner); Result := FServerMethodsGeralClient; end; end.
24.471698
130
0.813416
f1da42c5eb4017c3eec150530580b826a619995f
143
pas
Pascal
2021/DEC12/calculator.pas
PeteShepley/advent-of-code
a5dcd8fc93485617bde126a14d17cea8d112219b
[ "MIT" ]
null
null
null
2021/DEC12/calculator.pas
PeteShepley/advent-of-code
a5dcd8fc93485617bde126a14d17cea8d112219b
[ "MIT" ]
null
null
null
2021/DEC12/calculator.pas
PeteShepley/advent-of-code
a5dcd8fc93485617bde126a14d17cea8d112219b
[ "MIT" ]
null
null
null
unit Calculator; {$mode objfpc}{$H+} interface uses Classes, SysUtils; var a: Integer; implementation initialization a := 5; end.
7.15
20
0.678322
83f3376101df0ba26c7462b0552fdf65f1fc9334
5,801
pas
Pascal
Delphi/LibUser/MonitorFunc.pas
tdebaets/common
d94411a3cc1902f4bb3c788ca9ee66a2d9664708
[ "Apache-2.0" ]
4
2017-03-30T19:52:29.000Z
2022-02-10T04:20:52.000Z
Delphi/LibUser/MonitorFunc.pas
tdebaets/common
d94411a3cc1902f4bb3c788ca9ee66a2d9664708
[ "Apache-2.0" ]
null
null
null
Delphi/LibUser/MonitorFunc.pas
tdebaets/common
d94411a3cc1902f4bb3c788ca9ee66a2d9664708
[ "Apache-2.0" ]
3
2016-07-25T13:33:39.000Z
2018-12-27T05:17:50.000Z
(**************************************************************************** * * Copyright 2016 Tim De Baets * * 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. * **************************************************************************** * * Multi-monitor helper functions * ****************************************************************************) unit MonitorFunc; interface uses Windows, Classes, Math, MultiMon; function GetDisplayMonitors(Monitors: TList): Boolean; function GetDisplayWorkArea(hWnd: HWND): TRect; overload; function GetDisplayWorkArea(Pt: TPoint): TRect; overload; const MONITOR_CENTER = $0001; // center rect to monitor MONITOR_CLIP = $0000; // clip rect to monitor MONITOR_WORKAREA = $0002; // use monitor work area MONITOR_AREA = $0000; // use monitor entire area procedure ClipOrCenterRectToMonitor(var prc: TRect; flags: UINT); procedure ClipOrCenterWindowToMonitor(hwnd: HWND; flags: UINT); function CenterWindow(hwndChild, hwndParent: HWND): Boolean; implementation function MonitorEnumProc(hm: HMONITOR; dc: HDC; r: PRect; Monitors: TList): Boolean; stdcall; begin Result := True; if Assigned(Monitors) then Monitors.Add(Pointer(hm)); end; function GetDisplayMonitors(Monitors: TList): Boolean; begin Result := False; if not Assigned(Monitors) then Exit; Monitors.Clear; Result := EnumDisplayMonitors(0, nil, @MonitorEnumProc, Integer(Monitors)); end; function GetDisplayWorkArea(hWnd: HWND): TRect; var hMon: HMONITOR; mi: MONITORINFO; begin hMon := MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST); if hMon <> 0 then begin FillChar(mi, SizeOf(mi), 0); mi.cbSize := SizeOf(mi); if GetMonitorInfo(hMon, @mi) then Result := mi.rcWork; end; end; function GetDisplayWorkArea(Pt: TPoint): TRect; var hMon: HMONITOR; mi: MONITORINFO; begin hMon := MonitorFromPoint(Pt, MONITOR_DEFAULTTONEAREST); if hMon <> 0 then begin FillChar(mi, SizeOf(mi), 0); mi.cbSize := SizeOf(mi); if GetMonitorInfo(hMon, @mi) then Result := mi.rcWork; end; end; // // ClipOrCenterRectToMonitor // // The most common problem apps have when running on a // multimonitor system is that they "clip" or "pin" windows // based on the SM_CXSCREEN and SM_CYSCREEN system metrics. // Because of app compatibility reasons these system metrics // return the size of the primary monitor. // // This shows how you use the multi-monitor functions // to do the same thing. // procedure ClipOrCenterRectToMonitor(var prc: TRect; flags: UINT); var hMon: HMONITOR; mi: MONITORINFO; rc: TRect; w, h: Integer; begin w := prc.right - prc.left; h := prc.bottom - prc.top; // // get the nearest monitor to the passed rect. // hMon := MonitorFromRect(@prc, MONITOR_DEFAULTTONEAREST); // // get the work area or entire monitor rect. // mi.cbSize := SizeOf(mi); GetMonitorInfo(hMon, @mi); if flags and MONITOR_WORKAREA <> 0 then rc := mi.rcWork else rc := mi.rcMonitor; // // center or clip the passed rect to the monitor rect // if flags and MONITOR_CENTER <> 0 then begin prc.left := rc.left + (rc.right - rc.left - w) div 2; prc.top := rc.top + (rc.bottom - rc.top - h) div 2; prc.right := prc.left + w; prc.bottom := prc.top + h; end else begin prc.left := MaxIntValue([rc.left, MinIntValue([rc.right-w, prc.left])]); prc.top := MaxIntValue([rc.top, MinIntValue([rc.bottom-h, prc.top])]); prc.right := prc.left + w; prc.bottom := prc.top + h; end; end; procedure ClipOrCenterWindowToMonitor(hwnd: HWND; flags: UINT); var rc: TRect; begin GetWindowRect(hwnd, rc); ClipOrCenterRectToMonitor(rc, flags); SetWindowPos(hwnd, 0, rc.left, rc.top, 0, 0, SWP_NOSIZE or SWP_NOZORDER or SWP_NOACTIVATE); end; // Center with respect to another window. // Specifying NULL for hwndParent centers hwndChild relative to the // screen. function CenterWindow(hwndChild, hwndParent: HWND): Boolean; var rcChild, rcParent, rcScreen: TRect; cxChild, cyChild, cxParent, cyParent: Integer; xNew, yNew: Integer; begin // Get the Height and Width of the child window. GetWindowRect(hwndChild, rcChild); cxChild := rcChild.right - rcChild.left; cyChild := rcChild.bottom - rcChild.top; rcScreen := GetDisplayWorkArea(hWndChild); if hwndParent <> 0 then begin // Get the Height and Width of the parent window. GetWindowRect(hwndParent, rcParent); end else rcParent := rcScreen; cxParent := rcParent.right - rcParent.left; cyParent := rcParent.bottom - rcParent.top; // Calculate new X position, then adjust for screen. xNew := rcParent.left + ((cxParent - cxChild) div 2); if xNew < rcScreen.Left then xNew := rcScreen.Left else if (xNew + cxChild) > rcScreen.Right then xNew := rcScreen.Right - cxChild; // Calculate new Y position, then adjust for screen. yNew := rcParent.top + ((cyParent - cyChild) div 2); if yNew < rcScreen.Top then yNew := rcScreen.Top else if (yNew + cyChild) > rcScreen.Bottom then yNew := rcScreen.Bottom - cyChild; // Set it, and return. Result := SetWindowPos(hwndChild, 0, xNew, yNew, 0, 0, SWP_NOSIZE or SWP_NOZORDER); end; end.
28.717822
79
0.664196
f1e1ede044004c5d7d62ea17676830349b88726b
1,866
pas
Pascal
runtime/Pascal/Parse.Easy.Parser.State.pas
MahdiSafsafi/Parse-Easy
645cd2312cffeba30e9cbbb3b47e8482f26f1100
[ "Artistic-1.0-Perl" ]
16
2018-11-03T14:52:08.000Z
2021-09-19T10:05:09.000Z
runtime/Pascal/Parse.Easy.Parser.State.pas
MahdiSafsafi/Parse-Easy
645cd2312cffeba30e9cbbb3b47e8482f26f1100
[ "Artistic-1.0-Perl" ]
null
null
null
runtime/Pascal/Parse.Easy.Parser.State.pas
MahdiSafsafi/Parse-Easy
645cd2312cffeba30e9cbbb3b47e8482f26f1100
[ "Artistic-1.0-Perl" ]
1
2018-11-04T13:29:31.000Z
2018-11-04T13:29:31.000Z
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.Parser.State; interface uses System.Classes, System.SysUtils; type TState = class(TObject) private FIndex: Integer; FTerms: TList; FNoTerms: TList; FNumberOfTerms: Integer; FNumberOfNoTerms: Integer; procedure SetNumberOfNoTerms(const Value: Integer); procedure SetNumberOfTerms(const Value: Integer); public constructor Create; virtual; destructor Destroy; override; property Index: Integer read FIndex write FIndex; property NumberOfTerms: Integer read FNumberOfTerms write SetNumberOfTerms; property NumberOfNoTerms: Integer read FNumberOfNoTerms write SetNumberOfNoTerms; property Terms: TList read FTerms; property NoTerms: TList read FNoTerms; end; implementation { TState } constructor TState.Create; begin FNumberOfTerms := -1; FNumberOfNoTerms := -1; FTerms := TList.Create; FNoTerms := TList.Create; end; destructor TState.Destroy; var I: Integer; begin for I := 0 to FTerms.Count - 1 do if Assigned(FTerms[I]) then TObject(FTerms[I]).Free; for I := 0 to FNoTerms.Count - 1 do if Assigned(FNoTerms[I]) then TObject(FNoTerms[I]).Free; FTerms.Free; FNoTerms.Free; inherited; end; procedure TState.SetNumberOfNoTerms(const Value: Integer); var I: Integer; begin if (FNumberOfNoTerms <> Value) then begin FNumberOfNoTerms := Value; FNoTerms.Clear; for I := 0 to Value - 1 do FNoTerms.Add(nil); end; end; procedure TState.SetNumberOfTerms(const Value: Integer); var I: Integer; begin if (FNumberOfTerms <> Value) then begin FNumberOfTerms := Value; FTerms.Clear; for I := 0 to Value - 1 do FTerms.Add(nil); end; end; end.
20.966292
85
0.672562
f189b442dab930441e159c7f19a835a451e8bef8
46,093
pas
Pascal
hedgewars/uSound.pas
l29ah/hedgewars-cheats
111b6f926710db8bf40c53c5cb1ab875514aa24a
[ "Apache-2.0" ]
1
2020-05-22T13:49:27.000Z
2020-05-22T13:49:27.000Z
hedgewars/uSound.pas
l29ah/hedgewars-cheats
111b6f926710db8bf40c53c5cb1ab875514aa24a
[ "Apache-2.0" ]
null
null
null
hedgewars/uSound.pas
l29ah/hedgewars-cheats
111b6f926710db8bf40c53c5cb1ab875514aa24a
[ "Apache-2.0" ]
null
null
null
(* * Hedgewars, a free turn based strategy game * Copyright (c) 2004-2015 Andrey Korotaev <unC0Rr@gmail.com> * * 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; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *) {$INCLUDE "options.inc"} unit uSound; (* * This unit controls the sounds and music of the game. * Doesn't really do anything if isSoundEnabled = false and isMusicEnabled = false * * There are three basic types of sound controls: * Music - The background music of the game: * * will only be played if isMusicEnabled = true * * can be started, changed, paused and resumed * Sound - Can be started and stopped * Looped Sound - Subtype of sound: plays in a loop using a * "channel", of which the id is returned on start. * The channel id can be used to stop a specific sound loop. *) interface uses SDLh, uConsts, uTypes; procedure preInitModule; procedure initModule; procedure freeModule; procedure InitSound; // Initiates sound-system if isSoundEnabled. procedure ReleaseSound(complete: boolean); // Releases sound-system and used resources. procedure ResetSound; // Reset sound state to the previous state. procedure SetSound(enabled: boolean); // Enable/disable sound-system and backup status. procedure SetAudioDampen(enabled: boolean); // Enable/disable automatic dampening if losing window focus. // MUSIC // Obvious music commands for music track procedure SetMusic(enabled: boolean); // Enable/disable music. procedure SetMusicName(musicname: shortstring); // Set name of the file to play. procedure PlayMusic; // Play music from the start. procedure PauseMusic; // Pause music. procedure ResumeMusic; // Resume music from pause point. procedure ChangeMusic(musicname: shortstring); // Replaces music track with musicname and plays it. procedure StopMusic; // Stops and releases the current track. // SOUNDS // Plays the sound snd [from a given voicepack], // if keepPlaying is given and true, // then the sound's playback won't be interrupted if asked to play again. // Returns true if sound was found and is played, false otherwise. function PlaySound(snd: TSound): boolean; function PlaySound(snd: TSound; keepPlaying: boolean): boolean; function PlaySound(snd: TSound; keepPlaying: boolean; ignoreMask: boolean): boolean; function PlaySound(snd: TSound; keepPlaying, ignoreMask, soundAsMusic: boolean): boolean; function PlaySoundV(snd: TSound; voicepack: PVoicepack): boolean; function PlaySoundV(snd: TSound; voicepack: PVoicepack; keepPlaying: boolean): boolean; function PlaySoundV(snd: TSound; voicepack: PVoicepack; keepPlaying, ignoreMask: boolean): boolean; function PlaySoundV(snd: TSound; voicepack: PVoicepack; keepPlaying, ignoreMask, soundAsMusic: boolean): boolean; // Plays/stops a sound to replace the main background music temporarily. procedure PlayMusicSound(snd: TSound); procedure StopMusicSound(snd: TSound); // Plays sound snd [of voicepack] in a loop, but starts with fadems milliseconds of fade-in. // Returns sound channel of the looped sound. function LoopSound(snd: TSound): LongInt; function LoopSound(snd: TSound; fadems: LongInt): LongInt; function LoopSoundV(snd: TSound; voicepack: PVoicepack): LongInt; function LoopSoundV(snd: TSound; voicepack: PVoicepack; fadems: LongInt): LongInt; // Stops the normal/looped sound of the given type/in the given channel // [with a fade-out effect for fadems milliseconds]. procedure StopSound(snd: TSound); procedure StopSound(snd: TSound; soundAsMusic: boolean); procedure StopSoundChan(chn: LongInt); procedure StopSoundChan(chn, fadems: LongInt); // Add voice to the voice queue procedure AddVoice(snd: TSound; voicepack: PVoicepack); procedure AddVoice(snd: TSound; voicepack: PVoicepack; ignoreMask, isFallback: boolean); // Actually play next voice procedure PlayNextVoice; // GLOBAL FUNCTIONS // Drastically lower the volume when we lose focus (and restore the previous value). procedure DampenAudio; procedure UndampenAudio; // Mute/Unmute audio procedure MuteAudio; // MISC // Set the initial volume procedure SetVolume(vol: LongInt); // Modifies the sound volume of the game by voldelta and returns the new volume level. function ChangeVolume(voldelta: LongInt): LongInt; // Returns the current volume in percent. Intended for display on UI. function GetVolumePercent(): LongInt; // Returns a pointer to the voicepack with the given name. function AskForVoicepack(name: shortstring): Pointer; var MusicFN: shortstring; // music file name SDMusicFN: shortstring; // SD music file name FallbackMusicFN: shortstring; // fallback music file name FallbackSDMusicFN: shortstring; // fallback SD music fille name var Volume: LongInt; SoundTimerTicks: Longword; LastVoiceFailed: boolean; implementation uses uVariables, uConsole, uCommands, uDebug, uPhysFSLayer; const chanTPU = 32; var cInitVolume: LongInt; previousVolume: LongInt; // cached volume value lastChan: array [TSound] of LongInt; voicepacks: array[0..cMaxTeams] of TVoicepack; defVoicepack: PVoicepack; Mus: PMixMusic; // music pointer isMusicEnabled: boolean; isSoundEnabled: boolean; isAutoDampening: boolean; isSEBackup: boolean; VoiceList : array[0..7] of TVoice = ( ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false), ( snd: sndNone; voicepack: nil; isFallback: false)); Soundz: array[TSound] of record FileName: string[31]; Path, AltPath : TPathType; end = ( (FileName: ''; Path: ptNone; AltPath: ptNone),// sndNone (FileName: 'grenadeimpact.ogg'; Path: ptSounds; AltPath: ptNone),// sndGrenadeImpact (FileName: 'explosion.ogg'; Path: ptSounds; AltPath: ptNone),// sndExplosion (FileName: 'throwpowerup.ogg'; Path: ptSounds; AltPath: ptNone),// sndThrowPowerUp (FileName: 'throwrelease.ogg'; Path: ptSounds; AltPath: ptNone),// sndThrowRelease (FileName: 'splash.ogg'; Path: ptCurrTheme; AltPath: ptSounds),// sndSplash (FileName: 'shotgunreload.ogg'; Path: ptSounds; AltPath: ptNone),// sndShotgunReload (FileName: 'shotgunfire.ogg'; Path: ptSounds; AltPath: ptNone),// sndShotgunFire (FileName: 'graveimpact.ogg'; Path: ptSounds; AltPath: ptNone),// sndGraveImpact (FileName: 'mineimpact.ogg'; Path: ptSounds; AltPath: ptNone),// sndMineImpact (FileName: 'minetick.ogg'; Path: ptSounds; AltPath: ptNone),// sndMineTicks // TODO: New mudball sound? (FileName: 'Droplet1.ogg'; Path: ptSounds; AltPath: ptNone),// sndMudballImpact (FileName: 'pickhammer.ogg'; Path: ptSounds; AltPath: ptNone),// sndPickhammer (FileName: 'gun.ogg'; Path: ptSounds; AltPath: ptNone),// sndGun (FileName: 'bee.ogg'; Path: ptSounds; AltPath: ptNone),// sndBee (FileName: 'Jump1.ogg'; Path: ptVoices; AltPath: ptNone),// sndJump1 (FileName: 'Jump2.ogg'; Path: ptVoices; AltPath: ptNone),// sndJump2 (FileName: 'Jump3.ogg'; Path: ptVoices; AltPath: ptNone),// sndJump3 (FileName: 'Yessir.ogg'; Path: ptVoices; AltPath: ptNone),// sndYesSir (FileName: 'Laugh.ogg'; Path: ptVoices; AltPath: ptNone),// sndLaugh (FileName: 'Illgetyou.ogg'; Path: ptVoices; AltPath: ptNone),// sndIllGetYou (FileName: 'Justyouwait.ogg'; Path: ptVoices; AltPath: ptNone),// sndJustyouwait (FileName: 'Incoming.ogg'; Path: ptVoices; AltPath: ptNone),// sndIncoming (FileName: 'Missed.ogg'; Path: ptVoices; AltPath: ptNone),// sndMissed (FileName: 'Stupid.ogg'; Path: ptVoices; AltPath: ptNone),// sndStupid (FileName: 'Firstblood.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirstBlood (FileName: 'Boring.ogg'; Path: ptVoices; AltPath: ptNone),// sndBoring (FileName: 'Byebye.ogg'; Path: ptVoices; AltPath: ptNone),// sndByeBye (FileName: 'Sameteam.ogg'; Path: ptVoices; AltPath: ptNone),// sndSameTeam (FileName: 'Nutter.ogg'; Path: ptVoices; AltPath: ptNone),// sndNutter (FileName: 'Reinforcements.ogg'; Path: ptVoices; AltPath: ptNone),// sndReinforce (FileName: 'Traitor.ogg'; Path: ptVoices; AltPath: ptNone),// sndTraitor (FileName: 'Youllregretthat.ogg'; Path: ptVoices; AltPath: ptNone),// sndRegret (FileName: 'Enemydown.ogg'; Path: ptVoices; AltPath: ptNone),// sndEnemyDown (FileName: 'Coward.ogg'; Path: ptVoices; AltPath: ptNone),// sndCoward (FileName: 'Hurry.ogg'; Path: ptVoices; AltPath: ptNone),// sndHurry (FileName: 'Watchit.ogg'; Path: ptVoices; AltPath: ptNone),// sndWatchIt (FileName: 'Kamikaze.ogg'; Path: ptVoices; AltPath: ptNone),// sndKamikaze (FileName: 'cake2.ogg'; Path: ptSounds; AltPath: ptNone),// sndCake (FileName: 'Ow1.ogg'; Path: ptVoices; AltPath: ptNone),// sndOw1 (FileName: 'Ow2.ogg'; Path: ptVoices; AltPath: ptNone),// sndOw2 (FileName: 'Ow3.ogg'; Path: ptVoices; AltPath: ptNone),// sndOw3 (FileName: 'Ow4.ogg'; Path: ptVoices; AltPath: ptNone),// sndOw4 (FileName: 'Firepunch1.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirePunch1 (FileName: 'Firepunch2.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirePunch2 (FileName: 'Firepunch3.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirePunch3 (FileName: 'Firepunch4.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirePunch4 (FileName: 'Firepunch5.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirePunch5 (FileName: 'Firepunch6.ogg'; Path: ptVoices; AltPath: ptNone),// sndFirePunch6 (FileName: 'Melon.ogg'; Path: ptVoices; AltPath: ptNone),// sndMelon (FileName: 'Hellish.ogg'; Path: ptSounds; AltPath: ptNone),// sndHellish (FileName: 'Yoohoo.ogg'; Path: ptSounds; AltPath: ptNone),// sndYoohoo (FileName: 'rcplane.ogg'; Path: ptSounds; AltPath: ptNone),// sndRCPlane (FileName: 'whipcrack.ogg'; Path: ptSounds; AltPath: ptNone),// sndWhipCrack (FileName:'ride_of_the_valkyries.ogg'; Path: ptSounds; AltPath: ptNone),// sndRideOfTheValkyries (FileName: 'denied.ogg'; Path: ptSounds; AltPath: ptNone),// sndDenied (FileName: 'placed.ogg'; Path: ptSounds; AltPath: ptNone),// sndPlaced (FileName: 'baseballbat.ogg'; Path: ptSounds; AltPath: ptNone),// sndBaseballBat (FileName: 'steam.ogg'; Path: ptSounds; AltPath: ptNone),// sndVaporize (FileName: 'warp.ogg'; Path: ptSounds; AltPath: ptNone),// sndWarp (FileName: 'suddendeath.ogg'; Path: ptSounds; AltPath: ptNone),// sndSuddenDeath (FileName: 'mortar.ogg'; Path: ptSounds; AltPath: ptNone),// sndMortar (FileName: 'shutterclick.ogg'; Path: ptSounds; AltPath: ptNone),// sndShutter (FileName: 'homerun.ogg'; Path: ptSounds; AltPath: ptNone),// sndHomerun (FileName: 'molotov.ogg'; Path: ptSounds; AltPath: ptNone),// sndMolotov (FileName: 'Takecover.ogg'; Path: ptVoices; AltPath: ptNone),// sndCover (FileName: 'Uh-oh.ogg'; Path: ptVoices; AltPath: ptNone),// sndUhOh (FileName: 'Oops.ogg'; Path: ptVoices; AltPath: ptNone),// sndOops (FileName: 'Nooo.ogg'; Path: ptVoices; AltPath: ptNone),// sndNooo (FileName: 'Hello.ogg'; Path: ptVoices; AltPath: ptNone),// sndHello (FileName: 'ropeshot.ogg'; Path: ptSounds; AltPath: ptNone),// sndRopeShot (FileName: 'ropeattach.ogg'; Path: ptSounds; AltPath: ptNone),// sndRopeAttach (FileName: 'roperelease.ogg'; Path: ptSounds; AltPath: ptNone),// sndRopeRelease (FileName: 'switchhog.ogg'; Path: ptSounds; AltPath: ptNone),// sndSwitchHog (FileName: 'Victory.ogg'; Path: ptVoices; AltPath: ptNone),// sndVictory (FileName: 'Flawless.ogg'; Path: ptVoices; AltPath: ptNone),// sndFlawless (FileName: 'sniperreload.ogg'; Path: ptSounds; AltPath: ptNone),// sndSniperReload (FileName: 'steps.ogg'; Path: ptSounds; AltPath: ptNone),// sndSteps (FileName: 'lowgravity.ogg'; Path: ptSounds; AltPath: ptNone),// sndLowGravity (FileName: 'hell_growl.ogg'; Path: ptSounds; AltPath: ptNone),// sndHellishImpact1 (FileName: 'hell_ooff.ogg'; Path: ptSounds; AltPath: ptNone),// sndHellishImpact2 (FileName: 'hell_ow.ogg'; Path: ptSounds; AltPath: ptNone),// sndHellishImpact3 (FileName: 'hell_ugh.ogg'; Path: ptSounds; AltPath: ptNone),// sndHellishImpact4 (FileName: 'melonimpact.ogg'; Path: ptSounds; AltPath: ptNone),// sndMelonImpact (FileName: 'Droplet1.ogg'; Path: ptCurrTheme; AltPath: ptSounds),// sndDroplet1 (FileName: 'Droplet2.ogg'; Path: ptCurrTheme; AltPath: ptSounds),// sndDroplet2 (FileName: 'Droplet3.ogg'; Path: ptCurrTheme; AltPath: ptSounds),// sndDroplet3 (FileName: 'egg.ogg'; Path: ptSounds; AltPath: ptNone),// sndEggBreak (FileName: 'drillgun.ogg'; Path: ptSounds; AltPath: ptNone),// sndDrillRocket (FileName: 'PoisonCough.ogg'; Path: ptVoices; AltPath: ptDefaultVoice),// sndPoisonCough (FileName: 'PoisonMoan.ogg'; Path: ptVoices; AltPath: ptDefaultVoice),// sndPoisonMoan (FileName: 'BirdyLay.ogg'; Path: ptSounds; AltPath: ptNone),// sndBirdyLay (FileName: 'Whistle.ogg'; Path: ptSounds; AltPath: ptNone),// sndWhistle (FileName: 'beewater.ogg'; Path: ptSounds; AltPath: ptNone),// sndBeeWater (FileName: '1C.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano0 (FileName: '2D.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano1 (FileName: '3E.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano2 (FileName: '4F.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano3 (FileName: '5G.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano4 (FileName: '6A.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano5 (FileName: '7B.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano6 (FileName: '8C.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano7 (FileName: '9D.ogg'; Path: ptSounds; AltPath: ptNone),// sndPiano8 (FileName: 'skip.ogg'; Path: ptCurrTheme; AltPath: ptSounds),// sndSkip (FileName: 'sinegun.ogg'; Path: ptSounds; AltPath: ptNone),// sndSineGun (FileName: 'Ooff1.ogg'; Path: ptVoices; AltPath: ptNone),// sndOoff1 (FileName: 'Ooff2.ogg'; Path: ptVoices; AltPath: ptNone),// sndOoff2 (FileName: 'Ooff3.ogg'; Path: ptVoices; AltPath: ptNone),// sndOoff3 (FileName: 'hammer.ogg'; Path: ptSounds; AltPath: ptNone),// sndWhack (FileName: 'Comeonthen.ogg'; Path: ptVoices; AltPath: ptNone),// sndComeonthen (FileName: 'parachute.ogg'; Path: ptSounds; AltPath: ptNone),// sndParachute (FileName: 'bump.ogg'; Path: ptSounds; AltPath: ptNone),// sndBump (FileName: 'hogchant3.ogg'; Path: ptSounds; AltPath: ptNone),// sndResurrector (FileName: 'plane.ogg'; Path: ptSounds; AltPath: ptNone),// sndPlane (FileName: 'TARDIS.ogg'; Path: ptSounds; AltPath: ptNone),// sndTardis (FileName: 'frozen_hog_impact.ogg'; Path: ptSounds; AltPath: ptNone),// sndFrozenHogImpact (FileName: 'ice_beam.ogg'; Path: ptSounds; AltPath: ptNone),// sndIceBeam (FileName: 'hog_freeze.ogg'; Path: ptSounds; AltPath: ptNone), // sndHogFreeze (FileName: 'airmine_impact.ogg'; Path: ptSounds; AltPath: ptNone),// sndAirMineImpact (FileName: 'knife_impact.ogg'; Path: ptSounds; AltPath: ptNone),// sndKnifeImpact (FileName: 'extratime.ogg'; Path: ptSounds; AltPath: ptNone),// sndExtraTime (FileName: 'lasersight.ogg'; Path: ptSounds; AltPath: ptNone),// sndLaserSight (FileName: 'invulnerable.ogg'; Path: ptSounds; AltPath: ptNone),// sndInvulnerable (FileName: 'ufo.ogg'; Path: ptSounds; AltPath: ptNone),// sndJetpackLaunch (FileName: 'jetpackboost.ogg'; Path: ptSounds; AltPath: ptNone),// sndJetpackBoost (FileName: 'portalshot.ogg'; Path: ptSounds; AltPath: ptNone),// sndPortalShot (FileName: 'portalswitch.ogg'; Path: ptSounds; AltPath: ptNone),// sndPortalSwitch (FileName: 'portalopen.ogg'; Path: ptSounds; AltPath: ptNone),// sndPortalOpen (FileName: 'blowtorch.ogg'; Path: ptSounds; AltPath: ptNone),// sndBlowTorch (FileName: 'countdown1.ogg'; Path: ptSounds; AltPath: ptNone),// sndCountdown1 (FileName: 'countdown2.ogg'; Path: ptSounds; AltPath: ptNone),// sndCountdown2 (FileName: 'countdown3.ogg'; Path: ptSounds; AltPath: ptNone),// sndCountdown3 (FileName: 'countdown4.ogg'; Path: ptSounds; AltPath: ptNone),// sndCountdown4 // TODO: Check which creeper (formerly rubberduck) sounds are needed, maybe rename them (FileName: 'rubberduck_drop.ogg'; Path: ptSounds; AltPath: ptNone),// sndCreeperDrop (FileName: 'rubberduck_water.ogg'; Path: ptSounds; AltPath: ptNone),// sndCreeperWater (FileName: 'rubberduck_die.ogg'; Path: ptSounds; AltPath: ptNone),// sndCreeperDie (FileName: 'custom1.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom1 (FileName: 'custom2.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom2 (FileName: 'custom3.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom3 (FileName: 'custom4.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom4 (FileName: 'custom5.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom5 (FileName: 'custom6.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom6 (FileName: 'custom7.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom7 (FileName: 'custom8.ogg'; Path: ptSounds; AltPath: ptNone),// sndCustom8 (FileName: 'minigun.ogg'; Path: ptSounds; AltPath: ptNone),// sndMinigun (FileName: 'flamethrower.ogg'; Path: ptSounds; AltPath: ptNone),// sndFlamethrower (FileName: 'ice_beam_idle.ogg'; Path: ptSounds; AltPath: ptNone),// sndIceBeamIdle (FileName: 'landgun.ogg'; Path: ptSounds; AltPath: ptNone),// sndLandGun (FileName: 'graveimpact.ogg'; Path: ptSounds; AltPath: ptNone),// sndCaseImpact // TODO: New Extra Damage sound (FileName: 'hell_ugh.ogg'; Path: ptSounds; AltPath: ptNone),// sndExtraDamage (FileName: 'firepunch_hit.ogg'; Path: ptSounds; AltPath: ptNone),// sndFirePunchHit (FileName: 'Grenade.ogg'; Path: ptVoices; AltPath: ptNone),// sndGrenade (FileName: 'Thisoneismine.ogg'; Path: ptVoices; AltPath: ptNone),// sndThisOneIsMine (FileName: 'Whatthe.ogg'; Path: ptVoices; AltPath: ptNone),// sndWhatThe (FileName: 'Solong.ogg'; Path: ptVoices; AltPath: ptNone),// sndSoLong (FileName: 'Ohdear.ogg'; Path: ptVoices; AltPath: ptNone),// sndOhDear (FileName: 'Gonnagetyou.ogg'; Path: ptVoices; AltPath: ptNone),// sndGonnaGetYou (FileName: 'Drat.ogg'; Path: ptVoices; AltPath: ptNone),// sndDrat (FileName: 'Bugger.ogg'; Path: ptVoices; AltPath: ptNone),// sndBugger (FileName: 'Amazing.ogg'; Path: ptVoices; AltPath: ptNone),// sndAmazing (FileName: 'Brilliant.ogg'; Path: ptVoices; AltPath: ptNone),// sndBrilliant (FileName: 'Excellent.ogg'; Path: ptVoices; AltPath: ptNone),// sndExcellent (FileName: 'Fire.ogg'; Path: ptVoices; AltPath: ptNone),// sndFire (FileName: 'Watchthis.ogg'; Path: ptVoices; AltPath: ptNone),// sndWatchThis (FileName: 'Runaway.ogg'; Path: ptVoices; AltPath: ptNone),// sndRunAway (FileName: 'Revenge.ogg'; Path: ptVoices; AltPath: ptNone),// sndRevenge (FileName: 'Cutitout.ogg'; Path: ptVoices; AltPath: ptNone),// sndCutItOut (FileName: 'Leavemealone.ogg'; Path: ptVoices; AltPath: ptNone),// sndLeaveMeAlone (FileName: 'Ouch.ogg'; Path: ptVoices; AltPath: ptNone),// sndOuch (FileName: 'Hmm.ogg'; Path: ptVoices; AltPath: ptNone),// sndHmm (FileName: 'Kiss.ogg'; Path: ptSounds; AltPath: ptNone),// sndKiss (FileName: 'Flyaway.ogg'; Path: ptVoices; AltPath: ptNone),// sndFlyAway (FileName: 'planewater.ogg'; Path: ptSounds; AltPath: ptNone) // sndPlaneWater ); function AskForVoicepack(name: shortstring): Pointer; var i: Longword; tmp, nameStart, langName, path: shortstring; begin nameStart:= name; i:= 0; { Adjust for language suffix: Voicepacks can have an optional language suffix. It's an underscore followed by an ISO 639-1 or ISO 639-2 language code. The suffix “_qau” is special, it will enable automatic language selection of this voicepack. For example, if team has set Default_qau as voicepack, and the player language is Russian, the actual voicepack will be Default_ru, provided it can be found on the disk. “qau” is a valid ISO 639-2 language code reserved for local use. } tmp:= Copy(name, Length(name) - 3, 4); if (tmp = '_qau') then name:= Copy(name, 1, Length(name) - 4); if (cLanguage <> 'en') and (tmp = '_qau') then begin langName:= name+'_'+cLanguage; path:= cPathz[ptVoices] + '/' + langName; if pfsExists(path) then name:= langName else if Length(cLanguage) > 3 then begin langName:= name+'_'+Copy(cLanguage,1,2); path:= cPathz[ptVoices] + '/' + langName; if pfsExists(path) then name:= langName end end; path:= cPathz[ptVoices] + '/' + name; // Fallback to localized Default if voicepack can't be found at all if (nameStart <> 'Default_qau') and (not pfsExists(path)) then exit(AskForVoicepack('Default_qau')); while (voicepacks[i].name <> name) and (voicepacks[i].name <> '') and (i < cMaxTeams) do begin inc(i); //TryDo(i <= cMaxTeams, 'Engine bug: AskForVoicepack i > cMaxTeams', true) end; voicepacks[i].name:= name; AskForVoicepack:= @voicepacks[i] end; procedure InitSound; const channels: LongInt = 2; var success: boolean; s: shortstring; begin if not (isSoundEnabled or isMusicEnabled) then begin isAudioMuted:= true; cInitVolume:= 0; exit; end; WriteToConsole('Init sound...'); success:= SDL_InitSubSystem(SDL_INIT_AUDIO) = 0; if success then begin WriteLnToConsole(msgOK); WriteToConsole('Open audio...'); success:= Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, channels, 1024) = 0; end; if success then WriteLnToConsole(msgOK) else begin WriteLnToConsole(msgFailed); isSoundEnabled:= false; isMusicEnabled:= false; isAudioMuted:= true; cInitVolume:= 0; end; WriteToConsole('Init SDL_mixer... '); if (Mix_Init(MIX_INIT_OGG or MIX_INIT_OPUS) and MIX_INIT_OPUS) = 0 then begin s:= SDL_GetError(); WriteToConsole('Cannot init OPUS: ' + s); if SDLCheck(Mix_Init(MIX_INIT_OGG) <> 0, 'Mix_Init', true) then exit; end; WriteLnToConsole(msgOK); // from uVariables to be used by other modules cIsSoundEnabled:= true; Mix_AllocateChannels(Succ(chanTPU)); previousVolume:= cInitVolume; ChangeVolume(cInitVolume); end; procedure ResetSound; begin isSoundEnabled:= isSEBackup; end; procedure SetSound(enabled: boolean); begin isSEBackup:= isSoundEnabled; isSoundEnabled:= enabled; end; procedure SetAudioDampen(enabled: boolean); begin isAutoDampening:= enabled; end; // when complete is false, this procedure just releases some of the chucks on inactive channels // in this way music is not stopped, nor are chucks currently being played procedure ReleaseSound(complete: boolean); var i: TSound; t: Longword; begin // release and nil all sounds for t:= 0 to cMaxTeams do if voicepacks[t].name <> '' then for i:= Low(TSound) to High(TSound) do if voicepacks[t].chunks[i] <> nil then if complete or (Mix_Playing(lastChan[i]) = 0) then begin Mix_HaltChannel(lastChan[i]); lastChan[i]:= -1; Mix_FreeChunk(voicepacks[t].chunks[i]); voicepacks[t].chunks[i]:= nil; end; // stop music if complete then begin if Mus <> nil then begin Mix_HaltMusic(); Mix_FreeMusic(Mus); Mus:= nil; end; // make sure all instances of sdl_mixer are unloaded before continuing while Mix_Init(0) <> 0 do Mix_Quit(); Mix_CloseAudio(); end; end; // Get a fallback voice, assuming that snd is not available. Returns sndNone if none is found. function GetFallbackV(snd: TSound): TSound; begin // Fallback to sndFirePunch1 / sndOw1 / sndOoff1 if a "higher-numbered" sound is missing if (snd in [sndFirePunch2, sndFirePunch3, sndFirePunch4, sndFirePunch5, sndFirePunch6]) then GetFallbackV := sndFirePunch1 else if (snd in [sndOw2, sndOw3, sndOw4, sndOuch]) then GetFallbackV := sndOw1 else if (snd in [sndOoff2, sndOoff3]) then GetFallbackV := sndOoff1 // Other fallback sounds else if (snd = sndGrenade) then if random(2) = 0 then GetFallbackV := sndNooo else GetFallbackV := sndUhOh else if (snd in [sndDrat, sndBugger]) then GetFallbackV := sndStupid else if (snd in [sndGonnaGetYou, sndIllGetYou, sndJustYouWait, sndCutItOut, sndLeaveMeAlone]) then GetFallbackV := sndRegret else if (snd in [sndOhDear, sndSoLong]) then GetFallbackV := sndByeBye else if (snd in [sndWhatThe, sndUhOh]) then GetFallbackV := sndNooo else if (snd = sndRunAway) then GetFallbackV := sndOops else if (snd = sndThisOneIsMine) then GetFallbackV := sndReinforce else if (snd in [sndAmazing, sndBrilliant, sndExcellent]) then GetFallbackV := sndEnemyDown else if (snd = sndPoisonCough) then GetFallbackV := sndPoisonMoan else if (snd = sndPoisonMoan) then GetFallbackV := sndPoisonCough else if (snd = sndFlawless) then GetFallbackV := sndVictory else if (snd = sndSameTeam) then GetFallbackV := sndTraitor else if (snd = sndMelon) then GetFallbackV := sndCover // sndHmm is used for enemy turn start, so sndHello is an "okay" replacement else if (snd = sndHmm) then GetFallbackV := sndHello else GetFallbackV := sndNone; end; function PlaySound(snd: TSound): boolean; begin PlaySound:= PlaySoundV(snd, nil, false, false, false); end; function PlaySound(snd: TSound; keepPlaying: boolean): boolean; begin PlaySound:= PlaySoundV(snd, nil, keepPlaying, false, false); end; function PlaySound(snd: TSound; keepPlaying: boolean; ignoreMask: boolean): boolean; begin PlaySound:= PlaySoundV(snd, nil, keepPlaying, ignoreMask, false); end; function PlaySound(snd: TSound; keepPlaying: boolean; ignoreMask, soundAsMusic: boolean): boolean; begin PlaySound:= PlaySoundV(snd, nil, keepPlaying, ignoreMask, soundAsMusic); end; function PlaySoundV(snd: TSound; voicepack: PVoicepack): boolean; begin PlaySoundV:= PlaySoundV(snd, voicepack, false, false, false); end; function PlaySoundV(snd: TSound; voicepack: PVoicepack; keepPlaying: boolean): boolean; begin PlaySoundV:= PlaySoundV(snd, voicepack, keepPlaying, false, false); end; function PlaySoundV(snd: TSound; voicepack: PVoicepack; keepPlaying, ignoreMask: boolean): boolean; begin PlaySoundV:= PlaySoundV(snd, voicepack, keepPlaying, ignoreMask, false); end; function PlaySoundV(snd: TSound; voicepack: PVoicepack; keepPlaying, ignoreMask, soundAsMusic: boolean): boolean; var s: shortstring; tempSnd, loadSnd: TSound; rwops: PSDL_RWops; begin PlaySoundV:= false; if ((not isSoundEnabled) and (not (soundAsMusic and isMusicEnabled))) or fastUntilLag then exit; if keepPlaying and (lastChan[snd] <> -1) and (Mix_Playing(lastChan[snd]) <> 0) then exit; if (ignoreMask = false) and (MaskedSounds[snd] = true) then exit; if (voicepack <> nil) then begin if (voicepack^.chunks[snd] = nil) and (Soundz[snd].Path = ptVoices) and (Soundz[snd].FileName <> '') then begin loadSnd:= snd; s:= cPathz[Soundz[loadSnd].Path] + '/' + voicepack^.name + '/' + Soundz[loadSnd].FileName; // Fallback taunts if (not pfsExists(s)) then begin tempSnd := GetFallbackV(snd); if tempSnd <> sndNone then begin loadSnd := tempSnd; //LastVoice.snd := tempSnd; end; s:= cPathz[Soundz[loadSnd].Path] + '/' + voicepack^.name + '/' + Soundz[loadSnd].FileName; end; WriteToConsole(msgLoading + s + ' ... '); rwops := rwopsOpenRead(s); if rwops = nil then begin s:= cPathz[Soundz[loadSnd].AltPath] + '/' + Soundz[loadSnd].FileName; WriteToConsole(msgLoading + s + ' ... '); rwops := rwopsOpenRead(s); end; voicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwops, 1); if voicepack^.chunks[snd] = nil then WriteLnToConsole(msgFailed) else WriteLnToConsole(msgOK) end; lastChan[snd]:= Mix_PlayChannelTimed(-1, voicepack^.chunks[snd], 0, -1); PlaySoundV:= true; end else begin if (defVoicepack^.chunks[snd] = nil) and (Soundz[snd].Path <> ptVoices) and (Soundz[snd].FileName <> '') then begin s:= cPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName; WriteToConsole(msgLoading + s + ' ... '); rwops := rwopsOpenRead(s); if rwops = nil then begin s:= cPathz[Soundz[snd].AltPath] + '/' + Soundz[snd].FileName; WriteToConsole(msgLoading + s + ' ... '); rwops := rwopsOpenRead(s); end; defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwops, 1); if SDLCheck(defVoicepack^.chunks[snd] <> nil, 'Mix_LoadWAV_RW', true) then exit; WriteLnToConsole(msgOK); end; lastChan[snd]:= Mix_PlayChannelTimed(-1, defVoicepack^.chunks[snd], 0, -1); PlaySoundV:= true; end; end; procedure PlayMusicSound(snd: TSound); begin PauseMusic; PlaySound(snd, false, false, true); end; procedure StopMusicSound(snd: TSound); begin StopSound(snd, true); ResumeMusic; end; procedure AddVoice(snd: TSound; voicepack: PVoicepack); begin AddVoice(snd, voicepack, false, false); end; { AddVoice: Add a voice to the voice queue. * snd: Sound ID * voicepack: Hedgehog voicepack * ignoreMask: If true, the sound will be played anyway if masked by Lua * isFallback: If true, this sound is added as fallback if the sound previously added to the queue was not found. Useful to make sure a voice is always played, even if a voicepack is incomplete. Example: AddVoice(sndRevenge, voiceAttacker); AddVoice(sndRegret, voiceVictim, false, true); --> plays sndRegret if sndRevenge could not be played. } procedure AddVoice(snd: TSound; voicepack: PVoicepack; ignoreMask, isFallback: boolean); var i : LongInt; begin if (not isSoundEnabled) or fastUntilLag or ((LastVoice.snd = snd) and (LastVoice.voicepack = voicepack)) then exit; if (ignoreMask = false) and (MaskedSounds[snd] = true) then exit; if (snd = sndVictory) or (snd = sndFlawless) then begin Mix_FadeOutChannel(-1, 800); for i:= 0 to High(VoiceList) do VoiceList[i].snd:= sndNone; LastVoice.snd:= sndNone; end; i:= 0; while (i <= High(VoiceList)) and (VoiceList[i].snd <> sndNone) do inc(i); // skip playing same sound for same hog twice if (i>0) and (VoiceList[i-1].snd = snd) and (VoiceList[i-1].voicepack = voicepack) then exit; if(i <= High(VoiceList)) then begin VoiceList[i].snd:= snd; VoiceList[i].voicepack:= voicepack; VoiceList[i].isFallback:= isFallback; end end; procedure PlayNextVoice; var i : LongInt; played : boolean; begin if (not isSoundEnabled) or fastUntilLag or ((LastVoice.snd <> sndNone) and (lastChan[LastVoice.snd] <> -1) and (Mix_Playing(lastChan[LastVoice.snd]) <> 0)) then exit; i:= 0; while (i<High(VoiceList)) and (VoiceList[i].snd = sndNone) do inc(i); played:= false; if (VoiceList[i].snd <> sndNone) and ((not VoiceList[i].isFallback) or LastVoiceFailed) then begin LastVoice.snd:= VoiceList[i].snd; LastVoice.voicepack:= VoiceList[i].voicepack; LastVoice.isFallback:= VoiceList[i].isFallback; VoiceList[i].snd:= sndNone; played:= PlaySoundV(LastVoice.snd, LastVoice.voicepack); // Remember if sound was not played. LastVoiceFailed:= (not played); end else LastVoice.snd:= sndNone; end; function LoopSound(snd: TSound): LongInt; begin LoopSound:= LoopSoundV(snd, nil) end; function LoopSound(snd: TSound; fadems: LongInt): LongInt; begin LoopSound:= LoopSoundV(snd, nil, fadems) end; function LoopSoundV(snd: TSound; voicepack: PVoicepack): LongInt; begin voicepack:= voicepack; // avoid compiler hint LoopSoundV:= LoopSoundV(snd, nil, 0) end; function LoopSoundV(snd: TSound; voicepack: PVoicepack; fadems: LongInt): LongInt; var s: shortstring; rwops: PSDL_RWops; begin if (not isSoundEnabled) or fastUntilLag then begin LoopSoundV:= -1; exit end; if (voicepack <> nil) then begin if (voicepack^.chunks[snd] = nil) and (Soundz[snd].Path = ptVoices) and (Soundz[snd].FileName <> '') then begin s:= cPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName; WriteToConsole(msgLoading + s + ' '); rwops:=rwopsOpenRead(s); if rwops = nil then begin s:= cPathz[Soundz[snd].AltPath] + '/' + Soundz[snd].FileName; WriteToConsole(msgLoading + s + ' ... '); rwops:=rwopsOpenRead(s); end; voicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwops, 1); if voicepack^.chunks[snd] = nil then WriteLnToConsole(msgFailed) else WriteLnToConsole(msgOK) end; LoopSoundV:= Mix_PlayChannelTimed(-1, voicepack^.chunks[snd], -1, -1) end else begin if (defVoicepack^.chunks[snd] = nil) and (Soundz[snd].Path <> ptVoices) and (Soundz[snd].FileName <> '') then begin s:= cPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName; WriteToConsole(msgLoading + s + ' '); defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1); if SDLCheck(defVoicepack^.chunks[snd] <> nil, 'Mix_LoadWAV_RW', true) then exit(-1); WriteLnToConsole(msgOK); end; if fadems > 0 then LoopSoundV:= Mix_FadeInChannelTimed(-1, defVoicepack^.chunks[snd], -1, fadems, -1) else LoopSoundV:= Mix_PlayChannelTimed(-1, defVoicepack^.chunks[snd], -1, -1); end; end; procedure StopSound(snd: TSound); begin StopSound(snd, false); end; procedure StopSound(snd: TSound; soundAsMusic: boolean); begin if ((not isSoundEnabled) and (not (soundAsMusic and isMusicEnabled))) then exit; if (lastChan[snd] <> -1) and (Mix_Playing(lastChan[snd]) <> 0) then begin Mix_HaltChannel(lastChan[snd]); lastChan[snd]:= -1; end; end; procedure StopSoundChan(chn: LongInt); begin if not isSoundEnabled then exit; if (chn <> -1) and (Mix_Playing(chn) <> 0) then Mix_HaltChannel(chn); end; procedure StopSoundChan(chn, fadems: LongInt); begin if not isSoundEnabled then exit; if (chn <> -1) and (Mix_Playing(chn) <> 0) then if isAudioMuted then Mix_HaltChannel(chn) else Mix_FadeOutChannel(chn, fadems); end; procedure PlayMusic; var s: shortstring; begin if (MusicFN = '') or (not isMusicEnabled) then exit; if SuddenDeath and (SDMusicFN <> '') then s:= '/Music/' + SDMusicFN else s:= '/Music/' + MusicFN; WriteToConsole(msgLoading + s + ' '); // Load normal music Mus:= Mix_LoadMUS_RW(rwopsOpenRead(s)); SDLCheck(Mus <> nil, 'Mix_LoadMUS_RW', false); if Mus <> nil then WriteLnToConsole(msgOK); // If normal music failed, try to get fallback music if Mus = nil then begin WriteLnToConsole('Music not found. Trying fallback music.'); if SuddenDeath and (FallbackSDMusicFN <> '') then s:= '/Music/' + FallbackSDMusicFN else if (not SuddenDeath) and (FallbackMusicFN <> '') then s:= '/Music/' + FallbackMusicFN else begin WriteLnToConsole('No fallback music configured!'); s:= '' end; if (s <> '') then begin WriteLnToConsole(msgLoading + s + ' '); Mus:= Mix_LoadMUS_RW(rwopsOpenRead(s)); SDLCheck(Mus <> nil, 'Mix_LoadMUS_RW', false); if Mus <> nil then WriteLnToConsole(msgOK) end; end; SDLCheck(Mix_FadeInMusic(Mus, -1, 3000) <> -1, 'Mix_FadeInMusic', false) end; procedure SetVolume(vol: LongInt); begin cInitVolume:= vol; end; function GetVolumePercent(): LongInt; begin GetVolumePercent:= Volume * 100 div MIX_MAX_VOLUME; // 0 and 100 will only be displayed when at min/max values // to avoid confusion. if ((GetVolumePercent = 0) and (Volume > 0)) then GetVolumePercent:= 1 else if ((GetVolumePercent = 100) and (Volume < MIX_MAX_VOLUME)) then GetVolumePercent:= 99; end; function ChangeVolume(voldelta: LongInt): LongInt; begin ChangeVolume:= 0; if not (isSoundEnabled or isMusicEnabled) or ((voldelta = 0) and (not (cInitVolume = 0))) then exit; inc(Volume, voldelta); if Volume < 0 then Volume:= 0; // apply Volume to all channels Mix_Volume(-1, Volume); // get assigned Volume Volume:= Mix_Volume(-1, -1); if isMusicEnabled then Mix_VolumeMusic(Volume * 4 div 8); ChangeVolume:= GetVolumePercent(); if (isMusicEnabled) then if (Volume = 0) then PauseMusic else ResumeMusic; isAudioMuted:= (Volume = 0); end; procedure DampenAudio; begin if (isAudioMuted or (not isAutoDampening)) then exit; previousVolume:= Volume; ChangeVolume(-Volume * 7 div 9); end; procedure UndampenAudio; begin if (isAudioMuted or (not isAutoDampening)) then exit; ChangeVolume(previousVolume - Volume); end; procedure MuteAudio; begin if not (isSoundEnabled or isMusicEnabled) then exit; if (isAudioMuted) then begin ResumeMusic; ChangeVolume(previousVolume); end else begin PauseMusic; previousVolume:= Volume; ChangeVolume(-Volume); end; // isAudioMuted is updated in ChangeVolume end; procedure SetMusic(enabled: boolean); begin isMusicEnabled:= enabled; end; procedure SetMusicName(musicname: shortstring); begin MusicFN:= musicname; end; procedure PauseMusic; begin if (MusicFN = '') or (not isMusicEnabled) then exit; if Mus <> nil then Mix_PauseMusic(Mus); end; procedure ResumeMusic; begin if (MusicFN = '') or (not isMusicEnabled) then exit; if Mus <> nil then Mix_ResumeMusic(Mus); end; procedure ChangeMusic(musicname: shortstring); begin MusicFN:= musicname; if (MusicFN = '') or (not isMusicEnabled) then exit; StopMusic; PlayMusic; end; procedure StopMusic; begin if (MusicFN = '') or (not isMusicEnabled) then exit; if Mus <> nil then begin Mix_FreeMusic(Mus); Mus:= nil; end end; procedure chVoicepack(var s: shortstring); begin if CurrentTeam = nil then OutError(errmsgIncorrectUse + ' "/voicepack"', true); if s[1]='"' then Delete(s, 1, 1); if s[byte(s[0])]='"' then Delete(s, byte(s[0]), 1); CurrentTeam^.voicepack:= AskForVoicepack(s) end; procedure preInitModule; begin isMusicEnabled:= true; isSoundEnabled:= true; isAutoDampening:= true; cInitVolume:= 100; end; procedure initModule; var t: LongInt; i: TSound; begin RegisterVariable('voicepack', @chVoicepack, false); MusicFN:=''; SDMusicFN:= 'sdmusic.ogg'; FallbackMusicFN:=''; FallbackSDMusicFN:= 'sdmusic.ogg'; Mus:= nil; isAudioMuted:= false; isSEBackup:= isSoundEnabled; Volume:= 0; SoundTimerTicks:= 0; defVoicepack:= AskForVoicepack('Default_qau'); LastVoiceFailed:= false; for i:= Low(TSound) to High(TSound) do lastChan[i]:= -1; // initialize all voices to nil so that they can be loaded lazily for t:= 0 to cMaxTeams do if voicepacks[t].name <> '' then for i:= Low(TSound) to High(TSound) do voicepacks[t].chunks[i]:= nil; (* on MOBILE SDL_mixer has to be compiled against Tremor (USE_OGG_TREMOR) or sound files bigger than 32k will lockup the game on slow cpu *) for i:= Low(TSound) to High(TSound) do defVoicepack^.chunks[i]:= nil; end; procedure freeModule; begin if isSoundEnabled or isMusicEnabled then ReleaseSound(true); end; end.
42.997201
164
0.605211
f11de2586f327897857f1401922cfca13243ad34
11,272
pas
Pascal
theme/AMegaDemo/UnitTsSpeedButton.pas
AbdelliNasredine/gestion_budjet
ada33c945092d0036ef75a13f34b15cb2ad367e4
[ "MIT" ]
null
null
null
theme/AMegaDemo/UnitTsSpeedButton.pas
AbdelliNasredine/gestion_budjet
ada33c945092d0036ef75a13f34b15cb2ad367e4
[ "MIT" ]
null
null
null
theme/AMegaDemo/UnitTsSpeedButton.pas
AbdelliNasredine/gestion_budjet
ada33c945092d0036ef75a13f34b15cb2ad367e4
[ "MIT" ]
null
null
null
unit UnitTsSpeedButton; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, ExtCtrls, StdCtrls, Controls, Forms, Dialogs, Buttons, ImgList, ComCtrls, UnitBaseMenu, acAlphaImageList, sComboBox, sGroupBox, sRadioButton, sComboBoxes, sEdit, acPopupCtrls, sCheckBox, sSpeedButton, sFrameAdapter; type TFrameTsSpeedButton = class(TFrameBaseMenu) sTrackEdit3: TsTrackEdit; sGroupBox2: TsGroupBox; sCheckBox1: TsCheckBox; sTrackEdit2: TsTrackEdit; sGroupBox1: TsGroupBox; sCheckBox3: TsCheckBox; sCheckBox4: TsCheckBox; sCheckBox5: TsCheckBox; sCheckBox6: TsCheckBox; sRadioGroup3: TsRadioGroup; sRadioGroup1: TsRadioGroup; sSpeedButton1: TsSpeedButton; sRadioButton1: TsRadioButton; sRadioButton2: TsRadioButton; sRadioButton3: TsRadioButton; sRadioButton4: TsRadioButton; sGroupBox3: TsGroupBox; sTrackEdit1: TsTrackEdit; sCheckBox2: TsCheckBox; sRadioGroup2: TsRadioGroup; sSpeedButton3: TsSpeedButton; sComboBox4: TsComboBox; sColorBox1: TsColorBox; sCheckBox8: TsCheckBox; sCheckBox9: TsCheckBox; sColorBox2: TsColorBox; sSpeedButton4: TsSpeedButton; sTrackEdit4: TsTrackEdit; sTrackEdit5: TsTrackEdit; sVirtualImageList1: TsVirtualImageList; sGroupBox4: TsGroupBox; sCheckBox7: TsCheckBox; sComboBox1: TsComboBox; procedure sCheckBox1Click(Sender: TObject); procedure sCheckBox3Click(Sender: TObject); procedure sCheckBox4Click(Sender: TObject); procedure sCheckBox5Click(Sender: TObject); procedure sCheckBox6Click(Sender: TObject); procedure sTrackEdit2Change(Sender: TObject); procedure sTrackEdit3Change(Sender: TObject); procedure sRadioGroup1Click(Sender: TObject); procedure sRadioGroup3Click(Sender: TObject); procedure sRadioButton1Click(Sender: TObject); procedure sGroupBox1CheckBoxChanged(Sender: TObject); procedure sTrackEdit1Change(Sender: TObject); procedure sGroupBox3CheckBoxChanged(Sender: TObject); procedure sCheckBox2Click(Sender: TObject); procedure sRadioGroup2Change(Sender: TObject); procedure sSpeedButton1Click(Sender: TObject); procedure sCheckBox7Click(Sender: TObject); procedure sComboBox4Change(Sender: TObject); procedure sColorBox1Change(Sender: TObject); procedure sSpeedButton3Click(Sender: TObject); procedure sTrackEdit5Change(Sender: TObject); procedure sTrackEdit4Change(Sender: TObject); procedure sCheckBox8Click(Sender: TObject); procedure sCheckBox9Click(Sender: TObject); procedure sColorBox2Change(Sender: TObject); procedure sSpeedButton4Click(Sender: TObject); procedure sComboBox1Change(Sender: TObject); procedure sColorBox1ColorPreview(Sender: TObject; OriginColor, PreviousColor: TColor; var NewColor: TColor); procedure sColorBox2ColorPreview(Sender: TObject; OriginColor, PreviousColor: TColor; var NewColor: TColor); public procedure CheckLayoutControls; procedure CheckDisableGroup; procedure CheckTextGroup; end; var FrameTsSpeedButton: TFrameTsSpeedButton; implementation {$R *.dfm} uses sVCLUtils, sCommonData, sConst, UnitDataModule, UnitMain; const AlignmentArray: array [0..2] of TAlignment = (taLeftJustify, taRightJustify, taCenter); VertAlignmentArray: array [0..2] of TVerticalAlignment = (taAlignTop, taAlignBottom, taVerticalCenter); LayoutArray: array [0..3] of TButtonLayout = (blGlyphLeft, blGlyphRight, blGlyphTop, blGlyphBottom); procedure EnabledControls(Ctrl: TControl; Data: integer); begin Ctrl.Enabled := not boolean(Data); end; procedure TFrameTsSpeedButton.CheckDisableGroup; begin IterateControls(sGroupBox1, integer(sSpeedButton1.Enabled), EnabledControls); sCheckBox3.Enabled := not sSpeedButton1.Enabled; sCheckBox4.Enabled := not sSpeedButton1.Enabled; sCheckBox5.Enabled := not sSpeedButton1.Enabled and sGroupBox3.Checked; sCheckBox6.Enabled := not sSpeedButton1.Enabled and sGroupBox3.Checked; end; procedure TFrameTsSpeedButton.CheckLayoutControls; begin sRadioButton1.Enabled := sCheckBox1.Checked and sGroupBox3.Checked; sRadioButton2.Enabled := sCheckBox1.Checked and sGroupBox3.Checked; sRadioButton3.Enabled := sCheckBox1.Checked and sGroupBox3.Checked and (sRadioGroup1.ItemIndex = 2); sRadioButton4.Enabled := sCheckBox1.Checked and sGroupBox3.Checked and (sRadioGroup1.ItemIndex = 2); end; procedure TFrameTsSpeedButton.CheckTextGroup; begin sRadioGroup3.Enabled := sCheckBox1.Checked and sGroupBox3.Checked and ((sRadioGroup1.ItemIndex = 0) and sRadioButton1.Checked or (sRadioGroup1.ItemIndex = 1) and sRadioButton2.Checked); end; procedure TFrameTsSpeedButton.sCheckBox1Click(Sender: TObject); begin sSpeedButton1.ShowCaption := sCheckBox1.Checked; sTrackEdit3.Enabled := sCheckBox1.Checked and sGroupBox3.Checked; CheckTextGroup; CheckLayoutControls; end; procedure TFrameTsSpeedButton.sCheckBox2Click(Sender: TObject); begin sComboBox4.ItemIndex := 0; // Empty sSpeedButton1.SkinData.SkinSection := ''; sSpeedButton1.Flat := sCheckBox2.Checked; end; procedure TFrameTsSpeedButton.sCheckBox3Click(Sender: TObject); begin if sCheckBox3.Checked then sSpeedButton1.DisabledKind := sSpeedButton1.DisabledKind + [dkBlended] else sSpeedButton1.DisabledKind := sSpeedButton1.DisabledKind - [dkBlended]; end; procedure TFrameTsSpeedButton.sCheckBox4Click(Sender: TObject); begin sCheckBox6.Enabled := not sCheckBox4.Checked; if sCheckBox4.Checked then sSpeedButton1.DisabledKind := sSpeedButton1.DisabledKind + [dkGrayed] else sSpeedButton1.DisabledKind := sSpeedButton1.DisabledKind - [dkGrayed]; end; procedure TFrameTsSpeedButton.sCheckBox5Click(Sender: TObject); begin if sCheckBox5.Checked then sSpeedButton1.DisabledGlyphKind := sSpeedButton1.DisabledGlyphKind + [dgBlended] else sSpeedButton1.DisabledGlyphKind := sSpeedButton1.DisabledGlyphKind - [dgBlended]; end; procedure TFrameTsSpeedButton.sCheckBox6Click(Sender: TObject); begin sCheckBox4.Enabled := not sCheckBox6.Checked; if sCheckBox6.Checked then sSpeedButton1.DisabledGlyphKind := sSpeedButton1.DisabledGlyphKind + [dgGrayed] else sSpeedButton1.DisabledGlyphKind := sSpeedButton1.DisabledGlyphKind - [dgGrayed]; end; procedure TFrameTsSpeedButton.sCheckBox7Click(Sender: TObject); begin if sCheckBox7.Checked then sSpeedButton1.OnClick := sSpeedButton1Click else sSpeedButton1.OnClick := nil; sSpeedButton1.SkinData.Invalidate; sComboBox1.Enabled := Assigned(sSpeedButton1.OnClick); end; procedure TFrameTsSpeedButton.sCheckBox8Click(Sender: TObject); begin sSpeedButton1.Grayed := sCheckBox8.Checked; end; procedure TFrameTsSpeedButton.sCheckBox9Click(Sender: TObject); begin sSpeedButton1.Reflected := sCheckBox9.Checked; end; procedure TFrameTsSpeedButton.sColorBox1Change(Sender: TObject); begin sTrackEdit5.Value := 0; sTrackEdit5.OnChange(sTrackEdit5); sSpeedButton1.SkinData.ColorTone := sColorBox1.Selected; sTrackEdit5.Enabled := sColorBox1.Selected = clNone; sSpeedButton3.Enabled := sColorBox1.Selected <> sColorBox1.NoneColorColor; end; procedure TFrameTsSpeedButton.sColorBox1ColorPreview(Sender: TObject; OriginColor, PreviousColor: TColor; var NewColor: TColor); begin sTrackEdit5.Value := 0; sTrackEdit5.OnChange(sTrackEdit5); sSpeedButton1.SkinData.ColorTone := NewColor; sTrackEdit5.Enabled := sColorBox1.Selected = clNone; sSpeedButton3.Enabled := (NewColor <> clNone); end; procedure TFrameTsSpeedButton.sColorBox2Change(Sender: TObject); begin sSpeedButton1.GlyphColorTone := sColorBox2.Selected; sSpeedButton4.Enabled := sColorBox2.Selected <> sColorBox2.NoneColorColor; end; procedure TFrameTsSpeedButton.sColorBox2ColorPreview(Sender: TObject; OriginColor, PreviousColor: TColor; var NewColor: TColor); begin sSpeedButton1.GlyphColorTone := NewColor; sSpeedButton4.Enabled := (clNone <> NewColor); end; procedure TFrameTsSpeedButton.sComboBox1Change(Sender: TObject); begin sSpeedButton1.SplitterStyle := TacSplitterStyle(sComboBox1.ItemIndex); end; procedure TFrameTsSpeedButton.sComboBox4Change(Sender: TObject); begin sSpeedButton1.SkinData.SkinSection := sComboBox4.Text; end; procedure TFrameTsSpeedButton.sGroupBox1CheckBoxChanged(Sender: TObject); begin sSpeedButton1.Enabled := not sGroupBox1.Checked; CheckDisableGroup; end; procedure TFrameTsSpeedButton.sGroupBox3CheckBoxChanged(Sender: TObject); begin sTrackEdit3.Enabled := sCheckBox1.Checked and sGroupBox3.Checked; CheckTextGroup; CheckLayoutControls; CheckDisableGroup; if sGroupBox3.Checked then sSpeedButton1.Images := FormData.sCharImageList1 else sSpeedButton1.Images := nil; end; procedure TFrameTsSpeedButton.sRadioButton1Click(Sender: TObject); begin sSpeedButton1.Layout := LayoutArray[TsRadioButton(Sender).Tag]; sRadioGroup1.Controls[0].Enabled := TsRadioButton(Sender).Tag < 2; sRadioGroup1.Controls[1].Enabled := TsRadioButton(Sender).Tag < 2; CheckTextGroup; end; procedure TFrameTsSpeedButton.sRadioGroup1Click(Sender: TObject); begin sSpeedButton1.Alignment := AlignmentArray[sRadioGroup1.ItemIndex]; sTrackEdit2.Enabled := (sRadioGroup1.ItemIndex < 2); CheckTextGroup; CheckLayoutControls; end; procedure TFrameTsSpeedButton.sRadioGroup2Change(Sender: TObject); begin case sRadioGroup2.ItemIndex of 0: sSpeedButton1.ButtonStyle := tbsButton; 1: sSpeedButton1.ButtonStyle := tbsDivider; 3: sSpeedButton1.ButtonStyle := tbsSeparator; 2: sSpeedButton1.ButtonStyle := tbsDropDown; end; sGroupBox4.Enabled := sSpeedButton1.ButtonStyle = tbsDropDown; IterateControls(sGroupBox4, integer(not sGroupBox4.Enabled), EnabledControls); end; procedure TFrameTsSpeedButton.sRadioGroup3Click(Sender: TObject); begin sSpeedButton1.TextAlignment := AlignmentArray[sRadioGroup3.ItemIndex]; end; procedure TFrameTsSpeedButton.sSpeedButton1Click(Sender: TObject); begin ShowMessage('OnClick'); end; procedure TFrameTsSpeedButton.sSpeedButton3Click(Sender: TObject); begin sColorBox1.Selected := clNone; sSpeedButton3.Enabled := False; sColorBox1.OnChange(sColorBox1); end; procedure TFrameTsSpeedButton.sSpeedButton4Click(Sender: TObject); begin sColorBox2.Selected := clNone; sSpeedButton1.GlyphColorTone := clNone; sSpeedButton4.Enabled := False; end; procedure TFrameTsSpeedButton.sTrackEdit2Change(Sender: TObject); begin sSpeedButton1.Margin := sTrackEdit2.AsInteger; sSpeedButton1.SkinData.Invalidate; end; procedure TFrameTsSpeedButton.sTrackEdit3Change(Sender: TObject); begin sSpeedButton1.Spacing := sTrackEdit3.AsInteger; end; procedure TFrameTsSpeedButton.sTrackEdit4Change(Sender: TObject); begin sVirtualImageList1.AcBeginUpdate; sVirtualImageList1.Height := sTrackEdit4.AsInteger; sVirtualImageList1.Width := sTrackEdit4.AsInteger; sVirtualImageList1.AcEndUpdate(True); end; procedure TFrameTsSpeedButton.sTrackEdit5Change(Sender: TObject); begin sSpeedButton1.SkinData.HUEOffset := sTrackEdit5.AsInteger; end; procedure TFrameTsSpeedButton.sTrackEdit1Change(Sender: TObject); begin sSpeedButton1.Blend := sTrackEdit1.AsInteger; end; end.
30.301075
187
0.787881
f1eea3ba2ed26454ead4d2454f0f83fc40624050
6,029
pas
Pascal
Features/Connectivity/DW.Connectivity.iOS.pas
onyxadm/Kastri
c5ce1ea3dc6279aeac9d0850194eb8a640e6b94e
[ "MIT" ]
null
null
null
Features/Connectivity/DW.Connectivity.iOS.pas
onyxadm/Kastri
c5ce1ea3dc6279aeac9d0850194eb8a640e6b94e
[ "MIT" ]
null
null
null
Features/Connectivity/DW.Connectivity.iOS.pas
onyxadm/Kastri
c5ce1ea3dc6279aeac9d0850194eb8a640e6b94e
[ "MIT" ]
null
null
null
unit DW.Connectivity.iOS; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // RTL System.Net.Socket, // Mac Macapi.CoreFoundation, // DW DW.iOSapi.SystemConfiguration, DW.Connectivity; type TPlatformConnectivity = class(TObject) private FConnectivity: TConnectivity; public class function IsConnectedToInternet: Boolean; class function IsWifiEnabled: Boolean; class function IsWifiInternetConnection: Boolean; public constructor Create(const AConnectivity: TConnectivity); end; implementation uses // Mac Macapi.Helpers, // iOS iOSapi.Foundation, // Posix Posix.Base, Posix.SysSocket, Posix.NetinetIn, Posix.ArpaInet, Posix.NetIf; type TReachability = class(TObject) private class var FCurrent: TReachability; class constructor CreateClass; class destructor DestroyClass; class procedure ReachabilityCallback(reachability: SCNetworkReachabilityRef; flags: SCNetworkReachabilityFlags; info: Pointer); cdecl; static; private FConnectivity: TConnectivity; FIsConnectedToInternet: Boolean; FIsWifiInternetConnection: Boolean; FReachabilityRef: SCNetworkReachabilityRef; procedure ReachabilityChanged(const AFlags: SCNetworkReachabilityFlags); function Start: Boolean; procedure Stop; procedure UpdateReachability(const AFlags: SCNetworkReachabilityFlags); public class property Current: TReachability read FCurrent; public constructor Create; destructor Destroy; override; property Connectivity: TConnectivity read FConnectivity write FConnectivity; property IsConnectedToInternet: Boolean read FIsConnectedToInternet; property IsWifiInternetConnection: Boolean read FIsWifiInternetConnection; end; TOpenConnectivity = class(TConnectivity); const cWifiInterfaceName = 'awdl0'; // <----- That's a small L (l), not a one (1) function getifaddrs(var ifap: pifaddrs): Integer; cdecl; external libc name _PU + 'getifaddrs'; {do not localize} procedure freeifaddrs(ifap: pifaddrs); cdecl; external libc name _PU + 'freeifaddrs'; {do not localize} constructor TPlatformConnectivity.Create(const AConnectivity: TConnectivity); begin inherited Create; FConnectivity := AConnectivity; TReachability.Current.Connectivity := FConnectivity; end; class function TPlatformConnectivity.IsConnectedToInternet: Boolean; begin Result := TReachability.Current.IsConnectedToInternet; end; class function TPlatformConnectivity.IsWifiInternetConnection: Boolean; begin Result := TReachability.Current.IsWifiInternetConnection; end; class function TPlatformConnectivity.IsWifiEnabled: Boolean; var LAddrList, LAddrInfo: pifaddrs; LSet: NSCountedSet; begin Result := False; if getifaddrs(LAddrList) = 0 then try LSet := TNSCountedSet.Create; LAddrInfo := LAddrList; repeat {$WARN SYMBOL_PLATFORM OFF} if (LAddrInfo.ifa_flags and IFF_UP) = IFF_UP then LSet.addObject(TNSString.OCClass.stringWithUTF8String(LAddrInfo.ifa_name)); {$WARN SYMBOL_PLATFORM ON} LAddrInfo := LAddrInfo^.ifa_next; until LAddrInfo = nil; Result := LSet.countForObject(StringToID(cWifiInterfaceName)) > 1; finally freeifaddrs(LAddrList); end; end; { TReachability } class constructor TReachability.CreateClass; begin FCurrent := TReachability.Create; end; class destructor TReachability.DestroyClass; begin FCurrent.Free; end; constructor TReachability.Create; var LEndPoint: TNetEndpoint; LRawAddress: sockaddr; LFlags: SCNetworkReachabilityFlags; begin inherited; LEndPoint := TNetEndpoint.Create(TIPAddress.Any, 0); LRawAddress := LEndPoint; FReachabilityRef := SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, @LRawAddress); SCNetworkReachabilityGetFlags(FReachabilityRef, @LFlags); UpdateReachability(LFlags); Start; end; destructor TReachability.Destroy; begin Stop; CFRelease(FReachabilityRef); FReachabilityRef := nil; inherited; end; class procedure TReachability.ReachabilityCallback(reachability: SCNetworkReachabilityRef; flags: SCNetworkReachabilityFlags; info: Pointer); begin TReachability(info).ReachabilityChanged(flags); end; procedure TReachability.UpdateReachability(const AFlags: SCNetworkReachabilityFlags); begin FIsConnectedToInternet := (AFlags and kSCNetworkReachabilityFlagsReachable) > 0; FIsWifiInternetConnection := FIsConnectedToInternet and ((AFlags and kSCNetworkReachabilityFlagsIsWWAN) = 0); end; procedure TReachability.ReachabilityChanged(const AFlags: SCNetworkReachabilityFlags); begin UpdateReachability(AFlags); if FConnectivity <> nil then TOpenConnectivity(FConnectivity).DoConnectivityChange(FIsConnectedToInternet); end; function TReachability.Start: Boolean; var LContext: SCNetworkReachabilityContext; begin LContext := Default(SCNetworkReachabilityContext); LContext.info := Self; Result := SCNetworkReachabilitySetCallback(FReachabilityRef, @ReachabilityCallback, @LContext); Result := Result and SCNetworkReachabilityScheduleWithRunLoop(FReachabilityRef, CFRunLoopGetCurrent, kCFRunLoopDefaultMode); end; procedure TReachability.Stop; begin SCNetworkReachabilityUnscheduleFromRunLoop(FReachabilityRef, CFRunLoopGetCurrent, kCFRunLoopDefaultMode); end; end.
31.565445
147
0.708243
f12290321a909228a6e3466f1bcf942b717105b8
2,104
dpr
Pascal
Demos/SshExec/SshExec.dpr
atkins126/Ssh-Pascal
4ef05a150e314b6d248ba852745d4b3205bc9cb6
[ "MIT" ]
31
2020-07-12T03:52:28.000Z
2022-02-20T14:58:37.000Z
Demos/SshExec/SshExec.dpr
atkins126/Ssh-Pascal
4ef05a150e314b6d248ba852745d4b3205bc9cb6
[ "MIT" ]
10
2021-04-22T10:00:10.000Z
2021-09-05T14:14:30.000Z
Demos/SshExec/SshExec.dpr
atkins126/Ssh-Pascal
4ef05a150e314b6d248ba852745d4b3205bc9cb6
[ "MIT" ]
18
2020-07-12T03:57:06.000Z
2022-02-24T03:06:46.000Z
program SshExec; {$APPTYPE CONSOLE} uses Winapi.Winsock2, System.SysUtils, System.Classes, libssh2 in '..\..\Source\libssh2.pas', SocketUtils in '..\..\Source\SocketUtils.pas', Ssh2Client in '..\..\Source\Ssh2Client.pas', libssh2_sftp in '..\..\Source\libssh2_sftp.pas', SFtpClient in '..\..\Source\SFtpClient.pas'; function KeybIntCallback(const AuthName, AuthInstruction, Prompt: string; Echo: Boolean): string; begin if AuthName <> '' then WriteLn('Authorization Name: ', AuthName); if AuthInstruction <> '' then WriteLn('Authorization Instruction: ', AuthInstruction); Write(Prompt); // if Echo is False then you should mask the input // See https://stackoverflow.com/questions/3671042/mask-password-input-in-a-console-app ReadLn(Result); end; procedure Main; Var Host: string; UserName: string; Command: string; Session: ISshSession; SshExec: ISshExec; Output: string; ErrOutput: string; ExitCode: Integer; begin if ParamCount <> 3 then begin WriteLn('Usage: SshExec Host, UserName, Command'); Exit; end; Host := ParamStr(1); UserName := ParamStr(2); Command := ParamStr(3); Session := CreateSession(Host, 22); //Session.UseCompression := True; Session.SetKeybInteractiveCallback(KeybIntCallback); Session.Connect; WriteLn(Session.HostBanner); WriteLn(Session.SessionMethods); //if not Session.UserAuthInteractive(UserName) then if not Session.UserAuth(UserName) then begin WriteLn('Authorization Failure'); Exit; end; SshExec := CreateSshExec(Session); SshExec.Exec(Command, Output, ErrOutput, ExitCode); WriteLn('Command:', Command); WriteLn('Output:'); if Output <> '' then WriteLn(Output); WriteLn('Error Output:'); if ErrOutput <> '' then WriteLn(ErrOutput); WriteLn('Exit Code:', ExitCode.ToString); Writeln('All done!'); end; begin ReportMemoryLeaksOnShutdown := True; try Main; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; ReadLn; end.
25.349398
90
0.669677
f1f4f906b403396e3e510ed8ca933c1eb4a8bee8
4,256
pas
Pascal
package/indy-10.2.0.3/fpc/examples/httpget/httpprothandler.pas
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
1
2022-02-28T11:28:18.000Z
2022-02-28T11:28:18.000Z
package/indy-10.2.0.3/fpc/examples/httpget/httpprothandler.pas
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
null
null
null
package/indy-10.2.0.3/fpc/examples/httpget/httpprothandler.pas
RonaldoSurdi/Sistema-gerenciamento-websites-delphi
8cc7eec2d05312dc41f514bbd5f828f9be9c579e
[ "MIT" ]
null
null
null
unit httpprothandler; interface {$mode delphi}{$H+} {$ifdef unix} {$define usezlib} {$define useopenssl} {$endif} {$ifdef win32} {$define usezlib} {$define useopenssl} {$endif} uses {$ifdef usezlib} IdCompressorZLib, //for deflate and gzip content encoding {$endif} IdAuthenticationDigest, //MD5-Digest authentication {$ifdef useopenssl} IdSSLOpenSSL, //ssl IdAuthenticationNTLM, //NTLM - uses OpenSSL libraries {$endif} prothandler, Classes, SysUtils, IdHTTPHeaderInfo, //for HTTP request and response info. IdHTTP, IdURI; type THTTPProtHandler = class(TProtHandler) protected function GetTargetFileName(AHTTP : TIdHTTP; AURI : TIdURI) : String; public class function CanHandleURL(AURL : TIdURI) : Boolean; override; procedure GetFile(AURL : TIdURI); override; end; implementation class function THTTPProtHandler.CanHandleURL(AURL : TIdURI) : Boolean; begin Result := UpperCase(AURL.Protocol)='HTTP'; {$ifdef useopenssl} if not Result then begin Result := UpperCase(AURL.Protocol)='HTTPS'; end; {$endif} end; procedure THTTPProtHandler.GetFile(AURL : TIdURI); var {$ifdef useopenssl} LIO : TIdSSLIOHandlerSocketOpenSSL; {$endif} LHTTP : TIdHTTP; LStr : TMemoryStream; i : Integer; LHE : EIdHTTPProtocolException; LFName : String; {$ifdef usezlib} LC : TIdCompressorZLib; {$endif} begin {$ifdef useopenssl} LIO := TIdSSLIOHandlerSocketOpenSSL.Create; {$endif} {$ifdef usezlib} LC := TIdCompressorZLib.Create; {$endif} try LHTTP := TIdHTTP.Create; try {$ifdef useopenssl} LHTTP.Compressor := LC; {$endif} //set to false if you want this to simply raise an exception on redirects LHTTP.HandleRedirects := True; { Note that you probably should set the UserAgent because some servers now screen out requests from our default string "Mozilla/3.0 (compatible; Indy Library)" to prevent address harvesters and Denial of Service attacks. SOme people have used Indy for these. Note that you do need a Mozilla string for the UserAgent property. The format is like this: Mozilla/4.0 (compatible; MyProgram) } LHTTP.Request.UserAgent := 'Mozilla/4.0 (compatible; httpget)'; LStr := TMemoryStream.Create; {$ifdef useopenssl} LHTTP.IOHandler := LIO; {$endif} for i := 0 to LHTTP.Request.RawHeaders.Count -1 do begin FLogData.Add(LHTTP.Request.RawHeaders[i]); if FVerbose then begin WriteLn(stdout,LHTTP.Request.RawHeaders[i]); end; end; LHTTP.Get(AURL.URI,LStr); for i := 0 to LHTTP.Response.RawHeaders.Count -1 do begin FLogData.Add(LHTTP.Response.RawHeaders[i]); if FVerbose then begin WriteLn(stdout,LHTTP.Response.RawHeaders[i]); end; end; LFName := GetTargetFileName(LHTTP,AURL); if LFName <> '' then begin LStr.SaveToFile(LFName); end; except on E : Exception do begin if E is EIdHTTPProtocolException then begin LHE := E as EIdHTTPProtocolException; WriteLn(stderr,'HTTP Protocol Error - '+IntToStr(LHE.ErrorCode)); WriteLn(stderr,LHE.ErrorMessage); if Verbose = False then begin for i := 0 to FLogData.Count -1 do begin Writeln(stderr,FLogData[i]); end; end; end else begin Writeln(stderr,E.Message); end; end; end; FreeAndNil(LHTTP); FreeAndNil(LStr); finally {$ifdef useopenssl} FreeAndNil(LIO); {$endif} {$ifdef usezlib} FreeAndNil(LC); {$endif} end; end; function THTTPProtHandler.GetTargetFileName(AHTTP : TIdHTTP; AURI : TIdURI) : String; begin { We do things this way in case the server gave you a specific document type in response to a request. eg. Request: http://www.indyproject.org/ Response: http://www.indyproject.org/index.html } if AHTTP.Response.Location <> '' then begin AURI.URI := AHTTP.Response.Location; end; Result := AURI.Document; if Result = '' then begin Result := 'index.html'; end; end; end.
24.601156
97
0.648261
471f6814d80559042228804be8ca4a539c954029
13,419
pas
Pascal
scriv4lean/source/S4L.BibTeX.pas
gabr42/ScrivenerToLeanpub
784eadf2c8fef40cf77bafbe51ab06c83c0d1a60
[ "CC-BY-4.0" ]
4
2019-06-20T05:28:54.000Z
2021-01-17T18:16:40.000Z
scriv4lean/source/S4L.BibTeX.pas
gabr42/ScrivenerToLeanpub
784eadf2c8fef40cf77bafbe51ab06c83c0d1a60
[ "CC-BY-4.0" ]
3
2019-06-20T14:48:21.000Z
2019-06-25T14:35:20.000Z
scriv4lean/source/S4L.BibTeX.pas
gabr42/ScrivenerToLeanpub
784eadf2c8fef40cf77bafbe51ab06c83c0d1a60
[ "CC-BY-4.0" ]
null
null
null
unit S4L.BibTeX; interface uses S4L.Errors, S4L.Format; type IBibTeX = interface(IErrorBase) ['{8C6FC76A-8E53-460C-9D58-D8CD84882DD9}'] function CreateBibliography(const template: TArray<string>; orderByAppearance: boolean): TArray<string>; function GetCitationNumber(const citationKey: string): integer; function GetCitationTag(const citationKey, field: string; prettyPrint: boolean): string; function GetCitationURL(const citationKey: string): string; function HasCitation(const citationKey: string; var citationAnchor: string): boolean; function Read(const fileName: string): boolean; end; { IBibTeX } function CreateBibTeX(const format: IFormat): IBibTeX; implementation uses System.SysUtils, System.Classes, System.Math, System.StrUtils, System.RegularExpressions, System.Generics.Defaults, System.Generics.Collections, S4L.Reader; type TBibTeXItem = class strict private FAppearanceIndex: integer; FCitationKey : string; FIsUsed : boolean; FItemType : string; FTags : TDictionary<string, string>; strict protected function GetCitationKey: string; function GetTags: TDictionary<string, string>; function GetItemType: string; public constructor Create(const AItemType, ACitationKey: string; ATags: TDictionary<string, string>); destructor Destroy; override; property AppearanceIndex: integer read FAppearanceIndex write FAppearanceIndex; property CitationKey: string read GetCitationKey; property IsUsed: boolean read FIsUsed write FIsUsed; property ItemType: string read GetItemType; property Tags: TDictionary<string, string> read GetTags; end; { TBibTeXItem } TBibTeX = class(TErrorBase, IBibTeX) strict private const CURLTag = 'url'; var FCitationOrder : TStringList; FConditionalMatcher: TRegEx; FFormat : IFormat; FItems : TObjectList<TBibTeXItem>; FReader : IReader; FTagMatcher : TRegEx; strict protected function AllTagsHaveValues(const tags: TMatchCollection; const item: TBibTeXItem): boolean; function ApplyTemplate(const item: TBibTeXItem; const template: TArray<string>; useAppearanceIndex: boolean): TArray<string>; function Cleanup(const value: string): string; function FillTemplate(templates: TDictionary<string, TArray<string>>; orderByUseIndex: boolean): TArray<string>; function FilterConditionals(const line: string; const item: TBibTeXItem): string; function ItemKeys: TArray<string>; function MakeAnchor(const citationKey: string): string; function NormalizeAuthors(const authors: string): string; function ParseTemplate(const template: TArray<string>; templates: TDictionary<string, TArray<string>>): boolean; function ReadItem: boolean; procedure SkipPreamble; public constructor Create(const format: IFormat); destructor Destroy; override; function CreateBibliography(const template: TArray<string>; orderByUseIndex: boolean): TArray<string>; function GetCitationNumber(const citationKey: string): integer; function GetCitationTag(const citationKey, field: string; prettyPrint: boolean): string; function GetCitationURL(const citationKey: string): string; function HasCitation(const citationKey: string; var citationAnchor: string): boolean; function Read(const fileName: string): boolean; end; { TBibTeX } { exports } function CreateBibTeX(const format: IFormat): IBibTeX; begin Result := TBibTeX.Create(format); end; { CreateBibTeX } { TBibTeX } constructor TBibTeX.Create(const format: IFormat); begin inherited Create; FFormat := format; FItems := TObjectList<TBibTeXItem>.Create; FCitationOrder := TStringList.Create; FConditionalMatcher := TRegEx.Create('\[.*?@.*?@.*?\]'); FTagMatcher := TRegEx.Create('@.*?@'); end; { TBibTeX.Create } destructor TBibTeX.Destroy; begin FreeAndNil(FCitationOrder); FreeAndNil(FItems); inherited; end; { TBibTeX.Destroy } function TBibTeX.AllTagsHaveValues(const tags: TMatchCollection; const item: TBibTeXItem): boolean; var value: string; begin for var tag: TMatch in tags do if not (item.Tags.TryGetValue(tag.Value.Trim(['@']), value) and (value <> '')) then Exit(false); Result := true; end; { TBibTeX.AllTagsHaveValues } function TBibTeX.ApplyTemplate(const item: TBibTeXItem; const template: TArray<string>; useAppearanceIndex: boolean): TArray<string>; var kv: TPair<string, string>; begin var output := TStringList.Create; try for var templLine in template do begin var line := FilterConditionals(templLine, item); if Pos('@citationKey@', line) > 0 then line := StringReplace(line, '@citationKey@', '[' + IfThen(useAppearanceIndex, item.AppearanceIndex.ToString, item.CitationKey) + ']', [rfReplaceAll]) + FFormat.Anchor(MakeAnchor(item.CitationKey)); for kv in item.Tags do line := StringReplace(line, '@' + kv.Key + '@', kv.Value, [rfReplaceAll]); output.Add(line); end; Result := output.ToStringArray; finally FreeAndNil(output); end; end; { TBibTeX.ApplyTemplate } function TBibTeX.Cleanup(const value: string): string; begin Result := StringReplace( StringReplace( StringReplace(value, '{\v{c}}', 'č', [rfReplaceAll]), '{\v{s}}', 'š', [rfReplaceAll]), '{\v{z}}', 'ž', [rfReplaceAll]); end; { TBibTeX.Cleanup } function TBibTeX.CreateBibliography(const template: TArray<string>; orderByUseIndex: boolean): TArray<string>; var templates: TDictionary<string, TArray<string>>; begin templates := TDictionary<string, TArray<string>>.Create( TOrdinalIStringComparer(TIStringComparer.Ordinal)); try if not ParseTemplate(template, templates) then Exit; Result := FillTemplate(templates, orderByUseIndex); finally FreeAndNil(templates); end; end; { TBibTeX.CreateBibliography } function TBibTeX.FillTemplate(templates: TDictionary<string, TArray<string>>; orderByUseIndex: boolean): TArray<string>; begin var output := TStringList.Create; try if orderByUseIndex then begin for var item in FItems do item.AppearanceIndex := FCitationOrder.IndexOf(item.CitationKey) + 1; FItems.Sort( TComparer<TBibTeXItem>.Construct( function (const left, right: TBibTeXItem): integer begin Result := CompareValue(left.AppearanceIndex, right.AppearanceIndex); end)); end else FItems.Sort( TComparer<TBibTeXItem>.Construct( function (const left, right: TBibTeXItem): integer begin Result := TOrdinalIStringComparer(TIStringComparer.Ordinal).Compare(left.CitationKey, right.CitationKey); end)); for var item in FItems do begin var template: TArray<string>; if templates.TryGetValue(item.ItemType, template) then if item.IsUsed then output.AddStrings(ApplyTemplate(item, template, orderByUseIndex)); end; Result := output.ToStringArray; finally FreeAndNil(output); end; end; { TBibTeX.FillTemplate } function TBibTeX.FilterConditionals(const line: string; const item: TBibTeXItem): string; begin Result := line; var startPos := 1; repeat var match := FConditionalMatcher.Match(Result, startPos); if not match.Success then break; //repeat var tags := FTagMatcher.Matches(match.Value); if not AllTagsHaveValues(tags, item) then Delete(Result, match.Index, match.Length) else begin Delete(Result, match.Index, 1); startPos := match.Index + match.Length - 2; Delete(Result, startPos, 1); end; until false; end; { BibTeX.FilterConditionals } function TBibTeX.GetCitationNumber(const citationKey: string): integer; begin Result := FCitationOrder.IndexOf(citationKey); if Result < 0 then Result := FCitationOrder.Add(citationKey); Inc(Result); end; { BibTeX.GetCitationNumber } function TBibTeX.GetCitationTag(const citationKey, field: string; prettyPrint: boolean): string; begin for var item in FItems do if SameText(item.CitationKey, citationKey) then begin if not item.Tags.TryGetValue(field, Result) then Result := '' else if prettyPrint then if SameText(field, 'author') then Result := NormalizeAuthors(Result); end; end; { TBibTeX.GetCitationTag } function TBibTeX.GetCitationURL(const citationKey: string): string; begin Result := ''; for var item in FItems do if SameText(item.CitationKey, citationKey) then begin item.Tags.TryGetValue(CURLTag, Result); Exit; end; end; {BibTeX.GetCitationURL } function TBibTeX.HasCitation(const citationKey: string; var citationAnchor: string): boolean; begin Result := false; for var item in FItems do if SameText(item.CitationKey, citationKey) then begin item.IsUsed := true; citationAnchor := MakeAnchor(citationKey); Exit(true); end; end; { TBibTeX.HasCitation } function TBibTeX.ItemKeys: TArray<string>; begin var keys := TStringList.Create; try for var item in FItems do keys.Add(item.CitationKey); keys.Sort; Result := keys.ToStringArray; finally FreeAndNil(keys); end; end; { TBibTeX.ItemKeys } function TBibTeX.MakeAnchor(const citationKey: string): string; begin Result := 'scriv4lean-biblio-' + citationKey; end; { TBibTeX.MakeAnchor } function TBibTeX.NormalizeAuthors(const authors: string): string; begin var p := Pos(',', authors); if p <= 0 then Result := authors else Result := Copy(authors, p+1).Trim + ' ' + Copy(authors, 1, p-1).Trim; end; {BibTeX.NormalizeAuthors } function TBibTeX.ParseTemplate(const template: TArray<string>; templates: TDictionary<string, TArray<string>>): boolean; begin var templateStart := TRegEx.Create('^([A-Za-z]+)=(.*)$'); var itemType: string := ''; var currTemplate := TStringList.Create; try for var line in template do begin var match := templateStart.Match(line); if match.Success then begin if itemType <> '' then begin templates.Add(itemType, currTemplate.ToStringArray); currTemplate.Clear; end; itemType := match.Groups[1].Value; if match.Groups[2].Value <> '' then currTemplate.Add(match.Groups[2].Value); end else begin if line = '.' then currTemplate.Add('') else currTemplate.Add(line); end; end; if itemType <> '' then templates.Add(itemType, currTemplate.ToStringArray); finally FreeAndNil(currTemplate); end; Result := true; end; { TBibTeX.ParseTemplate } function TBibTeX.Read(const fileName: string): boolean; var errMsg: string; begin FReader := CreateReader(fileName, errMsg); if not assigned(FReader) then Exit(SetError(errMsg)); SkipPreamble; while ReadItem do ; Result := (ErrorMsg = ''); end; { TBibTeX.Read } function TBibTeX.ReadItem: boolean; var line: string; begin if not FReader.GetLine(line) then Exit(false); var intro: TArray<string> := line.TrimLeft(['@']).TrimRight([',']).Split(['{']); if not (line.StartsWith('@') and line.EndsWith(',') and line.Contains('{') and (Length(intro) = 2)) then Exit(SetError('Invalid format: ' + line)); var tags := TDictionary<string, string>.Create; try repeat if not FReader.GetLine(line) then Exit(SetError('Unexpected end of file')); if line.StartsWith('}') then break; //repeat var tagData := line.TrimRight([',']).Split(['='], '{', '}'); if Length(tagData) <> 2 then Exit(SetError('Invalid format: ' + line)); var tagValue := tagData[1].Trim; if (tagValue.StartsWith('{') and tagValue.EndsWith('}')) or (tagValue.StartsWith('"') and tagValue.EndsWith('"')) then tagValue := Copy(tagValue, 2, Length(tagValue) - 2); if (tagValue.StartsWith('{') and tagValue.EndsWith('}')) then tagValue := Copy(tagValue, 2, Length(tagValue) - 2); tags.Add(tagData[0].Trim, Cleanup(tagValue)); until false; FItems.Add(TBibTeXItem.Create(intro[0], intro[1], tags)); tags := nil; //FItems takes ownership finally FreeAndNil(tags); end; Result := true; end; { TBibTeX.ReadItem } procedure TBibTeX.SkipPreamble; var line: string; begin while FReader.GetLine(line) do if line.StartsWith('@') then begin FReader.PushBack(line); Exit end; end; { TBibTeX.SkipPreamble } constructor TBibTeXItem.Create(const AItemType, ACitationKey: string; ATags: TDictionary<string, string>); begin inherited Create; FItemType := AItemType; FCitationKey := ACitationKey; FTags := ATags; // takes ownership end; { TBibTeXItem.Create } destructor TBibTeXItem.Destroy; begin FreeAndNil(FTags); inherited; end; { TBibTeXItem.Destroy } function TBibTeXItem.GetCitationKey: string; begin Result := FCitationKey; end; { TBibTeXItem.GetCitationKey } function TBibTeXItem.GetTags: TDictionary<string, string>; begin Result := FTags; end; { TBibTeXItem.GetTags } function TBibTeXItem.GetItemType: string; begin Result := FItemType; end; { TBibTeXItem.GetItemType } end.
31.648585
117
0.685222
f1e6c79a53e03d52305a24a1d1ac4bc16bfe1d74
12,052
pas
Pascal
UILibSources/liblcl/urichedit.pas
topxeq/govcl
112c496aed90625768ad3bba7c88dd43b2c6a044
[ "Apache-2.0" ]
4
2020-12-26T22:42:21.000Z
2021-12-13T06:39:58.000Z
UILibSources/liblcl/urichedit.pas
ChristianWyld/govcl
2e1f110616af36165c3e3243f3980a7b91f35cca
[ "Apache-2.0" ]
null
null
null
UILibSources/liblcl/urichedit.pas
ChristianWyld/govcl
2e1f110616af36165c3e3243f3980a7b91f35cca
[ "Apache-2.0" ]
1
2022-01-24T08:56:38.000Z
2022-01-24T08:56:38.000Z
//---------------------------------------- // Copyright © ying32. All Rights Reserved. // // Licensed under Apache License 2.0 // //---------------------------------------- //---------------------------------------- // 用来兼容Delphi的TRichEdit //---------------------------------------- unit uRichEdit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, RichMemo, richmemohelpers, Graphics; type TSearchType = TSearchOption; TSearchTypes = TSearchOptions; TAttributeType = (atSelected, atDefaultText); TNumberingStyle = (nsNone, nsBullet); TRichEdit = class; { TTextAttributes } TTextAttributes = class(TPersistent) private FOwner: TRichMemo; FType: TAttributeType; function DoGetAttrs: TFontParams; private function GetCharset: TFontCharset; function GetColor: TColor; function GetHeight: Integer; function GetName: string; function GetPitch: TFontPitch; function GetSize: Integer; function GetStyle: TFontStyles; procedure SetCharset(AValue: TFontCharset); procedure SetColor(AValue: TColor); procedure SetHeight(AValue: Integer); procedure SetName(AValue: string); procedure SetPitch(AValue: TFontPitch); procedure SetSize(AValue: Integer); procedure SetStyle(AValue: TFontStyles); public constructor Create(AOwner: TRichMemo; AType: TAttributeType); procedure Assign(Source: TPersistent); override; property Name: string read GetName write SetName; property Pitch: TFontPitch read GetPitch write SetPitch; property Charset: TFontCharset read GetCharset write SetCharset; property Color: TColor read GetColor write SetColor; property Size: Integer read GetSize write SetSize; property Style: TFontStyles read GetStyle write SetStyle; property Height: Integer read GetHeight write SetHeight; end; { TParaAttributes } TParaAttributes = class(TPersistent) private FOwner: TRichMemo; function DoGetParaMetric: TParaMetric; private function GetAlignment: TAlignment; function GetFirstIndent: Integer; function GetLeftIndent: Integer; function GetNumbering: TNumberingStyle; function GetRightIndent: Integer; function GetTab(Index: Byte): Longint; function GetTabCount: Integer; procedure SetAlignment(AValue: TAlignment); procedure SetFirstIndent(AValue: Integer); procedure SetLeftIndent(AValue: Integer); procedure SetNumbering(AValue: TNumberingStyle); procedure SetRightIndent(AValue: Integer); procedure SetTab(Index: Byte; AValue: Longint); procedure SetTabCount(AValue: Integer); public constructor Create(AOwner: TRichMemo); procedure Assign(Source: TPersistent); override; property Alignment: TAlignment read GetAlignment write SetAlignment; property FirstIndent: Integer read GetFirstIndent write SetFirstIndent; property LeftIndent: Integer read GetLeftIndent write SetLeftIndent; property RightIndent: Integer read GetRightIndent write SetRightIndent; property Numbering: TNumberingStyle read GetNumbering write SetNumbering; property TabCount: Integer read GetTabCount write SetTabCount; property Tab[Index: Byte]: Longint read GetTab write SetTab; end; { TRichEdit } TRichEdit = class(TRichMemo) private FDefAttributes: TTextAttributes; FHideScrollBars: Boolean; FParagraph: TParaAttributes; FPlainText: Boolean; FSelAttributes: TTextAttributes; function GetZoom: Integer; procedure SetDefAttributes(AValue: TTextAttributes); procedure SetSelAttributes(AValue: TTextAttributes); procedure SetZoom(AValue: Integer); public constructor Create(AOnwer: TComponent); override; destructor Destroy; override; function FindText(ASearchStr: string; AStartPos: Integer; ALength: Integer; AOptions: TSearchTypes): Integer; property Zoom: Integer read GetZoom write SetZoom; property HideScrollBars: Boolean read FHideScrollBars write FHideScrollBars; property PlainText: Boolean read FPlainText write FPlainText; property DefAttributes: TTextAttributes read FDefAttributes write SetDefAttributes; property SelAttributes: TTextAttributes read FSelAttributes write SetSelAttributes; property Paragraph: TParaAttributes read FParagraph write FParagraph; public property Align; property Alignment; property Anchors; property BidiMode; property BorderSpacing; property BorderStyle; property Color; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property Lines; property MaxLength; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEditingDone; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnLinkAction; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnSelectionChange; property OnStartDrag; property OnPrintAction; property OnUTF8KeyPress; property ParentBidiMode; property ParentColor; property ParentFont; property PopupMenu; property ParentShowHint; property ReadOnly; //property Rtf: string read GetRTF write SetRTF; property ScrollBars; property ShowHint; property TabOrder; property TabStop; property Visible; property WantReturns; property WantTabs; property WordWrap; //property ZoomFactor; end; implementation procedure SafeFillChar(out x; ASize: SizeInt); begin FillChar(x, ASize, #0); end; { TParaAttributes } function TParaAttributes.DoGetParaMetric: TParaMetric; begin FillChar(Result, SizeOf(Result), #0); FOwner.GetParaMetric(FOwner.SelStart, Result); end; function TParaAttributes.GetAlignment: TAlignment; begin Result := TAlignment(RichMemoHelpers.TParaAttributes(TObject(FOwner)).Alignment); //Result := TAlignment(FOwner.GetParaAlignment(FOwner.SelStart)); end; function TParaAttributes.GetFirstIndent: Integer; begin Result := RichMemoHelpers.TParaAttributes(TObject(FOwner)).FirstIndent; //Result := Trunc(DoGetParaMetric.FirstLine); end; function TParaAttributes.GetLeftIndent: Integer; begin Result := RichMemoHelpers.TParaAttributes(TObject(FOwner)).LeftIndent; end; function TParaAttributes.GetNumbering: TNumberingStyle; begin Result := nsNone; end; function TParaAttributes.GetRightIndent: Integer; begin Result := RichMemoHelpers.TParaAttributes(TObject(FOwner)).RightIndent; end; function TParaAttributes.GetTab(Index: Byte): Longint; begin Result := RichMemoHelpers.TParaAttributes(TObject(FOwner)).Tab[Index]; end; function TParaAttributes.GetTabCount: Integer; begin Result := RichMemoHelpers.TParaAttributes(TObject(FOwner)).TabCount; end; procedure TParaAttributes.SetAlignment(AValue: TAlignment); begin RichMemoHelpers.TParaAttributes(TObject(FOwner)).Alignment := RichMemoHelpers.TRichEditAlignment(AValue); // TAlignment = (taLeftJustify, taRightJustify, taCenter); end; procedure TParaAttributes.SetFirstIndent(AValue: Integer); begin RichMemoHelpers.TParaAttributes(TObject(FOwner)).FirstIndent:=AValue; end; procedure TParaAttributes.SetLeftIndent(AValue: Integer); begin RichMemoHelpers.TParaAttributes(TObject(FOwner)).LeftIndent:=AValue; end; procedure TParaAttributes.SetNumbering(AValue: TNumberingStyle); begin end; procedure TParaAttributes.SetRightIndent(AValue: Integer); begin RichMemoHelpers.TParaAttributes(TObject(FOwner)).RightIndent:=AValue; end; procedure TParaAttributes.SetTab(Index: Byte; AValue: Longint); begin RichMemoHelpers.TParaAttributes(TObject(FOwner)).Tab[Index] := AValue; end; procedure TParaAttributes.SetTabCount(AValue: Integer); begin RichMemoHelpers.TParaAttributes(TObject(FOwner)).TabCount:=AValue; end; constructor TParaAttributes.Create(AOwner: TRichMemo); begin inherited Create; FOwner := AOwner; end; procedure TParaAttributes.Assign(Source: TPersistent); begin inherited Assign(Source); end; { TTextAttributes } function TTextAttributes.DoGetAttrs: TFontParams; begin SafeFillChar(Result, SizeOf(Result)); FOwner.GetTextAttributes(FOwner.SelStart, Result); end; function TTextAttributes.GetCharset: TFontCharset; begin Result := 0; //if FType = atDefaultText then //Result := FOwner.GetTextAttributes(); end; function TTextAttributes.GetColor: TColor; begin Result := DoGetAttrs.Color; end; function TTextAttributes.GetHeight: Integer; begin Result := 0; end; function TTextAttributes.GetName: string; begin Result := DoGetAttrs.Name; end; function TTextAttributes.GetPitch: TFontPitch; begin Result := fpDefault; end; function TTextAttributes.GetSize: Integer; begin Result := DoGetAttrs.Size; end; function TTextAttributes.GetStyle: TFontStyles; begin Result := DoGetAttrs.Style; end; procedure TTextAttributes.SetCharset(AValue: TFontCharset); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) end; procedure TTextAttributes.SetColor(AValue: TColor); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) else FOwner.SetRangeColor(FOwner.SelStart, FOwner.SelLength, AValue); end; procedure TTextAttributes.SetHeight(AValue: Integer); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) end; procedure TTextAttributes.SetName(AValue: string); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) else FOwner.SetRangeParams(FOwner.SelStart, FOwner.SelLength, [tmm_Name], AValue, 0, 0, [], []); end; procedure TTextAttributes.SetPitch(AValue: TFontPitch); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) end; procedure TTextAttributes.SetSize(AValue: Integer); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) else FOwner.SetRangeParams(FOwner.SelStart, FOwner.SelLength, [tmm_Size], '', AValue, 0, [], []); end; procedure TTextAttributes.SetStyle(AValue: TFontStyles); begin if FType = atDefaultText then FOwner.SetTextAttributes(FOwner.SelStart, FOwner.SelLength, FOwner.Font) else FOwner.SetRangeParams(FOwner.SelStart, FOwner.SelLength, [tmm_Styles], '', 0, 0, AValue, []); end; constructor TTextAttributes.Create(AOwner: TRichMemo; AType: TAttributeType); begin inherited Create; FOwner := AOwner; FType := AType; end; procedure TTextAttributes.Assign(Source: TPersistent); begin inherited Assign(Source); end; { TRichEdit } function TRichEdit.GetZoom: Integer; begin Result := Trunc(ZoomFactor); end; procedure TRichEdit.SetDefAttributes(AValue: TTextAttributes); begin if FDefAttributes=AValue then Exit; FDefAttributes:=AValue; end; procedure TRichEdit.SetSelAttributes(AValue: TTextAttributes); begin if FSelAttributes=AValue then Exit; FSelAttributes:=AValue; end; procedure TRichEdit.SetZoom(AValue: Integer); begin ZoomFactor := AValue; end; constructor TRichEdit.Create(AOnwer: TComponent); begin inherited Create(AOnwer); FDefAttributes := TTextAttributes.Create(Self, atDefaultText); FParagraph := TParaAttributes.Create(Self); FSelAttributes := TTextAttributes.Create(Self, atSelected); end; destructor TRichEdit.Destroy; begin FSelAttributes.Free; FParagraph.Free; FDefAttributes.Free; inherited Destroy; end; function TRichEdit.FindText(ASearchStr: string; AStartPos: Integer; ALength: Integer; AOptions: TSearchTypes): Integer; begin Result := Search(ASearchStr, AStartPos, ALength, AOptions); end; end.
27.328798
113
0.758878
471eca6ac595e83ae4c3eb56cbb0c0488fe9e531
227
dpr
Pascal
Chapter08/CODE/RECIPE01/PhotosWithEffects.dpr
PacktPublishing/DelphiCookbookThirdEdition
760fd16277dd21a75320571c664553af33e29950
[ "MIT" ]
51
2018-08-03T06:27:36.000Z
2022-03-16T09:10:10.000Z
Chapter08/CODE/RECIPE01/PhotosWithEffects.dpr
PacktPublishing/DelphiCookbookThirdEdition
760fd16277dd21a75320571c664553af33e29950
[ "MIT" ]
1
2019-10-28T16:51:11.000Z
2019-10-28T16:51:11.000Z
Chapter08/CODE/RECIPE01/PhotosWithEffects.dpr
PacktPublishing/DelphiCookbookThirdEdition
760fd16277dd21a75320571c664553af33e29950
[ "MIT" ]
28
2018-08-03T22:20:00.000Z
2021-12-02T03:49:03.000Z
program PhotosWithEffects; uses System.StartUpCopy, FMX.Forms, MainFormU in 'MainFormU.pas' {MainForm}; {$R *.res} begin Application.Initialize; Application.CreateForm(TMainForm, MainForm); Application.Run; end.
15.133333
46
0.744493
cd25230e1f2d23b62650681b1b1112229745ba91
512
dpr
Pascal
Pascal/1-8/1-3/ACT3_/X22/ACT3X3.dpr
DirkyJerky/OtherProgrammingClass
b7267d814e5cd235e56fd682b899602762401fa2
[ "MIT" ]
null
null
null
Pascal/1-8/1-3/ACT3_/X22/ACT3X3.dpr
DirkyJerky/OtherProgrammingClass
b7267d814e5cd235e56fd682b899602762401fa2
[ "MIT" ]
null
null
null
Pascal/1-8/1-3/ACT3_/X22/ACT3X3.dpr
DirkyJerky/OtherProgrammingClass
b7267d814e5cd235e56fd682b899602762401fa2
[ "MIT" ]
null
null
null
program ACT3X3; { Name: Geoff Yoerger Assignment: Lesson 3 EC 2 Due: EC Purpose: Convert years to minutes } {$APPTYPE CONSOLE} uses SysUtils; var years, minutes : real; begin { Intro to program } writeln('Welcome to the Year to Minutes converter'); writeln; { User Input } writeln('Number of years?'); readln(years); { Calculations } minutes := years * 365 * 24 * 24; { Output } writeln(years:0:2, ' years is ', minutes:0:0,' minutes.'); { Halt the console } readln; end.
14.222222
60
0.646484
83757c3c9af603ff41b99e47e36748b62b6af653
2,938
pas
Pascal
primitive_types.pas
Slipinir/enhanced_primitive_types
2e0c970ae8ecd3a7a0a8bffd8594e9f0320bebb7
[ "MIT" ]
null
null
null
primitive_types.pas
Slipinir/enhanced_primitive_types
2e0c970ae8ecd3a7a0a8bffd8594e9f0320bebb7
[ "MIT" ]
null
null
null
primitive_types.pas
Slipinir/enhanced_primitive_types
2e0c970ae8ecd3a7a0a8bffd8594e9f0320bebb7
[ "MIT" ]
null
null
null
{ MIT License Copyright (c) 2017 Luiz Carlos Mendonça Júnior Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit primitive_types; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { IntegerType } IntegerType = interface ['{FD9280BA-D955-4BD3-8F3C-FBE6E4B75A4E}'] function SetValue(const Value: integer): IntegerType; function Value: integer; function Inc: IntegerType; overload; function Inc(const AValue: integer): IntegerType; overload; function Dec: IntegerType; overload; function Dec(const AValue: integer): IntegerType; overload; end; { StringType } StringType = interface ['{AF4A47EB-36A2-4C97-8527-0223FD1B7AF4}'] function SetValue(const Value: string): StringType; function Value: string; function Length: IntegerType; function Copy(const FromPosition, Count: IntegerType): StringType; function Format(const Args: array of const): StringType; end; { DoubleType } DoubleType = interface ['{F30422F7-1ECE-47F2-8B68-12CBC325C828}'] function SetValue(const Value: double): DoubleType; function Value: double; end; { DateTimeType } DateTimeType = interface ['{8FD1AECE-028D-47BD-9318-19FF8ECEA69E}'] function SetValue(const Value: TDateTime): DateTimeType; function Value: TDateTime; end; { BooleanType } BooleanType = interface ['{31E2A743-8EF4-436F-9F66-38B708DBD765}'] function SetValue(const Value: boolean): BooleanType; function Value: boolean; function ToString(const IfTrue, IfFalse: StringType): StringType; overload; function ToInteger(const IfTrue, IfFalse: IntegerType): IntegerType; end; { StreamType } StreamType = interface ['{8B067126-C0FA-42A1-8139-04F4EFEAE96A}'] function SerValue(const Value: TStream): StreamType; function Value: TStream; end; implementation end.
30.604167
80
0.723962
cdb2250a1b7edae0f585f1c3a9fcf9c88ca1ba96
1,774
dpr
Pascal
references/mORMot/SQLite3/Samples/14 - Interface based services/Project14ServerExternal.dpr
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
851
2018-02-05T09:54:56.000Z
2022-03-24T23:13:10.000Z
references/mORMot/SQLite3/Samples/14 - Interface based services/Project14ServerExternal.dpr
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
200
2018-02-06T18:52:39.000Z
2022-03-24T19:59:14.000Z
references/mORMot/SQLite3/Samples/14 - Interface based services/Project14ServerExternal.dpr
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
197
2018-03-20T20:49:55.000Z
2022-03-21T17:38:14.000Z
program Project14ServerExternal; { this sample will create the main SQLite3 DB as in-memory, but will define all tables as external, in the same .db file than Project14Server -> just to demonstrate VirtualTableExternalRegisterAll() function and reproduce the https://synopse.info/forum/viewtopic.php?id=1008 issue } {$APPTYPE CONSOLE} uses {$I SynDprUses.inc} // use FastMM4 on older Delphi, or set FPC threads SysUtils, mORMot, mORMotSQLite3, SynCommons, SynLog, SynDB, SynDBSQLite3, SynSQLite3, SynSQLite3Static, mORMotDB, Project14Interface; type TServiceCalculator = class(TInterfacedObject, ICalculator) public function Add(n1,n2: integer): integer; end; function TServiceCalculator.Add(n1, n2: integer): integer; begin result := n1+n2; end; var aModel: TSQLModel; aProps: TSQLDBSQLite3ConnectionProperties; begin aProps := TSQLDBSQLite3ConnectionProperties.Create( StringToUtf8(ChangeFileExt(ExeVersion.ProgramFileName,'.db')),'','',''); try aModel := TSQLModel.Create([TSQLAuthGroup,TSQLAuthUser],ROOT_NAME); VirtualTableExternalRegisterAll(aModel,aProps); try with TSQLRestServerDB.Create(aModel,SQLITE_MEMORY_DATABASE_NAME,true) do try CreateMissingTables; // we need AuthGroup and AuthUser tables ServiceDefine(TServiceCalculator,[ICalculator],sicShared); if ExportServerNamedPipe(APPLICATION_NAME) then writeln('Background server is running.'#10) else writeln('Error launching the server'#10); write('Press [Enter] to close the server.'); readln; finally Free; end; finally aModel.Free; end; finally aProps.Free; end; end.
29.081967
80
0.697294
f1ccc6e44a636ff17b7a523c3840f0ce2d39995a
1,572
pas
Pascal
Source/Services/SimpleEmailV2/Base/Transform/AWS.SESv2.Transform.ListContactsFilterMarshaller.pas
herux/aws-sdk-delphi
4ef36e5bfc536b1d9426f78095d8fda887f390b5
[ "Apache-2.0" ]
67
2021-07-28T23:47:09.000Z
2022-03-15T11:48:35.000Z
Source/Services/SimpleEmailV2/Base/Transform/AWS.SESv2.Transform.ListContactsFilterMarshaller.pas
herux/aws-sdk-delphi
4ef36e5bfc536b1d9426f78095d8fda887f390b5
[ "Apache-2.0" ]
5
2021-09-01T09:31:16.000Z
2022-03-16T18:19:21.000Z
Source/Services/SimpleEmailV2/Base/Transform/AWS.SESv2.Transform.ListContactsFilterMarshaller.pas
herux/aws-sdk-delphi
4ef36e5bfc536b1d9426f78095d8fda887f390b5
[ "Apache-2.0" ]
13
2021-07-29T02:41:16.000Z
2022-03-16T10:22:38.000Z
unit AWS.SESv2.Transform.ListContactsFilterMarshaller; interface uses AWS.SESv2.Model.ListContactsFilter, AWS.Transform.RequestMarshaller, AWS.SESv2.Transform.TopicFilterMarshaller; type IListContactsFilterMarshaller = IRequestMarshaller<TListContactsFilter, TJsonMarshallerContext>; TListContactsFilterMarshaller = class(TInterfacedObject, IRequestMarshaller<TListContactsFilter, TJsonMarshallerContext>) strict private class var FInstance: IListContactsFilterMarshaller; class constructor Create; public procedure Marshall(ARequestObject: TListContactsFilter; Context: TJsonMarshallerContext); class function Instance: IListContactsFilterMarshaller; static; end; implementation { TListContactsFilterMarshaller } procedure TListContactsFilterMarshaller.Marshall(ARequestObject: TListContactsFilter; Context: TJsonMarshallerContext); begin if ARequestObject.IsSetFilteredStatus then begin Context.Writer.WriteName('FilteredStatus'); Context.Writer.WriteString(ARequestObject.FilteredStatus.Value); end; if ARequestObject.IsSetTopicFilter then begin Context.Writer.WriteName('TopicFilter'); Context.Writer.WriteBeginObject; TTopicFilterMarshaller.Instance.Marshall(ARequestObject.TopicFilter, Context); Context.Writer.WriteEndObject; end; end; class constructor TListContactsFilterMarshaller.Create; begin FInstance := TListContactsFilterMarshaller.Create; end; class function TListContactsFilterMarshaller.Instance: IListContactsFilterMarshaller; begin Result := FInstance; end; end.
29.660377
123
0.825064